clang  20.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/IgnoreExpr.h"
31 #include "clang/AST/NSAPI.h"
34 #include "clang/AST/RecordLayout.h"
35 #include "clang/AST/Stmt.h"
36 #include "clang/AST/TemplateBase.h"
37 #include "clang/AST/Type.h"
38 #include "clang/AST/TypeLoc.h"
41 #include "clang/Basic/CharInfo.h"
42 #include "clang/Basic/Diagnostic.h"
44 #include "clang/Basic/LLVM.h"
51 #include "clang/Basic/Specifiers.h"
52 #include "clang/Basic/SyncScope.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "clang/Basic/TypeTraits.h"
57 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59 #include "clang/Sema/Lookup.h"
60 #include "clang/Sema/Ownership.h"
61 #include "clang/Sema/Scope.h"
62 #include "clang/Sema/ScopeInfo.h"
63 #include "clang/Sema/Sema.h"
64 #include "clang/Sema/SemaAMDGPU.h"
65 #include "clang/Sema/SemaARM.h"
66 #include "clang/Sema/SemaBPF.h"
67 #include "clang/Sema/SemaHLSL.h"
68 #include "clang/Sema/SemaHexagon.h"
71 #include "clang/Sema/SemaMIPS.h"
72 #include "clang/Sema/SemaNVPTX.h"
73 #include "clang/Sema/SemaSYCL.h"
74 #include "clang/Sema/SemaObjC.h"
75 #include "clang/Sema/SemaOpenCL.h"
76 #include "clang/Sema/SemaPPC.h"
77 #include "clang/Sema/SemaRISCV.h"
78 #include "clang/Sema/SemaSystemZ.h"
79 #include "clang/Sema/SemaWasm.h"
80 #include "clang/Sema/SemaX86.h"
81 #include "llvm/ADT/APFloat.h"
82 #include "llvm/ADT/APInt.h"
83 #include "llvm/ADT/APSInt.h"
84 #include "llvm/ADT/ArrayRef.h"
85 #include "llvm/ADT/DenseMap.h"
86 #include "llvm/ADT/FoldingSet.h"
87 #include "llvm/ADT/STLExtras.h"
88 #include "llvm/ADT/SmallBitVector.h"
89 #include "llvm/ADT/SmallPtrSet.h"
90 #include "llvm/ADT/SmallString.h"
91 #include "llvm/ADT/SmallVector.h"
92 #include "llvm/ADT/StringExtras.h"
93 #include "llvm/ADT/StringRef.h"
94 #include "llvm/ADT/StringSet.h"
95 #include "llvm/ADT/StringSwitch.h"
96 #include "llvm/Support/AtomicOrdering.h"
97 #include "llvm/Support/Casting.h"
98 #include "llvm/Support/Compiler.h"
99 #include "llvm/Support/ConvertUTF.h"
100 #include "llvm/Support/ErrorHandling.h"
101 #include "llvm/Support/Format.h"
102 #include "llvm/Support/Locale.h"
103 #include "llvm/Support/MathExtras.h"
104 #include "llvm/Support/SaveAndRestore.h"
105 #include "llvm/Support/raw_ostream.h"
106 #include "llvm/TargetParser/RISCVTargetParser.h"
107 #include "llvm/TargetParser/Triple.h"
108 #include <algorithm>
109 #include <bitset>
110 #include <cassert>
111 #include <cctype>
112 #include <cstddef>
113 #include <cstdint>
114 #include <functional>
115 #include <limits>
116 #include <optional>
117 #include <string>
118 #include <tuple>
119 #include <utility>
120 
121 using namespace clang;
122 using namespace sema;
123 
124 static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
125  const Expr *E);
126 
128  unsigned ByteNo) const {
129  return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
130  Context.getTargetInfo());
131 }
132 
133 static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
135  return (A << 8) | B;
136 }
137 
138 bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
139  unsigned ArgCount = Call->getNumArgs();
140  if (ArgCount >= MinArgCount)
141  return false;
142 
143  return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
144  << 0 /*function call*/ << MinArgCount << ArgCount
145  << /*is non object*/ 0 << Call->getSourceRange();
146 }
147 
148 bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
149  unsigned ArgCount = Call->getNumArgs();
150  if (ArgCount <= MaxArgCount)
151  return false;
152  return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
153  << 0 /*function call*/ << MaxArgCount << ArgCount
154  << /*is non object*/ 0 << Call->getSourceRange();
155 }
156 
157 bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
158  unsigned MaxArgCount) {
159  return checkArgCountAtLeast(Call, MinArgCount) ||
160  checkArgCountAtMost(Call, MaxArgCount);
161 }
162 
163 bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
164  unsigned ArgCount = Call->getNumArgs();
165  if (ArgCount == DesiredArgCount)
166  return false;
167 
168  if (checkArgCountAtLeast(Call, DesiredArgCount))
169  return true;
170  assert(ArgCount > DesiredArgCount && "should have diagnosed this");
171 
172  // Highlight all the excess arguments.
173  SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
174  Call->getArg(ArgCount - 1)->getEndLoc());
175 
176  return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
177  << 0 /*function call*/ << DesiredArgCount << ArgCount
178  << /*is non object*/ 0 << Call->getArg(1)->getSourceRange();
179 }
180 
181 static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S) {
182  bool HasError = false;
183 
184  for (unsigned I = 0; I < Call->getNumArgs(); ++I) {
185  Expr *Arg = Call->getArg(I);
186 
187  if (Arg->isValueDependent())
188  continue;
189 
190  std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
191  int DiagMsgKind = -1;
192  // Arguments must be pointers to constant strings and cannot use '$'.
193  if (!ArgString.has_value())
194  DiagMsgKind = 0;
195  else if (ArgString->find('$') != std::string::npos)
196  DiagMsgKind = 1;
197 
198  if (DiagMsgKind >= 0) {
199  S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
200  << DiagMsgKind << Arg->getSourceRange();
201  HasError = true;
202  }
203  }
204 
205  return !HasError;
206 }
207 
208 static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {
209  if (Value->isTypeDependent())
210  return false;
211 
212  InitializedEntity Entity =
214  ExprResult Result =
216  if (Result.isInvalid())
217  return true;
218  Value = Result.get();
219  return false;
220 }
221 
222 /// Check that the first argument to __builtin_annotation is an integer
223 /// and the second argument is a non-wide string literal.
224 static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
225  if (S.checkArgCount(TheCall, 2))
226  return true;
227 
228  // First argument should be an integer.
229  Expr *ValArg = TheCall->getArg(0);
230  QualType Ty = ValArg->getType();
231  if (!Ty->isIntegerType()) {
232  S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
233  << ValArg->getSourceRange();
234  return true;
235  }
236 
237  // Second argument should be a constant string.
238  Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
239  StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
240  if (!Literal || !Literal->isOrdinary()) {
241  S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
242  << StrArg->getSourceRange();
243  return true;
244  }
245 
246  TheCall->setType(Ty);
247  return false;
248 }
249 
250 static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
251  // We need at least one argument.
252  if (TheCall->getNumArgs() < 1) {
253  S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
254  << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
255  << TheCall->getCallee()->getSourceRange();
256  return true;
257  }
258 
259  // All arguments should be wide string literals.
260  for (Expr *Arg : TheCall->arguments()) {
261  auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
262  if (!Literal || !Literal->isWide()) {
263  S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
264  << Arg->getSourceRange();
265  return true;
266  }
267  }
268 
269  return false;
270 }
271 
272 /// Check that the argument to __builtin_addressof is a glvalue, and set the
273 /// result type to the corresponding pointer type.
274 static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
275  if (S.checkArgCount(TheCall, 1))
276  return true;
277 
278  ExprResult Arg(TheCall->getArg(0));
279  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
280  if (ResultType.isNull())
281  return true;
282 
283  TheCall->setArg(0, Arg.get());
284  TheCall->setType(ResultType);
285  return false;
286 }
287 
288 /// Check that the argument to __builtin_function_start is a function.
289 static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
290  if (S.checkArgCount(TheCall, 1))
291  return true;
292 
294  if (Arg.isInvalid())
295  return true;
296 
297  TheCall->setArg(0, Arg.get());
298  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
300 
301  if (!FD) {
302  S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
303  << TheCall->getSourceRange();
304  return true;
305  }
306 
307  return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
308  TheCall->getBeginLoc());
309 }
310 
311 /// Check the number of arguments and set the result type to
312 /// the argument type.
313 static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
314  if (S.checkArgCount(TheCall, 1))
315  return true;
316 
317  TheCall->setType(TheCall->getArg(0)->getType());
318  return false;
319 }
320 
321 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
322 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
323 /// type (but not a function pointer) and that the alignment is a power-of-two.
324 static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
325  if (S.checkArgCount(TheCall, 2))
326  return true;
327 
328  clang::Expr *Source = TheCall->getArg(0);
329  bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
330 
331  auto IsValidIntegerType = [](QualType Ty) {
332  return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
333  };
334  QualType SrcTy = Source->getType();
335  // We should also be able to use it with arrays (but not functions!).
336  if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
337  SrcTy = S.Context.getDecayedType(SrcTy);
338  }
339  if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
340  SrcTy->isFunctionPointerType()) {
341  // FIXME: this is not quite the right error message since we don't allow
342  // floating point types, or member pointers.
343  S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
344  << SrcTy;
345  return true;
346  }
347 
348  clang::Expr *AlignOp = TheCall->getArg(1);
349  if (!IsValidIntegerType(AlignOp->getType())) {
350  S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
351  << AlignOp->getType();
352  return true;
353  }
354  Expr::EvalResult AlignResult;
355  unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
356  // We can't check validity of alignment if it is value dependent.
357  if (!AlignOp->isValueDependent() &&
358  AlignOp->EvaluateAsInt(AlignResult, S.Context,
360  llvm::APSInt AlignValue = AlignResult.Val.getInt();
361  llvm::APSInt MaxValue(
362  llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
363  if (AlignValue < 1) {
364  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
365  return true;
366  }
367  if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
368  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
369  << toString(MaxValue, 10);
370  return true;
371  }
372  if (!AlignValue.isPowerOf2()) {
373  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
374  return true;
375  }
376  if (AlignValue == 1) {
377  S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
378  << IsBooleanAlignBuiltin;
379  }
380  }
381 
384  SourceLocation(), Source);
385  if (SrcArg.isInvalid())
386  return true;
387  TheCall->setArg(0, SrcArg.get());
388  ExprResult AlignArg =
390  S.Context, AlignOp->getType(), false),
391  SourceLocation(), AlignOp);
392  if (AlignArg.isInvalid())
393  return true;
394  TheCall->setArg(1, AlignArg.get());
395  // For align_up/align_down, the return type is the same as the (potentially
396  // decayed) argument type including qualifiers. For is_aligned(), the result
397  // is always bool.
398  TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
399  return false;
400 }
401 
402 static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
403  if (S.checkArgCount(TheCall, 3))
404  return true;
405 
406  std::pair<unsigned, const char *> Builtins[] = {
407  { Builtin::BI__builtin_add_overflow, "ckd_add" },
408  { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
409  { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
410  };
411 
412  bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
413  const char *> &P) {
414  return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
416  S.getSourceManager(), S.getLangOpts()) == P.second;
417  });
418 
419  auto ValidCkdIntType = [](QualType QT) {
420  // A valid checked integer type is an integer type other than a plain char,
421  // bool, a bit-precise type, or an enumeration type.
422  if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
423  return (BT->getKind() >= BuiltinType::Short &&
424  BT->getKind() <= BuiltinType::Int128) || (
425  BT->getKind() >= BuiltinType::UShort &&
426  BT->getKind() <= BuiltinType::UInt128) ||
427  BT->getKind() == BuiltinType::UChar ||
428  BT->getKind() == BuiltinType::SChar;
429  return false;
430  };
431 
432  // First two arguments should be integers.
433  for (unsigned I = 0; I < 2; ++I) {
435  if (Arg.isInvalid()) return true;
436  TheCall->setArg(I, Arg.get());
437 
438  QualType Ty = Arg.get()->getType();
439  bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
440  if (!IsValid) {
441  S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
442  << CkdOperation << Ty << Arg.get()->getSourceRange();
443  return true;
444  }
445  }
446 
447  // Third argument should be a pointer to a non-const integer.
448  // IRGen correctly handles volatile, restrict, and address spaces, and
449  // the other qualifiers aren't possible.
450  {
452  if (Arg.isInvalid()) return true;
453  TheCall->setArg(2, Arg.get());
454 
455  QualType Ty = Arg.get()->getType();
456  const auto *PtrTy = Ty->getAs<PointerType>();
457  if (!PtrTy ||
458  !PtrTy->getPointeeType()->isIntegerType() ||
459  (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
460  PtrTy->getPointeeType().isConstQualified()) {
461  S.Diag(Arg.get()->getBeginLoc(),
462  diag::err_overflow_builtin_must_be_ptr_int)
463  << CkdOperation << Ty << Arg.get()->getSourceRange();
464  return true;
465  }
466  }
467 
468  // Disallow signed bit-precise integer args larger than 128 bits to mul
469  // function until we improve backend support.
470  if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
471  for (unsigned I = 0; I < 3; ++I) {
472  const auto Arg = TheCall->getArg(I);
473  // Third argument will be a pointer.
474  auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
475  if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
476  S.getASTContext().getIntWidth(Ty) > 128)
477  return S.Diag(Arg->getBeginLoc(),
478  diag::err_overflow_builtin_bit_int_max_size)
479  << 128;
480  }
481  }
482 
483  return false;
484 }
485 
486 namespace {
487 struct BuiltinDumpStructGenerator {
488  Sema &S;
489  CallExpr *TheCall;
490  SourceLocation Loc = TheCall->getBeginLoc();
491  SmallVector<Expr *, 32> Actions;
492  DiagnosticErrorTrap ErrorTracker;
493  PrintingPolicy Policy;
494 
495  BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
496  : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
497  Policy(S.Context.getPrintingPolicy()) {
498  Policy.AnonymousTagLocations = false;
499  }
500 
501  Expr *makeOpaqueValueExpr(Expr *Inner) {
502  auto *OVE = new (S.Context)
503  OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
504  Inner->getObjectKind(), Inner);
505  Actions.push_back(OVE);
506  return OVE;
507  }
508 
509  Expr *getStringLiteral(llvm::StringRef Str) {
511  // Wrap the literal in parentheses to attach a source location.
512  return new (S.Context) ParenExpr(Loc, Loc, Lit);
513  }
514 
515  bool callPrintFunction(llvm::StringRef Format,
516  llvm::ArrayRef<Expr *> Exprs = {}) {
518  assert(TheCall->getNumArgs() >= 2);
519  Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
520  Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
521  Args.push_back(getStringLiteral(Format));
522  Args.insert(Args.end(), Exprs.begin(), Exprs.end());
523 
524  // Register a note to explain why we're performing the call.
528  Ctx.CallArgs = Args.data();
529  Ctx.NumCallArgs = Args.size();
531 
532  ExprResult RealCall =
533  S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
534  TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
535 
537  if (!RealCall.isInvalid())
538  Actions.push_back(RealCall.get());
539  // Bail out if we've hit any errors, even if we managed to build the
540  // call. We don't want to produce more than one error.
541  return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
542  }
543 
544  Expr *getIndentString(unsigned Depth) {
545  if (!Depth)
546  return nullptr;
547 
549  Indent.resize(Depth * Policy.Indentation, ' ');
550  return getStringLiteral(Indent);
551  }
552 
554  return getStringLiteral(T.getAsString(Policy));
555  }
556 
557  bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
558  llvm::raw_svector_ostream OS(Str);
559 
560  // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
561  // than trying to print a single character.
562  if (auto *BT = T->getAs<BuiltinType>()) {
563  switch (BT->getKind()) {
564  case BuiltinType::Bool:
565  OS << "%d";
566  return true;
567  case BuiltinType::Char_U:
568  case BuiltinType::UChar:
569  OS << "%hhu";
570  return true;
571  case BuiltinType::Char_S:
572  case BuiltinType::SChar:
573  OS << "%hhd";
574  return true;
575  default:
576  break;
577  }
578  }
579 
581  if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
582  // We were able to guess how to format this.
583  if (Specifier.getConversionSpecifier().getKind() ==
585  // Wrap double-quotes around a '%s' specifier and limit its maximum
586  // length. Ideally we'd also somehow escape special characters in the
587  // contents but printf doesn't support that.
588  // FIXME: '%s' formatting is not safe in general.
589  OS << '"';
590  Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
591  Specifier.toString(OS);
592  OS << '"';
593  // FIXME: It would be nice to include a '...' if the string doesn't fit
594  // in the length limit.
595  } else {
596  Specifier.toString(OS);
597  }
598  return true;
599  }
600 
601  if (T->isPointerType()) {
602  // Format all pointers with '%p'.
603  OS << "%p";
604  return true;
605  }
606 
607  return false;
608  }
609 
610  bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
611  Expr *IndentLit = getIndentString(Depth);
612  Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
613  if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
614  : callPrintFunction("%s", {TypeLit}))
615  return true;
616 
617  return dumpRecordValue(RD, E, IndentLit, Depth);
618  }
619 
620  // Dump a record value. E should be a pointer or lvalue referring to an RD.
621  bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
622  unsigned Depth) {
623  // FIXME: Decide what to do if RD is a union. At least we should probably
624  // turn off printing `const char*` members with `%s`, because that is very
625  // likely to crash if that's not the active member. Whatever we decide, we
626  // should document it.
627 
628  // Build an OpaqueValueExpr so we can refer to E more than once without
629  // triggering re-evaluation.
630  Expr *RecordArg = makeOpaqueValueExpr(E);
631  bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
632 
633  if (callPrintFunction(" {\n"))
634  return true;
635 
636  // Dump each base class, regardless of whether they're aggregates.
637  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
638  for (const auto &Base : CXXRD->bases()) {
639  QualType BaseType =
640  RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
641  : S.Context.getLValueReferenceType(Base.getType());
642  ExprResult BasePtr = S.BuildCStyleCastExpr(
643  Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
644  RecordArg);
645  if (BasePtr.isInvalid() ||
646  dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
647  Depth + 1))
648  return true;
649  }
650  }
651 
652  Expr *FieldIndentArg = getIndentString(Depth + 1);
653 
654  // Dump each field.
655  for (auto *D : RD->decls()) {
656  auto *IFD = dyn_cast<IndirectFieldDecl>(D);
657  auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
658  if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
659  continue;
660 
661  llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
662  llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
663  getTypeString(FD->getType()),
664  getStringLiteral(FD->getName())};
665 
666  if (FD->isBitField()) {
667  Format += ": %zu ";
669  llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
670  FD->getBitWidthValue(S.Context));
671  Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
672  }
673 
674  Format += "=";
675 
676  ExprResult Field =
678  CXXScopeSpec(), Loc, IFD,
679  DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
681  RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
683  DeclarationNameInfo(FD->getDeclName(), Loc));
684  if (Field.isInvalid())
685  return true;
686 
687  auto *InnerRD = FD->getType()->getAsRecordDecl();
688  auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
689  if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
690  // Recursively print the values of members of aggregate record type.
691  if (callPrintFunction(Format, Args) ||
692  dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
693  return true;
694  } else {
695  Format += " ";
696  if (appendFormatSpecifier(FD->getType(), Format)) {
697  // We know how to print this field.
698  Args.push_back(Field.get());
699  } else {
700  // We don't know how to print this field. Print out its address
701  // with a format specifier that a smart tool will be able to
702  // recognize and treat specially.
703  Format += "*%p";
704  ExprResult FieldAddr =
705  S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
706  if (FieldAddr.isInvalid())
707  return true;
708  Args.push_back(FieldAddr.get());
709  }
710  Format += "\n";
711  if (callPrintFunction(Format, Args))
712  return true;
713  }
714  }
715 
716  return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
717  : callPrintFunction("}\n");
718  }
719 
720  Expr *buildWrapper() {
721  auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
723  TheCall->setType(Wrapper->getType());
724  TheCall->setValueKind(Wrapper->getValueKind());
725  return Wrapper;
726  }
727 };
728 } // namespace
729 
731  if (S.checkArgCountAtLeast(TheCall, 2))
732  return ExprError();
733 
734  ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
735  if (PtrArgResult.isInvalid())
736  return ExprError();
737  TheCall->setArg(0, PtrArgResult.get());
738 
739  // First argument should be a pointer to a struct.
740  QualType PtrArgType = PtrArgResult.get()->getType();
741  if (!PtrArgType->isPointerType() ||
742  !PtrArgType->getPointeeType()->isRecordType()) {
743  S.Diag(PtrArgResult.get()->getBeginLoc(),
744  diag::err_expected_struct_pointer_argument)
745  << 1 << TheCall->getDirectCallee() << PtrArgType;
746  return ExprError();
747  }
748  QualType Pointee = PtrArgType->getPointeeType();
749  const RecordDecl *RD = Pointee->getAsRecordDecl();
750  // Try to instantiate the class template as appropriate; otherwise, access to
751  // its data() may lead to a crash.
752  if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
753  diag::err_incomplete_type))
754  return ExprError();
755  // Second argument is a callable, but we can't fully validate it until we try
756  // calling it.
757  QualType FnArgType = TheCall->getArg(1)->getType();
758  if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
759  !FnArgType->isBlockPointerType() &&
760  !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
761  auto *BT = FnArgType->getAs<BuiltinType>();
762  switch (BT ? BT->getKind() : BuiltinType::Void) {
763  case BuiltinType::Dependent:
764  case BuiltinType::Overload:
765  case BuiltinType::BoundMember:
766  case BuiltinType::PseudoObject:
767  case BuiltinType::UnknownAny:
768  case BuiltinType::BuiltinFn:
769  // This might be a callable.
770  break;
771 
772  default:
773  S.Diag(TheCall->getArg(1)->getBeginLoc(),
774  diag::err_expected_callable_argument)
775  << 2 << TheCall->getDirectCallee() << FnArgType;
776  return ExprError();
777  }
778  }
779 
780  BuiltinDumpStructGenerator Generator(S, TheCall);
781 
782  // Wrap parentheses around the given pointer. This is not necessary for
783  // correct code generation, but it means that when we pretty-print the call
784  // arguments in our diagnostics we will produce '(&s)->n' instead of the
785  // incorrect '&s->n'.
786  Expr *PtrArg = PtrArgResult.get();
787  PtrArg = new (S.Context)
788  ParenExpr(PtrArg->getBeginLoc(),
789  S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
790  if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
791  return ExprError();
792 
793  return Generator.buildWrapper();
794 }
795 
796 static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
797  if (S.checkArgCount(BuiltinCall, 2))
798  return true;
799 
800  SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
801  Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
802  Expr *Call = BuiltinCall->getArg(0);
803  Expr *Chain = BuiltinCall->getArg(1);
804 
805  if (Call->getStmtClass() != Stmt::CallExprClass) {
806  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
807  << Call->getSourceRange();
808  return true;
809  }
810 
811  auto CE = cast<CallExpr>(Call);
812  if (CE->getCallee()->getType()->isBlockPointerType()) {
813  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
814  << Call->getSourceRange();
815  return true;
816  }
817 
818  const Decl *TargetDecl = CE->getCalleeDecl();
819  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
820  if (FD->getBuiltinID()) {
821  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
822  << Call->getSourceRange();
823  return true;
824  }
825 
826  if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
827  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
828  << Call->getSourceRange();
829  return true;
830  }
831 
832  ExprResult ChainResult = S.UsualUnaryConversions(Chain);
833  if (ChainResult.isInvalid())
834  return true;
835  if (!ChainResult.get()->getType()->isPointerType()) {
836  S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
837  << Chain->getSourceRange();
838  return true;
839  }
840 
841  QualType ReturnTy = CE->getCallReturnType(S.Context);
842  QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
843  QualType BuiltinTy = S.Context.getFunctionType(
844  ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
845  QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
846 
847  Builtin =
848  S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
849 
850  BuiltinCall->setType(CE->getType());
851  BuiltinCall->setValueKind(CE->getValueKind());
852  BuiltinCall->setObjectKind(CE->getObjectKind());
853  BuiltinCall->setCallee(Builtin);
854  BuiltinCall->setArg(1, ChainResult.get());
855 
856  return false;
857 }
858 
859 namespace {
860 
861 class ScanfDiagnosticFormatHandler
863  // Accepts the argument index (relative to the first destination index) of the
864  // argument whose size we want.
865  using ComputeSizeFunction =
866  llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
867 
868  // Accepts the argument index (relative to the first destination index), the
869  // destination size, and the source size).
870  using DiagnoseFunction =
871  llvm::function_ref<void(unsigned, unsigned, unsigned)>;
872 
873  ComputeSizeFunction ComputeSizeArgument;
874  DiagnoseFunction Diagnose;
875 
876 public:
877  ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
878  DiagnoseFunction Diagnose)
879  : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
880 
881  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
882  const char *StartSpecifier,
883  unsigned specifierLen) override {
884  if (!FS.consumesDataArgument())
885  return true;
886 
887  unsigned NulByte = 0;
888  switch ((FS.getConversionSpecifier().getKind())) {
889  default:
890  return true;
893  NulByte = 1;
894  break;
896  break;
897  }
898 
899  analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
900  if (FW.getHowSpecified() !=
901  analyze_format_string::OptionalAmount::HowSpecified::Constant)
902  return true;
903 
904  unsigned SourceSize = FW.getConstantAmount() + NulByte;
905 
906  std::optional<llvm::APSInt> DestSizeAPS =
907  ComputeSizeArgument(FS.getArgIndex());
908  if (!DestSizeAPS)
909  return true;
910 
911  unsigned DestSize = DestSizeAPS->getZExtValue();
912 
913  if (DestSize < SourceSize)
914  Diagnose(FS.getArgIndex(), DestSize, SourceSize);
915 
916  return true;
917  }
918 };
919 
920 class EstimateSizeFormatHandler
922  size_t Size;
923  /// Whether the format string contains Linux kernel's format specifier
924  /// extension.
925  bool IsKernelCompatible = true;
926 
927 public:
928  EstimateSizeFormatHandler(StringRef Format)
929  : Size(std::min(Format.find(0), Format.size()) +
930  1 /* null byte always written by sprintf */) {}
931 
932  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
933  const char *, unsigned SpecifierLen,
934  const TargetInfo &) override {
935 
936  const size_t FieldWidth = computeFieldWidth(FS);
937  const size_t Precision = computePrecision(FS);
938 
939  // The actual format.
940  switch (FS.getConversionSpecifier().getKind()) {
941  // Just a char.
944  Size += std::max(FieldWidth, (size_t)1);
945  break;
946  // Just an integer.
956  Size += std::max(FieldWidth, Precision);
957  break;
958 
959  // %g style conversion switches between %f or %e style dynamically.
960  // %g removes trailing zeros, and does not print decimal point if there are
961  // no digits that follow it. Thus %g can print a single digit.
962  // FIXME: If it is alternative form:
963  // For g and G conversions, trailing zeros are not removed from the result.
966  Size += 1;
967  break;
968 
969  // Floating point number in the form '[+]ddd.ddd'.
972  Size += std::max(FieldWidth, 1 /* integer part */ +
973  (Precision ? 1 + Precision
974  : 0) /* period + decimal */);
975  break;
976 
977  // Floating point number in the form '[-]d.ddde[+-]dd'.
980  Size +=
981  std::max(FieldWidth,
982  1 /* integer part */ +
983  (Precision ? 1 + Precision : 0) /* period + decimal */ +
984  1 /* e or E letter */ + 2 /* exponent */);
985  break;
986 
987  // Floating point number in the form '[-]0xh.hhhhp±dd'.
990  Size +=
991  std::max(FieldWidth,
992  2 /* 0x */ + 1 /* integer part */ +
993  (Precision ? 1 + Precision : 0) /* period + decimal */ +
994  1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
995  break;
996 
997  // Just a string.
1000  Size += FieldWidth;
1001  break;
1002 
1003  // Just a pointer in the form '0xddd'.
1005  // Linux kernel has its own extesion for `%p` specifier.
1006  // Kernel Document:
1007  // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1008  IsKernelCompatible = false;
1009  Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1010  break;
1011 
1012  // A plain percent.
1014  Size += 1;
1015  break;
1016 
1017  default:
1018  break;
1019  }
1020 
1021  Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
1022 
1023  if (FS.hasAlternativeForm()) {
1024  switch (FS.getConversionSpecifier().getKind()) {
1025  // For o conversion, it increases the precision, if and only if necessary,
1026  // to force the first digit of the result to be a zero
1027  // (if the value and precision are both 0, a single 0 is printed)
1029  // For b conversion, a nonzero result has 0b prefixed to it.
1031  // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1032  // it.
1035  // Note: even when the prefix is added, if
1036  // (prefix_width <= FieldWidth - formatted_length) holds,
1037  // the prefix does not increase the format
1038  // size. e.g.(("%#3x", 0xf) is "0xf")
1039 
1040  // If the result is zero, o, b, x, X adds nothing.
1041  break;
1042  // For a, A, e, E, f, F, g, and G conversions,
1043  // the result of converting a floating-point number always contains a
1044  // decimal-point
1053  Size += (Precision ? 0 : 1);
1054  break;
1055  // For other conversions, the behavior is undefined.
1056  default:
1057  break;
1058  }
1059  }
1060  assert(SpecifierLen <= Size && "no underflow");
1061  Size -= SpecifierLen;
1062  return true;
1063  }
1064 
1065  size_t getSizeLowerBound() const { return Size; }
1066  bool isKernelCompatible() const { return IsKernelCompatible; }
1067 
1068 private:
1069  static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1070  const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1071  size_t FieldWidth = 0;
1073  FieldWidth = FW.getConstantAmount();
1074  return FieldWidth;
1075  }
1076 
1077  static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1078  const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1079  size_t Precision = 0;
1080 
1081  // See man 3 printf for default precision value based on the specifier.
1082  switch (FW.getHowSpecified()) {
1084  switch (FS.getConversionSpecifier().getKind()) {
1085  default:
1086  break;
1090  Precision = 1;
1091  break;
1098  Precision = 1;
1099  break;
1106  Precision = 6;
1107  break;
1109  Precision = 1;
1110  break;
1111  }
1112  break;
1114  Precision = FW.getConstantAmount();
1115  break;
1116  default:
1117  break;
1118  }
1119  return Precision;
1120  }
1121 };
1122 
1123 } // namespace
1124 
1125 static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1126  StringRef &FormatStrRef, size_t &StrLen,
1127  ASTContext &Context) {
1128  if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1129  Format && (Format->isOrdinary() || Format->isUTF8())) {
1130  FormatStrRef = Format->getString();
1131  const ConstantArrayType *T =
1132  Context.getAsConstantArrayType(Format->getType());
1133  assert(T && "String literal not of constant array type!");
1134  size_t TypeSize = T->getZExtSize();
1135  // In case there's a null byte somewhere.
1136  StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1137  return true;
1138  }
1139  return false;
1140 }
1141 
1142 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1143  CallExpr *TheCall) {
1144  if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1145  isConstantEvaluatedContext())
1146  return;
1147 
1148  bool UseDABAttr = false;
1149  const FunctionDecl *UseDecl = FD;
1150 
1151  const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1152  if (DABAttr) {
1153  UseDecl = DABAttr->getFunction();
1154  assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1155  UseDABAttr = true;
1156  }
1157 
1158  unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1159 
1160  if (!BuiltinID)
1161  return;
1162 
1163  const TargetInfo &TI = getASTContext().getTargetInfo();
1164  unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1165 
1166  auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1167  // If we refer to a diagnose_as_builtin attribute, we need to change the
1168  // argument index to refer to the arguments of the called function. Unless
1169  // the index is out of bounds, which presumably means it's a variadic
1170  // function.
1171  if (!UseDABAttr)
1172  return Index;
1173  unsigned DABIndices = DABAttr->argIndices_size();
1174  unsigned NewIndex = Index < DABIndices
1175  ? DABAttr->argIndices_begin()[Index]
1176  : Index - DABIndices + FD->getNumParams();
1177  if (NewIndex >= TheCall->getNumArgs())
1178  return std::nullopt;
1179  return NewIndex;
1180  };
1181 
1182  auto ComputeExplicitObjectSizeArgument =
1183  [&](unsigned Index) -> std::optional<llvm::APSInt> {
1184  std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1185  if (!IndexOptional)
1186  return std::nullopt;
1187  unsigned NewIndex = *IndexOptional;
1188  Expr::EvalResult Result;
1189  Expr *SizeArg = TheCall->getArg(NewIndex);
1190  if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1191  return std::nullopt;
1192  llvm::APSInt Integer = Result.Val.getInt();
1193  Integer.setIsUnsigned(true);
1194  return Integer;
1195  };
1196 
1197  auto ComputeSizeArgument =
1198  [&](unsigned Index) -> std::optional<llvm::APSInt> {
1199  // If the parameter has a pass_object_size attribute, then we should use its
1200  // (potentially) more strict checking mode. Otherwise, conservatively assume
1201  // type 0.
1202  int BOSType = 0;
1203  // This check can fail for variadic functions.
1204  if (Index < FD->getNumParams()) {
1205  if (const auto *POS =
1206  FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1207  BOSType = POS->getType();
1208  }
1209 
1210  std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1211  if (!IndexOptional)
1212  return std::nullopt;
1213  unsigned NewIndex = *IndexOptional;
1214 
1215  if (NewIndex >= TheCall->getNumArgs())
1216  return std::nullopt;
1217 
1218  const Expr *ObjArg = TheCall->getArg(NewIndex);
1219  uint64_t Result;
1220  if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1221  return std::nullopt;
1222 
1223  // Get the object size in the target's size_t width.
1224  return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1225  };
1226 
1227  auto ComputeStrLenArgument =
1228  [&](unsigned Index) -> std::optional<llvm::APSInt> {
1229  std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1230  if (!IndexOptional)
1231  return std::nullopt;
1232  unsigned NewIndex = *IndexOptional;
1233 
1234  const Expr *ObjArg = TheCall->getArg(NewIndex);
1235  uint64_t Result;
1236  if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1237  return std::nullopt;
1238  // Add 1 for null byte.
1239  return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1240  };
1241 
1242  std::optional<llvm::APSInt> SourceSize;
1243  std::optional<llvm::APSInt> DestinationSize;
1244  unsigned DiagID = 0;
1245  bool IsChkVariant = false;
1246 
1247  auto GetFunctionName = [&]() {
1248  StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1249  // Skim off the details of whichever builtin was called to produce a better
1250  // diagnostic, as it's unlikely that the user wrote the __builtin
1251  // explicitly.
1252  if (IsChkVariant) {
1253  FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1254  FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1255  } else {
1256  FunctionName.consume_front("__builtin_");
1257  }
1258  return FunctionName;
1259  };
1260 
1261  switch (BuiltinID) {
1262  default:
1263  return;
1264  case Builtin::BI__builtin_strcpy:
1265  case Builtin::BIstrcpy: {
1266  DiagID = diag::warn_fortify_strlen_overflow;
1267  SourceSize = ComputeStrLenArgument(1);
1268  DestinationSize = ComputeSizeArgument(0);
1269  break;
1270  }
1271 
1272  case Builtin::BI__builtin___strcpy_chk: {
1273  DiagID = diag::warn_fortify_strlen_overflow;
1274  SourceSize = ComputeStrLenArgument(1);
1275  DestinationSize = ComputeExplicitObjectSizeArgument(2);
1276  IsChkVariant = true;
1277  break;
1278  }
1279 
1280  case Builtin::BIscanf:
1281  case Builtin::BIfscanf:
1282  case Builtin::BIsscanf: {
1283  unsigned FormatIndex = 1;
1284  unsigned DataIndex = 2;
1285  if (BuiltinID == Builtin::BIscanf) {
1286  FormatIndex = 0;
1287  DataIndex = 1;
1288  }
1289 
1290  const auto *FormatExpr =
1291  TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1292 
1293  StringRef FormatStrRef;
1294  size_t StrLen;
1295  if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1296  return;
1297 
1298  auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1299  unsigned SourceSize) {
1300  DiagID = diag::warn_fortify_scanf_overflow;
1301  unsigned Index = ArgIndex + DataIndex;
1302  StringRef FunctionName = GetFunctionName();
1303  DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1304  PDiag(DiagID) << FunctionName << (Index + 1)
1305  << DestSize << SourceSize);
1306  };
1307 
1308  auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1309  return ComputeSizeArgument(Index + DataIndex);
1310  };
1311  ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1312  const char *FormatBytes = FormatStrRef.data();
1314  FormatBytes + StrLen, getLangOpts(),
1315  Context.getTargetInfo());
1316 
1317  // Unlike the other cases, in this one we have already issued the diagnostic
1318  // here, so no need to continue (because unlike the other cases, here the
1319  // diagnostic refers to the argument number).
1320  return;
1321  }
1322 
1323  case Builtin::BIsprintf:
1324  case Builtin::BI__builtin___sprintf_chk: {
1325  size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1326  auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1327 
1328  StringRef FormatStrRef;
1329  size_t StrLen;
1330  if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1331  EstimateSizeFormatHandler H(FormatStrRef);
1332  const char *FormatBytes = FormatStrRef.data();
1334  H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1335  Context.getTargetInfo(), false)) {
1336  DiagID = H.isKernelCompatible()
1337  ? diag::warn_format_overflow
1338  : diag::warn_format_overflow_non_kprintf;
1339  SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1340  .extOrTrunc(SizeTypeWidth);
1341  if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1342  DestinationSize = ComputeExplicitObjectSizeArgument(2);
1343  IsChkVariant = true;
1344  } else {
1345  DestinationSize = ComputeSizeArgument(0);
1346  }
1347  break;
1348  }
1349  }
1350  return;
1351  }
1352  case Builtin::BI__builtin___memcpy_chk:
1353  case Builtin::BI__builtin___memmove_chk:
1354  case Builtin::BI__builtin___memset_chk:
1355  case Builtin::BI__builtin___strlcat_chk:
1356  case Builtin::BI__builtin___strlcpy_chk:
1357  case Builtin::BI__builtin___strncat_chk:
1358  case Builtin::BI__builtin___strncpy_chk:
1359  case Builtin::BI__builtin___stpncpy_chk:
1360  case Builtin::BI__builtin___memccpy_chk:
1361  case Builtin::BI__builtin___mempcpy_chk: {
1362  DiagID = diag::warn_builtin_chk_overflow;
1363  SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1364  DestinationSize =
1365  ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1366  IsChkVariant = true;
1367  break;
1368  }
1369 
1370  case Builtin::BI__builtin___snprintf_chk:
1371  case Builtin::BI__builtin___vsnprintf_chk: {
1372  DiagID = diag::warn_builtin_chk_overflow;
1373  SourceSize = ComputeExplicitObjectSizeArgument(1);
1374  DestinationSize = ComputeExplicitObjectSizeArgument(3);
1375  IsChkVariant = true;
1376  break;
1377  }
1378 
1379  case Builtin::BIstrncat:
1380  case Builtin::BI__builtin_strncat:
1381  case Builtin::BIstrncpy:
1382  case Builtin::BI__builtin_strncpy:
1383  case Builtin::BIstpncpy:
1384  case Builtin::BI__builtin_stpncpy: {
1385  // Whether these functions overflow depends on the runtime strlen of the
1386  // string, not just the buffer size, so emitting the "always overflow"
1387  // diagnostic isn't quite right. We should still diagnose passing a buffer
1388  // size larger than the destination buffer though; this is a runtime abort
1389  // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1390  DiagID = diag::warn_fortify_source_size_mismatch;
1391  SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1392  DestinationSize = ComputeSizeArgument(0);
1393  break;
1394  }
1395 
1396  case Builtin::BImemcpy:
1397  case Builtin::BI__builtin_memcpy:
1398  case Builtin::BImemmove:
1399  case Builtin::BI__builtin_memmove:
1400  case Builtin::BImemset:
1401  case Builtin::BI__builtin_memset:
1402  case Builtin::BImempcpy:
1403  case Builtin::BI__builtin_mempcpy: {
1404  DiagID = diag::warn_fortify_source_overflow;
1405  SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1406  DestinationSize = ComputeSizeArgument(0);
1407  break;
1408  }
1409  case Builtin::BIsnprintf:
1410  case Builtin::BI__builtin_snprintf:
1411  case Builtin::BIvsnprintf:
1412  case Builtin::BI__builtin_vsnprintf: {
1413  DiagID = diag::warn_fortify_source_size_mismatch;
1414  SourceSize = ComputeExplicitObjectSizeArgument(1);
1415  const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1416  StringRef FormatStrRef;
1417  size_t StrLen;
1418  if (SourceSize &&
1419  ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1420  EstimateSizeFormatHandler H(FormatStrRef);
1421  const char *FormatBytes = FormatStrRef.data();
1423  H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1424  Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1425  llvm::APSInt FormatSize =
1426  llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1427  .extOrTrunc(SizeTypeWidth);
1428  if (FormatSize > *SourceSize && *SourceSize != 0) {
1429  unsigned TruncationDiagID =
1430  H.isKernelCompatible() ? diag::warn_format_truncation
1431  : diag::warn_format_truncation_non_kprintf;
1432  SmallString<16> SpecifiedSizeStr;
1433  SmallString<16> FormatSizeStr;
1434  SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1435  FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1436  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1437  PDiag(TruncationDiagID)
1438  << GetFunctionName() << SpecifiedSizeStr
1439  << FormatSizeStr);
1440  }
1441  }
1442  }
1443  DestinationSize = ComputeSizeArgument(0);
1444  }
1445  }
1446 
1447  if (!SourceSize || !DestinationSize ||
1448  llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1449  return;
1450 
1451  StringRef FunctionName = GetFunctionName();
1452 
1453  SmallString<16> DestinationStr;
1454  SmallString<16> SourceStr;
1455  DestinationSize->toString(DestinationStr, /*Radix=*/10);
1456  SourceSize->toString(SourceStr, /*Radix=*/10);
1457  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1458  PDiag(DiagID)
1459  << FunctionName << DestinationStr << SourceStr);
1460 }
1461 
1462 static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1463  Scope::ScopeFlags NeededScopeFlags,
1464  unsigned DiagID) {
1465  // Scopes aren't available during instantiation. Fortunately, builtin
1466  // functions cannot be template args so they cannot be formed through template
1467  // instantiation. Therefore checking once during the parse is sufficient.
1468  if (SemaRef.inTemplateInstantiation())
1469  return false;
1470 
1471  Scope *S = SemaRef.getCurScope();
1472  while (S && !S->isSEHExceptScope())
1473  S = S->getParent();
1474  if (!S || !(S->getFlags() & NeededScopeFlags)) {
1475  auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1476  SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1477  << DRE->getDecl()->getIdentifier();
1478  return true;
1479  }
1480 
1481  return false;
1482 }
1483 
1484 // In OpenCL, __builtin_alloca_* should return a pointer to address space
1485 // that corresponds to the stack address space i.e private address space.
1486 static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1487  QualType RT = TheCall->getType();
1488  assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1489  "__builtin_alloca has invalid address space");
1490 
1491  RT = RT->getPointeeType();
1493  TheCall->setType(S.Context.getPointerType(RT));
1494 }
1495 
1496 namespace {
1497 enum PointerAuthOpKind {
1498  PAO_Strip,
1499  PAO_Sign,
1500  PAO_Auth,
1501  PAO_SignGeneric,
1502  PAO_Discriminator,
1503  PAO_BlendPointer,
1504  PAO_BlendInteger
1505 };
1506 }
1507 
1509  if (getLangOpts().PointerAuthIntrinsics)
1510  return false;
1511 
1512  Diag(Loc, diag::err_ptrauth_disabled) << Range;
1513  return true;
1514 }
1515 
1516 static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1518 }
1519 
1520 static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1521  // Convert it to type 'int'.
1522  if (convertArgumentToType(S, Arg, S.Context.IntTy))
1523  return true;
1524 
1525  // Value-dependent expressions are okay; wait for template instantiation.
1526  if (Arg->isValueDependent())
1527  return false;
1528 
1529  unsigned KeyValue;
1530  return S.checkConstantPointerAuthKey(Arg, KeyValue);
1531 }
1532 
1533 bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1534  // Attempt to constant-evaluate the expression.
1535  std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1536  if (!KeyValue) {
1537  Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1538  << 0 << Arg->getSourceRange();
1539  return true;
1540  }
1541 
1542  // Ask the target to validate the key parameter.
1543  if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1545  {
1546  llvm::raw_svector_ostream Str(Value);
1547  Str << *KeyValue;
1548  }
1549 
1550  Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1551  << Value << Arg->getSourceRange();
1552  return true;
1553  }
1554 
1555  Result = KeyValue->getZExtValue();
1556  return false;
1557 }
1558 
1559 static std::pair<const ValueDecl *, CharUnits>
1561  // Must evaluate as a pointer.
1562  Expr::EvalResult Result;
1563  if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1564  return {nullptr, CharUnits()};
1565 
1566  const auto *BaseDecl =
1567  Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1568  if (!BaseDecl)
1569  return {nullptr, CharUnits()};
1570 
1571  return {BaseDecl, Result.Val.getLValueOffset()};
1572 }
1573 
1574 static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1575  bool RequireConstant = false) {
1576  if (Arg->hasPlaceholderType()) {
1577  ExprResult R = S.CheckPlaceholderExpr(Arg);
1578  if (R.isInvalid())
1579  return true;
1580  Arg = R.get();
1581  }
1582 
1583  auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1584  return OpKind != PAO_BlendInteger;
1585  };
1586  auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1587  return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1588  OpKind == PAO_SignGeneric;
1589  };
1590 
1591  // Require the value to have the right range of type.
1592  QualType ExpectedTy;
1593  if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1594  ExpectedTy = Arg->getType().getUnqualifiedType();
1595  } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1596  ExpectedTy = S.Context.VoidPtrTy;
1597  } else if (AllowsInteger(OpKind) &&
1599  ExpectedTy = S.Context.getUIntPtrType();
1600 
1601  } else {
1602  // Diagnose the failures.
1603  S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1604  << unsigned(OpKind == PAO_Discriminator ? 1
1605  : OpKind == PAO_BlendPointer ? 2
1606  : OpKind == PAO_BlendInteger ? 3
1607  : 0)
1608  << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1609  << Arg->getType() << Arg->getSourceRange();
1610  return true;
1611  }
1612 
1613  // Convert to that type. This should just be an lvalue-to-rvalue
1614  // conversion.
1615  if (convertArgumentToType(S, Arg, ExpectedTy))
1616  return true;
1617 
1618  if (!RequireConstant) {
1619  // Warn about null pointers for non-generic sign and auth operations.
1620  if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1622  S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1623  ? diag::warn_ptrauth_sign_null_pointer
1624  : diag::warn_ptrauth_auth_null_pointer)
1625  << Arg->getSourceRange();
1626  }
1627 
1628  return false;
1629  }
1630 
1631  // Perform special checking on the arguments to ptrauth_sign_constant.
1632 
1633  // The main argument.
1634  if (OpKind == PAO_Sign) {
1635  // Require the value we're signing to have a special form.
1636  auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1637  bool Invalid;
1638 
1639  // Must be rooted in a declaration reference.
1640  if (!BaseDecl)
1641  Invalid = true;
1642 
1643  // If it's a function declaration, we can't have an offset.
1644  else if (isa<FunctionDecl>(BaseDecl))
1645  Invalid = !Offset.isZero();
1646 
1647  // Otherwise we're fine.
1648  else
1649  Invalid = false;
1650 
1651  if (Invalid)
1652  S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1653  return Invalid;
1654  }
1655 
1656  // The discriminator argument.
1657  assert(OpKind == PAO_Discriminator);
1658 
1659  // Must be a pointer or integer or blend thereof.
1660  Expr *Pointer = nullptr;
1661  Expr *Integer = nullptr;
1662  if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1663  if (Call->getBuiltinCallee() ==
1664  Builtin::BI__builtin_ptrauth_blend_discriminator) {
1665  Pointer = Call->getArg(0);
1666  Integer = Call->getArg(1);
1667  }
1668  }
1669  if (!Pointer && !Integer) {
1670  if (Arg->getType()->isPointerType())
1671  Pointer = Arg;
1672  else
1673  Integer = Arg;
1674  }
1675 
1676  // Check the pointer.
1677  bool Invalid = false;
1678  if (Pointer) {
1679  assert(Pointer->getType()->isPointerType());
1680 
1681  // TODO: if we're initializing a global, check that the address is
1682  // somehow related to what we're initializing. This probably will
1683  // never really be feasible and we'll have to catch it at link-time.
1684  auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1685  if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1686  Invalid = true;
1687  }
1688 
1689  // Check the integer.
1690  if (Integer) {
1691  assert(Integer->getType()->isIntegerType());
1692  if (!Integer->isEvaluatable(S.Context))
1693  Invalid = true;
1694  }
1695 
1696  if (Invalid)
1697  S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1698  return Invalid;
1699 }
1700 
1702  if (S.checkArgCount(Call, 2))
1703  return ExprError();
1704  if (checkPointerAuthEnabled(S, Call))
1705  return ExprError();
1706  if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1707  checkPointerAuthKey(S, Call->getArgs()[1]))
1708  return ExprError();
1709 
1710  Call->setType(Call->getArgs()[0]->getType());
1711  return Call;
1712 }
1713 
1715  if (S.checkArgCount(Call, 2))
1716  return ExprError();
1717  if (checkPointerAuthEnabled(S, Call))
1718  return ExprError();
1719  if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1720  checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1721  return ExprError();
1722 
1723  Call->setType(S.Context.getUIntPtrType());
1724  return Call;
1725 }
1726 
1728  if (S.checkArgCount(Call, 2))
1729  return ExprError();
1730  if (checkPointerAuthEnabled(S, Call))
1731  return ExprError();
1732  if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1733  checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1734  return ExprError();
1735 
1736  Call->setType(S.Context.getUIntPtrType());
1737  return Call;
1738 }
1739 
1741  PointerAuthOpKind OpKind,
1742  bool RequireConstant) {
1743  if (S.checkArgCount(Call, 3))
1744  return ExprError();
1745  if (checkPointerAuthEnabled(S, Call))
1746  return ExprError();
1747  if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1748  checkPointerAuthKey(S, Call->getArgs()[1]) ||
1749  checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1750  RequireConstant))
1751  return ExprError();
1752 
1753  Call->setType(Call->getArgs()[0]->getType());
1754  return Call;
1755 }
1756 
1758  if (S.checkArgCount(Call, 5))
1759  return ExprError();
1760  if (checkPointerAuthEnabled(S, Call))
1761  return ExprError();
1762  if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1763  checkPointerAuthKey(S, Call->getArgs()[1]) ||
1764  checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1765  checkPointerAuthKey(S, Call->getArgs()[3]) ||
1766  checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1767  return ExprError();
1768 
1769  Call->setType(Call->getArgs()[0]->getType());
1770  return Call;
1771 }
1772 
1774  if (checkPointerAuthEnabled(S, Call))
1775  return ExprError();
1776 
1777  // We've already performed normal call type-checking.
1778  const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1779 
1780  // Operand must be an ordinary or UTF-8 string literal.
1781  const auto *Literal = dyn_cast<StringLiteral>(Arg);
1782  if (!Literal || Literal->getCharByteWidth() != 1) {
1783  S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1784  << (Literal ? 1 : 0) << Arg->getSourceRange();
1785  return ExprError();
1786  }
1787 
1788  return Call;
1789 }
1790 
1791 static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
1792  if (S.checkArgCount(TheCall, 1))
1793  return ExprError();
1794 
1795  // Compute __builtin_launder's parameter type from the argument.
1796  // The parameter type is:
1797  // * The type of the argument if it's not an array or function type,
1798  // Otherwise,
1799  // * The decayed argument type.
1800  QualType ParamTy = [&]() {
1801  QualType ArgTy = TheCall->getArg(0)->getType();
1802  if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1803  return S.Context.getPointerType(Ty->getElementType());
1804  if (ArgTy->isFunctionType()) {
1805  return S.Context.getPointerType(ArgTy);
1806  }
1807  return ArgTy;
1808  }();
1809 
1810  TheCall->setType(ParamTy);
1811 
1812  auto DiagSelect = [&]() -> std::optional<unsigned> {
1813  if (!ParamTy->isPointerType())
1814  return 0;
1815  if (ParamTy->isFunctionPointerType())
1816  return 1;
1817  if (ParamTy->isVoidPointerType())
1818  return 2;
1819  return std::optional<unsigned>{};
1820  }();
1821  if (DiagSelect) {
1822  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1823  << *DiagSelect << TheCall->getSourceRange();
1824  return ExprError();
1825  }
1826 
1827  // We either have an incomplete class type, or we have a class template
1828  // whose instantiation has not been forced. Example:
1829  //
1830  // template <class T> struct Foo { T value; };
1831  // Foo<int> *p = nullptr;
1832  // auto *d = __builtin_launder(p);
1833  if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1834  diag::err_incomplete_type))
1835  return ExprError();
1836 
1837  assert(ParamTy->getPointeeType()->isObjectType() &&
1838  "Unhandled non-object pointer case");
1839 
1840  InitializedEntity Entity =
1842  ExprResult Arg =
1843  S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1844  if (Arg.isInvalid())
1845  return ExprError();
1846  TheCall->setArg(0, Arg.get());
1847 
1848  return TheCall;
1849 }
1850 
1851 // Emit an error and return true if the current object format type is in the
1852 // list of unsupported types.
1854  Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1855  ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1856  llvm::Triple::ObjectFormatType CurObjFormat =
1857  S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1858  if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1859  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1860  << TheCall->getSourceRange();
1861  return true;
1862  }
1863  return false;
1864 }
1865 
1866 // Emit an error and return true if the current architecture is not in the list
1867 // of supported architectures.
1868 static bool
1870  ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1871  llvm::Triple::ArchType CurArch =
1872  S.getASTContext().getTargetInfo().getTriple().getArch();
1873  if (llvm::is_contained(SupportedArchs, CurArch))
1874  return false;
1875  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1876  << TheCall->getSourceRange();
1877  return true;
1878 }
1879 
1880 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1881  SourceLocation CallSiteLoc);
1882 
1883 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1884  CallExpr *TheCall) {
1885  switch (TI.getTriple().getArch()) {
1886  default:
1887  // Some builtins don't require additional checking, so just consider these
1888  // acceptable.
1889  return false;
1890  case llvm::Triple::arm:
1891  case llvm::Triple::armeb:
1892  case llvm::Triple::thumb:
1893  case llvm::Triple::thumbeb:
1894  return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1895  case llvm::Triple::aarch64:
1896  case llvm::Triple::aarch64_32:
1897  case llvm::Triple::aarch64_be:
1898  return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1899  case llvm::Triple::bpfeb:
1900  case llvm::Triple::bpfel:
1901  return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1902  case llvm::Triple::hexagon:
1903  return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1904  case llvm::Triple::mips:
1905  case llvm::Triple::mipsel:
1906  case llvm::Triple::mips64:
1907  case llvm::Triple::mips64el:
1908  return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1909  case llvm::Triple::systemz:
1910  return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1911  case llvm::Triple::x86:
1912  case llvm::Triple::x86_64:
1913  return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
1914  case llvm::Triple::ppc:
1915  case llvm::Triple::ppcle:
1916  case llvm::Triple::ppc64:
1917  case llvm::Triple::ppc64le:
1918  return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1919  case llvm::Triple::amdgcn:
1920  return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1921  case llvm::Triple::riscv32:
1922  case llvm::Triple::riscv64:
1923  return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
1924  case llvm::Triple::loongarch32:
1925  case llvm::Triple::loongarch64:
1926  return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
1927  TheCall);
1928  case llvm::Triple::wasm32:
1929  case llvm::Triple::wasm64:
1930  return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
1931  case llvm::Triple::nvptx:
1932  case llvm::Triple::nvptx64:
1933  return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
1934  }
1935 }
1936 
1937 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
1938 // not a valid type, emit an error message and return true. Otherwise return
1939 // false.
1941  QualType ArgTy, int ArgIndex) {
1942  if (!ArgTy->getAs<VectorType>() &&
1944  return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
1945  << ArgIndex << /* vector, integer or float ty*/ 0 << ArgTy;
1946  }
1947 
1948  return false;
1949 }
1950 
1952  QualType ArgTy, int ArgIndex) {
1953  QualType EltTy = ArgTy;
1954  if (auto *VecTy = EltTy->getAs<VectorType>())
1955  EltTy = VecTy->getElementType();
1956 
1957  if (!EltTy->isRealFloatingType()) {
1958  return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
1959  << ArgIndex << /* vector or float ty*/ 5 << ArgTy;
1960  }
1961 
1962  return false;
1963 }
1964 
1965 /// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
1966 /// This checks that the target supports the builtin and that the string
1967 /// argument is constant and valid.
1968 static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
1969  const TargetInfo *AuxTI, unsigned BuiltinID) {
1970  assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
1971  BuiltinID == Builtin::BI__builtin_cpu_is) &&
1972  "Expecting __builtin_cpu_...");
1973 
1974  bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
1975  const TargetInfo *TheTI = &TI;
1976  auto SupportsBI = [=](const TargetInfo *TInfo) {
1977  return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
1978  (!IsCPUSupports && TInfo->supportsCpuIs()));
1979  };
1980  if (!SupportsBI(&TI) && SupportsBI(AuxTI))
1981  TheTI = AuxTI;
1982 
1983  if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
1984  (IsCPUSupports && !TheTI->supportsCpuSupports()))
1985  return S.Diag(TheCall->getBeginLoc(),
1986  TI.getTriple().isOSAIX()
1987  ? diag::err_builtin_aix_os_unsupported
1988  : diag::err_builtin_target_unsupported)
1989  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
1990 
1991  Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
1992  // Check if the argument is a string literal.
1993  if (!isa<StringLiteral>(Arg))
1994  return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
1995  << Arg->getSourceRange();
1996 
1997  // Check the contents of the string.
1998  StringRef Feature = cast<StringLiteral>(Arg)->getString();
1999  if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2000  S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2001  << Arg->getSourceRange();
2002  return false;
2003  }
2004  if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2005  return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2006  << Arg->getSourceRange();
2007  return false;
2008 }
2009 
2010 /// Checks that __builtin_popcountg was called with a single argument, which is
2011 /// an unsigned integer.
2012 static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2013  if (S.checkArgCount(TheCall, 1))
2014  return true;
2015 
2016  ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2017  if (ArgRes.isInvalid())
2018  return true;
2019 
2020  Expr *Arg = ArgRes.get();
2021  TheCall->setArg(0, Arg);
2022 
2023  QualType ArgTy = Arg->getType();
2024 
2025  if (!ArgTy->isUnsignedIntegerType()) {
2026  S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2027  << 1 << /*unsigned integer ty*/ 7 << ArgTy;
2028  return true;
2029  }
2030  return false;
2031 }
2032 
2033 /// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2034 /// an unsigned integer, and an optional second argument, which is promoted to
2035 /// an 'int'.
2036 static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2037  if (S.checkArgCountRange(TheCall, 1, 2))
2038  return true;
2039 
2040  ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2041  if (Arg0Res.isInvalid())
2042  return true;
2043 
2044  Expr *Arg0 = Arg0Res.get();
2045  TheCall->setArg(0, Arg0);
2046 
2047  QualType Arg0Ty = Arg0->getType();
2048 
2049  if (!Arg0Ty->isUnsignedIntegerType()) {
2050  S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2051  << 1 << /*unsigned integer ty*/ 7 << Arg0Ty;
2052  return true;
2053  }
2054 
2055  if (TheCall->getNumArgs() > 1) {
2056  ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2057  if (Arg1Res.isInvalid())
2058  return true;
2059 
2060  Expr *Arg1 = Arg1Res.get();
2061  TheCall->setArg(1, Arg1);
2062 
2063  QualType Arg1Ty = Arg1->getType();
2064 
2065  if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2066  S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2067  << 2 << /*'int' ty*/ 8 << Arg1Ty;
2068  return true;
2069  }
2070  }
2071 
2072  return false;
2073 }
2074 
2075 ExprResult
2076 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2077  CallExpr *TheCall) {
2078  ExprResult TheCallResult(TheCall);
2079 
2080  // Find out if any arguments are required to be integer constant expressions.
2081  unsigned ICEArguments = 0;
2083  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2084  if (Error != ASTContext::GE_None)
2085  ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2086 
2087  // If any arguments are required to be ICE's, check and diagnose.
2088  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2089  // Skip arguments not required to be ICE's.
2090  if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2091 
2092  llvm::APSInt Result;
2093  // If we don't have enough arguments, continue so we can issue better
2094  // diagnostic in checkArgCount(...)
2095  if (ArgNo < TheCall->getNumArgs() &&
2096  BuiltinConstantArg(TheCall, ArgNo, Result))
2097  return true;
2098  ICEArguments &= ~(1 << ArgNo);
2099  }
2100 
2101  FPOptions FPO;
2102  switch (BuiltinID) {
2103  case Builtin::BI__builtin_cpu_supports:
2104  case Builtin::BI__builtin_cpu_is:
2105  if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2106  Context.getAuxTargetInfo(), BuiltinID))
2107  return ExprError();
2108  break;
2109  case Builtin::BI__builtin_cpu_init:
2110  if (!Context.getTargetInfo().supportsCpuInit()) {
2111  Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2112  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2113  return ExprError();
2114  }
2115  break;
2116  case Builtin::BI__builtin___CFStringMakeConstantString:
2117  // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2118  // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2120  *this, BuiltinID, TheCall,
2121  {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2122  return ExprError();
2123  assert(TheCall->getNumArgs() == 1 &&
2124  "Wrong # arguments to builtin CFStringMakeConstantString");
2125  if (ObjC().CheckObjCString(TheCall->getArg(0)))
2126  return ExprError();
2127  break;
2128  case Builtin::BI__builtin_ms_va_start:
2129  case Builtin::BI__builtin_stdarg_start:
2130  case Builtin::BI__builtin_va_start:
2131  if (BuiltinVAStart(BuiltinID, TheCall))
2132  return ExprError();
2133  break;
2134  case Builtin::BI__va_start: {
2135  switch (Context.getTargetInfo().getTriple().getArch()) {
2136  case llvm::Triple::aarch64:
2137  case llvm::Triple::arm:
2138  case llvm::Triple::thumb:
2139  if (BuiltinVAStartARMMicrosoft(TheCall))
2140  return ExprError();
2141  break;
2142  default:
2143  if (BuiltinVAStart(BuiltinID, TheCall))
2144  return ExprError();
2145  break;
2146  }
2147  break;
2148  }
2149 
2150  // The acquire, release, and no fence variants are ARM and AArch64 only.
2151  case Builtin::BI_interlockedbittestandset_acq:
2152  case Builtin::BI_interlockedbittestandset_rel:
2153  case Builtin::BI_interlockedbittestandset_nf:
2154  case Builtin::BI_interlockedbittestandreset_acq:
2155  case Builtin::BI_interlockedbittestandreset_rel:
2156  case Builtin::BI_interlockedbittestandreset_nf:
2158  *this, TheCall,
2159  {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2160  return ExprError();
2161  break;
2162 
2163  // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2164  case Builtin::BI_bittest64:
2165  case Builtin::BI_bittestandcomplement64:
2166  case Builtin::BI_bittestandreset64:
2167  case Builtin::BI_bittestandset64:
2168  case Builtin::BI_interlockedbittestandreset64:
2169  case Builtin::BI_interlockedbittestandset64:
2171  *this, TheCall,
2172  {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2173  llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2174  return ExprError();
2175  break;
2176 
2177  case Builtin::BI__builtin_set_flt_rounds:
2179  *this, TheCall,
2180  {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2181  llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2182  return ExprError();
2183  break;
2184 
2185  case Builtin::BI__builtin_isgreater:
2186  case Builtin::BI__builtin_isgreaterequal:
2187  case Builtin::BI__builtin_isless:
2188  case Builtin::BI__builtin_islessequal:
2189  case Builtin::BI__builtin_islessgreater:
2190  case Builtin::BI__builtin_isunordered:
2191  if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2192  return ExprError();
2193  break;
2194  case Builtin::BI__builtin_fpclassify:
2195  if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2196  return ExprError();
2197  break;
2198  case Builtin::BI__builtin_isfpclass:
2199  if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2200  return ExprError();
2201  break;
2202  case Builtin::BI__builtin_isfinite:
2203  case Builtin::BI__builtin_isinf:
2204  case Builtin::BI__builtin_isinf_sign:
2205  case Builtin::BI__builtin_isnan:
2206  case Builtin::BI__builtin_issignaling:
2207  case Builtin::BI__builtin_isnormal:
2208  case Builtin::BI__builtin_issubnormal:
2209  case Builtin::BI__builtin_iszero:
2210  case Builtin::BI__builtin_signbit:
2211  case Builtin::BI__builtin_signbitf:
2212  case Builtin::BI__builtin_signbitl:
2213  if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2214  return ExprError();
2215  break;
2216  case Builtin::BI__builtin_shufflevector:
2217  return BuiltinShuffleVector(TheCall);
2218  // TheCall will be freed by the smart pointer here, but that's fine, since
2219  // BuiltinShuffleVector guts it, but then doesn't release it.
2220  case Builtin::BI__builtin_prefetch:
2221  if (BuiltinPrefetch(TheCall))
2222  return ExprError();
2223  break;
2224  case Builtin::BI__builtin_alloca_with_align:
2225  case Builtin::BI__builtin_alloca_with_align_uninitialized:
2226  if (BuiltinAllocaWithAlign(TheCall))
2227  return ExprError();
2228  [[fallthrough]];
2229  case Builtin::BI__builtin_alloca:
2230  case Builtin::BI__builtin_alloca_uninitialized:
2231  Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2232  << TheCall->getDirectCallee();
2233  if (getLangOpts().OpenCL) {
2234  builtinAllocaAddrSpace(*this, TheCall);
2235  }
2236  break;
2237  case Builtin::BI__arithmetic_fence:
2238  if (BuiltinArithmeticFence(TheCall))
2239  return ExprError();
2240  break;
2241  case Builtin::BI__assume:
2242  case Builtin::BI__builtin_assume:
2243  if (BuiltinAssume(TheCall))
2244  return ExprError();
2245  break;
2246  case Builtin::BI__builtin_assume_aligned:
2247  if (BuiltinAssumeAligned(TheCall))
2248  return ExprError();
2249  break;
2250  case Builtin::BI__builtin_dynamic_object_size:
2251  case Builtin::BI__builtin_object_size:
2252  if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2253  return ExprError();
2254  break;
2255  case Builtin::BI__builtin_longjmp:
2256  if (BuiltinLongjmp(TheCall))
2257  return ExprError();
2258  break;
2259  case Builtin::BI__builtin_setjmp:
2260  if (BuiltinSetjmp(TheCall))
2261  return ExprError();
2262  break;
2263  case Builtin::BI__builtin_classify_type:
2264  if (checkArgCount(TheCall, 1))
2265  return true;
2266  TheCall->setType(Context.IntTy);
2267  break;
2268  case Builtin::BI__builtin_complex:
2269  if (BuiltinComplex(TheCall))
2270  return ExprError();
2271  break;
2272  case Builtin::BI__builtin_constant_p: {
2273  if (checkArgCount(TheCall, 1))
2274  return true;
2275  ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
2276  if (Arg.isInvalid()) return true;
2277  TheCall->setArg(0, Arg.get());
2278  TheCall->setType(Context.IntTy);
2279  break;
2280  }
2281  case Builtin::BI__builtin_launder:
2282  return BuiltinLaunder(*this, TheCall);
2283  case Builtin::BI__sync_fetch_and_add:
2284  case Builtin::BI__sync_fetch_and_add_1:
2285  case Builtin::BI__sync_fetch_and_add_2:
2286  case Builtin::BI__sync_fetch_and_add_4:
2287  case Builtin::BI__sync_fetch_and_add_8:
2288  case Builtin::BI__sync_fetch_and_add_16:
2289  case Builtin::BI__sync_fetch_and_sub:
2290  case Builtin::BI__sync_fetch_and_sub_1:
2291  case Builtin::BI__sync_fetch_and_sub_2:
2292  case Builtin::BI__sync_fetch_and_sub_4:
2293  case Builtin::BI__sync_fetch_and_sub_8:
2294  case Builtin::BI__sync_fetch_and_sub_16:
2295  case Builtin::BI__sync_fetch_and_or:
2296  case Builtin::BI__sync_fetch_and_or_1:
2297  case Builtin::BI__sync_fetch_and_or_2:
2298  case Builtin::BI__sync_fetch_and_or_4:
2299  case Builtin::BI__sync_fetch_and_or_8:
2300  case Builtin::BI__sync_fetch_and_or_16:
2301  case Builtin::BI__sync_fetch_and_and:
2302  case Builtin::BI__sync_fetch_and_and_1:
2303  case Builtin::BI__sync_fetch_and_and_2:
2304  case Builtin::BI__sync_fetch_and_and_4:
2305  case Builtin::BI__sync_fetch_and_and_8:
2306  case Builtin::BI__sync_fetch_and_and_16:
2307  case Builtin::BI__sync_fetch_and_xor:
2308  case Builtin::BI__sync_fetch_and_xor_1:
2309  case Builtin::BI__sync_fetch_and_xor_2:
2310  case Builtin::BI__sync_fetch_and_xor_4:
2311  case Builtin::BI__sync_fetch_and_xor_8:
2312  case Builtin::BI__sync_fetch_and_xor_16:
2313  case Builtin::BI__sync_fetch_and_nand:
2314  case Builtin::BI__sync_fetch_and_nand_1:
2315  case Builtin::BI__sync_fetch_and_nand_2:
2316  case Builtin::BI__sync_fetch_and_nand_4:
2317  case Builtin::BI__sync_fetch_and_nand_8:
2318  case Builtin::BI__sync_fetch_and_nand_16:
2319  case Builtin::BI__sync_add_and_fetch:
2320  case Builtin::BI__sync_add_and_fetch_1:
2321  case Builtin::BI__sync_add_and_fetch_2:
2322  case Builtin::BI__sync_add_and_fetch_4:
2323  case Builtin::BI__sync_add_and_fetch_8:
2324  case Builtin::BI__sync_add_and_fetch_16:
2325  case Builtin::BI__sync_sub_and_fetch:
2326  case Builtin::BI__sync_sub_and_fetch_1:
2327  case Builtin::BI__sync_sub_and_fetch_2:
2328  case Builtin::BI__sync_sub_and_fetch_4:
2329  case Builtin::BI__sync_sub_and_fetch_8:
2330  case Builtin::BI__sync_sub_and_fetch_16:
2331  case Builtin::BI__sync_and_and_fetch:
2332  case Builtin::BI__sync_and_and_fetch_1:
2333  case Builtin::BI__sync_and_and_fetch_2:
2334  case Builtin::BI__sync_and_and_fetch_4:
2335  case Builtin::BI__sync_and_and_fetch_8:
2336  case Builtin::BI__sync_and_and_fetch_16:
2337  case Builtin::BI__sync_or_and_fetch:
2338  case Builtin::BI__sync_or_and_fetch_1:
2339  case Builtin::BI__sync_or_and_fetch_2:
2340  case Builtin::BI__sync_or_and_fetch_4:
2341  case Builtin::BI__sync_or_and_fetch_8:
2342  case Builtin::BI__sync_or_and_fetch_16:
2343  case Builtin::BI__sync_xor_and_fetch:
2344  case Builtin::BI__sync_xor_and_fetch_1:
2345  case Builtin::BI__sync_xor_and_fetch_2:
2346  case Builtin::BI__sync_xor_and_fetch_4:
2347  case Builtin::BI__sync_xor_and_fetch_8:
2348  case Builtin::BI__sync_xor_and_fetch_16:
2349  case Builtin::BI__sync_nand_and_fetch:
2350  case Builtin::BI__sync_nand_and_fetch_1:
2351  case Builtin::BI__sync_nand_and_fetch_2:
2352  case Builtin::BI__sync_nand_and_fetch_4:
2353  case Builtin::BI__sync_nand_and_fetch_8:
2354  case Builtin::BI__sync_nand_and_fetch_16:
2355  case Builtin::BI__sync_val_compare_and_swap:
2356  case Builtin::BI__sync_val_compare_and_swap_1:
2357  case Builtin::BI__sync_val_compare_and_swap_2:
2358  case Builtin::BI__sync_val_compare_and_swap_4:
2359  case Builtin::BI__sync_val_compare_and_swap_8:
2360  case Builtin::BI__sync_val_compare_and_swap_16:
2361  case Builtin::BI__sync_bool_compare_and_swap:
2362  case Builtin::BI__sync_bool_compare_and_swap_1:
2363  case Builtin::BI__sync_bool_compare_and_swap_2:
2364  case Builtin::BI__sync_bool_compare_and_swap_4:
2365  case Builtin::BI__sync_bool_compare_and_swap_8:
2366  case Builtin::BI__sync_bool_compare_and_swap_16:
2367  case Builtin::BI__sync_lock_test_and_set:
2368  case Builtin::BI__sync_lock_test_and_set_1:
2369  case Builtin::BI__sync_lock_test_and_set_2:
2370  case Builtin::BI__sync_lock_test_and_set_4:
2371  case Builtin::BI__sync_lock_test_and_set_8:
2372  case Builtin::BI__sync_lock_test_and_set_16:
2373  case Builtin::BI__sync_lock_release:
2374  case Builtin::BI__sync_lock_release_1:
2375  case Builtin::BI__sync_lock_release_2:
2376  case Builtin::BI__sync_lock_release_4:
2377  case Builtin::BI__sync_lock_release_8:
2378  case Builtin::BI__sync_lock_release_16:
2379  case Builtin::BI__sync_swap:
2380  case Builtin::BI__sync_swap_1:
2381  case Builtin::BI__sync_swap_2:
2382  case Builtin::BI__sync_swap_4:
2383  case Builtin::BI__sync_swap_8:
2384  case Builtin::BI__sync_swap_16:
2385  return BuiltinAtomicOverloaded(TheCallResult);
2386  case Builtin::BI__sync_synchronize:
2387  Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2388  << TheCall->getCallee()->getSourceRange();
2389  break;
2390  case Builtin::BI__builtin_nontemporal_load:
2391  case Builtin::BI__builtin_nontemporal_store:
2392  return BuiltinNontemporalOverloaded(TheCallResult);
2393  case Builtin::BI__builtin_memcpy_inline: {
2394  clang::Expr *SizeOp = TheCall->getArg(2);
2395  // We warn about copying to or from `nullptr` pointers when `size` is
2396  // greater than 0. When `size` is value dependent we cannot evaluate its
2397  // value so we bail out.
2398  if (SizeOp->isValueDependent())
2399  break;
2400  if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2401  CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2402  CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2403  }
2404  break;
2405  }
2406  case Builtin::BI__builtin_memset_inline: {
2407  clang::Expr *SizeOp = TheCall->getArg(2);
2408  // We warn about filling to `nullptr` pointers when `size` is greater than
2409  // 0. When `size` is value dependent we cannot evaluate its value so we bail
2410  // out.
2411  if (SizeOp->isValueDependent())
2412  break;
2413  if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2414  CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2415  break;
2416  }
2417 #define BUILTIN(ID, TYPE, ATTRS)
2418 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2419  case Builtin::BI##ID: \
2420  return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2421 #include "clang/Basic/Builtins.inc"
2422  case Builtin::BI__annotation:
2423  if (BuiltinMSVCAnnotation(*this, TheCall))
2424  return ExprError();
2425  break;
2426  case Builtin::BI__builtin_annotation:
2427  if (BuiltinAnnotation(*this, TheCall))
2428  return ExprError();
2429  break;
2430  case Builtin::BI__builtin_addressof:
2431  if (BuiltinAddressof(*this, TheCall))
2432  return ExprError();
2433  break;
2434  case Builtin::BI__builtin_function_start:
2435  if (BuiltinFunctionStart(*this, TheCall))
2436  return ExprError();
2437  break;
2438  case Builtin::BI__builtin_is_aligned:
2439  case Builtin::BI__builtin_align_up:
2440  case Builtin::BI__builtin_align_down:
2441  if (BuiltinAlignment(*this, TheCall, BuiltinID))
2442  return ExprError();
2443  break;
2444  case Builtin::BI__builtin_add_overflow:
2445  case Builtin::BI__builtin_sub_overflow:
2446  case Builtin::BI__builtin_mul_overflow:
2447  if (BuiltinOverflow(*this, TheCall, BuiltinID))
2448  return ExprError();
2449  break;
2450  case Builtin::BI__builtin_operator_new:
2451  case Builtin::BI__builtin_operator_delete: {
2452  bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2453  ExprResult Res =
2454  BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2455  if (Res.isInvalid())
2456  CorrectDelayedTyposInExpr(TheCallResult.get());
2457  return Res;
2458  }
2459  case Builtin::BI__builtin_dump_struct:
2460  return BuiltinDumpStruct(*this, TheCall);
2461  case Builtin::BI__builtin_expect_with_probability: {
2462  // We first want to ensure we are called with 3 arguments
2463  if (checkArgCount(TheCall, 3))
2464  return ExprError();
2465  // then check probability is constant float in range [0.0, 1.0]
2466  const Expr *ProbArg = TheCall->getArg(2);
2468  Expr::EvalResult Eval;
2469  Eval.Diag = &Notes;
2470  if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2471  !Eval.Val.isFloat()) {
2472  Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2473  << ProbArg->getSourceRange();
2474  for (const PartialDiagnosticAt &PDiag : Notes)
2475  Diag(PDiag.first, PDiag.second);
2476  return ExprError();
2477  }
2478  llvm::APFloat Probability = Eval.Val.getFloat();
2479  bool LoseInfo = false;
2480  Probability.convert(llvm::APFloat::IEEEdouble(),
2481  llvm::RoundingMode::Dynamic, &LoseInfo);
2482  if (!(Probability >= llvm::APFloat(0.0) &&
2483  Probability <= llvm::APFloat(1.0))) {
2484  Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2485  << ProbArg->getSourceRange();
2486  return ExprError();
2487  }
2488  break;
2489  }
2490  case Builtin::BI__builtin_preserve_access_index:
2491  if (BuiltinPreserveAI(*this, TheCall))
2492  return ExprError();
2493  break;
2494  case Builtin::BI__builtin_call_with_static_chain:
2495  if (BuiltinCallWithStaticChain(*this, TheCall))
2496  return ExprError();
2497  break;
2498  case Builtin::BI__exception_code:
2499  case Builtin::BI_exception_code:
2500  if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2501  diag::err_seh___except_block))
2502  return ExprError();
2503  break;
2504  case Builtin::BI__exception_info:
2505  case Builtin::BI_exception_info:
2506  if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2507  diag::err_seh___except_filter))
2508  return ExprError();
2509  break;
2510  case Builtin::BI__GetExceptionInfo:
2511  if (checkArgCount(TheCall, 1))
2512  return ExprError();
2513 
2514  if (CheckCXXThrowOperand(
2515  TheCall->getBeginLoc(),
2516  Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2517  TheCall))
2518  return ExprError();
2519 
2520  TheCall->setType(Context.VoidPtrTy);
2521  break;
2522  case Builtin::BIaddressof:
2523  case Builtin::BI__addressof:
2524  case Builtin::BIforward:
2525  case Builtin::BIforward_like:
2526  case Builtin::BImove:
2527  case Builtin::BImove_if_noexcept:
2528  case Builtin::BIas_const: {
2529  // These are all expected to be of the form
2530  // T &/&&/* f(U &/&&)
2531  // where T and U only differ in qualification.
2532  if (checkArgCount(TheCall, 1))
2533  return ExprError();
2534  QualType Param = FDecl->getParamDecl(0)->getType();
2535  QualType Result = FDecl->getReturnType();
2536  bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2537  BuiltinID == Builtin::BI__addressof;
2538  if (!(Param->isReferenceType() &&
2539  (ReturnsPointer ? Result->isAnyPointerType()
2540  : Result->isReferenceType()) &&
2541  Context.hasSameUnqualifiedType(Param->getPointeeType(),
2542  Result->getPointeeType()))) {
2543  Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2544  << FDecl;
2545  return ExprError();
2546  }
2547  break;
2548  }
2549  case Builtin::BI__builtin_ptrauth_strip:
2550  return PointerAuthStrip(*this, TheCall);
2551  case Builtin::BI__builtin_ptrauth_blend_discriminator:
2552  return PointerAuthBlendDiscriminator(*this, TheCall);
2553  case Builtin::BI__builtin_ptrauth_sign_constant:
2554  return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
2555  /*RequireConstant=*/true);
2556  case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
2557  return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
2558  /*RequireConstant=*/false);
2559  case Builtin::BI__builtin_ptrauth_auth:
2560  return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
2561  /*RequireConstant=*/false);
2562  case Builtin::BI__builtin_ptrauth_sign_generic_data:
2563  return PointerAuthSignGenericData(*this, TheCall);
2564  case Builtin::BI__builtin_ptrauth_auth_and_resign:
2565  return PointerAuthAuthAndResign(*this, TheCall);
2566  case Builtin::BI__builtin_ptrauth_string_discriminator:
2567  return PointerAuthStringDiscriminator(*this, TheCall);
2568  // OpenCL v2.0, s6.13.16 - Pipe functions
2569  case Builtin::BIread_pipe:
2570  case Builtin::BIwrite_pipe:
2571  // Since those two functions are declared with var args, we need a semantic
2572  // check for the argument.
2573  if (OpenCL().checkBuiltinRWPipe(TheCall))
2574  return ExprError();
2575  break;
2576  case Builtin::BIreserve_read_pipe:
2577  case Builtin::BIreserve_write_pipe:
2578  case Builtin::BIwork_group_reserve_read_pipe:
2579  case Builtin::BIwork_group_reserve_write_pipe:
2580  if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
2581  return ExprError();
2582  break;
2583  case Builtin::BIsub_group_reserve_read_pipe:
2584  case Builtin::BIsub_group_reserve_write_pipe:
2585  if (OpenCL().checkSubgroupExt(TheCall) ||
2586  OpenCL().checkBuiltinReserveRWPipe(TheCall))
2587  return ExprError();
2588  break;
2589  case Builtin::BIcommit_read_pipe:
2590  case Builtin::BIcommit_write_pipe:
2591  case Builtin::BIwork_group_commit_read_pipe:
2592  case Builtin::BIwork_group_commit_write_pipe:
2593  if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
2594  return ExprError();
2595  break;
2596  case Builtin::BIsub_group_commit_read_pipe:
2597  case Builtin::BIsub_group_commit_write_pipe:
2598  if (OpenCL().checkSubgroupExt(TheCall) ||
2599  OpenCL().checkBuiltinCommitRWPipe(TheCall))
2600  return ExprError();
2601  break;
2602  case Builtin::BIget_pipe_num_packets:
2603  case Builtin::BIget_pipe_max_packets:
2604  if (OpenCL().checkBuiltinPipePackets(TheCall))
2605  return ExprError();
2606  break;
2607  case Builtin::BIto_global:
2608  case Builtin::BIto_local:
2609  case Builtin::BIto_private:
2610  if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
2611  return ExprError();
2612  break;
2613  // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2614  case Builtin::BIenqueue_kernel:
2615  if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
2616  return ExprError();
2617  break;
2618  case Builtin::BIget_kernel_work_group_size:
2619  case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2620  if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
2621  return ExprError();
2622  break;
2623  case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2624  case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2625  if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
2626  return ExprError();
2627  break;
2628  case Builtin::BI__builtin_os_log_format:
2629  Cleanup.setExprNeedsCleanups(true);
2630  [[fallthrough]];
2631  case Builtin::BI__builtin_os_log_format_buffer_size:
2632  if (BuiltinOSLogFormat(TheCall))
2633  return ExprError();
2634  break;
2635  case Builtin::BI__builtin_intel_fpga_reg:
2636  if (!Context.getLangOpts().SYCLIsDevice) {
2637  Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_language)
2638  << "__builtin_intel_fpga_reg"
2639  << "SYCL device";
2640  return ExprError();
2641  }
2642  if (CheckIntelFPGARegBuiltinFunctionCall(BuiltinID, TheCall))
2643  return ExprError();
2644  break;
2645  case Builtin::BI__builtin_intel_sycl_ptr_annotation:
2646  if (!Context.getLangOpts().SYCLIsDevice) {
2647  Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_language)
2648  << "__builtin_intel_sycl_ptr_annotation"
2649  << "SYCL device";
2650  return ExprError();
2651  }
2652  if (CheckIntelSYCLPtrAnnotationBuiltinFunctionCall(BuiltinID, TheCall))
2653  return ExprError();
2654  break;
2655  case Builtin::BI__builtin_intel_sycl_alloca:
2656  case Builtin::BI__builtin_intel_sycl_alloca_with_align:
2657  if (!Context.getLangOpts().SYCLIsDevice) {
2658  Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_language)
2659  << (BuiltinID == Builtin::BI__builtin_intel_sycl_alloca
2660  ? "__builtin_intel_sycl_alloca"
2661  : "__builtin_intel_sycl_alloca_with_align")
2662  << "SYCL device";
2663  return ExprError();
2664  }
2665  if (getASTContext().getTargetInfo().getTriple().isSPIRAOT()) {
2666  Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported);
2667  Diag(TheCall->getBeginLoc(), diag::note_intel_sycl_alloca_aot)
2668  << (BuiltinID == Builtin::BI__builtin_intel_sycl_alloca_with_align);
2669  return ExprError();
2670  }
2671  if (CheckIntelSYCLAllocaBuiltinFunctionCall(BuiltinID, TheCall))
2672  return ExprError();
2673  break;
2674  case Builtin::BI__builtin_intel_fpga_mem:
2675  if (!Context.getLangOpts().SYCLIsDevice) {
2676  Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_language)
2677  << "__builtin_intel_fpga_mem"
2678  << "SYCL device";
2679  return ExprError();
2680  }
2681  if (CheckIntelFPGAMemBuiltinFunctionCall(TheCall))
2682  return ExprError();
2683  break;
2684  case Builtin::BI__builtin_frame_address:
2685  case Builtin::BI__builtin_return_address: {
2686  if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2687  return ExprError();
2688 
2689  // -Wframe-address warning if non-zero passed to builtin
2690  // return/frame address.
2691  Expr::EvalResult Result;
2692  if (!TheCall->getArg(0)->isValueDependent() &&
2693  TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2694  Result.Val.getInt() != 0)
2695  Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2696  << ((BuiltinID == Builtin::BI__builtin_return_address)
2697  ? "__builtin_return_address"
2698  : "__builtin_frame_address")
2699  << TheCall->getSourceRange();
2700  break;
2701  }
2702 
2703  case Builtin::BI__builtin_nondeterministic_value: {
2704  if (BuiltinNonDeterministicValue(TheCall))
2705  return ExprError();
2706  break;
2707  }
2708 
2709  // __builtin_elementwise_abs restricts the element type to signed integers or
2710  // floating point types only.
2711  case Builtin::BI__builtin_elementwise_abs: {
2712  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2713  return ExprError();
2714 
2715  QualType ArgTy = TheCall->getArg(0)->getType();
2716  QualType EltTy = ArgTy;
2717 
2718  if (auto *VecTy = EltTy->getAs<VectorType>())
2719  EltTy = VecTy->getElementType();
2720  if (EltTy->isUnsignedIntegerType()) {
2721  Diag(TheCall->getArg(0)->getBeginLoc(),
2722  diag::err_builtin_invalid_arg_type)
2723  << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2724  return ExprError();
2725  }
2726  break;
2727  }
2728 
2729  // These builtins restrict the element type to floating point
2730  // types only.
2731  case Builtin::BI__builtin_elementwise_acos:
2732  case Builtin::BI__builtin_elementwise_asin:
2733  case Builtin::BI__builtin_elementwise_atan:
2734  case Builtin::BI__builtin_elementwise_ceil:
2735  case Builtin::BI__builtin_elementwise_cos:
2736  case Builtin::BI__builtin_elementwise_cosh:
2737  case Builtin::BI__builtin_elementwise_exp:
2738  case Builtin::BI__builtin_elementwise_exp2:
2739  case Builtin::BI__builtin_elementwise_floor:
2740  case Builtin::BI__builtin_elementwise_log:
2741  case Builtin::BI__builtin_elementwise_log2:
2742  case Builtin::BI__builtin_elementwise_log10:
2743  case Builtin::BI__builtin_elementwise_roundeven:
2744  case Builtin::BI__builtin_elementwise_round:
2745  case Builtin::BI__builtin_elementwise_rint:
2746  case Builtin::BI__builtin_elementwise_nearbyint:
2747  case Builtin::BI__builtin_elementwise_sin:
2748  case Builtin::BI__builtin_elementwise_sinh:
2749  case Builtin::BI__builtin_elementwise_sqrt:
2750  case Builtin::BI__builtin_elementwise_tan:
2751  case Builtin::BI__builtin_elementwise_tanh:
2752  case Builtin::BI__builtin_elementwise_trunc:
2753  case Builtin::BI__builtin_elementwise_canonicalize: {
2754  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2755  return ExprError();
2756 
2757  QualType ArgTy = TheCall->getArg(0)->getType();
2758  if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2759  ArgTy, 1))
2760  return ExprError();
2761  break;
2762  }
2763  case Builtin::BI__builtin_elementwise_fma: {
2764  if (BuiltinElementwiseTernaryMath(TheCall))
2765  return ExprError();
2766  break;
2767  }
2768 
2769  // These builtins restrict the element type to floating point
2770  // types only, and take in two arguments.
2771  case Builtin::BI__builtin_elementwise_pow: {
2772  if (BuiltinElementwiseMath(TheCall))
2773  return ExprError();
2774 
2775  QualType ArgTy = TheCall->getArg(0)->getType();
2776  if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2777  ArgTy, 1) ||
2778  checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
2779  ArgTy, 2))
2780  return ExprError();
2781  break;
2782  }
2783 
2784  // These builtins restrict the element type to integer
2785  // types only.
2786  case Builtin::BI__builtin_elementwise_add_sat:
2787  case Builtin::BI__builtin_elementwise_sub_sat: {
2788  if (BuiltinElementwiseMath(TheCall))
2789  return ExprError();
2790 
2791  const Expr *Arg = TheCall->getArg(0);
2792  QualType ArgTy = Arg->getType();
2793  QualType EltTy = ArgTy;
2794 
2795  if (auto *VecTy = EltTy->getAs<VectorType>())
2796  EltTy = VecTy->getElementType();
2797 
2798  if (!EltTy->isIntegerType()) {
2799  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2800  << 1 << /* integer ty */ 6 << ArgTy;
2801  return ExprError();
2802  }
2803  break;
2804  }
2805 
2806  case Builtin::BI__builtin_elementwise_min:
2807  case Builtin::BI__builtin_elementwise_max:
2808  if (BuiltinElementwiseMath(TheCall))
2809  return ExprError();
2810  break;
2811 
2812  case Builtin::BI__builtin_elementwise_bitreverse: {
2813  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2814  return ExprError();
2815 
2816  const Expr *Arg = TheCall->getArg(0);
2817  QualType ArgTy = Arg->getType();
2818  QualType EltTy = ArgTy;
2819 
2820  if (auto *VecTy = EltTy->getAs<VectorType>())
2821  EltTy = VecTy->getElementType();
2822 
2823  if (!EltTy->isIntegerType()) {
2824  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2825  << 1 << /* integer ty */ 6 << ArgTy;
2826  return ExprError();
2827  }
2828  break;
2829  }
2830 
2831  case Builtin::BI__builtin_elementwise_copysign: {
2832  if (checkArgCount(TheCall, 2))
2833  return ExprError();
2834 
2835  ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
2836  ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
2837  if (Magnitude.isInvalid() || Sign.isInvalid())
2838  return ExprError();
2839 
2840  QualType MagnitudeTy = Magnitude.get()->getType();
2841  QualType SignTy = Sign.get()->getType();
2842  if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2843  MagnitudeTy, 1) ||
2844  checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
2845  SignTy, 2)) {
2846  return ExprError();
2847  }
2848 
2849  if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
2850  return Diag(Sign.get()->getBeginLoc(),
2851  diag::err_typecheck_call_different_arg_types)
2852  << MagnitudeTy << SignTy;
2853  }
2854 
2855  TheCall->setArg(0, Magnitude.get());
2856  TheCall->setArg(1, Sign.get());
2857  TheCall->setType(Magnitude.get()->getType());
2858  break;
2859  }
2860  case Builtin::BI__builtin_reduce_max:
2861  case Builtin::BI__builtin_reduce_min: {
2862  if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2863  return ExprError();
2864 
2865  const Expr *Arg = TheCall->getArg(0);
2866  const auto *TyA = Arg->getType()->getAs<VectorType>();
2867 
2868  QualType ElTy;
2869  if (TyA)
2870  ElTy = TyA->getElementType();
2871  else if (Arg->getType()->isSizelessVectorType())
2872  ElTy = Arg->getType()->getSizelessVectorEltType(Context);
2873 
2874  if (ElTy.isNull()) {
2875  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2876  << 1 << /* vector ty*/ 4 << Arg->getType();
2877  return ExprError();
2878  }
2879 
2880  TheCall->setType(ElTy);
2881  break;
2882  }
2883 
2884  // These builtins support vectors of integers only.
2885  // TODO: ADD/MUL should support floating-point types.
2886  case Builtin::BI__builtin_reduce_add:
2887  case Builtin::BI__builtin_reduce_mul:
2888  case Builtin::BI__builtin_reduce_xor:
2889  case Builtin::BI__builtin_reduce_or:
2890  case Builtin::BI__builtin_reduce_and: {
2891  if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2892  return ExprError();
2893 
2894  const Expr *Arg = TheCall->getArg(0);
2895  const auto *TyA = Arg->getType()->getAs<VectorType>();
2896 
2897  QualType ElTy;
2898  if (TyA)
2899  ElTy = TyA->getElementType();
2900  else if (Arg->getType()->isSizelessVectorType())
2901  ElTy = Arg->getType()->getSizelessVectorEltType(Context);
2902 
2903  if (ElTy.isNull() || !ElTy->isIntegerType()) {
2904  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2905  << 1 << /* vector of integers */ 6 << Arg->getType();
2906  return ExprError();
2907  }
2908 
2909  TheCall->setType(ElTy);
2910  break;
2911  }
2912 
2913  case Builtin::BI__builtin_matrix_transpose:
2914  return BuiltinMatrixTranspose(TheCall, TheCallResult);
2915 
2916  case Builtin::BI__builtin_matrix_column_major_load:
2917  return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2918 
2919  case Builtin::BI__builtin_matrix_column_major_store:
2920  return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2921 
2922  case Builtin::BI__builtin_verbose_trap:
2923  if (!checkBuiltinVerboseTrap(TheCall, *this))
2924  return ExprError();
2925  break;
2926 
2927  case Builtin::BI__builtin_get_device_side_mangled_name: {
2928  auto Check = [](CallExpr *TheCall) {
2929  if (TheCall->getNumArgs() != 1)
2930  return false;
2931  auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2932  if (!DRE)
2933  return false;
2934  auto *D = DRE->getDecl();
2935  if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2936  return false;
2937  return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2938  D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2939  };
2940  if (!Check(TheCall)) {
2941  Diag(TheCall->getBeginLoc(),
2942  diag::err_hip_invalid_args_builtin_mangled_name);
2943  return ExprError();
2944  }
2945  break;
2946  }
2947  case Builtin::BI__builtin_popcountg:
2948  if (BuiltinPopcountg(*this, TheCall))
2949  return ExprError();
2950  break;
2951  case Builtin::BI__builtin_clzg:
2952  case Builtin::BI__builtin_ctzg:
2953  if (BuiltinCountZeroBitsGeneric(*this, TheCall))
2954  return ExprError();
2955  break;
2956 
2957  case Builtin::BI__builtin_allow_runtime_check: {
2958  Expr *Arg = TheCall->getArg(0);
2959  // Check if the argument is a string literal.
2960  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {
2961  Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2962  << Arg->getSourceRange();
2963  return ExprError();
2964  }
2965  break;
2966  }
2967  }
2968 
2969  if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
2970  return ExprError();
2971 
2972  // Since the target specific builtins for each arch overlap, only check those
2973  // of the arch we are compiling for.
2974  if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2975  if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2976  assert(Context.getAuxTargetInfo() &&
2977  "Aux Target Builtin, but not an aux target?");
2978 
2979  if (CheckTSBuiltinFunctionCall(
2980  *Context.getAuxTargetInfo(),
2981  Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2982  return ExprError();
2983 
2984  // Detect when host builtins are used in device code only
2985  if (getLangOpts().SYCLIsDevice)
2986  SYCL().DiagIfDeviceCode(TheCall->getBeginLoc(),
2987  diag::err_builtin_target_unsupported);
2988  } else {
2989  if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2990  TheCall))
2991  return ExprError();
2992  }
2993  }
2994 
2995  return TheCallResult;
2996 }
2997 
2998 bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
2999  llvm::APSInt Result;
3000  // We can't check the value of a dependent argument.
3001  Expr *Arg = TheCall->getArg(ArgNum);
3002  if (Arg->isTypeDependent() || Arg->isValueDependent())
3003  return false;
3004 
3005  // Check constant-ness first.
3006  if (BuiltinConstantArg(TheCall, ArgNum, Result))
3007  return true;
3008 
3009  // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3010  if (Result.isShiftedMask() || (~Result).isShiftedMask())
3011  return false;
3012 
3013  return Diag(TheCall->getBeginLoc(),
3014  diag::err_argument_not_contiguous_bit_field)
3015  << ArgNum << Arg->getSourceRange();
3016 }
3017 
3018 static bool checkIntelFPGARegArgument(Sema &S, QualType ArgType,
3019  SourceLocation &Loc) {
3020  if (ArgType.getTypePtr()->isArrayType())
3021  return true;
3022 
3023  // Non-POD classes are allowed. Each field is checked for illegal type.
3024  if (CXXRecordDecl *Record = ArgType->getAsCXXRecordDecl()) {
3025  for (auto *FD : Record->fields()) {
3026  QualType T = FD->getType();
3027  Loc = FD->getLocation();
3028  if (const ArrayType *AT = T->getAsArrayTypeUnsafe())
3029  T = AT->getElementType();
3030  if (checkIntelFPGARegArgument(S, T, Loc))
3031  return true;
3032  }
3033  return false;
3034  }
3035 
3036  QualType CTy = ArgType.getCanonicalType();
3037 
3038  if (CTy->isFunctionPointerType() || CTy->isImageType() ||
3039  CTy->isEventT() || CTy->isSamplerT() || CTy->isPipeType())
3040  return true;
3041 
3042  // Check to filter out unintended types. Records are handled above.
3043  if (!CTy.isCXX98PODType(S.Context))
3044  return true;
3045 
3046  return false;
3047 }
3048 
3049 bool Sema::CheckIntelFPGARegBuiltinFunctionCall(unsigned BuiltinID,
3050  CallExpr *TheCall) {
3051  switch (BuiltinID) {
3052  case Builtin::BI__builtin_intel_fpga_reg: {
3053  if (checkArgCount(TheCall, 1))
3054  return true;
3055 
3056  Expr *Arg = TheCall->getArg(0);
3057  QualType ArgType = Arg->getType();
3059 
3060  if (checkIntelFPGARegArgument(*this, ArgType, Loc)) {
3061  Diag(TheCall->getBeginLoc(), diag::err_intel_fpga_reg_limitations)
3062  << (ArgType.getTypePtr()->isRecordType() ? 1 : 0) << ArgType
3063  << TheCall->getSourceRange();
3064  if (ArgType.getTypePtr()->isRecordType())
3065  Diag(Loc, diag::illegal_type_declared_here);
3066  return true;
3067  }
3068 
3069  TheCall->setType(ArgType);
3070 
3071  return false;
3072  }
3073  default:
3074  return true;
3075  }
3076 }
3077 
3078 bool Sema::CheckIntelFPGAMemBuiltinFunctionCall(CallExpr *TheCall) {
3079  const unsigned MinNumArgs = 3;
3080  const unsigned MaxNumArgs = 7;
3081  unsigned NumArgs = TheCall->getNumArgs();
3082 
3083  // Make sure we have the minimum number of provided arguments.
3084  if (checkArgCountAtLeast(TheCall, MinNumArgs))
3085  return true;
3086 
3087  // Make sure we don't have too many arguments.
3088  if (checkArgCountAtMost(TheCall, MaxNumArgs))
3089  return true;
3090 
3091  Expr *PointerArg = TheCall->getArg(0);
3092  QualType PointerArgType = PointerArg->getType();
3093 
3094  // Make sure that the first argument is a pointer
3095  if (!isa<PointerType>(PointerArgType))
3096  return Diag(PointerArg->getBeginLoc(),
3097  diag::err_intel_fpga_mem_arg_mismatch)
3098  << 0;
3099 
3100  // Make sure that the pointer points to a legal type
3101  // We use the same argument checks used for __builtin_intel_fpga_reg
3102  QualType PointeeType = PointerArgType->getPointeeType();
3104  if (checkIntelFPGARegArgument(*this, PointeeType, Loc)) {
3105  Diag(TheCall->getBeginLoc(), diag::err_intel_fpga_mem_limitations)
3106  << (PointeeType->isRecordType() ? 1 : 0) << PointerArgType
3107  << TheCall->getSourceRange();
3108  if (PointeeType->isRecordType())
3109  Diag(Loc, diag::illegal_type_declared_here);
3110  return true;
3111  }
3112 
3113  // Second argument must be a constant integer
3114  llvm::APSInt Result;
3115  if (BuiltinConstantArg(TheCall, 1, Result))
3116  return true;
3117 
3118  // Third argument (CacheSize) must be a non-negative constant integer
3119  if (BuiltinConstantArg(TheCall, 2, Result))
3120  return true;
3121  if (Result < 0)
3122  return Diag(TheCall->getArg(2)->getBeginLoc(),
3123  diag::err_intel_fpga_mem_arg_mismatch) << 1;
3124 
3125  // The last four optional arguments must be signed constant integers.
3126  for (unsigned I = MinNumArgs; I != NumArgs; ++I) {
3127  if (BuiltinConstantArg(TheCall, I, Result))
3128  return true;
3129  }
3130 
3131  // Set the return type to be the same as the type of the first argument
3132  // (pointer argument)
3133  TheCall->setType(PointerArgType);
3134  return false;
3135 }
3136 
3137 bool Sema::CheckIntelSYCLPtrAnnotationBuiltinFunctionCall(unsigned BuiltinID,
3138  CallExpr *TheCall) {
3139  unsigned NumArgs = TheCall->getNumArgs();
3140  // Make sure we have the minimum number of provided arguments.
3141  if (checkArgCountAtLeast(TheCall, 1)) {
3142  return true;
3143  }
3144 
3145  // Make sure we have odd number of arguments.
3146  if (!(NumArgs & 0x1)) {
3147  return Diag(TheCall->getEndLoc(),
3148  diag::err_intel_sycl_ptr_annotation_arg_number_mismatch);
3149  }
3150 
3151  // First argument should be a pointer.
3152  Expr *PointerArg = TheCall->getArg(0);
3153  QualType PointerArgType = PointerArg->getType();
3154 
3155  if (!isa<PointerType>(PointerArgType))
3156  return Diag(PointerArg->getBeginLoc(),
3157  diag::err_intel_sycl_ptr_annotation_mismatch)
3158  << 0;
3159 
3160  // Following arguments are paired in format ("String", integer).
3161  unsigned I = 1;
3162  for (; I <= NumArgs / 2; ++I) {
3163  // must be string Literal/const char*
3164  auto Arg = TheCall->getArg(I)->IgnoreParenImpCasts();
3165  Expr::EvalResult Result;
3166  if (!isa<StringLiteral>(Arg) &&
3167  !maybeConstEvalStringLiteral(this->Context, Arg)) {
3168  Diag(TheCall->getArg(I)->getBeginLoc(),
3169  diag::err_intel_sycl_ptr_annotation_mismatch)
3170  << 1;
3171  return true;
3172  }
3173  }
3174 
3175  llvm::APSInt Result;
3176  for (; I != NumArgs; ++I) {
3177  // must be integer
3178  if (BuiltinConstantArg(TheCall, I, Result))
3179  return true;
3180  }
3181 
3182  // Set the return type to be the same as the type of the first argument
3183  TheCall->setType(PointerArgType);
3184  return false;
3185 }
3186 
3188  const VarDecl *VD) {
3189  assert(VD && "Expecting valid declaration");
3190  APValue *SpecializationId = VD->evaluateValue();
3191  assert(SpecializationId && "Expecting a non-null SpecializationId");
3192  assert(SpecializationId->getKind() == APValue::ValueKind::Struct &&
3193  "Expecting SpecializationId to be of kind Struct");
3194  assert(SpecializationId->getStructNumFields() == 1 &&
3195  "Expecting SpecializationId to have a single field for the default "
3196  "value");
3197  APValue Default = SpecializationId->getStructField(0);
3198  assert(Default.isInt() && "Expecting the default value to be an integer");
3199  return Default.getInt();
3200 }
3201 
3202 bool Sema::CheckIntelSYCLAllocaBuiltinFunctionCall(unsigned BuiltinID,
3203  CallExpr *Call) {
3204  assert(getLangOpts().SYCLIsDevice &&
3205  "Builtin can only be used in SYCL device code");
3206 
3207  assert((BuiltinID == Builtin::BI__builtin_intel_sycl_alloca ||
3208  BuiltinID == Builtin::BI__builtin_intel_sycl_alloca_with_align) &&
3209  "Unexpected builtin");
3210 
3211  bool IsAlignedAlloca =
3212  BuiltinID == Builtin::BI__builtin_intel_sycl_alloca_with_align;
3213 
3214  constexpr unsigned InvalidIndex = -1;
3215  constexpr unsigned ElementTypeIndex = 0;
3216  const unsigned AlignmentIndex = IsAlignedAlloca ? 1 : InvalidIndex;
3217  const unsigned SpecNameIndex = IsAlignedAlloca ? 2 : 1;
3218 
3219  SourceLocation Loc = Call->getBeginLoc();
3220 
3221  // This builtin cannot be called directly. As it needs to pass template
3222  // arguments, this is always an alias.
3223  const FunctionDecl *FD = Call->getDirectCallee();
3224  assert(FD && "Builtin cannot be called from a function pointer");
3225  if (!FD->hasAttr<BuiltinAliasAttr>()) {
3226  Diag(Loc, diag::err_intel_sycl_alloca_no_alias) << IsAlignedAlloca;
3227  return true;
3228  }
3229 
3230  // Check a single argument is passed
3231  if (checkArgCount(Call, 1))
3232  return true;
3233 
3234  // Check three template arguments are passed
3235  unsigned DesiredTemplateArgumentsCount = IsAlignedAlloca ? 4 : 3;
3237  if (!CST || CST->size() != DesiredTemplateArgumentsCount) {
3238  Diag(Loc, diag::err_intel_sycl_alloca_wrong_template_arg_count)
3239  << IsAlignedAlloca << (CST ? CST->size() : 0);
3240  return true;
3241  }
3242 
3243  // Check the single argument is of type `sycl::kernel_handler &`
3244  constexpr auto CheckArg = [](QualType Ty) {
3245  if (!Ty->isLValueReferenceType())
3246  return true;
3247  Ty = Ty->getPointeeType();
3248  return !(Ty.getQualifiers().empty() &&
3249  SemaSYCL::isSyclType(Ty, SYCLTypeAttr::kernel_handler));
3250  };
3251  if (CheckArg(FD->getParamDecl(0)->getType())) {
3252  Diag(Loc, diag::err_intel_sycl_alloca_wrong_arg)
3253  << IsAlignedAlloca << FD->getParamDecl(0)->getType();
3254  return true;
3255  }
3256 
3257  // Check the return type is `sycl::multi_ptr<ET,
3258  // sycl::access::address_space::private_space, DecoratedAddress>`:
3259  // - `ET`: cv-unqualified trivial type
3260  constexpr auto CheckType = [](QualType RT, const ASTContext &Ctx) {
3261  if (!SemaSYCL::isSyclType(RT, SYCLTypeAttr::multi_ptr))
3262  return true;
3263  // Check element type
3264  const TemplateArgumentList &TAL =
3265  cast<ClassTemplateSpecializationDecl>(RT->getAsRecordDecl())
3266  ->getTemplateArgs();
3267  QualType ET = TAL.get(0).getAsType();
3268  if (ET.isConstQualified() || ET.isVolatileQualified() ||
3269  !ET.isTrivialType(Ctx))
3270  return true;
3271  constexpr uint64_t PrivateAS = 0;
3272  return TAL.get(1).getAsIntegral() != PrivateAS;
3273  };
3274  if (CheckType(FD->getReturnType(), getASTContext())) {
3275  Diag(Loc, diag::err_intel_sycl_alloca_wrong_type)
3276  << IsAlignedAlloca << FD->getReturnType();
3277  return true;
3278  }
3279 
3280  // Check size is passed as a specialization constant
3281  const auto CheckSize = [this, IsAlignedAlloca, SpecNameIndex](
3282  const ASTContext &Ctx, SourceLocation Loc,
3283  const TemplateArgumentList *CST) {
3284  TemplateArgument TA = CST->get(SpecNameIndex);
3286  if (Ty.isNull() || !Ty->isReferenceType())
3287  return true;
3288  Ty = Ty->getPointeeType();
3289  if (!SemaSYCL::isSyclType(Ty, SYCLTypeAttr::specialization_id))
3290  return true;
3291  const TemplateArgumentList &TAL =
3292  cast<ClassTemplateSpecializationDecl>(Ty->getAsCXXRecordDecl())
3293  ->getTemplateArgs();
3294  if (!TAL.get(0).getAsType()->isIntegralType(Ctx))
3295  return true;
3296  llvm::APSInt DefaultSize =
3297  getSYCLAllocaDefaultSize(Ctx, cast<VarDecl>(TA.getAsDecl()));
3298  if (DefaultSize < 1)
3299  Diag(Loc, diag::warn_intel_sycl_alloca_bad_default_value)
3300  << IsAlignedAlloca << DefaultSize.getSExtValue();
3301  return false;
3302  };
3303  if (CheckSize(getASTContext(), Loc, CST)) {
3304  TemplateArgument TA = CST->get(SpecNameIndex);
3306  const SemaDiagnosticBuilder &D =
3307  Diag(Loc, diag::err_intel_sycl_alloca_wrong_size);
3308  D << IsAlignedAlloca;
3309  if (Ty.isNull())
3310  D << TA;
3311  else
3312  D << Ty;
3313  return true;
3314  }
3315 
3316  if (IsAlignedAlloca) {
3317  TemplateArgument AlignmentArg = CST->get(AlignmentIndex);
3318  llvm::APSInt RequestedAlign = AlignmentArg.getAsIntegral();
3319  if (!RequestedAlign.isPowerOf2())
3320  return Diag(Loc, diag::err_alignment_not_power_of_two);
3321  constexpr int32_t MaxAllowedAlign = std::numeric_limits<int32_t>::max() / 8;
3322  if (RequestedAlign > MaxAllowedAlign)
3323  return Diag(Loc, diag::err_alignment_too_big) << MaxAllowedAlign;
3324  QualType AllocaType = CST->get(ElementTypeIndex).getAsType();
3325  int64_t AllocaRequiredAlignment =
3326  Context.getTypeAlignInChars(AllocaType).getQuantity();
3327  if (RequestedAlign < AllocaRequiredAlignment)
3328  return Diag(Loc, diag::err_alignas_underaligned)
3329  << AllocaType << AllocaRequiredAlignment;
3330  }
3331 
3332  return false;
3333 }
3334 
3335 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3336  bool IsVariadic, FormatStringInfo *FSI) {
3337  if (Format->getFirstArg() == 0)
3338  FSI->ArgPassingKind = FAPK_VAList;
3339  else if (IsVariadic)
3340  FSI->ArgPassingKind = FAPK_Variadic;
3341  else
3342  FSI->ArgPassingKind = FAPK_Fixed;
3343  FSI->FormatIdx = Format->getFormatIdx() - 1;
3344  FSI->FirstDataArg =
3345  FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
3346 
3347  // The way the format attribute works in GCC, the implicit this argument
3348  // of member functions is counted. However, it doesn't appear in our own
3349  // lists, so decrement format_idx in that case.
3350  if (IsCXXMember) {
3351  if(FSI->FormatIdx == 0)
3352  return false;
3353  --FSI->FormatIdx;
3354  if (FSI->FirstDataArg != 0)
3355  --FSI->FirstDataArg;
3356  }
3357  return true;
3358 }
3359 
3360 /// Checks if a the given expression evaluates to null.
3361 ///
3362 /// Returns true if the value evaluates to null.
3363 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3364  // Treat (smart) pointers constructed from nullptr as null, whether we can
3365  // const-evaluate them or not.
3366  // This must happen first: the smart pointer expr might have _Nonnull type!
3367  if (isa<CXXNullPtrLiteralExpr>(
3370  return true;
3371 
3372  // If the expression has non-null type, it doesn't evaluate to null.
3373  if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3374  if (*nullability == NullabilityKind::NonNull)
3375  return false;
3376  }
3377 
3378  // As a special case, transparent unions initialized with zero are
3379  // considered null for the purposes of the nonnull attribute.
3380  if (const RecordType *UT = Expr->getType()->getAsUnionType();
3381  UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
3382  if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3383  if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3384  Expr = ILE->getInit(0);
3385  }
3386 
3387  bool Result;
3388  return (!Expr->isValueDependent() &&
3389  Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3390  !Result);
3391 }
3392 
3394  const Expr *ArgExpr,
3395  SourceLocation CallSiteLoc) {
3396  if (CheckNonNullExpr(S, ArgExpr))
3397  S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3398  S.PDiag(diag::warn_null_arg)
3399  << ArgExpr->getSourceRange());
3400 }
3401 
3402 /// Determine whether the given type has a non-null nullability annotation.
3404  if (auto nullability = type->getNullability())
3405  return *nullability == NullabilityKind::NonNull;
3406 
3407  return false;
3408 }
3409 
3411  const NamedDecl *FDecl,
3412  const FunctionProtoType *Proto,
3414  SourceLocation CallSiteLoc) {
3415  assert((FDecl || Proto) && "Need a function declaration or prototype");
3416 
3417  // Already checked by constant evaluator.
3419  return;
3420  // Check the attributes attached to the method/function itself.
3421  llvm::SmallBitVector NonNullArgs;
3422  if (FDecl) {
3423  // Handle the nonnull attribute on the function/method declaration itself.
3424  for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3425  if (!NonNull->args_size()) {
3426  // Easy case: all pointer arguments are nonnull.
3427  for (const auto *Arg : Args)
3428  if (S.isValidPointerAttrType(Arg->getType()))
3429  CheckNonNullArgument(S, Arg, CallSiteLoc);
3430  return;
3431  }
3432 
3433  for (const ParamIdx &Idx : NonNull->args()) {
3434  unsigned IdxAST = Idx.getASTIndex();
3435  if (IdxAST >= Args.size())
3436  continue;
3437  if (NonNullArgs.empty())
3438  NonNullArgs.resize(Args.size());
3439  NonNullArgs.set(IdxAST);
3440  }
3441  }
3442  }
3443 
3444  if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3445  // Handle the nonnull attribute on the parameters of the
3446  // function/method.
3447  ArrayRef<ParmVarDecl*> parms;
3448  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3449  parms = FD->parameters();
3450  else
3451  parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3452 
3453  unsigned ParamIndex = 0;
3454  for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3455  I != E; ++I, ++ParamIndex) {
3456  const ParmVarDecl *PVD = *I;
3457  if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3458  if (NonNullArgs.empty())
3459  NonNullArgs.resize(Args.size());
3460 
3461  NonNullArgs.set(ParamIndex);
3462  }
3463  }
3464  } else {
3465  // If we have a non-function, non-method declaration but no
3466  // function prototype, try to dig out the function prototype.
3467  if (!Proto) {
3468  if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3469  QualType type = VD->getType().getNonReferenceType();
3470  if (auto pointerType = type->getAs<PointerType>())
3471  type = pointerType->getPointeeType();
3472  else if (auto blockType = type->getAs<BlockPointerType>())
3473  type = blockType->getPointeeType();
3474  // FIXME: data member pointers?
3475 
3476  // Dig out the function prototype, if there is one.
3477  Proto = type->getAs<FunctionProtoType>();
3478  }
3479  }
3480 
3481  // Fill in non-null argument information from the nullability
3482  // information on the parameter types (if we have them).
3483  if (Proto) {
3484  unsigned Index = 0;
3485  for (auto paramType : Proto->getParamTypes()) {
3486  if (isNonNullType(paramType)) {
3487  if (NonNullArgs.empty())
3488  NonNullArgs.resize(Args.size());
3489 
3490  NonNullArgs.set(Index);
3491  }
3492 
3493  ++Index;
3494  }
3495  }
3496  }
3497 
3498  // Check for non-null arguments.
3499  for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3500  ArgIndex != ArgIndexEnd; ++ArgIndex) {
3501  if (NonNullArgs[ArgIndex])
3502  CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3503  }
3504 }
3505 
3506 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3507  StringRef ParamName, QualType ArgTy,
3508  QualType ParamTy) {
3509 
3510  // If a function accepts a pointer or reference type
3511  if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3512  return;
3513 
3514  // If the parameter is a pointer type, get the pointee type for the
3515  // argument too. If the parameter is a reference type, don't try to get
3516  // the pointee type for the argument.
3517  if (ParamTy->isPointerType())
3518  ArgTy = ArgTy->getPointeeType();
3519 
3520  // Remove reference or pointer
3521  ParamTy = ParamTy->getPointeeType();
3522 
3523  // Find expected alignment, and the actual alignment of the passed object.
3524  // getTypeAlignInChars requires complete types
3525  if (ArgTy.isNull() || ParamTy->isDependentType() ||
3526  ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3527  ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3528  return;
3529 
3530  CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3531  CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3532 
3533  // If the argument is less aligned than the parameter, there is a
3534  // potential alignment issue.
3535  if (ArgAlign < ParamAlign)
3536  Diag(Loc, diag::warn_param_mismatched_alignment)
3537  << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3538  << ParamName << (FDecl != nullptr) << FDecl;
3539 }
3540 
3541 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
3542  const Expr *ThisArg, ArrayRef<const Expr *> Args,
3543  bool IsMemberFunction, SourceLocation Loc,
3544  SourceRange Range, VariadicCallType CallType) {
3545  // FIXME: We should check as much as we can in the template definition.
3546  if (CurContext->isDependentContext())
3547  return;
3548 
3549  // Printf and scanf checking.
3550  llvm::SmallBitVector CheckedVarArgs;
3551  if (FDecl) {
3552  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3553  // Only create vector if there are format attributes.
3554  CheckedVarArgs.resize(Args.size());
3555 
3556  CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3557  CheckedVarArgs);
3558  }
3559  }
3560 
3561  // Refuse POD arguments that weren't caught by the format string
3562  // checks above.
3563  auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3564  if (CallType != VariadicDoesNotApply &&
3565  (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3566  unsigned NumParams = Proto ? Proto->getNumParams()
3567  : isa_and_nonnull<FunctionDecl>(FDecl)
3568  ? cast<FunctionDecl>(FDecl)->getNumParams()
3569  : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3570  ? cast<ObjCMethodDecl>(FDecl)->param_size()
3571  : 0;
3572 
3573  for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3574  // Args[ArgIdx] can be null in malformed code.
3575  if (const Expr *Arg = Args[ArgIdx]) {
3576  if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3577  checkVariadicArgument(Arg, CallType);
3578  }
3579  }
3580  }
3581 
3582  if (FDecl || Proto) {
3583  CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3584 
3585  // Type safety checking.
3586  if (FDecl) {
3587  for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3588  CheckArgumentWithTypeTag(I, Args, Loc);
3589  }
3590  }
3591 
3592  // Check that passed arguments match the alignment of original arguments.
3593  // Try to get the missing prototype from the declaration.
3594  if (!Proto && FDecl) {
3595  const auto *FT = FDecl->getFunctionType();
3596  if (isa_and_nonnull<FunctionProtoType>(FT))
3597  Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3598  }
3599  if (Proto) {
3600  // For variadic functions, we may have more args than parameters.
3601  // For some K&R functions, we may have less args than parameters.
3602  const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3603  bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3604  bool IsScalableArg = false;
3605  for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3606  // Args[ArgIdx] can be null in malformed code.
3607  if (const Expr *Arg = Args[ArgIdx]) {
3608  if (Arg->containsErrors())
3609  continue;
3610 
3611  if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3612  FDecl->hasLinkage() &&
3613  FDecl->getFormalLinkage() != Linkage::Internal &&
3614  CallType == VariadicDoesNotApply)
3615  PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3616 
3617  QualType ParamTy = Proto->getParamType(ArgIdx);
3618  if (ParamTy->isSizelessVectorType())
3619  IsScalableArg = true;
3620  QualType ArgTy = Arg->getType();
3621  CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3622  ArgTy, ParamTy);
3623  }
3624  }
3625 
3626  // If the callee has an AArch64 SME attribute to indicate that it is an
3627  // __arm_streaming function, then the caller requires SME to be available.
3630  if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3631  llvm::StringMap<bool> CallerFeatureMap;
3632  Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3633  if (!CallerFeatureMap.contains("sme"))
3634  Diag(Loc, diag::err_sme_call_in_non_sme_target);
3635  } else if (!Context.getTargetInfo().hasFeature("sme")) {
3636  Diag(Loc, diag::err_sme_call_in_non_sme_target);
3637  }
3638  }
3639 
3640  // If the call requires a streaming-mode change and has scalable vector
3641  // arguments or return values, then warn the user that the streaming and
3642  // non-streaming vector lengths may be different.
3643  const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3644  if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3645  (IsScalableArg || IsScalableRet)) {
3646  bool IsCalleeStreaming =
3648  bool IsCalleeStreamingCompatible =
3649  ExtInfo.AArch64SMEAttributes &
3651  SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3652  if (!IsCalleeStreamingCompatible &&
3653  (CallerFnType == SemaARM::ArmStreamingCompatible ||
3654  ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3655  if (IsScalableArg)
3656  Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3657  << /*IsArg=*/true;
3658  if (IsScalableRet)
3659  Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3660  << /*IsArg=*/false;
3661  }
3662  }
3663 
3664  FunctionType::ArmStateValue CalleeArmZAState =
3666  FunctionType::ArmStateValue CalleeArmZT0State =
3668  if (CalleeArmZAState != FunctionType::ARM_None ||
3669  CalleeArmZT0State != FunctionType::ARM_None) {
3670  bool CallerHasZAState = false;
3671  bool CallerHasZT0State = false;
3672  if (CallerFD) {
3673  auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3674  if (Attr && Attr->isNewZA())
3675  CallerHasZAState = true;
3676  if (Attr && Attr->isNewZT0())
3677  CallerHasZT0State = true;
3678  if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3679  CallerHasZAState |=
3681  FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3683  CallerHasZT0State |=
3685  FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3687  }
3688  }
3689 
3690  if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
3691  Diag(Loc, diag::err_sme_za_call_no_za_state);
3692 
3693  if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
3694  Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
3695 
3696  if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
3697  CalleeArmZT0State != FunctionType::ARM_None) {
3698  Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
3699  Diag(Loc, diag::note_sme_use_preserves_za);
3700  }
3701  }
3702  }
3703 
3704  if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3705  auto *AA = FDecl->getAttr<AllocAlignAttr>();
3706  const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3707  if (!Arg->isValueDependent()) {
3708  Expr::EvalResult Align;
3709  if (Arg->EvaluateAsInt(Align, Context)) {
3710  const llvm::APSInt &I = Align.Val.getInt();
3711  if (!I.isPowerOf2())
3712  Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3713  << Arg->getSourceRange();
3714 
3715  if (I > Sema::MaximumAlignment)
3716  Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3717  << Arg->getSourceRange() << Sema::MaximumAlignment;
3718  }
3719  }
3720  }
3721 
3722  if (FD)
3723  diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3724 
3725  if (FD && FD->hasAttr<SYCLKernelAttr>())
3726  SYCL().CheckSYCLKernelCall(FD, Args);
3727 
3728  // Diagnose variadic calls in SYCL.
3729  if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
3730  !isUnevaluatedContext() && !SYCL().isDeclAllowedInSYCLDeviceCode(FD))
3731  SYCL().DiagIfDeviceCode(Loc, diag::err_sycl_restrict)
3733 }
3734 
3736  if (ConceptDecl *Decl = AutoT->getTypeConstraintConcept()) {
3737  DiagnoseUseOfDecl(Decl, Loc);
3738  }
3739 }
3740 
3741 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3743  const FunctionProtoType *Proto,
3744  SourceLocation Loc) {
3745  VariadicCallType CallType =
3746  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3747 
3748  auto *Ctor = cast<CXXConstructorDecl>(FDecl);
3749  CheckArgAlignment(
3750  Loc, FDecl, "'this'", Context.getPointerType(ThisType),
3751  Context.getPointerType(Ctor->getFunctionObjectParameterType()));
3752 
3753  checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3754  Loc, SourceRange(), CallType);
3755 }
3756 
3758  const FunctionProtoType *Proto) {
3759  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3760  isa<CXXMethodDecl>(FDecl);
3761  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3762  IsMemberOperatorCall;
3763  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3764  TheCall->getCallee());
3765  Expr** Args = TheCall->getArgs();
3766  unsigned NumArgs = TheCall->getNumArgs();
3767 
3768  Expr *ImplicitThis = nullptr;
3769  if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
3770  // If this is a call to a member operator, hide the first
3771  // argument from checkCall.
3772  // FIXME: Our choice of AST representation here is less than ideal.
3773  ImplicitThis = Args[0];
3774  ++Args;
3775  --NumArgs;
3776  } else if (IsMemberFunction && !FDecl->isStatic() &&
3778  ImplicitThis =
3779  cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3780 
3781  if (ImplicitThis) {
3782  // ImplicitThis may or may not be a pointer, depending on whether . or -> is
3783  // used.
3784  QualType ThisType = ImplicitThis->getType();
3785  if (!ThisType->isPointerType()) {
3786  assert(!ThisType->isReferenceType());
3787  ThisType = Context.getPointerType(ThisType);
3788  }
3789 
3790  QualType ThisTypeFromDecl = Context.getPointerType(
3791  cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
3792 
3793  CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
3794  ThisTypeFromDecl);
3795  }
3796 
3797  checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
3798  IsMemberFunction, TheCall->getRParenLoc(),
3799  TheCall->getCallee()->getSourceRange(), CallType);
3800 
3801  IdentifierInfo *FnInfo = FDecl->getIdentifier();
3802  // None of the checks below are needed for functions that don't have
3803  // simple names (e.g., C++ conversion functions).
3804  if (!FnInfo)
3805  return false;
3806 
3807  // Enforce TCB except for builtin calls, which are always allowed.
3808  if (FDecl->getBuiltinID() == 0)
3809  CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
3810 
3811  CheckAbsoluteValueFunction(TheCall, FDecl);
3812  CheckMaxUnsignedZero(TheCall, FDecl);
3813  CheckInfNaNFunction(TheCall, FDecl);
3814 
3815  if (getLangOpts().ObjC)
3816  ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
3817 
3818  unsigned CMId = FDecl->getMemoryFunctionKind();
3819 
3820  // Handle memory setting and copying functions.
3821  switch (CMId) {
3822  case 0:
3823  return false;
3824  case Builtin::BIstrlcpy: // fallthrough
3825  case Builtin::BIstrlcat:
3826  CheckStrlcpycatArguments(TheCall, FnInfo);
3827  break;
3828  case Builtin::BIstrncat:
3829  CheckStrncatArguments(TheCall, FnInfo);
3830  break;
3831  case Builtin::BIfree:
3832  CheckFreeArguments(TheCall);
3833  break;
3834  default:
3835  CheckMemaccessArguments(TheCall, CMId, FnInfo);
3836  }
3837 
3838  return false;
3839 }
3840 
3841 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3842  const FunctionProtoType *Proto) {
3843  QualType Ty;
3844  if (const auto *V = dyn_cast<VarDecl>(NDecl))
3845  Ty = V->getType().getNonReferenceType();
3846  else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3847  Ty = F->getType().getNonReferenceType();
3848  else
3849  return false;
3850 
3851  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3852  !Ty->isFunctionProtoType())
3853  return false;
3854 
3855  VariadicCallType CallType;
3856  if (!Proto || !Proto->isVariadic()) {
3857  CallType = VariadicDoesNotApply;
3858  } else if (Ty->isBlockPointerType()) {
3859  CallType = VariadicBlock;
3860  } else { // Ty->isFunctionPointerType()
3861  CallType = VariadicFunction;
3862  }
3863 
3864  checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
3865  llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3866  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3867  TheCall->getCallee()->getSourceRange(), CallType);
3868 
3869  return false;
3870 }
3871 
3872 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
3873  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
3874  TheCall->getCallee());
3875  checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
3876  llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3877  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3878  TheCall->getCallee()->getSourceRange(), CallType);
3879 
3880  return false;
3881 }
3882 
3884  if (!llvm::isValidAtomicOrderingCABI(Ordering))
3885  return false;
3886 
3887  auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
3888  switch (Op) {
3889  case AtomicExpr::AO__c11_atomic_init:
3890  case AtomicExpr::AO__opencl_atomic_init:
3891  llvm_unreachable("There is no ordering argument for an init");
3892 
3893  case AtomicExpr::AO__c11_atomic_load:
3894  case AtomicExpr::AO__opencl_atomic_load:
3895  case AtomicExpr::AO__hip_atomic_load:
3896  case AtomicExpr::AO__atomic_load_n:
3897  case AtomicExpr::AO__atomic_load:
3898  case AtomicExpr::AO__scoped_atomic_load_n:
3899  case AtomicExpr::AO__scoped_atomic_load:
3900  return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3901  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3902 
3903  case AtomicExpr::AO__c11_atomic_store:
3904  case AtomicExpr::AO__opencl_atomic_store:
3905  case AtomicExpr::AO__hip_atomic_store:
3906  case AtomicExpr::AO__atomic_store:
3907  case AtomicExpr::AO__atomic_store_n:
3908  case AtomicExpr::AO__scoped_atomic_store:
3909  case AtomicExpr::AO__scoped_atomic_store_n:
3910  return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3911  OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3912  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3913 
3914  default:
3915  return true;
3916  }
3917 }
3918 
3919 ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
3920  AtomicExpr::AtomicOp Op) {
3921  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3922  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3923  MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
3924  return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
3925  DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
3926  Op);
3927 }
3928 
3930  SourceLocation RParenLoc, MultiExprArg Args,
3932  AtomicArgumentOrder ArgOrder) {
3933  // All the non-OpenCL operations take one of the following forms.
3934  // The OpenCL operations take the __c11 forms with one extra argument for
3935  // synchronization scope.
3936  enum {
3937  // C __c11_atomic_init(A *, C)
3938  Init,
3939 
3940  // C __c11_atomic_load(A *, int)
3941  Load,
3942 
3943  // void __atomic_load(A *, CP, int)
3944  LoadCopy,
3945 
3946  // void __atomic_store(A *, CP, int)
3947  Copy,
3948 
3949  // C __c11_atomic_add(A *, M, int)
3950  Arithmetic,
3951 
3952  // C __atomic_exchange_n(A *, CP, int)
3953  Xchg,
3954 
3955  // void __atomic_exchange(A *, C *, CP, int)
3956  GNUXchg,
3957 
3958  // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3959  C11CmpXchg,
3960 
3961  // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3962  GNUCmpXchg
3963  } Form = Init;
3964 
3965  const unsigned NumForm = GNUCmpXchg + 1;
3966  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3967  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
3968  // where:
3969  // C is an appropriate type,
3970  // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3971  // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3972  // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3973  // the int parameters are for orderings.
3974 
3975  static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3976  && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3977  "need to update code for modified forms");
3978  static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
3979  AtomicExpr::AO__atomic_xor_fetch + 1 ==
3980  AtomicExpr::AO__c11_atomic_compare_exchange_strong,
3981  "need to update code for modified C11 atomics");
3982  bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
3983  Op <= AtomicExpr::AO__opencl_atomic_store;
3984  bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
3985  Op <= AtomicExpr::AO__hip_atomic_store;
3986  bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
3987  Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
3988  bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
3989  Op <= AtomicExpr::AO__c11_atomic_store) ||
3990  IsOpenCL;
3991  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3992  Op == AtomicExpr::AO__atomic_store_n ||
3993  Op == AtomicExpr::AO__atomic_exchange_n ||
3994  Op == AtomicExpr::AO__atomic_compare_exchange_n ||
3995  Op == AtomicExpr::AO__scoped_atomic_load_n ||
3996  Op == AtomicExpr::AO__scoped_atomic_store_n ||
3997  Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
3998  Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
3999  // Bit mask for extra allowed value types other than integers for atomic
4000  // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4001  // allow floating point.
4002  enum ArithOpExtraValueType {
4003  AOEVT_None = 0,
4004  AOEVT_Pointer = 1,
4005  AOEVT_FP = 2,
4006  };
4007  unsigned ArithAllows = AOEVT_None;
4008 
4009  switch (Op) {
4010  case AtomicExpr::AO__c11_atomic_init:
4011  case AtomicExpr::AO__opencl_atomic_init:
4012  Form = Init;
4013  break;
4014 
4015  case AtomicExpr::AO__c11_atomic_load:
4016  case AtomicExpr::AO__opencl_atomic_load:
4017  case AtomicExpr::AO__hip_atomic_load:
4018  case AtomicExpr::AO__atomic_load_n:
4019  case AtomicExpr::AO__scoped_atomic_load_n:
4020  Form = Load;
4021  break;
4022 
4023  case AtomicExpr::AO__atomic_load:
4024  case AtomicExpr::AO__scoped_atomic_load:
4025  Form = LoadCopy;
4026  break;
4027 
4028  case AtomicExpr::AO__c11_atomic_store:
4029  case AtomicExpr::AO__opencl_atomic_store:
4030  case AtomicExpr::AO__hip_atomic_store:
4031  case AtomicExpr::AO__atomic_store:
4032  case AtomicExpr::AO__atomic_store_n:
4033  case AtomicExpr::AO__scoped_atomic_store:
4034  case AtomicExpr::AO__scoped_atomic_store_n:
4035  Form = Copy;
4036  break;
4037  case AtomicExpr::AO__atomic_fetch_add:
4038  case AtomicExpr::AO__atomic_fetch_sub:
4039  case AtomicExpr::AO__atomic_add_fetch:
4040  case AtomicExpr::AO__atomic_sub_fetch:
4041  case AtomicExpr::AO__scoped_atomic_fetch_add:
4042  case AtomicExpr::AO__scoped_atomic_fetch_sub:
4043  case AtomicExpr::AO__scoped_atomic_add_fetch:
4044  case AtomicExpr::AO__scoped_atomic_sub_fetch:
4045  case AtomicExpr::AO__c11_atomic_fetch_add:
4046  case AtomicExpr::AO__c11_atomic_fetch_sub:
4047  case AtomicExpr::AO__opencl_atomic_fetch_add:
4048  case AtomicExpr::AO__opencl_atomic_fetch_sub:
4049  case AtomicExpr::AO__hip_atomic_fetch_add:
4050  case AtomicExpr::AO__hip_atomic_fetch_sub:
4051  ArithAllows = AOEVT_Pointer | AOEVT_FP;
4052  Form = Arithmetic;
4053  break;
4054  case AtomicExpr::AO__atomic_fetch_max:
4055  case AtomicExpr::AO__atomic_fetch_min:
4056  case AtomicExpr::AO__atomic_max_fetch:
4057  case AtomicExpr::AO__atomic_min_fetch:
4058  case AtomicExpr::AO__scoped_atomic_fetch_max:
4059  case AtomicExpr::AO__scoped_atomic_fetch_min:
4060  case AtomicExpr::AO__scoped_atomic_max_fetch:
4061  case AtomicExpr::AO__scoped_atomic_min_fetch:
4062  case AtomicExpr::AO__c11_atomic_fetch_max:
4063  case AtomicExpr::AO__c11_atomic_fetch_min:
4064  case AtomicExpr::AO__opencl_atomic_fetch_max:
4065  case AtomicExpr::AO__opencl_atomic_fetch_min:
4066  case AtomicExpr::AO__hip_atomic_fetch_max:
4067  case AtomicExpr::AO__hip_atomic_fetch_min:
4068  ArithAllows = AOEVT_FP;
4069  Form = Arithmetic;
4070  break;
4071  case AtomicExpr::AO__c11_atomic_fetch_and:
4072  case AtomicExpr::AO__c11_atomic_fetch_or:
4073  case AtomicExpr::AO__c11_atomic_fetch_xor:
4074  case AtomicExpr::AO__hip_atomic_fetch_and:
4075  case AtomicExpr::AO__hip_atomic_fetch_or:
4076  case AtomicExpr::AO__hip_atomic_fetch_xor:
4077  case AtomicExpr::AO__c11_atomic_fetch_nand:
4078  case AtomicExpr::AO__opencl_atomic_fetch_and:
4079  case AtomicExpr::AO__opencl_atomic_fetch_or:
4080  case AtomicExpr::AO__opencl_atomic_fetch_xor:
4081  case AtomicExpr::AO__atomic_fetch_and:
4082  case AtomicExpr::AO__atomic_fetch_or:
4083  case AtomicExpr::AO__atomic_fetch_xor:
4084  case AtomicExpr::AO__atomic_fetch_nand:
4085  case AtomicExpr::AO__atomic_and_fetch:
4086  case AtomicExpr::AO__atomic_or_fetch:
4087  case AtomicExpr::AO__atomic_xor_fetch:
4088  case AtomicExpr::AO__atomic_nand_fetch:
4089  case AtomicExpr::AO__scoped_atomic_fetch_and:
4090  case AtomicExpr::AO__scoped_atomic_fetch_or:
4091  case AtomicExpr::AO__scoped_atomic_fetch_xor:
4092  case AtomicExpr::AO__scoped_atomic_fetch_nand:
4093  case AtomicExpr::AO__scoped_atomic_and_fetch:
4094  case AtomicExpr::AO__scoped_atomic_or_fetch:
4095  case AtomicExpr::AO__scoped_atomic_xor_fetch:
4096  case AtomicExpr::AO__scoped_atomic_nand_fetch:
4097  Form = Arithmetic;
4098  break;
4099 
4100  case AtomicExpr::AO__c11_atomic_exchange:
4101  case AtomicExpr::AO__hip_atomic_exchange:
4102  case AtomicExpr::AO__opencl_atomic_exchange:
4103  case AtomicExpr::AO__atomic_exchange_n:
4104  case AtomicExpr::AO__scoped_atomic_exchange_n:
4105  Form = Xchg;
4106  break;
4107 
4108  case AtomicExpr::AO__atomic_exchange:
4109  case AtomicExpr::AO__scoped_atomic_exchange:
4110  Form = GNUXchg;
4111  break;
4112 
4113  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4114  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4115  case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4116  case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4117  case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4118  case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4119  Form = C11CmpXchg;
4120  break;
4121 
4122  case AtomicExpr::AO__atomic_compare_exchange:
4123  case AtomicExpr::AO__atomic_compare_exchange_n:
4124  case AtomicExpr::AO__scoped_atomic_compare_exchange:
4125  case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4126  Form = GNUCmpXchg;
4127  break;
4128  }
4129 
4130  unsigned AdjustedNumArgs = NumArgs[Form];
4131  if ((IsOpenCL || IsHIP || IsScoped) &&
4132  Op != AtomicExpr::AO__opencl_atomic_init)
4133  ++AdjustedNumArgs;
4134  // Check we have the right number of arguments.
4135  if (Args.size() < AdjustedNumArgs) {
4136  Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4137  << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4138  << /*is non object*/ 0 << ExprRange;
4139  return ExprError();
4140  } else if (Args.size() > AdjustedNumArgs) {
4141  Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4142  diag::err_typecheck_call_too_many_args)
4143  << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4144  << /*is non object*/ 0 << ExprRange;
4145  return ExprError();
4146  }
4147 
4148  // Inspect the first argument of the atomic operation.
4149  Expr *Ptr = Args[0];
4150  ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4151  if (ConvertedPtr.isInvalid())
4152  return ExprError();
4153 
4154  Ptr = ConvertedPtr.get();
4155  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4156  if (!pointerType) {
4157  Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4158  << Ptr->getType() << 0 << Ptr->getSourceRange();
4159  return ExprError();
4160  }
4161 
4162  // For a __c11 builtin, this should be a pointer to an _Atomic type.
4163  QualType AtomTy = pointerType->getPointeeType(); // 'A'
4164  QualType ValType = AtomTy; // 'C'
4165  if (IsC11) {
4166  if (!AtomTy->isAtomicType()) {
4167  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4168  << Ptr->getType() << Ptr->getSourceRange();
4169  return ExprError();
4170  }
4171  if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4173  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4174  << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4175  << Ptr->getSourceRange();
4176  return ExprError();
4177  }
4178  ValType = AtomTy->castAs<AtomicType>()->getValueType();
4179  } else if (Form != Load && Form != LoadCopy) {
4180  if (ValType.isConstQualified()) {
4181  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4182  << Ptr->getType() << Ptr->getSourceRange();
4183  return ExprError();
4184  }
4185  }
4186 
4187  // Pointer to object of size zero is not allowed.
4188  if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4189  diag::err_incomplete_type))
4190  return ExprError();
4191  if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4192  Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4193  << Ptr->getType() << 1 << Ptr->getSourceRange();
4194  return ExprError();
4195  }
4196 
4197  // For an arithmetic operation, the implied arithmetic must be well-formed.
4198  if (Form == Arithmetic) {
4199  // GCC does not enforce these rules for GNU atomics, but we do to help catch
4200  // trivial type errors.
4201  auto IsAllowedValueType = [&](QualType ValType,
4202  unsigned AllowedType) -> bool {
4203  if (ValType->isIntegerType())
4204  return true;
4205  if (ValType->isPointerType())
4206  return AllowedType & AOEVT_Pointer;
4207  if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4208  return false;
4209  // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4210  if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4211  &Context.getTargetInfo().getLongDoubleFormat() ==
4212  &llvm::APFloat::x87DoubleExtended())
4213  return false;
4214  return true;
4215  };
4216  if (!IsAllowedValueType(ValType, ArithAllows)) {
4217  auto DID = ArithAllows & AOEVT_FP
4218  ? (ArithAllows & AOEVT_Pointer
4219  ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4220  : diag::err_atomic_op_needs_atomic_int_or_fp)
4221  : diag::err_atomic_op_needs_atomic_int;
4222  Diag(ExprRange.getBegin(), DID)
4223  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4224  return ExprError();
4225  }
4226  if (IsC11 && ValType->isPointerType() &&
4227  RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4228  diag::err_incomplete_type)) {
4229  return ExprError();
4230  }
4231  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4232  // For __atomic_*_n operations, the value type must be a scalar integral or
4233  // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4234  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4235  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4236  return ExprError();
4237  }
4238 
4239  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4240  !AtomTy->isScalarType()) {
4241  // For GNU atomics, require a trivially-copyable type. This is not part of
4242  // the GNU atomics specification but we enforce it for consistency with
4243  // other atomics which generally all require a trivially-copyable type. This
4244  // is because atomics just copy bits.
4245  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4246  << Ptr->getType() << Ptr->getSourceRange();
4247  return ExprError();
4248  }
4249 
4250  switch (ValType.getObjCLifetime()) {
4251  case Qualifiers::OCL_None:
4253  // okay
4254  break;
4255 
4256  case Qualifiers::OCL_Weak:
4259  // FIXME: Can this happen? By this point, ValType should be known
4260  // to be trivially copyable.
4261  Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4262  << ValType << Ptr->getSourceRange();
4263  return ExprError();
4264  }
4265 
4266  // All atomic operations have an overload which takes a pointer to a volatile
4267  // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4268  // into the result or the other operands. Similarly atomic_load takes a
4269  // pointer to a const 'A'.
4270  ValType.removeLocalVolatile();
4271  ValType.removeLocalConst();
4272  QualType ResultType = ValType;
4273  if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4274  Form == Init)
4275  ResultType = Context.VoidTy;
4276  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4277  ResultType = Context.BoolTy;
4278 
4279  // The type of a parameter passed 'by value'. In the GNU atomics, such
4280  // arguments are actually passed as pointers.
4281  QualType ByValType = ValType; // 'CP'
4282  bool IsPassedByAddress = false;
4283  if (!IsC11 && !IsHIP && !IsN) {
4284  ByValType = Ptr->getType();
4285  IsPassedByAddress = true;
4286  }
4287 
4288  SmallVector<Expr *, 5> APIOrderedArgs;
4289  if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4290  APIOrderedArgs.push_back(Args[0]);
4291  switch (Form) {
4292  case Init:
4293  case Load:
4294  APIOrderedArgs.push_back(Args[1]); // Val1/Order
4295  break;
4296  case LoadCopy:
4297  case Copy:
4298  case Arithmetic:
4299  case Xchg:
4300  APIOrderedArgs.push_back(Args[2]); // Val1
4301  APIOrderedArgs.push_back(Args[1]); // Order
4302  break;
4303  case GNUXchg:
4304  APIOrderedArgs.push_back(Args[2]); // Val1
4305  APIOrderedArgs.push_back(Args[3]); // Val2
4306  APIOrderedArgs.push_back(Args[1]); // Order
4307  break;
4308  case C11CmpXchg:
4309  APIOrderedArgs.push_back(Args[2]); // Val1
4310  APIOrderedArgs.push_back(Args[4]); // Val2
4311  APIOrderedArgs.push_back(Args[1]); // Order
4312  APIOrderedArgs.push_back(Args[3]); // OrderFail
4313  break;
4314  case GNUCmpXchg:
4315  APIOrderedArgs.push_back(Args[2]); // Val1
4316  APIOrderedArgs.push_back(Args[4]); // Val2
4317  APIOrderedArgs.push_back(Args[5]); // Weak
4318  APIOrderedArgs.push_back(Args[1]); // Order
4319  APIOrderedArgs.push_back(Args[3]); // OrderFail
4320  break;
4321  }
4322  } else
4323  APIOrderedArgs.append(Args.begin(), Args.end());
4324 
4325  // The first argument's non-CV pointer type is used to deduce the type of
4326  // subsequent arguments, except for:
4327  // - weak flag (always converted to bool)
4328  // - memory order (always converted to int)
4329  // - scope (always converted to int)
4330  for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4331  QualType Ty;
4332  if (i < NumVals[Form] + 1) {
4333  switch (i) {
4334  case 0:
4335  // The first argument is always a pointer. It has a fixed type.
4336  // It is always dereferenced, a nullptr is undefined.
4337  CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4338  // Nothing else to do: we already know all we want about this pointer.
4339  continue;
4340  case 1:
4341  // The second argument is the non-atomic operand. For arithmetic, this
4342  // is always passed by value, and for a compare_exchange it is always
4343  // passed by address. For the rest, GNU uses by-address and C11 uses
4344  // by-value.
4345  assert(Form != Load);
4346  if (Form == Arithmetic && ValType->isPointerType())
4347  Ty = Context.getPointerDiffType();
4348  else if (Form == Init || Form == Arithmetic)
4349  Ty = ValType;
4350  else if (Form == Copy || Form == Xchg) {
4351  if (IsPassedByAddress) {
4352  // The value pointer is always dereferenced, a nullptr is undefined.
4353  CheckNonNullArgument(*this, APIOrderedArgs[i],
4354  ExprRange.getBegin());
4355  }
4356  Ty = ByValType;
4357  } else {
4358  Expr *ValArg = APIOrderedArgs[i];
4359  // The value pointer is always dereferenced, a nullptr is undefined.
4360  CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4361  LangAS AS = LangAS::Default;
4362  // Keep address space of non-atomic pointer type.
4363  if (const PointerType *PtrTy =
4364  ValArg->getType()->getAs<PointerType>()) {
4365  AS = PtrTy->getPointeeType().getAddressSpace();
4366  }
4367  Ty = Context.getPointerType(
4368  Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4369  }
4370  break;
4371  case 2:
4372  // The third argument to compare_exchange / GNU exchange is the desired
4373  // value, either by-value (for the C11 and *_n variant) or as a pointer.
4374  if (IsPassedByAddress)
4375  CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4376  Ty = ByValType;
4377  break;
4378  case 3:
4379  // The fourth argument to GNU compare_exchange is a 'weak' flag.
4380  Ty = Context.BoolTy;
4381  break;
4382  }
4383  } else {
4384  // The order(s) and scope are always converted to int.
4385  Ty = Context.IntTy;
4386  }
4387 
4388  InitializedEntity Entity =
4389  InitializedEntity::InitializeParameter(Context, Ty, false);
4390  ExprResult Arg = APIOrderedArgs[i];
4391  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4392  if (Arg.isInvalid())
4393  return true;
4394  APIOrderedArgs[i] = Arg.get();
4395  }
4396 
4397  // Permute the arguments into a 'consistent' order.
4398  SmallVector<Expr*, 5> SubExprs;
4399  SubExprs.push_back(Ptr);
4400  switch (Form) {
4401  case Init:
4402  // Note, AtomicExpr::getVal1() has a special case for this atomic.
4403  SubExprs.push_back(APIOrderedArgs[1]); // Val1
4404  break;
4405  case Load:
4406  SubExprs.push_back(APIOrderedArgs[1]); // Order
4407  break;
4408  case LoadCopy:
4409  case Copy:
4410  case Arithmetic:
4411  case Xchg:
4412  SubExprs.push_back(APIOrderedArgs[2]); // Order
4413  SubExprs.push_back(APIOrderedArgs[1]); // Val1
4414  break;
4415  case GNUXchg:
4416  // Note, AtomicExpr::getVal2() has a special case for this atomic.
4417  SubExprs.push_back(APIOrderedArgs[3]); // Order
4418  SubExprs.push_back(APIOrderedArgs[1]); // Val1
4419  SubExprs.push_back(APIOrderedArgs[2]); // Val2
4420  break;
4421  case C11CmpXchg:
4422  SubExprs.push_back(APIOrderedArgs[3]); // Order
4423  SubExprs.push_back(APIOrderedArgs[1]); // Val1
4424  SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4425  SubExprs.push_back(APIOrderedArgs[2]); // Val2
4426  break;
4427  case GNUCmpXchg:
4428  SubExprs.push_back(APIOrderedArgs[4]); // Order
4429  SubExprs.push_back(APIOrderedArgs[1]); // Val1
4430  SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4431  SubExprs.push_back(APIOrderedArgs[2]); // Val2
4432  SubExprs.push_back(APIOrderedArgs[3]); // Weak
4433  break;
4434  }
4435 
4436  // If the memory orders are constants, check they are valid.
4437  if (SubExprs.size() >= 2 && Form != Init) {
4438  std::optional<llvm::APSInt> Success =
4439  SubExprs[1]->getIntegerConstantExpr(Context);
4440  if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4441  Diag(SubExprs[1]->getBeginLoc(),
4442  diag::warn_atomic_op_has_invalid_memory_order)
4443  << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4444  << SubExprs[1]->getSourceRange();
4445  }
4446  if (SubExprs.size() >= 5) {
4447  if (std::optional<llvm::APSInt> Failure =
4448  SubExprs[3]->getIntegerConstantExpr(Context)) {
4449  if (!llvm::is_contained(
4450  {llvm::AtomicOrderingCABI::relaxed,
4451  llvm::AtomicOrderingCABI::consume,
4452  llvm::AtomicOrderingCABI::acquire,
4453  llvm::AtomicOrderingCABI::seq_cst},
4454  (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4455  Diag(SubExprs[3]->getBeginLoc(),
4456  diag::warn_atomic_op_has_invalid_memory_order)
4457  << /*failure=*/2 << SubExprs[3]->getSourceRange();
4458  }
4459  }
4460  }
4461  }
4462 
4463  if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4464  auto *Scope = Args[Args.size() - 1];
4465  if (std::optional<llvm::APSInt> Result =
4466  Scope->getIntegerConstantExpr(Context)) {
4467  if (!ScopeModel->isValid(Result->getZExtValue()))
4468  Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4469  << Scope->getSourceRange();
4470  }
4471  SubExprs.push_back(Scope);
4472  }
4473 
4474  AtomicExpr *AE = new (Context)
4475  AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4476 
4477  if ((Op == AtomicExpr::AO__c11_atomic_load ||
4478  Op == AtomicExpr::AO__c11_atomic_store ||
4479  Op == AtomicExpr::AO__opencl_atomic_load ||
4480  Op == AtomicExpr::AO__hip_atomic_load ||
4481  Op == AtomicExpr::AO__opencl_atomic_store ||
4482  Op == AtomicExpr::AO__hip_atomic_store) &&
4483  Context.AtomicUsesUnsupportedLibcall(AE))
4484  Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4485  << ((Op == AtomicExpr::AO__c11_atomic_load ||
4486  Op == AtomicExpr::AO__opencl_atomic_load ||
4487  Op == AtomicExpr::AO__hip_atomic_load)
4488  ? 0
4489  : 1);
4490 
4491  if (ValType->isBitIntType()) {
4492  Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4493  return ExprError();
4494  }
4495 
4496  return AE;
4497 }
4498 
4499 /// checkBuiltinArgument - Given a call to a builtin function, perform
4500 /// normal type-checking on the given argument, updating the call in
4501 /// place. This is useful when a builtin function requires custom
4502 /// type-checking for some of its arguments but not necessarily all of
4503 /// them.
4504 ///
4505 /// Returns true on error.
4506 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4507  FunctionDecl *Fn = E->getDirectCallee();
4508  assert(Fn && "builtin call without direct callee!");
4509 
4510  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4511  InitializedEntity Entity =
4513 
4514  ExprResult Arg = E->getArg(ArgIndex);
4515  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4516  if (Arg.isInvalid())
4517  return true;
4518 
4519  E->setArg(ArgIndex, Arg.get());
4520  return false;
4521 }
4522 
4523 ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4524  CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4525  Expr *Callee = TheCall->getCallee();
4526  DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4527  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4528 
4529  // Ensure that we have at least one argument to do type inference from.
4530  if (TheCall->getNumArgs() < 1) {
4531  Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4532  << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4533  << Callee->getSourceRange();
4534  return ExprError();
4535  }
4536 
4537  // Inspect the first argument of the atomic builtin. This should always be
4538  // a pointer type, whose element is an integral scalar or pointer type.
4539  // Because it is a pointer type, we don't have to worry about any implicit
4540  // casts here.
4541  // FIXME: We don't allow floating point scalars as input.
4542  Expr *FirstArg = TheCall->getArg(0);
4543  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4544  if (FirstArgResult.isInvalid())
4545  return ExprError();
4546  FirstArg = FirstArgResult.get();
4547  TheCall->setArg(0, FirstArg);
4548 
4549  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4550  if (!pointerType) {
4551  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4552  << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4553  return ExprError();
4554  }
4555 
4556  QualType ValType = pointerType->getPointeeType();
4557  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4558  !ValType->isBlockPointerType()) {
4559  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4560  << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4561  return ExprError();
4562  }
4563 
4564  if (ValType.isConstQualified()) {
4565  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4566  << FirstArg->getType() << FirstArg->getSourceRange();
4567  return ExprError();
4568  }
4569 
4570  switch (ValType.getObjCLifetime()) {
4571  case Qualifiers::OCL_None:
4573  // okay
4574  break;
4575 
4576  case Qualifiers::OCL_Weak:
4579  Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4580  << ValType << FirstArg->getSourceRange();
4581  return ExprError();
4582  }
4583 
4584  // Strip any qualifiers off ValType.
4585  ValType = ValType.getUnqualifiedType();
4586 
4587  // The majority of builtins return a value, but a few have special return
4588  // types, so allow them to override appropriately below.
4589  QualType ResultType = ValType;
4590 
4591  // We need to figure out which concrete builtin this maps onto. For example,
4592  // __sync_fetch_and_add with a 2 byte object turns into
4593  // __sync_fetch_and_add_2.
4594 #define BUILTIN_ROW(x) \
4595  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4596  Builtin::BI##x##_8, Builtin::BI##x##_16 }
4597 
4598  static const unsigned BuiltinIndices[][5] = {
4599  BUILTIN_ROW(__sync_fetch_and_add),
4600  BUILTIN_ROW(__sync_fetch_and_sub),
4601  BUILTIN_ROW(__sync_fetch_and_or),
4602  BUILTIN_ROW(__sync_fetch_and_and),
4603  BUILTIN_ROW(__sync_fetch_and_xor),
4604  BUILTIN_ROW(__sync_fetch_and_nand),
4605 
4606  BUILTIN_ROW(__sync_add_and_fetch),
4607  BUILTIN_ROW(__sync_sub_and_fetch),
4608  BUILTIN_ROW(__sync_and_and_fetch),
4609  BUILTIN_ROW(__sync_or_and_fetch),
4610  BUILTIN_ROW(__sync_xor_and_fetch),
4611  BUILTIN_ROW(__sync_nand_and_fetch),
4612 
4613  BUILTIN_ROW(__sync_val_compare_and_swap),
4614  BUILTIN_ROW(__sync_bool_compare_and_swap),
4615  BUILTIN_ROW(__sync_lock_test_and_set),
4616  BUILTIN_ROW(__sync_lock_release),
4617  BUILTIN_ROW(__sync_swap)
4618  };
4619 #undef BUILTIN_ROW
4620 
4621  // Determine the index of the size.
4622  unsigned SizeIndex;
4623  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4624  case 1: SizeIndex = 0; break;
4625  case 2: SizeIndex = 1; break;
4626  case 4: SizeIndex = 2; break;
4627  case 8: SizeIndex = 3; break;
4628  case 16: SizeIndex = 4; break;
4629  default:
4630  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4631  << FirstArg->getType() << FirstArg->getSourceRange();
4632  return ExprError();
4633  }
4634 
4635  // Each of these builtins has one pointer argument, followed by some number of
4636  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4637  // that we ignore. Find out which row of BuiltinIndices to read from as well
4638  // as the number of fixed args.
4639  unsigned BuiltinID = FDecl->getBuiltinID();
4640  unsigned BuiltinIndex, NumFixed = 1;
4641  bool WarnAboutSemanticsChange = false;
4642  switch (BuiltinID) {
4643  default: llvm_unreachable("Unknown overloaded atomic builtin!");
4644  case Builtin::BI__sync_fetch_and_add:
4645  case Builtin::BI__sync_fetch_and_add_1:
4646  case Builtin::BI__sync_fetch_and_add_2:
4647  case Builtin::BI__sync_fetch_and_add_4:
4648  case Builtin::BI__sync_fetch_and_add_8:
4649  case Builtin::BI__sync_fetch_and_add_16:
4650  BuiltinIndex = 0;
4651  break;
4652 
4653  case Builtin::BI__sync_fetch_and_sub:
4654  case Builtin::BI__sync_fetch_and_sub_1:
4655  case Builtin::BI__sync_fetch_and_sub_2:
4656  case Builtin::BI__sync_fetch_and_sub_4:
4657  case Builtin::BI__sync_fetch_and_sub_8:
4658  case Builtin::BI__sync_fetch_and_sub_16:
4659  BuiltinIndex = 1;
4660  break;
4661 
4662  case Builtin::BI__sync_fetch_and_or:
4663  case Builtin::BI__sync_fetch_and_or_1:
4664  case Builtin::BI__sync_fetch_and_or_2:
4665  case Builtin::BI__sync_fetch_and_or_4:
4666  case Builtin::BI__sync_fetch_and_or_8:
4667  case Builtin::BI__sync_fetch_and_or_16:
4668  BuiltinIndex = 2;
4669  break;
4670 
4671  case Builtin::BI__sync_fetch_and_and:
4672  case Builtin::BI__sync_fetch_and_and_1:
4673  case Builtin::BI__sync_fetch_and_and_2:
4674  case Builtin::BI__sync_fetch_and_and_4:
4675  case Builtin::BI__sync_fetch_and_and_8:
4676  case Builtin::BI__sync_fetch_and_and_16:
4677  BuiltinIndex = 3;
4678  break;
4679 
4680  case Builtin::BI__sync_fetch_and_xor:
4681  case Builtin::BI__sync_fetch_and_xor_1:
4682  case Builtin::BI__sync_fetch_and_xor_2:
4683  case Builtin::BI__sync_fetch_and_xor_4:
4684  case Builtin::BI__sync_fetch_and_xor_8:
4685  case Builtin::BI__sync_fetch_and_xor_16:
4686  BuiltinIndex = 4;
4687  break;
4688 
4689  case Builtin::BI__sync_fetch_and_nand:
4690  case Builtin::BI__sync_fetch_and_nand_1:
4691  case Builtin::BI__sync_fetch_and_nand_2:
4692  case Builtin::BI__sync_fetch_and_nand_4:
4693  case Builtin::BI__sync_fetch_and_nand_8:
4694  case Builtin::BI__sync_fetch_and_nand_16:
4695  BuiltinIndex = 5;
4696  WarnAboutSemanticsChange = true;
4697  break;
4698 
4699  case Builtin::BI__sync_add_and_fetch:
4700  case Builtin::BI__sync_add_and_fetch_1:
4701  case Builtin::BI__sync_add_and_fetch_2:
4702  case Builtin::BI__sync_add_and_fetch_4:
4703  case Builtin::BI__sync_add_and_fetch_8:
4704  case Builtin::BI__sync_add_and_fetch_16:
4705  BuiltinIndex = 6;
4706  break;
4707 
4708  case Builtin::BI__sync_sub_and_fetch:
4709  case Builtin::BI__sync_sub_and_fetch_1:
4710  case Builtin::BI__sync_sub_and_fetch_2:
4711  case Builtin::BI__sync_sub_and_fetch_4:
4712  case Builtin::BI__sync_sub_and_fetch_8:
4713  case Builtin::BI__sync_sub_and_fetch_16:
4714  BuiltinIndex = 7;
4715  break;
4716 
4717  case Builtin::BI__sync_and_and_fetch:
4718  case Builtin::BI__sync_and_and_fetch_1:
4719  case Builtin::BI__sync_and_and_fetch_2:
4720  case Builtin::BI__sync_and_and_fetch_4:
4721  case Builtin::BI__sync_and_and_fetch_8:
4722  case Builtin::BI__sync_and_and_fetch_16:
4723  BuiltinIndex = 8;
4724  break;
4725 
4726  case Builtin::BI__sync_or_and_fetch:
4727  case Builtin::BI__sync_or_and_fetch_1:
4728  case Builtin::BI__sync_or_and_fetch_2:
4729  case Builtin::BI__sync_or_and_fetch_4:
4730  case Builtin::BI__sync_or_and_fetch_8:
4731  case Builtin::BI__sync_or_and_fetch_16:
4732  BuiltinIndex = 9;
4733  break;
4734 
4735  case Builtin::BI__sync_xor_and_fetch:
4736  case Builtin::BI__sync_xor_and_fetch_1:
4737  case Builtin::BI__sync_xor_and_fetch_2:
4738  case Builtin::BI__sync_xor_and_fetch_4:
4739  case Builtin::BI__sync_xor_and_fetch_8:
4740  case Builtin::BI__sync_xor_and_fetch_16:
4741  BuiltinIndex = 10;
4742  break;
4743 
4744  case Builtin::BI__sync_nand_and_fetch:
4745  case Builtin::BI__sync_nand_and_fetch_1:
4746  case Builtin::BI__sync_nand_and_fetch_2:
4747  case Builtin::BI__sync_nand_and_fetch_4:
4748  case Builtin::BI__sync_nand_and_fetch_8:
4749  case Builtin::BI__sync_nand_and_fetch_16:
4750  BuiltinIndex = 11;
4751  WarnAboutSemanticsChange = true;
4752  break;
4753 
4754  case Builtin::BI__sync_val_compare_and_swap:
4755  case Builtin::BI__sync_val_compare_and_swap_1:
4756  case Builtin::BI__sync_val_compare_and_swap_2:
4757  case Builtin::BI__sync_val_compare_and_swap_4:
4758  case Builtin::BI__sync_val_compare_and_swap_8:
4759  case Builtin::BI__sync_val_compare_and_swap_16:
4760  BuiltinIndex = 12;
4761  NumFixed = 2;
4762  break;
4763 
4764  case Builtin::BI__sync_bool_compare_and_swap:
4765  case Builtin::BI__sync_bool_compare_and_swap_1:
4766  case Builtin::BI__sync_bool_compare_and_swap_2:
4767  case Builtin::BI__sync_bool_compare_and_swap_4:
4768  case Builtin::BI__sync_bool_compare_and_swap_8:
4769  case Builtin::BI__sync_bool_compare_and_swap_16:
4770  BuiltinIndex = 13;
4771  NumFixed = 2;
4772  ResultType = Context.BoolTy;
4773  break;
4774 
4775  case Builtin::BI__sync_lock_test_and_set:
4776  case Builtin::BI__sync_lock_test_and_set_1:
4777  case Builtin::BI__sync_lock_test_and_set_2:
4778  case Builtin::BI__sync_lock_test_and_set_4:
4779  case Builtin::BI__sync_lock_test_and_set_8:
4780  case Builtin::BI__sync_lock_test_and_set_16:
4781  BuiltinIndex = 14;
4782  break;
4783 
4784  case Builtin::BI__sync_lock_release:
4785  case Builtin::BI__sync_lock_release_1:
4786  case Builtin::BI__sync_lock_release_2:
4787  case Builtin::BI__sync_lock_release_4:
4788  case Builtin::BI__sync_lock_release_8:
4789  case Builtin::BI__sync_lock_release_16:
4790  BuiltinIndex = 15;
4791  NumFixed = 0;
4792  ResultType = Context.VoidTy;
4793  break;
4794 
4795  case Builtin::BI__sync_swap:
4796  case Builtin::BI__sync_swap_1:
4797  case Builtin::BI__sync_swap_2:
4798  case Builtin::BI__sync_swap_4:
4799  case Builtin::BI__sync_swap_8:
4800  case Builtin::BI__sync_swap_16:
4801  BuiltinIndex = 16;
4802  break;
4803  }
4804 
4805  // Now that we know how many fixed arguments we expect, first check that we
4806  // have at least that many.
4807  if (TheCall->getNumArgs() < 1+NumFixed) {
4808  Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4809  << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
4810  << Callee->getSourceRange();
4811  return ExprError();
4812  }
4813 
4814  Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4815  << Callee->getSourceRange();
4816 
4817  if (WarnAboutSemanticsChange) {
4818  Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4819  << Callee->getSourceRange();
4820  }
4821 
4822  // Get the decl for the concrete builtin from this, we can tell what the
4823  // concrete integer type we should convert to is.
4824  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4825  StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4826  FunctionDecl *NewBuiltinDecl;
4827  if (NewBuiltinID == BuiltinID)
4828  NewBuiltinDecl = FDecl;
4829  else {
4830  // Perform builtin lookup to avoid redeclaring it.
4831  DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4832  LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4833  LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4834  assert(Res.getFoundDecl());
4835  NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4836  if (!NewBuiltinDecl)
4837  return ExprError();
4838  }
4839 
4840  // The first argument --- the pointer --- has a fixed type; we
4841  // deduce the types of the rest of the arguments accordingly. Walk
4842  // the remaining arguments, converting them to the deduced value type.
4843  for (unsigned i = 0; i != NumFixed; ++i) {
4844  ExprResult Arg = TheCall->getArg(i+1);
4845 
4846  // GCC does an implicit conversion to the pointer or integer ValType. This
4847  // can fail in some cases (1i -> int**), check for this error case now.
4848  // Initialize the argument.
4850  ValType, /*consume*/ false);
4851  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4852  if (Arg.isInvalid())
4853  return ExprError();
4854 
4855  // Okay, we have something that *can* be converted to the right type. Check
4856  // to see if there is a potentially weird extension going on here. This can
4857  // happen when you do an atomic operation on something like an char* and
4858  // pass in 42. The 42 gets converted to char. This is even more strange
4859  // for things like 45.123 -> char, etc.
4860  // FIXME: Do this check.
4861  TheCall->setArg(i+1, Arg.get());
4862  }
4863 
4864  // Create a new DeclRefExpr to refer to the new decl.
4865  DeclRefExpr *NewDRE = DeclRefExpr::Create(
4866  Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
4867  /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
4868  DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
4869 
4870  // Set the callee in the CallExpr.
4871  // FIXME: This loses syntactic information.
4872  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4873  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4874  CK_BuiltinFnToFnPtr);
4875  TheCall->setCallee(PromotedCall.get());
4876 
4877  // Change the result type of the call to match the original value type. This
4878  // is arbitrary, but the codegen for these builtins ins design to handle it
4879  // gracefully.
4880  TheCall->setType(ResultType);
4881 
4882  // Prohibit problematic uses of bit-precise integer types with atomic
4883  // builtins. The arguments would have already been converted to the first
4884  // argument's type, so only need to check the first argument.
4885  const auto *BitIntValType = ValType->getAs<BitIntType>();
4886  if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
4887  Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
4888  return ExprError();
4889  }
4890 
4891  return TheCallResult;
4892 }
4893 
4894 ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4895  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4896  DeclRefExpr *DRE =
4897  cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4898  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4899  unsigned BuiltinID = FDecl->getBuiltinID();
4900  assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4901  BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4902  "Unexpected nontemporal load/store builtin!");
4903  bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4904  unsigned numArgs = isStore ? 2 : 1;
4905 
4906  // Ensure that we have the proper number of arguments.
4907  if (checkArgCount(TheCall, numArgs))
4908  return ExprError();
4909 
4910  // Inspect the last argument of the nontemporal builtin. This should always
4911  // be a pointer type, from which we imply the type of the memory access.
4912  // Because it is a pointer type, we don't have to worry about any implicit
4913  // casts here.
4914  Expr *PointerArg = TheCall->getArg(numArgs - 1);
4915  ExprResult PointerArgResult =
4916  DefaultFunctionArrayLvalueConversion(PointerArg);
4917 
4918  if (PointerArgResult.isInvalid())
4919  return ExprError();
4920  PointerArg = PointerArgResult.get();
4921  TheCall->setArg(numArgs - 1, PointerArg);
4922 
4923  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4924  if (!pointerType) {
4925  Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
4926  << PointerArg->getType() << PointerArg->getSourceRange();
4927  return ExprError();
4928  }
4929 
4930  QualType ValType = pointerType->getPointeeType();
4931 
4932  // Strip any qualifiers off ValType.
4933  ValType = ValType.getUnqualifiedType();
4934  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4935  !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4936  !ValType->isVectorType()) {
4937  Diag(DRE->getBeginLoc(),
4938  diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4939  << PointerArg->getType() << PointerArg->getSourceRange();
4940  return ExprError();
4941  }
4942 
4943  if (!isStore) {
4944  TheCall->setType(ValType);
4945  return TheCallResult;
4946  }
4947 
4948  ExprResult ValArg = TheCall->getArg(0);
4950  Context, ValType, /*consume*/ false);
4951  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4952  if (ValArg.isInvalid())
4953  return ExprError();
4954 
4955  TheCall->setArg(0, ValArg.get());
4956  TheCall->setType(Context.VoidTy);
4957  return TheCallResult;
4958 }
4959 
4960 /// CheckObjCString - Checks that the format string argument to the os_log()
4961 /// and os_trace() functions is correct, and converts it to const char *.
4962 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4963  Arg = Arg->IgnoreParenCasts();
4964  auto *Literal = dyn_cast<StringLiteral>(Arg);
4965  if (!Literal) {
4966  if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4967  Literal = ObjcLiteral->getString();
4968  }
4969  }
4970 
4971  if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
4972  return ExprError(
4973  Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
4974  << Arg->getSourceRange());
4975  }
4976 
4977  ExprResult Result(Literal);
4978  QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4979  InitializedEntity Entity =
4980  InitializedEntity::InitializeParameter(Context, ResultTy, false);
4981  Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4982  return Result;
4983 }
4984 
4985 /// Check that the user is calling the appropriate va_start builtin for the
4986 /// target and calling convention.
4987 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4988  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4989  bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
4990  bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
4991  TT.getArch() == llvm::Triple::aarch64_32);
4992  bool IsWindows = TT.isOSWindows();
4993  bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4994  if (IsX64 || IsAArch64) {
4995  CallingConv CC = CC_C;
4996  if (const FunctionDecl *FD = S.getCurFunctionDecl())
4997  CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4998  if (IsMSVAStart) {
4999  // Don't allow this in System V ABI functions.
5000  if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5001  return S.Diag(Fn->getBeginLoc(),
5002  diag::err_ms_va_start_used_in_sysv_function);
5003  } else {
5004  // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5005  // On x64 Windows, don't allow this in System V ABI functions.
5006  // (Yes, that means there's no corresponding way to support variadic
5007  // System V ABI functions on Windows.)
5008  if ((IsWindows && CC == CC_X86_64SysV) ||
5009  (!IsWindows && CC == CC_Win64))
5010  return S.Diag(Fn->getBeginLoc(),
5011  diag::err_va_start_used_in_wrong_abi_function)
5012  << !IsWindows;
5013  }
5014  return false;
5015  }
5016 
5017  if (IsMSVAStart)
5018  return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5019  return false;
5020 }
5021 
5023  ParmVarDecl **LastParam = nullptr) {
5024  // Determine whether the current function, block, or obj-c method is variadic
5025  // and get its parameter list.
5026  bool IsVariadic = false;
5027  ArrayRef<ParmVarDecl *> Params;
5028  DeclContext *Caller = S.CurContext;
5029  if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5030  IsVariadic = Block->isVariadic();
5031  Params = Block->parameters();
5032  } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5033  IsVariadic = FD->isVariadic();
5034  Params = FD->parameters();
5035  } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5036  IsVariadic = MD->isVariadic();
5037  // FIXME: This isn't correct for methods (results in bogus warning).
5038  Params = MD->parameters();
5039  } else if (isa<CapturedDecl>(Caller)) {
5040  // We don't support va_start in a CapturedDecl.
5041  S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5042  return true;
5043  } else {
5044  // This must be some other declcontext that parses exprs.
5045  S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5046  return true;
5047  }
5048 
5049  if (!IsVariadic) {
5050  S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5051  return true;
5052  }
5053 
5054  if (LastParam)
5055  *LastParam = Params.empty() ? nullptr : Params.back();
5056 
5057  return false;
5058 }
5059 
5060 bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5061  Expr *Fn = TheCall->getCallee();
5062 
5063  if (checkVAStartABI(*this, BuiltinID, Fn))
5064  return true;
5065 
5066  // In C23 mode, va_start only needs one argument. However, the builtin still
5067  // requires two arguments (which matches the behavior of the GCC builtin),
5068  // <stdarg.h> passes `0` as the second argument in C23 mode.
5069  if (checkArgCount(TheCall, 2))
5070  return true;
5071 
5072  // Type-check the first argument normally.
5073  if (checkBuiltinArgument(*this, TheCall, 0))
5074  return true;
5075 
5076  // Check that the current function is variadic, and get its last parameter.
5077  ParmVarDecl *LastParam;
5078  if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5079  return true;
5080 
5081  // Verify that the second argument to the builtin is the last argument of the
5082  // current function or method. In C23 mode, if the second argument is an
5083  // integer constant expression with value 0, then we don't bother with this
5084  // check.
5085  bool SecondArgIsLastNamedArgument = false;
5086  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5087  if (std::optional<llvm::APSInt> Val =
5088  TheCall->getArg(1)->getIntegerConstantExpr(Context);
5089  Val && LangOpts.C23 && *Val == 0)
5090  return false;
5091 
5092  // These are valid if SecondArgIsLastNamedArgument is false after the next
5093  // block.
5094  QualType Type;
5095  SourceLocation ParamLoc;
5096  bool IsCRegister = false;
5097 
5098  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5099  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5100  SecondArgIsLastNamedArgument = PV == LastParam;
5101 
5102  Type = PV->getType();
5103  ParamLoc = PV->getLocation();
5104  IsCRegister =
5105  PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5106  }
5107  }
5108 
5109  if (!SecondArgIsLastNamedArgument)
5110  Diag(TheCall->getArg(1)->getBeginLoc(),
5111  diag::warn_second_arg_of_va_start_not_last_named_param);
5112  else if (IsCRegister || Type->isReferenceType() ||
5114  // Promotable integers are UB, but enumerations need a bit of
5115  // extra checking to see what their promotable type actually is.
5116  if (!Context.isPromotableIntegerType(Type))
5117  return false;
5118  if (!Type->isEnumeralType())
5119  return true;
5120  const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5121  return !(ED &&
5122  Context.typesAreCompatible(ED->getPromotionType(), Type));
5123  }()) {
5124  unsigned Reason = 0;
5125  if (Type->isReferenceType()) Reason = 1;
5126  else if (IsCRegister) Reason = 2;
5127  Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5128  Diag(ParamLoc, diag::note_parameter_type) << Type;
5129  }
5130 
5131  return false;
5132 }
5133 
5134 bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5135  auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5136  const LangOptions &LO = getLangOpts();
5137 
5138  if (LO.CPlusPlus)
5139  return Arg->getType()
5140  .getCanonicalType()
5141  .getTypePtr()
5142  ->getPointeeType()
5143  .withoutLocalFastQualifiers() == Context.CharTy;
5144 
5145  // In C, allow aliasing through `char *`, this is required for AArch64 at
5146  // least.
5147  return true;
5148  };
5149 
5150  // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5151  // const char *named_addr);
5152 
5153  Expr *Func = Call->getCallee();
5154 
5155  if (Call->getNumArgs() < 3)
5156  return Diag(Call->getEndLoc(),
5157  diag::err_typecheck_call_too_few_args_at_least)
5158  << 0 /*function call*/ << 3 << Call->getNumArgs()
5159  << /*is non object*/ 0;
5160 
5161  // Type-check the first argument normally.
5162  if (checkBuiltinArgument(*this, Call, 0))
5163  return true;
5164 
5165  // Check that the current function is variadic.
5166  if (checkVAStartIsInVariadicFunction(*this, Func))
5167  return true;
5168 
5169  // __va_start on Windows does not validate the parameter qualifiers
5170 
5171  const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5172  const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5173 
5174  const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5175  const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5176 
5177  const QualType &ConstCharPtrTy =
5178  Context.getPointerType(Context.CharTy.withConst());
5179  if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5180  Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5181  << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5182  << 0 /* qualifier difference */
5183  << 3 /* parameter mismatch */
5184  << 2 << Arg1->getType() << ConstCharPtrTy;
5185 
5186  const QualType SizeTy = Context.getSizeType();
5187  if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5188  Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5189  << Arg2->getType() << SizeTy << 1 /* different class */
5190  << 0 /* qualifier difference */
5191  << 3 /* parameter mismatch */
5192  << 3 << Arg2->getType() << SizeTy;
5193 
5194  return false;
5195 }
5196 
5197 bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5198  if (checkArgCount(TheCall, 2))
5199  return true;
5200 
5201  if (BuiltinID == Builtin::BI__builtin_isunordered &&
5202  TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5203  Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5204  << 1 << 0 << TheCall->getSourceRange();
5205 
5206  ExprResult OrigArg0 = TheCall->getArg(0);
5207  ExprResult OrigArg1 = TheCall->getArg(1);
5208 
5209  // Do standard promotions between the two arguments, returning their common
5210  // type.
5211  QualType Res = UsualArithmeticConversions(
5212  OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5213  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5214  return true;
5215 
5216  // Make sure any conversions are pushed back into the call; this is
5217  // type safe since unordered compare builtins are declared as "_Bool
5218  // foo(...)".
5219  TheCall->setArg(0, OrigArg0.get());
5220  TheCall->setArg(1, OrigArg1.get());
5221 
5222  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5223  return false;
5224 
5225  // If the common type isn't a real floating type, then the arguments were
5226  // invalid for this operation.
5227  if (Res.isNull() || !Res->isRealFloatingType())
5228  return Diag(OrigArg0.get()->getBeginLoc(),
5229  diag::err_typecheck_call_invalid_ordered_compare)
5230  << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5231  << SourceRange(OrigArg0.get()->getBeginLoc(),
5232  OrigArg1.get()->getEndLoc());
5233 
5234  return false;
5235 }
5236 
5237 bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5238  unsigned BuiltinID) {
5239  if (checkArgCount(TheCall, NumArgs))
5240  return true;
5241 
5242  FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5243  if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5244  BuiltinID == Builtin::BI__builtin_isinf ||
5245  BuiltinID == Builtin::BI__builtin_isinf_sign))
5246  Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5247  << 0 << 0 << TheCall->getSourceRange();
5248 
5249  if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5250  BuiltinID == Builtin::BI__builtin_isunordered))
5251  Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5252  << 1 << 0 << TheCall->getSourceRange();
5253 
5254  bool IsFPClass = NumArgs == 2;
5255 
5256  // Find out position of floating-point argument.
5257  unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5258 
5259  // We can count on all parameters preceding the floating-point just being int.
5260  // Try all of those.
5261  for (unsigned i = 0; i < FPArgNo; ++i) {
5262  Expr *Arg = TheCall->getArg(i);
5263 
5264  if (Arg->isTypeDependent())
5265  return false;
5266 
5267  ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5268 
5269  if (Res.isInvalid())
5270  return true;
5271  TheCall->setArg(i, Res.get());
5272  }
5273 
5274  Expr *OrigArg = TheCall->getArg(FPArgNo);
5275 
5276  if (OrigArg->isTypeDependent())
5277  return false;
5278 
5279  // Usual Unary Conversions will convert half to float, which we want for
5280  // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5281  // type how it is, but do normal L->Rvalue conversions.
5283  OrigArg = UsualUnaryConversions(OrigArg).get();
5284  else
5285  OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5286  TheCall->setArg(FPArgNo, OrigArg);
5287 
5288  QualType VectorResultTy;
5289  QualType ElementTy = OrigArg->getType();
5290  // TODO: When all classification function are implemented with is_fpclass,
5291  // vector argument can be supported in all of them.
5292  if (ElementTy->isVectorType() && IsFPClass) {
5293  VectorResultTy = GetSignedVectorType(ElementTy);
5294  ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5295  }
5296 
5297  // This operation requires a non-_Complex floating-point number.
5298  if (!ElementTy->isRealFloatingType())
5299  return Diag(OrigArg->getBeginLoc(),
5300  diag::err_typecheck_call_invalid_unary_fp)
5301  << OrigArg->getType() << OrigArg->getSourceRange();
5302 
5303  // __builtin_isfpclass has integer parameter that specify test mask. It is
5304  // passed in (...), so it should be analyzed completely here.
5305  if (IsFPClass)
5306  if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5307  return true;
5308 
5309  // TODO: enable this code to all classification functions.
5310  if (IsFPClass) {
5311  QualType ResultTy;
5312  if (!VectorResultTy.isNull())
5313  ResultTy = VectorResultTy;
5314  else
5315  ResultTy = Context.IntTy;
5316  TheCall->setType(ResultTy);
5317  }
5318 
5319  return false;
5320 }
5321 
5322 bool Sema::BuiltinComplex(CallExpr *TheCall) {
5323  if (checkArgCount(TheCall, 2))
5324  return true;
5325 
5326  bool Dependent = false;
5327  for (unsigned I = 0; I != 2; ++I) {
5328  Expr *Arg = TheCall->getArg(I);
5329  QualType T = Arg->getType();
5330  if (T->isDependentType()) {
5331  Dependent = true;
5332  continue;
5333  }
5334 
5335  // Despite supporting _Complex int, GCC requires a real floating point type
5336  // for the operands of __builtin_complex.
5337  if (!T->isRealFloatingType()) {
5338  return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5339  << Arg->getType() << Arg->getSourceRange();
5340  }
5341 
5342  ExprResult Converted = DefaultLvalueConversion(Arg);
5343  if (Converted.isInvalid())
5344  return true;
5345  TheCall->setArg(I, Converted.get());
5346  }
5347 
5348  if (Dependent) {
5349  TheCall->setType(Context.DependentTy);
5350  return false;
5351  }
5352 
5353  Expr *Real = TheCall->getArg(0);
5354  Expr *Imag = TheCall->getArg(1);
5355  if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5356  return Diag(Real->getBeginLoc(),
5357  diag::err_typecheck_call_different_arg_types)
5358  << Real->getType() << Imag->getType()
5359  << Real->getSourceRange() << Imag->getSourceRange();
5360  }
5361 
5362  // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
5363  // don't allow this builtin to form those types either.
5364  // FIXME: Should we allow these types?
5365  if (Real->getType()->isFloat16Type())
5366  return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5367  << "_Float16";
5368  if (Real->getType()->isHalfType())
5369  return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5370  << "half";
5371 
5372  TheCall->setType(Context.getComplexType(Real->getType()));
5373  return false;
5374 }
5375 
5376 /// BuiltinShuffleVector - Handle __builtin_shufflevector.
5377 // This is declared to take (...), so we have to check everything.
5379  if (TheCall->getNumArgs() < 2)
5380  return ExprError(Diag(TheCall->getEndLoc(),
5381  diag::err_typecheck_call_too_few_args_at_least)
5382  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5383  << /*is non object*/ 0 << TheCall->getSourceRange());
5384 
5385  // Determine which of the following types of shufflevector we're checking:
5386  // 1) unary, vector mask: (lhs, mask)
5387  // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5388  QualType resType = TheCall->getArg(0)->getType();
5389  unsigned numElements = 0;
5390 
5391  if (!TheCall->getArg(0)->isTypeDependent() &&
5392  !TheCall->getArg(1)->isTypeDependent()) {
5393  QualType LHSType = TheCall->getArg(0)->getType();
5394  QualType RHSType = TheCall->getArg(1)->getType();
5395 
5396  if (!LHSType->isVectorType() || !RHSType->isVectorType())
5397  return ExprError(
5398  Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5399  << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
5400  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5401  TheCall->getArg(1)->getEndLoc()));
5402 
5403  numElements = LHSType->castAs<VectorType>()->getNumElements();
5404  unsigned numResElements = TheCall->getNumArgs() - 2;
5405 
5406  // Check to see if we have a call with 2 vector arguments, the unary shuffle
5407  // with mask. If so, verify that RHS is an integer vector type with the
5408  // same number of elts as lhs.
5409  if (TheCall->getNumArgs() == 2) {
5410  if (!RHSType->hasIntegerRepresentation() ||
5411  RHSType->castAs<VectorType>()->getNumElements() != numElements)
5412  return ExprError(Diag(TheCall->getBeginLoc(),
5413  diag::err_vec_builtin_incompatible_vector)
5414  << TheCall->getDirectCallee()
5415  << /*isMorethantwoArgs*/ false
5416  << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5417  TheCall->getArg(1)->getEndLoc()));
5418  } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5419  return ExprError(Diag(TheCall->getBeginLoc(),
5420  diag::err_vec_builtin_incompatible_vector)
5421  << TheCall->getDirectCallee()
5422  << /*isMorethantwoArgs*/ false
5423  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5424  TheCall->getArg(1)->getEndLoc()));
5425  } else if (numElements != numResElements) {
5426  QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5427  resType =
5428  Context.getVectorType(eltType, numResElements, VectorKind::Generic);
5429  }
5430  }
5431 
5432  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5433  if (TheCall->getArg(i)->isTypeDependent() ||
5434  TheCall->getArg(i)->isValueDependent())
5435  continue;
5436 
5437  std::optional<llvm::APSInt> Result;
5438  if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
5439  return ExprError(Diag(TheCall->getBeginLoc(),
5440  diag::err_shufflevector_nonconstant_argument)
5441  << TheCall->getArg(i)->getSourceRange());
5442 
5443  // Allow -1 which will be translated to undef in the IR.
5444  if (Result->isSigned() && Result->isAllOnes())
5445  continue;
5446 
5447  if (Result->getActiveBits() > 64 ||
5448  Result->getZExtValue() >= numElements * 2)
5449  return ExprError(Diag(TheCall->getBeginLoc(),
5450  diag::err_shufflevector_argument_too_large)
5451  << TheCall->getArg(i)->getSourceRange());
5452  }
5453 
5454  SmallVector<Expr*, 32> exprs;
5455 
5456  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5457  exprs.push_back(TheCall->getArg(i));
5458  TheCall->setArg(i, nullptr);
5459  }
5460 
5461  return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5462  TheCall->getCallee()->getBeginLoc(),
5463  TheCall->getRParenLoc());
5464 }
5465 
5467  SourceLocation BuiltinLoc,
5468  SourceLocation RParenLoc) {
5471  QualType DstTy = TInfo->getType();
5472  QualType SrcTy = E->getType();
5473 
5474  if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5475  return ExprError(Diag(BuiltinLoc,
5476  diag::err_convertvector_non_vector)
5477  << E->getSourceRange());
5478  if (!DstTy->isVectorType() && !DstTy->isDependentType())
5479  return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5480  << "second"
5481  << "__builtin_convertvector");
5482 
5483  if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5484  unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5485  unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5486  if (SrcElts != DstElts)
5487  return ExprError(Diag(BuiltinLoc,
5488  diag::err_convertvector_incompatible_vector)
5489  << E->getSourceRange());
5490  }
5491 
5492  return new (Context) class ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
5493  BuiltinLoc, RParenLoc);
5494 }
5495 
5496 bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5497  unsigned NumArgs = TheCall->getNumArgs();
5498 
5499  if (checkArgCountAtMost(TheCall, 3))
5500  return true;
5501 
5502  // Argument 0 is checked for us and the remaining arguments must be
5503  // constant integers.
5504  for (unsigned i = 1; i != NumArgs; ++i)
5505  if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5506  return true;
5507 
5508  return false;
5509 }
5510 
5511 bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5513  return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5514  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5515  if (checkArgCount(TheCall, 1))
5516  return true;
5517  Expr *Arg = TheCall->getArg(0);
5518  if (Arg->isInstantiationDependent())
5519  return false;
5520 
5521  QualType ArgTy = Arg->getType();
5522  if (!ArgTy->hasFloatingRepresentation())
5523  return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5524  << ArgTy;
5525  if (Arg->isLValue()) {
5526  ExprResult FirstArg = DefaultLvalueConversion(Arg);
5527  TheCall->setArg(0, FirstArg.get());
5528  }
5529  TheCall->setType(TheCall->getArg(0)->getType());
5530  return false;
5531 }
5532 
5533 bool Sema::BuiltinAssume(CallExpr *TheCall) {
5534  Expr *Arg = TheCall->getArg(0);
5535  if (Arg->isInstantiationDependent()) return false;
5536 
5537  if (Arg->HasSideEffects(Context))
5538  Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5539  << Arg->getSourceRange()
5540  << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5541 
5542  return false;
5543 }
5544 
5545 bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5546  // The alignment must be a constant integer.
5547  Expr *Arg = TheCall->getArg(1);
5548 
5549  // We can't check the value of a dependent argument.
5550  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5551  if (const auto *UE =
5552  dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5553  if (UE->getKind() == UETT_AlignOf ||
5554  UE->getKind() == UETT_PreferredAlignOf)
5555  Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5556  << Arg->getSourceRange();
5557 
5558  llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5559 
5560  if (!Result.isPowerOf2())
5561  return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5562  << Arg->getSourceRange();
5563 
5564  if (Result < Context.getCharWidth())
5565  return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5566  << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5567 
5568  if (Result > std::numeric_limits<int32_t>::max())
5569  return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5571  }
5572 
5573  return false;
5574 }
5575 
5576 bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5577  if (checkArgCountRange(TheCall, 2, 3))
5578  return true;
5579 
5580  unsigned NumArgs = TheCall->getNumArgs();
5581  Expr *FirstArg = TheCall->getArg(0);
5582 
5583  {
5584  ExprResult FirstArgResult =
5585  DefaultFunctionArrayLvalueConversion(FirstArg);
5586  if (checkBuiltinArgument(*this, TheCall, 0))
5587  return true;
5588  /// In-place updation of FirstArg by checkBuiltinArgument is ignored.
5589  TheCall->setArg(0, FirstArgResult.get());
5590  }
5591 
5592  // The alignment must be a constant integer.
5593  Expr *SecondArg = TheCall->getArg(1);
5594 
5595  // We can't check the value of a dependent argument.
5596  if (!SecondArg->isValueDependent()) {
5597  llvm::APSInt Result;
5598  if (BuiltinConstantArg(TheCall, 1, Result))
5599  return true;
5600 
5601  if (!Result.isPowerOf2())
5602  return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5603  << SecondArg->getSourceRange();
5604 
5605  if (Result > Sema::MaximumAlignment)
5606  Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5607  << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5608  }
5609 
5610  if (NumArgs > 2) {
5611  Expr *ThirdArg = TheCall->getArg(2);
5612  if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5613  return true;
5614  TheCall->setArg(2, ThirdArg);
5615  }
5616 
5617  return false;
5618 }
5619 
5620 bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5621  unsigned BuiltinID =
5622  cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5623  bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5624 
5625  unsigned NumArgs = TheCall->getNumArgs();
5626  unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5627  if (NumArgs < NumRequiredArgs) {
5628  return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5629  << 0 /* function call */ << NumRequiredArgs << NumArgs
5630  << /*is non object*/ 0 << TheCall->getSourceRange();
5631  }
5632  if (checkArgCountAtMost(TheCall, NumRequiredArgs + 0xff))
5633  return true;
5634  unsigned i = 0;
5635 
5636  // For formatting call, check buffer arg.
5637  if (!IsSizeCall) {
5638  ExprResult Arg(TheCall->getArg(i));
5640  Context, Context.VoidPtrTy, false);
5641  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5642  if (Arg.isInvalid())
5643  return true;
5644  TheCall->setArg(i, Arg.get());
5645  i++;
5646  }
5647 
5648  // Check string literal arg.
5649  unsigned FormatIdx = i;
5650  {
5651  ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5652  if (Arg.isInvalid())
5653  return true;
5654  TheCall->setArg(i, Arg.get());
5655  i++;
5656  }
5657 
5658  // Make sure variadic args are scalar.
5659  unsigned FirstDataArg = i;
5660  while (i < NumArgs) {
5661  ExprResult Arg = DefaultVariadicArgumentPromotion(
5662  TheCall->getArg(i), VariadicFunction, nullptr);
5663  if (Arg.isInvalid())
5664  return true;
5665  CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5666  if (ArgSize.getQuantity() >= 0x100) {
5667  return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5668  << i << (int)ArgSize.getQuantity() << 0xff
5669  << TheCall->getSourceRange();
5670  }
5671  TheCall->setArg(i, Arg.get());
5672  i++;
5673  }
5674 
5675  // Check formatting specifiers. NOTE: We're only doing this for the non-size
5676  // call to avoid duplicate diagnostics.
5677  if (!IsSizeCall) {
5678  llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5679  ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5680  bool Success = CheckFormatArguments(
5681  Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,
5682  VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5683  CheckedVarArgs);
5684  if (!Success)
5685  return true;
5686  }
5687 
5688  if (IsSizeCall) {
5689  TheCall->setType(Context.getSizeType());
5690  } else {
5691  TheCall->setType(Context.VoidPtrTy);
5692  }
5693  return false;
5694 }
5695 
5696 bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5697  llvm::APSInt &Result) {
5698  Expr *Arg = TheCall->getArg(ArgNum);
5699  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5700  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5701 
5702  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5703 
5704  std::optional<llvm::APSInt> R;
5705  if (!(R = Arg->getIntegerConstantExpr(Context)))
5706  return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5707  << FDecl->getDeclName() << Arg->getSourceRange();
5708  Result = *R;
5709  return false;
5710 }
5711 
5712 bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
5713  int High, bool RangeIsError) {
5714  if (isConstantEvaluatedContext())
5715  return false;
5716  llvm::APSInt Result;
5717 
5718  // We can't check the value of a dependent argument.
5719  Expr *Arg = TheCall->getArg(ArgNum);
5720  if (Arg->isTypeDependent() || Arg->isValueDependent())
5721  return false;
5722 
5723  // Check constant-ness first.
5724  if (BuiltinConstantArg(TheCall, ArgNum, Result))
5725  return true;
5726 
5727  if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5728  if (RangeIsError)
5729  return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5730  << toString(Result, 10) << Low << High << Arg->getSourceRange();
5731  else
5732  // Defer the warning until we know if the code will be emitted so that
5733  // dead code can ignore this.
5734  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5735  PDiag(diag::warn_argument_invalid_range)
5736  << toString(Result, 10) << Low << High
5737  << Arg->getSourceRange());
5738  }
5739 
5740  return false;
5741 }
5742 
5743 bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5744  unsigned Num) {
5745  llvm::APSInt Result;
5746 
5747  // We can't check the value of a dependent argument.
5748  Expr *Arg = TheCall->getArg(ArgNum);
5749  if (Arg->isTypeDependent() || Arg->isValueDependent())
5750  return false;
5751 
5752  // Check constant-ness first.
5753  if (BuiltinConstantArg(TheCall, ArgNum, Result))
5754  return true;
5755 
5756  if (Result.getSExtValue() % Num != 0)
5757  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5758  << Num << Arg->getSourceRange();
5759 
5760  return false;
5761 }
5762 
5763 bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5764  llvm::APSInt Result;
5765 
5766  // We can't check the value of a dependent argument.
5767  Expr *Arg = TheCall->getArg(ArgNum);
5768  if (Arg->isTypeDependent() || Arg->isValueDependent())
5769  return false;
5770 
5771  // Check constant-ness first.
5772  if (BuiltinConstantArg(TheCall, ArgNum, Result))
5773  return true;
5774 
5775  // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5776  // and only if x is a power of 2.
5777  if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5778  return false;
5779 
5780  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5781  << Arg->getSourceRange();
5782 }
5783 
5785  if (Value.isNegative())
5786  return false;
5787 
5788  // Check if it's a shifted byte, by shifting it down
5789  while (true) {
5790  // If the value fits in the bottom byte, the check passes.
5791  if (Value < 0x100)
5792  return true;
5793 
5794  // Otherwise, if the value has _any_ bits in the bottom byte, the check
5795  // fails.
5796  if ((Value & 0xFF) != 0)
5797  return false;
5798 
5799  // If the bottom 8 bits are all 0, but something above that is nonzero,
5800  // then shifting the value right by 8 bits won't affect whether it's a
5801  // shifted byte or not. So do that, and go round again.
5802  Value >>= 8;
5803  }
5804 }
5805 
5807  unsigned ArgBits) {
5808  llvm::APSInt Result;
5809 
5810  // We can't check the value of a dependent argument.
5811  Expr *Arg = TheCall->getArg(ArgNum);
5812  if (Arg->isTypeDependent() || Arg->isValueDependent())
5813  return false;
5814 
5815  // Check constant-ness first.
5816  if (BuiltinConstantArg(TheCall, ArgNum, Result))
5817  return true;
5818 
5819  // Truncate to the given size.
5820  Result = Result.getLoBits(ArgBits);
5821  Result.setIsUnsigned(true);
5822 
5823  if (IsShiftedByte(Result))
5824  return false;
5825 
5826  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
5827  << Arg->getSourceRange();
5828 }
5829 
5831  unsigned ArgBits) {
5832  llvm::APSInt Result;
5833 
5834  // We can't check the value of a dependent argument.
5835  Expr *Arg = TheCall->getArg(ArgNum);
5836  if (Arg->isTypeDependent() || Arg->isValueDependent())
5837  return false;
5838 
5839  // Check constant-ness first.
5840  if (BuiltinConstantArg(TheCall, ArgNum, Result))
5841  return true;
5842 
5843  // Truncate to the given size.
5844  Result = Result.getLoBits(ArgBits);
5845  Result.setIsUnsigned(true);
5846 
5847  // Check to see if it's in either of the required forms.
5848  if (IsShiftedByte(Result) ||
5849  (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
5850  return false;
5851 
5852  return Diag(TheCall->getBeginLoc(),
5853  diag::err_argument_not_shifted_byte_or_xxff)
5854  << Arg->getSourceRange();
5855 }
5856 
5857 bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
5858  if (!Context.getTargetInfo().hasSjLjLowering())
5859  return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
5860  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5861 
5862  Expr *Arg = TheCall->getArg(1);
5863  llvm::APSInt Result;
5864 
5865  // TODO: This is less than ideal. Overload this to take a value.
5866  if (BuiltinConstantArg(TheCall, 1, Result))
5867  return true;
5868 
5869  if (Result != 1)
5870  return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
5871  << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
5872 
5873  return false;
5874 }
5875 
5876 bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
5877  if (!Context.getTargetInfo().hasSjLjLowering())
5878  return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
5879  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5880  return false;
5881 }
5882 
5883 namespace {
5884 
5885 class UncoveredArgHandler {
5886  enum { Unknown = -1, AllCovered = -2 };
5887 
5888  signed FirstUncoveredArg = Unknown;
5889  SmallVector<const Expr *, 4> DiagnosticExprs;
5890 
5891 public:
5892  UncoveredArgHandler() = default;
5893 
5894  bool hasUncoveredArg() const {
5895  return (FirstUncoveredArg >= 0);
5896  }
5897 
5898  unsigned getUncoveredArg() const {
5899  assert(hasUncoveredArg() && "no uncovered argument");
5900  return FirstUncoveredArg;
5901  }
5902 
5903  void setAllCovered() {
5904  // A string has been found with all arguments covered, so clear out
5905  // the diagnostics.
5906  DiagnosticExprs.clear();
5907  FirstUncoveredArg = AllCovered;
5908  }
5909 
5910  void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5911  assert(NewFirstUncoveredArg >= 0 && "Outside range");
5912 
5913  // Don't update if a previous string covers all arguments.
5914  if (FirstUncoveredArg == AllCovered)
5915  return;
5916 
5917  // UncoveredArgHandler tracks the highest uncovered argument index
5918  // and with it all the strings that match this index.
5919  if (NewFirstUncoveredArg == FirstUncoveredArg)
5920  DiagnosticExprs.push_back(StrExpr);
5921  else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5922  DiagnosticExprs.clear();
5923  DiagnosticExprs.push_back(StrExpr);
5924  FirstUncoveredArg = NewFirstUncoveredArg;
5925  }
5926  }
5927 
5928  void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5929 };
5930 
5931 enum StringLiteralCheckType {
5932  SLCT_NotALiteral,
5933  SLCT_UncheckedLiteral,
5934  SLCT_CheckedLiteral
5935 };
5936 
5937 } // namespace
5938 
5940  BinaryOperatorKind BinOpKind,
5941  bool AddendIsRight) {
5942  unsigned BitWidth = Offset.getBitWidth();
5943  unsigned AddendBitWidth = Addend.getBitWidth();
5944  // There might be negative interim results.
5945  if (Addend.isUnsigned()) {
5946  Addend = Addend.zext(++AddendBitWidth);
5947  Addend.setIsSigned(true);
5948  }
5949  // Adjust the bit width of the APSInts.
5950  if (AddendBitWidth > BitWidth) {
5951  Offset = Offset.sext(AddendBitWidth);
5952  BitWidth = AddendBitWidth;
5953  } else if (BitWidth > AddendBitWidth) {
5954  Addend = Addend.sext(BitWidth);
5955  }
5956 
5957  bool Ov = false;
5958  llvm::APSInt ResOffset = Offset;
5959  if (BinOpKind == BO_Add)
5960  ResOffset = Offset.sadd_ov(Addend, Ov);
5961  else {
5962  assert(AddendIsRight && BinOpKind == BO_Sub &&
5963  "operator must be add or sub with addend on the right");
5964  ResOffset = Offset.ssub_ov(Addend, Ov);
5965  }
5966 
5967  // We add an offset to a pointer here so we should support an offset as big as
5968  // possible.
5969  if (Ov) {
5970  assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5971  "index (intermediate) result too big");
5972  Offset = Offset.sext(2 * BitWidth);
5973  sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5974  return;
5975  }
5976 
5977  Offset = ResOffset;
5978 }
5979 
5980 namespace {
5981 
5982 // This is a wrapper class around StringLiteral to support offsetted string
5983 // literals as format strings. It takes the offset into account when returning
5984 // the string and its length or the source locations to display notes correctly.
5985 class FormatStringLiteral {
5986  const StringLiteral *FExpr;
5987  int64_t Offset;
5988 
5989  public:
5990  FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5991  : FExpr(fexpr), Offset(Offset) {}
5992 
5993  StringRef getString() const {
5994  return FExpr->getString().drop_front(Offset);
5995  }
5996 
5997  unsigned getByteLength() const {
5998  return FExpr->getByteLength() - getCharByteWidth() * Offset;
5999  }
6000 
6001  unsigned getLength() const { return FExpr->getLength() - Offset; }
6002  unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6003 
6004  StringLiteralKind getKind() const { return FExpr->getKind(); }
6005 
6006  QualType getType() const { return FExpr->getType(); }
6007 
6008  bool isAscii() const { return FExpr->isOrdinary(); }
6009  bool isWide() const { return FExpr->isWide(); }
6010  bool isUTF8() const { return FExpr->isUTF8(); }
6011  bool isUTF16() const { return FExpr->isUTF16(); }
6012  bool isUTF32() const { return FExpr->isUTF32(); }
6013  bool isPascal() const { return FExpr->isPascal(); }
6014 
6015  SourceLocation getLocationOfByte(
6016  unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6017  const TargetInfo &Target, unsigned *StartToken = nullptr,
6018  unsigned *StartTokenByteOffset = nullptr) const {
6019  return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6020  StartToken, StartTokenByteOffset);
6021  }
6022 
6023  SourceLocation getBeginLoc() const LLVM_READONLY {
6024  return FExpr->getBeginLoc().getLocWithOffset(Offset);
6025  }
6026 
6027  SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6028 };
6029 
6030 } // namespace
6031 
6032 static void CheckFormatString(
6033  Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
6035  unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
6036  bool inFunctionCall, Sema::VariadicCallType CallType,
6037  llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6038  bool IgnoreStringsWithoutSpecifiers);
6039 
6040 // Determine if an expression is a string literal or constant string.
6041 // If this function returns false on the arguments to a function expecting a
6042 // format string, we will usually need to emit a warning.
6043 // True string literals are then checked by CheckFormatString.
6044 static StringLiteralCheckType
6046  Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6047  unsigned firstDataArg, Sema::FormatStringType Type,
6048  Sema::VariadicCallType CallType, bool InFunctionCall,
6049  llvm::SmallBitVector &CheckedVarArgs,
6050  UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6051  bool IgnoreStringsWithoutSpecifiers = false) {
6053  return SLCT_NotALiteral;
6054 tryAgain:
6055  assert(Offset.isSigned() && "invalid offset");
6056 
6057  if (E->isTypeDependent() || E->isValueDependent())
6058  return SLCT_NotALiteral;
6059 
6060  E = E->IgnoreParenCasts();
6061 
6063  // Technically -Wformat-nonliteral does not warn about this case.
6064  // The behavior of printf and friends in this case is implementation
6065  // dependent. Ideally if the format string cannot be null then
6066  // it should have a 'nonnull' attribute in the function prototype.
6067  return SLCT_UncheckedLiteral;
6068 
6069  switch (E->getStmtClass()) {
6070  case Stmt::InitListExprClass:
6071  // Handle expressions like {"foobar"}.
6072  if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6073  return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
6074  Type, CallType, /*InFunctionCall*/ false,
6075  CheckedVarArgs, UncoveredArg, Offset,
6076  IgnoreStringsWithoutSpecifiers);
6077  }
6078  return SLCT_NotALiteral;
6079  case Stmt::BinaryConditionalOperatorClass:
6080  case Stmt::ConditionalOperatorClass: {
6081  // The expression is a literal if both sub-expressions were, and it was
6082  // completely checked only if both sub-expressions were checked.
6083  const AbstractConditionalOperator *C =
6084  cast<AbstractConditionalOperator>(E);
6085 
6086  // Determine whether it is necessary to check both sub-expressions, for
6087  // example, because the condition expression is a constant that can be
6088  // evaluated at compile time.
6089  bool CheckLeft = true, CheckRight = true;
6090 
6091  bool Cond;
6092  if (C->getCond()->EvaluateAsBooleanCondition(
6093  Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
6094  if (Cond)
6095  CheckRight = false;
6096  else
6097  CheckLeft = false;
6098  }
6099 
6100  // We need to maintain the offsets for the right and the left hand side
6101  // separately to check if every possible indexed expression is a valid
6102  // string literal. They might have different offsets for different string
6103  // literals in the end.
6104  StringLiteralCheckType Left;
6105  if (!CheckLeft)
6106  Left = SLCT_UncheckedLiteral;
6107  else {
6108  Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
6109  firstDataArg, Type, CallType, InFunctionCall,
6110  CheckedVarArgs, UncoveredArg, Offset,
6111  IgnoreStringsWithoutSpecifiers);
6112  if (Left == SLCT_NotALiteral || !CheckRight) {
6113  return Left;
6114  }
6115  }
6116 
6117  StringLiteralCheckType Right = checkFormatStringExpr(
6118  S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
6119  CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6120  IgnoreStringsWithoutSpecifiers);
6121 
6122  return (CheckLeft && Left < Right) ? Left : Right;
6123  }
6124 
6125  case Stmt::ImplicitCastExprClass:
6126  E = cast<ImplicitCastExpr>(E)->getSubExpr();
6127  goto tryAgain;
6128 
6129  case Stmt::OpaqueValueExprClass:
6130  if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6131  E = src;
6132  goto tryAgain;
6133  }
6134  return SLCT_NotALiteral;
6135 
6136  case Stmt::PredefinedExprClass:
6137  // While __func__, etc., are technically not string literals, they
6138  // cannot contain format specifiers and thus are not a security
6139  // liability.
6140  return SLCT_UncheckedLiteral;
6141 
6142  case Stmt::DeclRefExprClass: {
6143  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6144 
6145  // As an exception, do not flag errors for variables binding to
6146  // const string literals.
6147  if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6148  bool isConstant = false;
6149  QualType T = DR->getType();
6150 
6151  if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6152  isConstant = AT->getElementType().isConstant(S.Context);
6153  } else if (const PointerType *PT = T->getAs<PointerType>()) {
6154  isConstant = T.isConstant(S.Context) &&
6156  } else if (T->isObjCObjectPointerType()) {
6157  // In ObjC, there is usually no "const ObjectPointer" type,
6158  // so don't check if the pointee type is constant.
6159  isConstant = T.isConstant(S.Context);
6160  }
6161 
6162  if (isConstant) {
6163  if (const Expr *Init = VD->getAnyInitializer()) {
6164  // Look through initializers like const char c[] = { "foo" }
6165  if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6166  if (InitList->isStringLiteralInit())
6167  Init = InitList->getInit(0)->IgnoreParenImpCasts();
6168  }
6169  return checkFormatStringExpr(
6170  S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,
6171  /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6172  }
6173  }
6174 
6175  // When the format argument is an argument of this function, and this
6176  // function also has the format attribute, there are several interactions
6177  // for which there shouldn't be a warning. For instance, when calling
6178  // v*printf from a function that has the printf format attribute, we
6179  // should not emit a warning about using `fmt`, even though it's not
6180  // constant, because the arguments have already been checked for the
6181  // caller of `logmessage`:
6182  //
6183  // __attribute__((format(printf, 1, 2)))
6184  // void logmessage(char const *fmt, ...) {
6185  // va_list ap;
6186  // va_start(ap, fmt);
6187  // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6188  // ...
6189  // }
6190  //
6191  // Another interaction that we need to support is calling a variadic
6192  // format function from a format function that has fixed arguments. For
6193  // instance:
6194  //
6195  // __attribute__((format(printf, 1, 2)))
6196  // void logstring(char const *fmt, char const *str) {
6197  // printf(fmt, str); /* do not emit a warning about "fmt" */
6198  // }
6199  //
6200  // Same (and perhaps more relatably) for the variadic template case:
6201  //
6202  // template<typename... Args>
6203  // __attribute__((format(printf, 1, 2)))
6204  // void log(const char *fmt, Args&&... args) {
6205  // printf(fmt, forward<Args>(args)...);
6206  // /* do not emit a warning about "fmt" */
6207  // }
6208  //
6209  // Due to implementation difficulty, we only check the format, not the
6210  // format arguments, in all cases.
6211  //
6212  if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6213  if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6214  for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6215  bool IsCXXMember = false;
6216  if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
6217  IsCXXMember = MD->isInstance();
6218 
6219  bool IsVariadic = false;
6220  if (const FunctionType *FnTy = D->getFunctionType())
6221  IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
6222  else if (const auto *BD = dyn_cast<BlockDecl>(D))
6223  IsVariadic = BD->isVariadic();
6224  else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
6225  IsVariadic = OMD->isVariadic();
6226 
6227  Sema::FormatStringInfo CallerFSI;
6228  if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,
6229  &CallerFSI)) {
6230  // We also check if the formats are compatible.
6231  // We can't pass a 'scanf' string to a 'printf' function.
6232  if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
6233  Type == S.GetFormatStringType(PVFormat)) {
6234  // Lastly, check that argument passing kinds transition in a
6235  // way that makes sense:
6236  // from a caller with FAPK_VAList, allow FAPK_VAList
6237  // from a caller with FAPK_Fixed, allow FAPK_Fixed
6238  // from a caller with FAPK_Fixed, allow FAPK_Variadic
6239  // from a caller with FAPK_Variadic, allow FAPK_VAList
6240  switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6245  return SLCT_UncheckedLiteral;
6246  }
6247  }
6248  }
6249  }
6250  }
6251  }
6252  }
6253 
6254  return SLCT_NotALiteral;
6255  }
6256 
6257  case Stmt::CallExprClass:
6258  case Stmt::CXXMemberCallExprClass: {
6259  const CallExpr *CE = cast<CallExpr>(E);
6260  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6261  bool IsFirst = true;
6262  StringLiteralCheckType CommonResult;
6263  for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6264  const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6265  StringLiteralCheckType Result = checkFormatStringExpr(
6266  S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
6267  InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6268  IgnoreStringsWithoutSpecifiers);
6269  if (IsFirst) {
6270  CommonResult = Result;
6271  IsFirst = false;
6272  }
6273  }
6274  if (!IsFirst)
6275  return CommonResult;
6276 
6277  if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6278  unsigned BuiltinID = FD->getBuiltinID();
6279  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6280  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6281  const Expr *Arg = CE->getArg(0);
6282  return checkFormatStringExpr(
6283  S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
6284  InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6285  IgnoreStringsWithoutSpecifiers);
6286  }
6287  }
6288  }
6289  if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6290  return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
6291  Type, CallType, /*InFunctionCall*/ false,
6292  CheckedVarArgs, UncoveredArg, Offset,
6293  IgnoreStringsWithoutSpecifiers);
6294  return SLCT_NotALiteral;
6295  }
6296  case Stmt::ObjCMessageExprClass: {
6297  const auto *ME = cast<ObjCMessageExpr>(E);
6298  if (const auto *MD = ME->getMethodDecl()) {
6299  if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6300  // As a special case heuristic, if we're using the method -[NSBundle
6301  // localizedStringForKey:value:table:], ignore any key strings that lack
6302  // format specifiers. The idea is that if the key doesn't have any
6303  // format specifiers then its probably just a key to map to the
6304  // localized strings. If it does have format specifiers though, then its
6305  // likely that the text of the key is the format string in the
6306  // programmer's language, and should be checked.
6307  const ObjCInterfaceDecl *IFace;
6308  if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6309  IFace->getIdentifier()->isStr("NSBundle") &&
6310  MD->getSelector().isKeywordSelector(
6311  {"localizedStringForKey", "value", "table"})) {
6312  IgnoreStringsWithoutSpecifiers = true;
6313  }
6314 
6315  const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6316  return checkFormatStringExpr(
6317  S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
6318  InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6319  IgnoreStringsWithoutSpecifiers);
6320  }
6321  }
6322 
6323  return SLCT_NotALiteral;
6324  }
6325  case Stmt::ObjCStringLiteralClass:
6326  case Stmt::StringLiteralClass: {
6327  const StringLiteral *StrE = nullptr;
6328 
6329  if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6330  StrE = ObjCFExpr->getString();
6331  else
6332  StrE = cast<StringLiteral>(E);
6333 
6334  if (StrE) {
6335  if (Offset.isNegative() || Offset > StrE->getLength()) {
6336  // TODO: It would be better to have an explicit warning for out of
6337  // bounds literals.
6338  return SLCT_NotALiteral;
6339  }
6340  FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6341  CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,
6342  InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,
6343  IgnoreStringsWithoutSpecifiers);
6344  return SLCT_CheckedLiteral;
6345  }
6346 
6347  return SLCT_NotALiteral;
6348  }
6349  case Stmt::BinaryOperatorClass: {
6350  const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6351 
6352  // A string literal + an int offset is still a string literal.
6353  if (BinOp->isAdditiveOp()) {
6354  Expr::EvalResult LResult, RResult;
6355 
6356  bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6357  LResult, S.Context, Expr::SE_NoSideEffects,
6359  bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6360  RResult, S.Context, Expr::SE_NoSideEffects,
6362 
6363  if (LIsInt != RIsInt) {
6364  BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6365 
6366  if (LIsInt) {
6367  if (BinOpKind == BO_Add) {
6368  sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6369  E = BinOp->getRHS();
6370  goto tryAgain;
6371  }
6372  } else {
6373  sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6374  E = BinOp->getLHS();
6375  goto tryAgain;
6376  }
6377  }
6378  }
6379 
6380  return SLCT_NotALiteral;
6381  }
6382  case Stmt::UnaryOperatorClass: {
6383  const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6384  auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6385  if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6386  Expr::EvalResult IndexResult;
6387  if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6390  sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6391  /*RHS is int*/ true);
6392  E = ASE->getBase();
6393  goto tryAgain;
6394  }
6395  }
6396 
6397  return SLCT_NotALiteral;
6398  }
6399 
6400  default:
6401  return SLCT_NotALiteral;
6402  }
6403 }
6404 
6405 // If this expression can be evaluated at compile-time,
6406 // check if the result is a StringLiteral and return it
6407 // otherwise return nullptr
6409  const Expr *E) {
6410  Expr::EvalResult Result;
6411  if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6412  const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6413  if (isa_and_nonnull<StringLiteral>(LVE))
6414  return LVE;
6415  }
6416  return nullptr;
6417 }
6418 
6420  return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6421  .Case("scanf", FST_Scanf)
6422  .Cases("printf", "printf0", "syslog", FST_Printf)
6423  .Cases("NSString", "CFString", FST_NSString)
6424  .Case("strftime", FST_Strftime)
6425  .Case("strfmon", FST_Strfmon)
6426  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6427  .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6428  .Case("os_trace", FST_OSLog)
6429  .Case("os_log", FST_OSLog)
6430  .Default(FST_Unknown);
6431 }
6432 
6433 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6434  ArrayRef<const Expr *> Args, bool IsCXXMember,
6435  VariadicCallType CallType, SourceLocation Loc,
6436  SourceRange Range,
6437  llvm::SmallBitVector &CheckedVarArgs) {
6438  FormatStringInfo FSI;
6439  if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,
6440  &FSI))
6441  return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,
6442  FSI.FirstDataArg, GetFormatStringType(Format),
6443  CallType, Loc, Range, CheckedVarArgs);
6444  return false;
6445 }
6446 
6447 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6449  unsigned format_idx, unsigned firstDataArg,
6450  FormatStringType Type,
6451  VariadicCallType CallType, SourceLocation Loc,
6452  SourceRange Range,
6453  llvm::SmallBitVector &CheckedVarArgs) {
6454  // CHECK: printf/scanf-like function is called with no format string.
6455  if (format_idx >= Args.size()) {
6456  Diag(Loc, diag::warn_missing_format_string) << Range;
6457  return false;
6458  }
6459 
6460  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6461 
6462  // CHECK: format string is not a string literal.
6463  //
6464  // Dynamically generated format strings are difficult to
6465  // automatically vet at compile time. Requiring that format strings
6466  // are string literals: (1) permits the checking of format strings by
6467  // the compiler and thereby (2) can practically remove the source of
6468  // many format string exploits.
6469 
6470  // Format string can be either ObjC string (e.g. @"%d") or
6471  // C string (e.g. "%d")
6472  // ObjC string uses the same format specifiers as C string, so we can use
6473  // the same format string checking logic for both ObjC and C strings.
6474  UncoveredArgHandler UncoveredArg;
6475  StringLiteralCheckType CT = checkFormatStringExpr(
6476  *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,
6477  CallType,
6478  /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
6479  /*no string offset*/ llvm::APSInt(64, false) = 0);
6480 
6481  // Generate a diagnostic where an uncovered argument is detected.
6482  if (UncoveredArg.hasUncoveredArg()) {
6483  unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6484  assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6485  UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6486  }
6487 
6488  if (CT != SLCT_NotALiteral)
6489  // Literal format string found, check done!
6490  return CT == SLCT_CheckedLiteral;
6491 
6492  // Strftime is particular as it always uses a single 'time' argument,
6493  // so it is safe to pass a non-literal string.
6494  if (Type == FST_Strftime)
6495  return false;
6496 
6497  // Do not emit diag when the string param is a macro expansion and the
6498  // format is either NSString or CFString. This is a hack to prevent
6499  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6500  // which are usually used in place of NS and CF string literals.
6501  SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6502  if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6503  return false;
6504 
6505  // If there are no arguments specified, warn with -Wformat-security, otherwise
6506  // warn only with -Wformat-nonliteral.
6507  if (Args.size() == firstDataArg) {
6508  Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6509  << OrigFormatExpr->getSourceRange();
6510  switch (Type) {
6511  default:
6512  break;
6513  case FST_Kprintf:
6514  case FST_FreeBSDKPrintf:
6515  case FST_Printf:
6516  case FST_Syslog:
6517  Diag(FormatLoc, diag::note_format_security_fixit)
6518  << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6519  break;
6520  case FST_NSString:
6521  Diag(FormatLoc, diag::note_format_security_fixit)
6522  << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6523  break;
6524  }
6525  } else {
6526  Diag(FormatLoc, diag::warn_format_nonliteral)
6527  << OrigFormatExpr->getSourceRange();
6528  }
6529  return false;
6530 }
6531 
6532 namespace {
6533 
6534 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6535 protected:
6536  Sema &S;
6537  const FormatStringLiteral *FExpr;
6538  const Expr *OrigFormatExpr;
6539  const Sema::FormatStringType FSType;
6540  const unsigned FirstDataArg;
6541  const unsigned NumDataArgs;
6542  const char *Beg; // Start of format string.
6543  const Sema::FormatArgumentPassingKind ArgPassingKind;
6545  unsigned FormatIdx;
6546  llvm::SmallBitVector CoveredArgs;
6547  bool usesPositionalArgs = false;
6548  bool atFirstArg = true;
6549  bool inFunctionCall;
6550  Sema::VariadicCallType CallType;
6551  llvm::SmallBitVector &CheckedVarArgs;
6552  UncoveredArgHandler &UncoveredArg;
6553 
6554 public:
6555  CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6556  const Expr *origFormatExpr,
6557  const Sema::FormatStringType type, unsigned firstDataArg,
6558  unsigned numDataArgs, const char *beg,
6560  ArrayRef<const Expr *> Args, unsigned formatIdx,
6561  bool inFunctionCall, Sema::VariadicCallType callType,
6562  llvm::SmallBitVector &CheckedVarArgs,
6563  UncoveredArgHandler &UncoveredArg)
6564  : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6565  FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6566  ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
6567  inFunctionCall(inFunctionCall), CallType(callType),
6568  CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6569  CoveredArgs.resize(numDataArgs);
6570  CoveredArgs.reset();
6571  }
6572 
6573  void DoneProcessing();
6574 
6575  void HandleIncompleteSpecifier(const char *startSpecifier,
6576  unsigned specifierLen) override;
6577 
6578  void HandleInvalidLengthModifier(
6581  const char *startSpecifier, unsigned specifierLen,
6582  unsigned DiagID);
6583 
6584  void HandleNonStandardLengthModifier(
6586  const char *startSpecifier, unsigned specifierLen);
6587 
6588  void HandleNonStandardConversionSpecifier(
6590  const char *startSpecifier, unsigned specifierLen);
6591 
6592  void HandlePosition(const char *startPos, unsigned posLen) override;
6593 
6594  void HandleInvalidPosition(const char *startSpecifier,
6595  unsigned specifierLen,
6597 
6598  void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6599 
6600  void HandleNullChar(const char *nullCharacter) override;
6601 
6602  template <typename Range>
6603  static void
6604  EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6605  const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6606  bool IsStringLocation, Range StringRange,
6607  ArrayRef<FixItHint> Fixit = std::nullopt);
6608 
6609 protected:
6610  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6611  const char *startSpec,
6612  unsigned specifierLen,
6613  const char *csStart, unsigned csLen);
6614 
6615  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6616  const char *startSpec,
6617  unsigned specifierLen);
6618 
6619  SourceRange getFormatStringRange();
6620  CharSourceRange getSpecifierRange(const char *startSpecifier,
6621  unsigned specifierLen);
6622  SourceLocation getLocationOfByte(const char *x);
6623 
6624  const Expr *getDataArg(unsigned i) const;
6625 
6626  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6628  const char *startSpecifier, unsigned specifierLen,
6629  unsigned argIndex);
6630 
6631  template <typename Range>
6632  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6633  bool IsStringLocation, Range StringRange,
6634  ArrayRef<FixItHint> Fixit = std::nullopt);
6635 };
6636 
6637 } // namespace
6638 
6639 SourceRange CheckFormatHandler::getFormatStringRange() {
6640  return OrigFormatExpr->getSourceRange();
6641 }
6642 
6643 CharSourceRange CheckFormatHandler::
6644 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6645  SourceLocation Start = getLocationOfByte(startSpecifier);
6646  SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
6647 
6648  // Advance the end SourceLocation by one due to half-open ranges.
6649  End = End.getLocWithOffset(1);
6650 
6651  return CharSourceRange::getCharRange(Start, End);
6652 }
6653 
6654 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6655  return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6656  S.getLangOpts(), S.Context.getTargetInfo());
6657 }
6658 
6659 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6660  unsigned specifierLen){
6661  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6662  getLocationOfByte(startSpecifier),
6663  /*IsStringLocation*/true,
6664  getSpecifierRange(startSpecifier, specifierLen));
6665 }
6666 
6667 void CheckFormatHandler::HandleInvalidLengthModifier(
6670  const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6671  using namespace analyze_format_string;
6672 
6673  const LengthModifier &LM = FS.getLengthModifier();
6674  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6675 
6676  // See if we know how to fix this length modifier.
6677  std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6678  if (FixedLM) {
6679  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6680  getLocationOfByte(LM.getStart()),
6681  /*IsStringLocation*/true,
6682  getSpecifierRange(startSpecifier, specifierLen));
6683 
6684  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6685  << FixedLM->toString()
6686  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6687 
6688  } else {
6689  FixItHint Hint;
6690  if (DiagID == diag::warn_format_nonsensical_length)
6691  Hint = FixItHint::CreateRemoval(LMRange);
6692 
6693  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6694  getLocationOfByte(LM.getStart()),
6695  /*IsStringLocation*/true,
6696  getSpecifierRange(startSpecifier, specifierLen),
6697  Hint);
6698  }
6699 }
6700 
6701 void CheckFormatHandler::HandleNonStandardLengthModifier(
6703  const char *startSpecifier, unsigned specifierLen) {
6704  using namespace analyze_format_string;
6705 
6706  const LengthModifier &LM = FS.getLengthModifier();
6707  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6708 
6709  // See if we know how to fix this length modifier.
6710  std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6711  if (FixedLM) {
6712  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6713  << LM.toString() << 0,
6714  getLocationOfByte(LM.getStart()),
6715  /*IsStringLocation*/true,
6716  getSpecifierRange(startSpecifier, specifierLen));
6717 
6718  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6719  << FixedLM->toString()
6720  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6721 
6722  } else {
6723  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6724  << LM.toString() << 0,
6725  getLocationOfByte(LM.getStart()),
6726  /*IsStringLocation*/true,
6727  getSpecifierRange(startSpecifier, specifierLen));
6728  }
6729 }
6730 
6731 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6733  const char *startSpecifier, unsigned specifierLen) {
6734  using namespace analyze_format_string;
6735 
6736  // See if we know how to fix this conversion specifier.
6737  std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6738  if (FixedCS) {
6739  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6740  << CS.toString() << /*conversion specifier*/1,
6741  getLocationOfByte(CS.getStart()),
6742  /*IsStringLocation*/true,
6743  getSpecifierRange(startSpecifier, specifierLen));
6744 
6745  CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6746  S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6747  << FixedCS->toString()
6748  << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6749  } else {
6750  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6751  << CS.toString() << /*conversion specifier*/1,
6752  getLocationOfByte(CS.getStart()),
6753  /*IsStringLocation*/true,
6754  getSpecifierRange(startSpecifier, specifierLen));
6755  }
6756 }
6757 
6758 void CheckFormatHandler::HandlePosition(const char *startPos,
6759  unsigned posLen) {
6760  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6761  getLocationOfByte(startPos),
6762  /*IsStringLocation*/true,
6763  getSpecifierRange(startPos, posLen));
6764 }
6765 
6766 void CheckFormatHandler::HandleInvalidPosition(
6767  const char *startSpecifier, unsigned specifierLen,
6769  EmitFormatDiagnostic(
6770  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
6771  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
6772  getSpecifierRange(startSpecifier, specifierLen));
6773 }
6774 
6775 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6776  unsigned posLen) {
6777  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6778  getLocationOfByte(startPos),
6779  /*IsStringLocation*/true,
6780  getSpecifierRange(startPos, posLen));
6781 }
6782 
6783 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6784  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6785  // The presence of a null character is likely an error.
6786  EmitFormatDiagnostic(
6787  S.PDiag(diag::warn_printf_format_string_contains_null_char),
6788  getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6789  getFormatStringRange());
6790  }
6791 }
6792 
6793 // Note that this may return NULL if there was an error parsing or building
6794 // one of the argument expressions.
6795 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6796  return Args[FirstDataArg + i];
6797 }
6798 
6799 void CheckFormatHandler::DoneProcessing() {
6800  // Does the number of data arguments exceed the number of
6801  // format conversions in the format string?
6802  if (ArgPassingKind != Sema::FAPK_VAList) {
6803  // Find any arguments that weren't covered.
6804  CoveredArgs.flip();
6805  signed notCoveredArg = CoveredArgs.find_first();
6806  if (notCoveredArg >= 0) {
6807  assert((unsigned)notCoveredArg < NumDataArgs);
6808  UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6809  } else {
6810  UncoveredArg.setAllCovered();
6811  }
6812  }
6813 }
6814 
6815 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6816  const Expr *ArgExpr) {
6817  assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
6818  "Invalid state");
6819 
6820  if (!ArgExpr)
6821  return;
6822 
6823  SourceLocation Loc = ArgExpr->getBeginLoc();
6824 
6826  return;
6827 
6828  PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6829  for (auto E : DiagnosticExprs)
6830  PDiag << E->getSourceRange();
6831 
6832  CheckFormatHandler::EmitFormatDiagnostic(
6833  S, IsFunctionCall, DiagnosticExprs[0],
6834  PDiag, Loc, /*IsStringLocation*/false,
6835  DiagnosticExprs[0]->getSourceRange());
6836 }
6837 
6838 bool
6839 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6841  const char *startSpec,
6842  unsigned specifierLen,
6843  const char *csStart,
6844  unsigned csLen) {
6845  bool keepGoing = true;
6846  if (argIndex < NumDataArgs) {
6847  // Consider the argument coverered, even though the specifier doesn't
6848  // make sense.
6849  CoveredArgs.set(argIndex);
6850  }
6851  else {
6852  // If argIndex exceeds the number of data arguments we
6853  // don't issue a warning because that is just a cascade of warnings (and
6854  // they may have intended '%%' anyway). We don't want to continue processing
6855  // the format string after this point, however, as we will like just get
6856  // gibberish when trying to match arguments.
6857  keepGoing = false;
6858  }
6859 
6860  StringRef Specifier(csStart, csLen);
6861 
6862  // If the specifier in non-printable, it could be the first byte of a UTF-8
6863  // sequence. In that case, print the UTF-8 code point. If not, print the byte
6864  // hex value.
6865  std::string CodePointStr;
6866  if (!llvm::sys::locale::isPrint(*csStart)) {
6867  llvm::UTF32 CodePoint;
6868  const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6869  const llvm::UTF8 *E =
6870  reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6871  llvm::ConversionResult Result =
6872  llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6873 
6874  if (Result != llvm::conversionOK) {
6875  unsigned char FirstChar = *csStart;
6876  CodePoint = (llvm::UTF32)FirstChar;
6877  }
6878 
6879  llvm::raw_string_ostream OS(CodePointStr);
6880  if (CodePoint < 256)
6881  OS << "\\x" << llvm::format("%02x", CodePoint);
6882  else if (CodePoint <= 0xFFFF)
6883  OS << "\\u" << llvm::format("%04x", CodePoint);
6884  else
6885  OS << "\\U" << llvm::format("%08x", CodePoint);
6886  OS.flush();
6887  Specifier = CodePointStr;
6888  }
6889 
6890  EmitFormatDiagnostic(
6891  S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6892  /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6893 
6894  return keepGoing;
6895 }
6896 
6897 void
6898 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6899  const char *startSpec,
6900  unsigned specifierLen) {
6901  EmitFormatDiagnostic(
6902  S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6903  Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6904 }
6905 
6906 bool
6907 CheckFormatHandler::CheckNumArgs(
6910  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6911 
6912  if (argIndex >= NumDataArgs) {
6913  PartialDiagnostic PDiag = FS.usesPositionalArg()
6914  ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6915  << (argIndex+1) << NumDataArgs)
6916  : S.PDiag(diag::warn_printf_insufficient_data_args);
6917  EmitFormatDiagnostic(
6918  PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6919  getSpecifierRange(startSpecifier, specifierLen));
6920 
6921  // Since more arguments than conversion tokens are given, by extension
6922  // all arguments are covered, so mark this as so.
6923  UncoveredArg.setAllCovered();
6924  return false;
6925  }
6926  return true;
6927 }
6928 
6929 template<typename Range>
6930 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6932  bool IsStringLocation,
6933  Range StringRange,
6935  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
6936  Loc, IsStringLocation, StringRange, FixIt);
6937 }
6938 
6939 /// If the format string is not within the function call, emit a note
6940 /// so that the function call and string are in diagnostic messages.
6941 ///
6942 /// \param InFunctionCall if true, the format string is within the function
6943 /// call and only one diagnostic message will be produced. Otherwise, an
6944 /// extra note will be emitted pointing to location of the format string.
6945 ///
6946 /// \param ArgumentExpr the expression that is passed as the format string
6947 /// argument in the function call. Used for getting locations when two
6948 /// diagnostics are emitted.
6949 ///
6950 /// \param PDiag the callee should already have provided any strings for the
6951 /// diagnostic message. This function only adds locations and fixits
6952 /// to diagnostics.
6953 ///
6954 /// \param Loc primary location for diagnostic. If two diagnostics are
6955 /// required, one will be at Loc and a new SourceLocation will be created for
6956 /// the other one.
6957 ///
6958 /// \param IsStringLocation if true, Loc points to the format string should be
6959 /// used for the note. Otherwise, Loc points to the argument list and will
6960 /// be used with PDiag.
6961 ///
6962 /// \param StringRange some or all of the string to highlight. This is
6963 /// templated so it can accept either a CharSourceRange or a SourceRange.
6964 ///
6965 /// \param FixIt optional fix it hint for the format string.
6966 template <typename Range>
6967 void CheckFormatHandler::EmitFormatDiagnostic(
6968  Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6969  const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6970  Range StringRange, ArrayRef<FixItHint> FixIt) {
6971  if (InFunctionCall) {
6972  const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6973  D << StringRange;
6974  D << FixIt;
6975  } else {
6976  S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6977  << ArgumentExpr->getSourceRange();
6978 
6979  const Sema::SemaDiagnosticBuilder &Note =
6980  S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6981  diag::note_format_string_defined);
6982 
6983  Note << StringRange;
6984  Note << FixIt;
6985  }
6986 }
6987 
6988 //===--- CHECK: Printf format string checking -----------------------------===//
6989 
6990 namespace {
6991 
6992 class CheckPrintfHandler : public CheckFormatHandler {
6993 public:
6994  CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
6995  const Expr *origFormatExpr,
6996  const Sema::FormatStringType type, unsigned firstDataArg,
6997  unsigned numDataArgs, bool isObjC, const char *beg,
6999  ArrayRef<const Expr *> Args, unsigned formatIdx,
7000  bool inFunctionCall, Sema::VariadicCallType CallType,
7001  llvm::SmallBitVector &CheckedVarArgs,
7002  UncoveredArgHandler &UncoveredArg)
7003  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7004  numDataArgs, beg, APK, Args, formatIdx,
7005  inFunctionCall, CallType, CheckedVarArgs,
7006  UncoveredArg) {}
7007 
7008  bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7009 
7010  /// Returns true if '%@' specifiers are allowed in the format string.
7011  bool allowsObjCArg() const {
7012  return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7013  FSType == Sema::FST_OSTrace;
7014  }
7015 
7016  bool HandleInvalidPrintfConversionSpecifier(
7018  const char *startSpecifier,
7019  unsigned specifierLen) override;
7020 
7021  void handleInvalidMaskType(StringRef MaskType) override;
7022 
7023  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7024  const char *startSpecifier, unsigned specifierLen,
7025  const TargetInfo &Target) override;
7026  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7027  const char *StartSpecifier,
7028  unsigned SpecifierLen,
7029  const Expr *E);
7030 
7031  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7032  const char *startSpecifier, unsigned specifierLen);
7033  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7034  const analyze_printf::OptionalAmount &Amt,
7035  unsigned type,
7036  const char *startSpecifier, unsigned specifierLen);
7037  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7038  const analyze_printf::OptionalFlag &flag,
7039  const char *startSpecifier, unsigned specifierLen);
7040  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7041  const analyze_printf::OptionalFlag &ignoredFlag,
7042  const analyze_printf::OptionalFlag &flag,
7043  const char *startSpecifier, unsigned specifierLen);
7044  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7045  const Expr *E);
7046 
7047  void HandleEmptyObjCModifierFlag(const char *startFlag,
7048  unsigned flagLen) override;
7049 
7050  void HandleInvalidObjCModifierFlag(const char *startFlag,
7051  unsigned flagLen) override;
7052 
7053  void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7054  const char *flagsEnd,
7055  const char *conversionPosition)
7056  override;
7057 };
7058 
7059 } // namespace
7060 
7061 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7063  const char *startSpecifier,
7064  unsigned specifierLen) {
7066  FS.getConversionSpecifier();
7067 
7068  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7069  getLocationOfByte(CS.getStart()),
7070  startSpecifier, specifierLen,
7071  CS.getStart(), CS.getLength());
7072 }
7073 
7074 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7075  S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7076 }
7077 
7078 bool CheckPrintfHandler::HandleAmount(
7079  const analyze_format_string::OptionalAmount &Amt, unsigned k,
7080  const char *startSpecifier, unsigned specifierLen) {
7081  if (Amt.hasDataArgument()) {
7082  if (ArgPassingKind != Sema::FAPK_VAList) {
7083  unsigned argIndex = Amt.getArgIndex();
7084  if (argIndex >= NumDataArgs) {
7085  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7086  << k,
7087  getLocationOfByte(Amt.getStart()),
7088  /*IsStringLocation*/ true,
7089  getSpecifierRange(startSpecifier, specifierLen));
7090  // Don't do any more checking. We will just emit
7091  // spurious errors.
7092  return false;
7093  }
7094 
7095  // Type check the data argument. It should be an 'int'.
7096  // Although not in conformance with C99, we also allow the argument to be
7097  // an 'unsigned int' as that is a reasonably safe case. GCC also
7098  // doesn't emit a warning for that case.
7099  CoveredArgs.set(argIndex);
7100  const Expr *Arg = getDataArg(argIndex);
7101  if (!Arg)
7102  return false;
7103 
7104  QualType T = Arg->getType();
7105 
7106  const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7107  assert(AT.isValid());
7108 
7109  if (!AT.matchesType(S.Context, T)) {
7110  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7111  << k << AT.getRepresentativeTypeName(S.Context)
7112  << T << Arg->getSourceRange(),
7113  getLocationOfByte(Amt.getStart()),
7114  /*IsStringLocation*/true,
7115  getSpecifierRange(startSpecifier, specifierLen));
7116  // Don't do any more checking. We will just emit
7117  // spurious errors.
7118  return false;
7119  }
7120  }
7121  }
7122  return true;
7123 }
7124 
7125 void CheckPrintfHandler::HandleInvalidAmount(
7127  const analyze_printf::OptionalAmount &Amt,
7128  unsigned type,
7129  const char *startSpecifier,
7130  unsigned specifierLen) {
7132  FS.getConversionSpecifier();
7133 
7134  FixItHint fixit =
7135  Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7136  ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7137  Amt.getConstantLength()))
7138  : FixItHint();
7139 
7140  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7141  << type << CS.toString(),
7142  getLocationOfByte(Amt.getStart()),
7143  /*IsStringLocation*/true,
7144  getSpecifierRange(startSpecifier, specifierLen),
7145  fixit);
7146 }
7147 
7148 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7149  const analyze_printf::OptionalFlag &flag,
7150  const char *startSpecifier,
7151  unsigned specifierLen) {
7152  // Warn about pointless flag with a fixit removal.
7154  FS.getConversionSpecifier();
7155  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7156  << flag.toString() << CS.toString(),
7157  getLocationOfByte(flag.getPosition()),
7158  /*IsStringLocation*/true,
7159  getSpecifierRange(startSpecifier, specifierLen),
7161  getSpecifierRange(flag.getPosition(), 1)));
7162 }
7163 
7164 void CheckPrintfHandler::HandleIgnoredFlag(
7166  const analyze_printf::OptionalFlag &ignoredFlag,
7167  const analyze_printf::OptionalFlag &flag,
7168  const char *startSpecifier,
7169  unsigned specifierLen) {
7170  // Warn about ignored flag with a fixit removal.
7171  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7172  << ignoredFlag.toString() << flag.toString(),
7173  getLocationOfByte(ignoredFlag.getPosition()),
7174  /*IsStringLocation*/true,
7175  getSpecifierRange(startSpecifier, specifierLen),
7177  getSpecifierRange(ignoredFlag.getPosition(), 1)));
7178 }
7179 
7180 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7181  unsigned flagLen) {
7182  // Warn about an empty flag.
7183  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7184  getLocationOfByte(startFlag),
7185  /*IsStringLocation*/true,
7186  getSpecifierRange(startFlag, flagLen));
7187 }
7188 
7189 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7190  unsigned flagLen) {
7191  // Warn about an invalid flag.
7192  auto Range = getSpecifierRange(startFlag, flagLen);
7193  StringRef flag(startFlag, flagLen);
7194  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7195  getLocationOfByte(startFlag),
7196  /*IsStringLocation*/true,
7197  Range, FixItHint::CreateRemoval(Range));
7198 }
7199 
7200 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7201  const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7202  // Warn about using '[...]' without a '@' conversion.
7203  auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7204  auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7205  EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7206  getLocationOfByte(conversionPosition),
7207  /*IsStringLocation*/true,
7208  Range, FixItHint::CreateRemoval(Range));
7209 }
7210 
7211 // Determines if the specified is a C++ class or struct containing
7212 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7213 // "c_str()").
7214 template<typename MemberKind>
7216 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7217  const RecordType *RT = Ty->getAs<RecordType>();
7219 
7220  if (!RT)
7221  return Results;
7222  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7223  if (!RD || !RD->getDefinition())
7224  return Results;
7225 
7226  LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7228  R.suppressDiagnostics();
7229 
7230  // We just need to include all members of the right kind turned up by the
7231  // filter, at this point.
7232  if (S.LookupQualifiedName(R, RT->getDecl()))
7233  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7234  NamedDecl *decl = (*I)->getUnderlyingDecl();
7235  if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7236  Results.insert(FK);
7237  }
7238  return Results;
7239 }
7240 
7241 /// Check if we could call '.c_str()' on an object.
7242 ///
7243 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7244 /// allow the call, or if it would be ambiguous).
7246  using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7247 
7248  MethodSet Results =
7249  CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7250  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7251  MI != ME; ++MI)
7252  if ((*MI)->getMinRequiredArguments() == 0)
7253  return true;
7254  return false;
7255 }
7256 
7257 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7258 // better diagnostic if so. AT is assumed to be valid.
7259 // Returns true when a c_str() conversion method is found.
7260 bool CheckPrintfHandler::checkForCStrMembers(
7261  const analyze_printf::ArgType &AT, const Expr *E) {
7262  using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7263 
7264  MethodSet Results =
7265  CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7266 
7267  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7268  MI != ME; ++MI) {
7269  const CXXMethodDecl *Method = *MI;
7270  if (Method->getMinRequiredArguments() == 0 &&
7271  AT.matchesType(S.Context, Method->getReturnType())) {
7272  // FIXME: Suggest parens if the expression needs them.
7274  S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7275  << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7276  return true;
7277  }
7278  }
7279 
7280  return false;
7281 }
7282 
7283 bool CheckPrintfHandler::HandlePrintfSpecifier(
7284  const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7285  unsigned specifierLen, const TargetInfo &Target) {
7286  using namespace analyze_format_string;
7287  using namespace analyze_printf;
7288 
7289  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7290 
7291  if (FS.consumesDataArgument()) {
7292  if (atFirstArg) {
7293  atFirstArg = false;
7294  usesPositionalArgs = FS.usesPositionalArg();
7295  }
7296  else if (usesPositionalArgs != FS.usesPositionalArg()) {
7297  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7298  startSpecifier, specifierLen);
7299  return false;
7300  }
7301  }
7302 
7303  // First check if the field width, precision, and conversion specifier
7304  // have matching data arguments.
7305  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7306  startSpecifier, specifierLen)) {
7307  return false;
7308  }
7309 
7310  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7311  startSpecifier, specifierLen)) {
7312  return false;
7313  }
7314 
7315  if (!CS.consumesDataArgument()) {
7316  // FIXME: Technically specifying a precision or field width here
7317  // makes no sense. Worth issuing a warning at some point.
7318  return true;
7319  }
7320 
7321  // Consume the argument.
7322  unsigned argIndex = FS.getArgIndex();
7323  if (argIndex < NumDataArgs) {
7324  // The check to see if the argIndex is valid will come later.
7325  // We set the bit here because we may exit early from this
7326  // function if we encounter some other error.
7327  CoveredArgs.set(argIndex);
7328  }
7329 
7330  // FreeBSD kernel extensions.
7331  if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7332  CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7333  // We need at least two arguments.
7334  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7335  return false;
7336 
7337  // Claim the second argument.
7338  CoveredArgs.set(argIndex + 1);
7339 
7340  // Type check the first argument (int for %b, pointer for %D)
7341  const Expr *Ex = getDataArg(argIndex);
7342  const analyze_printf::ArgType &AT =
7343  (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7344  ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7345  if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7346  EmitFormatDiagnostic(
7347  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7348  << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7349  << false << Ex->getSourceRange(),
7350  Ex->getBeginLoc(), /*IsStringLocation*/ false,
7351  getSpecifierRange(startSpecifier, specifierLen));
7352 
7353  // Type check the second argument (char * for both %b and %D)
7354  Ex = getDataArg(argIndex + 1);
7355  const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7356  if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7357  EmitFormatDiagnostic(
7358  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7359  << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7360  << false << Ex->getSourceRange(),
7361  Ex->getBeginLoc(), /*IsStringLocation*/ false,
7362  getSpecifierRange(startSpecifier, specifierLen));
7363 
7364  return true;
7365  }
7366 
7367  // Check for using an Objective-C specific conversion specifier
7368  // in a non-ObjC literal.
7369  if (!allowsObjCArg() && CS.isObjCArg()) {
7370  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7371  specifierLen);
7372  }
7373 
7374  // %P can only be used with os_log.
7375  if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7376  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7377  specifierLen);
7378  }
7379 
7380  // %n is not allowed with os_log.
7381  if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7382  EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7383  getLocationOfByte(CS.getStart()),
7384  /*IsStringLocation*/ false,
7385  getSpecifierRange(startSpecifier, specifierLen));
7386 
7387  return true;
7388  }
7389 
7390  // Only scalars are allowed for os_trace.
7391  if (FSType == Sema::FST_OSTrace &&
7392  (CS.getKind() == ConversionSpecifier::PArg ||
7393  CS.getKind() == ConversionSpecifier::sArg ||
7394  CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7395  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7396  specifierLen);
7397  }
7398 
7399  // Check for use of public/private annotation outside of os_log().
7400  if (FSType != Sema::FST_OSLog) {
7401  if (FS.isPublic().isSet()) {
7402  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7403  << "public",
7404  getLocationOfByte(FS.isPublic().getPosition()),
7405  /*IsStringLocation*/ false,
7406  getSpecifierRange(startSpecifier, specifierLen));
7407  }
7408  if (FS.isPrivate().isSet()) {
7409  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7410  << "private",
7411  getLocationOfByte(FS.isPrivate().getPosition()),
7412  /*IsStringLocation*/ false,
7413  getSpecifierRange(startSpecifier, specifierLen));
7414  }
7415  }
7416 
7417  const llvm::Triple &Triple = Target.getTriple();
7418  if (CS.getKind() == ConversionSpecifier::nArg &&
7419  (Triple.isAndroid() || Triple.isOSFuchsia())) {
7420  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
7421  getLocationOfByte(CS.getStart()),
7422  /*IsStringLocation*/ false,
7423  getSpecifierRange(startSpecifier, specifierLen));
7424  }
7425 
7426  // Check for invalid use of field width
7427  if (!FS.hasValidFieldWidth()) {
7428  HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7429  startSpecifier, specifierLen);
7430  }
7431 
7432  // Check for invalid use of precision
7433  if (!FS.hasValidPrecision()) {
7434  HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7435  startSpecifier, specifierLen);
7436  }
7437 
7438  // Precision is mandatory for %P specifier.
7439  if (CS.getKind() == ConversionSpecifier::PArg &&
7440  FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7441  EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7442  getLocationOfByte(startSpecifier),
7443  /*IsStringLocation*/ false,
7444  getSpecifierRange(startSpecifier, specifierLen));
7445  }
7446 
7447  // Check each flag does not conflict with any other component.
7448  if (!FS.hasValidThousandsGroupingPrefix())
7449  HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7450  if (!FS.hasValidLeadingZeros())
7451  HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7452  if (!FS.hasValidPlusPrefix())
7453  HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7454  if (!FS.hasValidSpacePrefix())
7455  HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7456  if (!FS.hasValidAlternativeForm())
7457  HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7458  if (!FS.hasValidLeftJustified())
7459  HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7460 
7461  // Check that flags are not ignored by another flag
7462  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7463  HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7464  startSpecifier, specifierLen);
7465  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7466  HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7467  startSpecifier, specifierLen);
7468 
7469  // Check the length modifier is valid with the given conversion specifier.
7470  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7471  S.getLangOpts()))
7472  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7473  diag::warn_format_nonsensical_length);
7474  else if (!FS.hasStandardLengthModifier())
7475  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7476  else if (!FS.hasStandardLengthConversionCombination())
7477  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7478  diag::warn_format_non_standard_conversion_spec);
7479 
7480  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7481  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7482 
7483  // The remaining checks depend on the data arguments.
7484  if (ArgPassingKind == Sema::FAPK_VAList)
7485  return true;
7486 
7487  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7488  return false;
7489 
7490  const Expr *Arg = getDataArg(argIndex);
7491  if (!Arg)
7492  return true;
7493 
7494  return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7495 }
7496 
7497 static bool requiresParensToAddCast(const Expr *E) {
7498  // FIXME: We should have a general way to reason about operator
7499  // precedence and whether parens are actually needed here.
7500  // Take care of a few common cases where they aren't.
7501  const Expr *Inside = E->IgnoreImpCasts();
7502  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7503  Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7504 
7505  switch (Inside->getStmtClass()) {
7506  case Stmt::ArraySubscriptExprClass:
7507  case Stmt::CallExprClass:
7508  case Stmt::CharacterLiteralClass:
7509  case Stmt::CXXBoolLiteralExprClass:
7510  case Stmt::DeclRefExprClass:
7511  case Stmt::FloatingLiteralClass:
7512  case Stmt::IntegerLiteralClass:
7513  case Stmt::MemberExprClass:
7514  case Stmt::ObjCArrayLiteralClass:
7515  case Stmt::ObjCBoolLiteralExprClass:
7516  case Stmt::ObjCBoxedExprClass:
7517  case Stmt::ObjCDictionaryLiteralClass:
7518  case Stmt::ObjCEncodeExprClass:
7519  case Stmt::ObjCIvarRefExprClass:
7520  case Stmt::ObjCMessageExprClass:
7521  case Stmt::ObjCPropertyRefExprClass:
7522  case Stmt::ObjCStringLiteralClass:
7523  case Stmt::ObjCSubscriptRefExprClass:
7524  case Stmt::ParenExprClass:
7525  case Stmt::StringLiteralClass:
7526  case Stmt::UnaryOperatorClass:
7527  return false;
7528  default:
7529  return true;
7530  }
7531 }
7532 
7533 static std::pair<QualType, StringRef>
7535  QualType IntendedTy,
7536  const Expr *E) {
7537  // Use a 'while' to peel off layers of typedefs.
7538  QualType TyTy = IntendedTy;
7539  while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7540  StringRef Name = UserTy->getDecl()->getName();
7541  QualType CastTy = llvm::StringSwitch<QualType>(Name)
7542  .Case("CFIndex", Context.getNSIntegerType())
7543  .Case("NSInteger", Context.getNSIntegerType())
7544  .Case("NSUInteger", Context.getNSUIntegerType())
7545  .Case("SInt32", Context.IntTy)
7546  .Case("UInt32", Context.UnsignedIntTy)
7547  .Default(QualType());
7548 
7549  if (!CastTy.isNull())
7550  return std::make_pair(CastTy, Name);
7551 
7552  TyTy = UserTy->desugar();
7553  }
7554 
7555  // Strip parens if necessary.
7556  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7557  return shouldNotPrintDirectly(Context,
7558  PE->getSubExpr()->getType(),
7559  PE->getSubExpr());
7560 
7561  // If this is a conditional expression, then its result type is constructed
7562  // via usual arithmetic conversions and thus there might be no necessary
7563  // typedef sugar there. Recurse to operands to check for NSInteger &
7564  // Co. usage condition.
7565  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7566  QualType TrueTy, FalseTy;
7567  StringRef TrueName, FalseName;
7568 
7569  std::tie(TrueTy, TrueName) =
7570  shouldNotPrintDirectly(Context,
7571  CO->getTrueExpr()->getType(),
7572  CO->getTrueExpr());
7573  std::tie(FalseTy, FalseName) =
7574  shouldNotPrintDirectly(Context,
7575  CO->getFalseExpr()->getType(),
7576  CO->getFalseExpr());
7577 
7578  if (TrueTy == FalseTy)
7579  return std::make_pair(TrueTy, TrueName);
7580  else if (TrueTy.isNull())
7581  return std::make_pair(FalseTy, FalseName);
7582  else if (FalseTy.isNull())
7583  return std::make_pair(TrueTy, TrueName);
7584  }
7585 
7586  return std::make_pair(QualType(), StringRef());
7587 }
7588 
7589 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7590 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7591 /// type do not count.
7592 static bool
7594  QualType From = ICE->getSubExpr()->getType();
7595  QualType To = ICE->getType();
7596  // It's an integer promotion if the destination type is the promoted
7597  // source type.
7598  if (ICE->getCastKind() == CK_IntegralCast &&
7599  S.Context.isPromotableIntegerType(From) &&
7600  S.Context.getPromotedIntegerType(From) == To)
7601  return true;
7602  // Look through vector types, since we do default argument promotion for
7603  // those in OpenCL.
7604  if (const auto *VecTy = From->getAs<ExtVectorType>())
7605  From = VecTy->getElementType();
7606  if (const auto *VecTy = To->getAs<ExtVectorType>())
7607  To = VecTy->getElementType();
7608  // It's a floating promotion if the source type is a lower rank.
7609  return ICE->getCastKind() == CK_FloatingCast &&
7610  S.Context.getFloatingTypeOrder(From, To) < 0;
7611 }
7612 
7617  Match =
7618  Diags.isIgnored(
7619  diag::warn_format_conversion_argument_type_mismatch_signedness, Loc)
7622  }
7623  return Match;
7624 }
7625 
7626 bool
7627 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7628  const char *StartSpecifier,
7629  unsigned SpecifierLen,
7630  const Expr *E) {
7631  using namespace analyze_format_string;
7632  using namespace analyze_printf;
7633 
7634  // Now type check the data expression that matches the
7635  // format specifier.
7636  const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7637  if (!AT.isValid())
7638  return true;
7639 
7640  QualType ExprTy = E->getType();
7641  while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7642  ExprTy = TET->getUnderlyingExpr()->getType();
7643  }
7644 
7645  // When using the format attribute in C++, you can receive a function or an
7646  // array that will necessarily decay to a pointer when passed to the final
7647  // format consumer. Apply decay before type comparison.
7648  if (ExprTy->canDecayToPointerType())
7649  ExprTy = S.Context.getDecayedType(ExprTy);
7650 
7651  // Diagnose attempts to print a boolean value as a character. Unlike other
7652  // -Wformat diagnostics, this is fine from a type perspective, but it still
7653  // doesn't make sense.
7654  if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
7656  const CharSourceRange &CSR =
7657  getSpecifierRange(StartSpecifier, SpecifierLen);
7658  SmallString<4> FSString;
7659  llvm::raw_svector_ostream os(FSString);
7660  FS.toString(os);
7661  EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
7662  << FSString,
7663  E->getExprLoc(), false, CSR);
7664  return true;
7665  }
7666 
7667  // Diagnose attempts to use '%P' with ObjC object types, which will result in
7668  // dumping raw class data (like is-a pointer), not actual data.
7669  if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
7670  ExprTy->isObjCObjectPointerType()) {
7671  const CharSourceRange &CSR =
7672  getSpecifierRange(StartSpecifier, SpecifierLen);
7673  EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
7674  E->getExprLoc(), false, CSR);
7675  return true;
7676  }
7677 
7678  ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
7679  ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
7680  ArgType::MatchKind OrigMatch = Match;
7681 
7682  Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc());
7683  if (Match == ArgType::Match)
7684  return true;
7685 
7686  // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
7687  assert(Match != ArgType::NoMatchPromotionTypeConfusion);
7688 
7689  // Look through argument promotions for our error message's reported type.
7690  // This includes the integral and floating promotions, but excludes array
7691  // and function pointer decay (seeing that an argument intended to be a
7692  // string has type 'char [6]' is probably more confusing than 'char *') and
7693  // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7694  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7695  if (isArithmeticArgumentPromotion(S, ICE)) {
7696  E = ICE->getSubExpr();
7697  ExprTy = E->getType();
7698 
7699  // Check if we didn't match because of an implicit cast from a 'char'
7700  // or 'short' to an 'int'. This is done because printf is a varargs
7701  // function.
7702  if (ICE->getType() == S.Context.IntTy ||
7703  ICE->getType() == S.Context.UnsignedIntTy) {
7704  // All further checking is done on the subexpression
7705  ImplicitMatch = AT.matchesType(S.Context, ExprTy);
7706  if (OrigMatch == ArgType::NoMatchSignedness &&
7707  ImplicitMatch != ArgType::NoMatchSignedness)
7708  // If the original match was a signedness match this match on the
7709  // implicit cast type also need to be signedness match otherwise we
7710  // might introduce new unexpected warnings from -Wformat-signedness.
7711  return true;
7712  ImplicitMatch = handleFormatSignedness(
7713  ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
7714  if (ImplicitMatch == ArgType::Match)
7715  return true;
7716  }
7717  }
7718  } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7719  // Special case for 'a', which has type 'int' in C.
7720  // Note, however, that we do /not/ want to treat multibyte constants like
7721  // 'MooV' as characters! This form is deprecated but still exists. In
7722  // addition, don't treat expressions as of type 'char' if one byte length
7723  // modifier is provided.
7724  if (ExprTy == S.Context.IntTy &&
7725  FS.getLengthModifier().getKind() != LengthModifier::AsChar)
7726  if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
7727  ExprTy = S.Context.CharTy;
7728  // To improve check results, we consider a character literal in C
7729  // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
7730  // more likely a type confusion situation, so we will suggest to
7731  // use '%hhd' instead by discarding the MatchPromotion.
7732  if (Match == ArgType::MatchPromotion)
7733  Match = ArgType::NoMatch;
7734  }
7735  }
7736  if (Match == ArgType::MatchPromotion) {
7737  // WG14 N2562 only clarified promotions in *printf
7738  // For NSLog in ObjC, just preserve -Wformat behavior
7739  if (!S.getLangOpts().ObjC &&
7740  ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
7741  ImplicitMatch != ArgType::NoMatchTypeConfusion)
7742  return true;
7743  Match = ArgType::NoMatch;
7744  }
7745  if (ImplicitMatch == ArgType::NoMatchPedantic ||
7746  ImplicitMatch == ArgType::NoMatchTypeConfusion)
7747  Match = ImplicitMatch;
7748  assert(Match != ArgType::MatchPromotion);
7749 
7750  // Look through unscoped enums to their underlying type.
7751  bool IsEnum = false;
7752  bool IsScopedEnum = false;
7753  QualType IntendedTy = ExprTy;
7754  if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7755  IntendedTy = EnumTy->getDecl()->getIntegerType();
7756  if (EnumTy->isUnscopedEnumerationType()) {
7757  ExprTy = IntendedTy;
7758  // This controls whether we're talking about the underlying type or not,
7759  // which we only want to do when it's an unscoped enum.
7760  IsEnum = true;
7761  } else {
7762  IsScopedEnum = true;
7763  }
7764  }
7765 
7766  // %C in an Objective-C context prints a unichar, not a wchar_t.
7767  // If the argument is an integer of some kind, believe the %C and suggest
7768  // a cast instead of changing the conversion specifier.
7769  if (isObjCContext() &&
7770  FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7771  if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7772  !ExprTy->isCharType()) {
7773  // 'unichar' is defined as a typedef of unsigned short, but we should
7774  // prefer using the typedef if it is visible.
7775  IntendedTy = S.Context.UnsignedShortTy;
7776 
7777  // While we are here, check if the value is an IntegerLiteral that happens
7778  // to be within the valid range.
7779  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7780  const llvm::APInt &V = IL->getValue();
7781  if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7782  return true;
7783  }
7784 
7785  LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7787  if (S.LookupName(Result, S.getCurScope())) {
7788  NamedDecl *ND = Result.getFoundDecl();
7789  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7790  if (TD->getUnderlyingType() == IntendedTy)
7791  IntendedTy = S.Context.getTypedefType(TD);
7792  }
7793  }
7794  }
7795 
7796  // Special-case some of Darwin's platform-independence types by suggesting
7797  // casts to primitive types that are known to be large enough.
7798  bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7799  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7800  QualType CastTy;
7801  std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7802  if (!CastTy.isNull()) {
7803  // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7804  // (long in ASTContext). Only complain to pedants or when they're the
7805  // underlying type of a scoped enum (which always needs a cast).
7806  if (!IsScopedEnum &&
7807  (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7808  (AT.isSizeT() || AT.isPtrdiffT()) &&
7809  AT.matchesType(S.Context, CastTy))
7810  Match = ArgType::NoMatchPedantic;
7811  IntendedTy = CastTy;
7812  ShouldNotPrintDirectly = true;
7813  }
7814  }
7815 
7816  // We may be able to offer a FixItHint if it is a supported type.
7817  PrintfSpecifier fixedFS = FS;
7818  bool Success =
7819  fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7820 
7821  if (Success) {
7822  // Get the fix string from the fixed format specifier
7823  SmallString<16> buf;
7824  llvm::raw_svector_ostream os(buf);
7825  fixedFS.toString(os);
7826 
7827  CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7828 
7829  if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
7830  unsigned Diag;
7831  switch (Match) {
7832  case ArgType::Match:
7833  case ArgType::MatchPromotion:
7834  case ArgType::NoMatchPromotionTypeConfusion:
7835  case ArgType::NoMatchSignedness:
7836  llvm_unreachable("expected non-matching");
7837  case ArgType::NoMatchPedantic:
7838  Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7839  break;
7840  case ArgType::NoMatchTypeConfusion:
7841  Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7842  break;
7843  case ArgType::NoMatch:
7844  Diag = diag::warn_format_conversion_argument_type_mismatch;
7845  break;
7846  }
7847 
7848  // In this case, the specifier is wrong and should be changed to match
7849  // the argument.
7850  EmitFormatDiagnostic(S.PDiag(Diag)
7851  << AT.getRepresentativeTypeName(S.Context)
7852  << IntendedTy << IsEnum << E->getSourceRange(),
7853  E->getBeginLoc(),
7854  /*IsStringLocation*/ false, SpecRange,
7855  FixItHint::CreateReplacement(SpecRange, os.str()));
7856  } else {
7857  // The canonical type for formatting this value is different from the
7858  // actual type of the expression. (This occurs, for example, with Darwin's
7859  // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7860  // should be printed as 'long' for 64-bit compatibility.)
7861  // Rather than emitting a normal format/argument mismatch, we want to
7862  // add a cast to the recommended type (and correct the format string
7863  // if necessary). We should also do so for scoped enumerations.
7864  SmallString<16> CastBuf;
7865  llvm::raw_svector_ostream CastFix(CastBuf);
7866  CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
7867  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7868  CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
7869 
7871  ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
7872  IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
7873  E->getExprLoc());
7874  if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
7875  Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7876 
7877  if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7878  // If there's already a cast present, just replace it.
7879  SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7880  Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7881 
7882  } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
7883  // If the expression has high enough precedence,
7884  // just write the C-style cast.
7885  Hints.push_back(
7886  FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7887  } else {
7888  // Otherwise, add parens around the expression as well as the cast.
7889  CastFix << "(";
7890  Hints.push_back(
7891  FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7892 
7893  // We don't use getLocForEndOfToken because it returns invalid source
7894  // locations for macro expansions (by design).
7898  Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7899  }
7900 
7901  if (ShouldNotPrintDirectly && !IsScopedEnum) {
7902  // The expression has a type that should not be printed directly.
7903  // We extract the name from the typedef because we don't want to show
7904  // the underlying type in the diagnostic.
7905  StringRef Name;
7906  if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
7907  Name = TypedefTy->getDecl()->getName();
7908  else
7909  Name = CastTyName;
7910  unsigned Diag = Match == ArgType::NoMatchPedantic
7911  ? diag::warn_format_argument_needs_cast_pedantic
7912  : diag::warn_format_argument_needs_cast;
7913  EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7914  << E->getSourceRange(),
7915  E->getBeginLoc(), /*IsStringLocation=*/false,
7916  SpecRange, Hints);
7917  } else {
7918  // In this case, the expression could be printed using a different
7919  // specifier, but we've decided that the specifier is probably correct
7920  // and we should cast instead. Just use the normal warning message.
7921 
7922  unsigned Diag =
7923  IsScopedEnum
7924  ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7925  : diag::warn_format_conversion_argument_type_mismatch;
7926 
7927  EmitFormatDiagnostic(
7928  S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7929  << IsEnum << E->getSourceRange(),
7930  E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7931  }
7932  }
7933  } else {
7934  const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7935  SpecifierLen);
7936  // Since the warning for passing non-POD types to variadic functions
7937  // was deferred until now, we emit a warning for non-POD
7938  // arguments here.
7939  bool EmitTypeMismatch = false;
7940  switch (S.isValidVarArgType(ExprTy)) {
7941  case Sema::VAK_Valid:
7942  case Sema::VAK_ValidInCXX11: {
7943  unsigned Diag;
7944  switch (Match) {
7945  case ArgType::Match:
7946  case ArgType::MatchPromotion:
7947  case ArgType::NoMatchPromotionTypeConfusion:
7948  case ArgType::NoMatchSignedness:
7949  llvm_unreachable("expected non-matching");
7950  case ArgType::NoMatchPedantic:
7951  Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7952  break;
7953  case ArgType::NoMatchTypeConfusion:
7954  Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7955  break;
7956  case ArgType::NoMatch:
7957  Diag = diag::warn_format_conversion_argument_type_mismatch;
7958  break;
7959  }
7960 
7961  EmitFormatDiagnostic(
7962  S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7963  << IsEnum << CSR << E->getSourceRange(),
7964  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7965  break;
7966  }
7967  case Sema::VAK_Undefined:
7969  if (CallType == Sema::VariadicDoesNotApply) {
7970  EmitTypeMismatch = true;
7971  } else {
7972  EmitFormatDiagnostic(
7973  S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7974  << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7975  << AT.getRepresentativeTypeName(S.Context) << CSR
7976  << E->getSourceRange(),
7977  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7978  checkForCStrMembers(AT, E);
7979  }
7980  break;
7981 
7982  case Sema::VAK_Invalid:
7983  if (CallType == Sema::VariadicDoesNotApply)
7984  EmitTypeMismatch = true;
7985  else if (ExprTy->isObjCObjectType())
7986  EmitFormatDiagnostic(
7987  S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7988  << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7989  << AT.getRepresentativeTypeName(S.Context) << CSR
7990  << E->getSourceRange(),
7991  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7992  else
7993  // FIXME: If this is an initializer list, suggest removing the braces
7994  // or inserting a cast to the target type.
7995  S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7996  << isa<InitListExpr>(E) << ExprTy << CallType
7997  << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
7998  break;
7999  }
8000 
8001  if (EmitTypeMismatch) {
8002  // The function is not variadic, so we do not generate warnings about
8003  // being allowed to pass that object as a variadic argument. Instead,
8004  // since there are inherently no printf specifiers for types which cannot
8005  // be passed as variadic arguments, emit a plain old specifier mismatch
8006  // argument.
8007  EmitFormatDiagnostic(
8008  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8009  << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
8010  << E->getSourceRange(),
8011  E->getBeginLoc(), false, CSR);
8012  }
8013 
8014  assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8015  "format string specifier index out of range");
8016  CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8017  }
8018 
8019  return true;
8020 }
8021 
8022 //===--- CHECK: Scanf format string checking ------------------------------===//
8023 
8024 namespace {
8025 
8026 class CheckScanfHandler : public CheckFormatHandler {
8027 public:
8028  CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8029  const Expr *origFormatExpr, Sema::FormatStringType type,
8030  unsigned firstDataArg, unsigned numDataArgs,
8031  const char *beg, Sema::FormatArgumentPassingKind APK,
8032  ArrayRef<const Expr *> Args, unsigned formatIdx,
8033  bool inFunctionCall, Sema::VariadicCallType CallType,
8034  llvm::SmallBitVector &CheckedVarArgs,
8035  UncoveredArgHandler &UncoveredArg)
8036  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8037  numDataArgs, beg, APK, Args, formatIdx,
8038  inFunctionCall, CallType, CheckedVarArgs,
8039  UncoveredArg) {}
8040 
8041  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8042  const char *startSpecifier,
8043  unsigned specifierLen) override;
8044 
8045  bool HandleInvalidScanfConversionSpecifier(
8047  const char *startSpecifier,
8048  unsigned specifierLen) override;
8049 
8050  void HandleIncompleteScanList(const char *start, const char *end) override;
8051 };
8052 
8053 } // namespace
8054 
8055 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8056  const char *end) {
8057  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8058  getLocationOfByte(end), /*IsStringLocation*/true,
8059  getSpecifierRange(start, end - start));
8060 }
8061 
8062 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8064  const char *startSpecifier,
8065  unsigned specifierLen) {
8067  FS.getConversionSpecifier();
8068 
8069  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8070  getLocationOfByte(CS.getStart()),
8071  startSpecifier, specifierLen,
8072  CS.getStart(), CS.getLength());
8073 }
8074 
8075 bool CheckScanfHandler::HandleScanfSpecifier(
8077  const char *startSpecifier,
8078  unsigned specifierLen) {
8079  using namespace analyze_scanf;
8080  using namespace analyze_format_string;
8081 
8082  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8083 
8084  // Handle case where '%' and '*' don't consume an argument. These shouldn't
8085  // be used to decide if we are using positional arguments consistently.
8086  if (FS.consumesDataArgument()) {
8087  if (atFirstArg) {
8088  atFirstArg = false;
8089  usesPositionalArgs = FS.usesPositionalArg();
8090  }
8091  else if (usesPositionalArgs != FS.usesPositionalArg()) {
8092  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8093  startSpecifier, specifierLen);
8094  return false;
8095  }
8096  }
8097 
8098  // Check if the field with is non-zero.
8099  const OptionalAmount &Amt = FS.getFieldWidth();
8100  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8101  if (Amt.getConstantAmount() == 0) {
8102  const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8103  Amt.getConstantLength());
8104  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8105  getLocationOfByte(Amt.getStart()),
8106  /*IsStringLocation*/true, R,
8108  }
8109  }
8110 
8111  if (!FS.consumesDataArgument()) {
8112  // FIXME: Technically specifying a precision or field width here
8113  // makes no sense. Worth issuing a warning at some point.
8114  return true;
8115  }
8116 
8117  // Consume the argument.
8118  unsigned argIndex = FS.getArgIndex();
8119  if (argIndex < NumDataArgs) {
8120  // The check to see if the argIndex is valid will come later.
8121  // We set the bit here because we may exit early from this
8122  // function if we encounter some other error.
8123  CoveredArgs.set(argIndex);
8124  }
8125 
8126  // Check the length modifier is valid with the given conversion specifier.
8127  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8128  S.getLangOpts()))
8129  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8130  diag::warn_format_nonsensical_length);
8131  else if (!FS.hasStandardLengthModifier())
8132  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8133  else if (!FS.hasStandardLengthConversionCombination())
8134  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8135  diag::warn_format_non_standard_conversion_spec);
8136 
8137  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8138  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8139 
8140  // The remaining checks depend on the data arguments.
8141  if (ArgPassingKind == Sema::FAPK_VAList)
8142  return true;
8143 
8144  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8145  return false;
8146 
8147  // Check that the argument type matches the format specifier.
8148  const Expr *Ex = getDataArg(argIndex);
8149  if (!Ex)
8150  return true;
8151 
8152  const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8153 
8154  if (!AT.isValid()) {
8155  return true;
8156  }
8157 
8159  AT.matchesType(S.Context, Ex->getType());
8160  Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc());
8163  return true;
8164 
8165  ScanfSpecifier fixedFS = FS;
8166  bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8167  S.getLangOpts(), S.Context);
8168 
8169  unsigned Diag =
8170  Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8171  : diag::warn_format_conversion_argument_type_mismatch;
8172 
8173  if (Success) {
8174  // Get the fix string from the fixed format specifier.
8175  SmallString<128> buf;
8176  llvm::raw_svector_ostream os(buf);
8177  fixedFS.toString(os);
8178 
8179  EmitFormatDiagnostic(
8181  << Ex->getType() << false << Ex->getSourceRange(),
8182  Ex->getBeginLoc(),
8183  /*IsStringLocation*/ false,
8184  getSpecifierRange(startSpecifier, specifierLen),
8186  getSpecifierRange(startSpecifier, specifierLen), os.str()));
8187  } else {
8188  EmitFormatDiagnostic(S.PDiag(Diag)
8190  << Ex->getType() << false << Ex->getSourceRange(),
8191  Ex->getBeginLoc(),
8192  /*IsStringLocation*/ false,
8193  getSpecifierRange(startSpecifier, specifierLen));
8194  }
8195 
8196  return true;
8197 }
8198 
8199 static void CheckFormatString(
8200  Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
8202  unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
8203  bool inFunctionCall, Sema::VariadicCallType CallType,
8204  llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
8205  bool IgnoreStringsWithoutSpecifiers) {
8206  // CHECK: is the format string a wide literal?
8207  if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8208  CheckFormatHandler::EmitFormatDiagnostic(
8209  S, inFunctionCall, Args[format_idx],
8210  S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8211  /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8212  return;
8213  }
8214 
8215  // Str - The format string. NOTE: this is NOT null-terminated!
8216  StringRef StrRef = FExpr->getString();
8217  const char *Str = StrRef.data();
8218  // Account for cases where the string literal is truncated in a declaration.
8219  const ConstantArrayType *T =
8220  S.Context.getAsConstantArrayType(FExpr->getType());
8221  assert(T && "String literal not of constant array type!");
8222  size_t TypeSize = T->getZExtSize();
8223  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8224  const unsigned numDataArgs = Args.size() - firstDataArg;
8225 
8226  if (IgnoreStringsWithoutSpecifiers &&
8228  Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8229  return;
8230 
8231  // Emit a warning if the string literal is truncated and does not contain an
8232  // embedded null character.
8233  if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
8234  CheckFormatHandler::EmitFormatDiagnostic(
8235  S, inFunctionCall, Args[format_idx],
8236  S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8237  FExpr->getBeginLoc(),
8238  /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8239  return;
8240  }
8241 
8242  // CHECK: empty format string?
8243  if (StrLen == 0 && numDataArgs > 0) {
8244  CheckFormatHandler::EmitFormatDiagnostic(
8245  S, inFunctionCall, Args[format_idx],
8246  S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8247  /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8248  return;
8249  }
8250 
8254  CheckPrintfHandler H(
8255  S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8256  (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,
8257  Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,
8258  UncoveredArg);
8259 
8261  H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
8263  H.DoneProcessing();
8264  } else if (Type == Sema::FST_Scanf) {
8265  CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8266  numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
8267  CallType, CheckedVarArgs, UncoveredArg);
8268 
8270  H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8271  H.DoneProcessing();
8272  } // TODO: handle other formats
8273 }
8274 
8276  // Str - The format string. NOTE: this is NOT null-terminated!
8277  StringRef StrRef = FExpr->getString();
8278  const char *Str = StrRef.data();
8279  // Account for cases where the string literal is truncated in a declaration.
8280  const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8281  assert(T && "String literal not of constant array type!");
8282  size_t TypeSize = T->getZExtSize();
8283  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8284  return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8285  getLangOpts(),
8286  Context.getTargetInfo());
8287 }
8288 
8289 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8290 
8291 // Returns the related absolute value function that is larger, of 0 if one
8292 // does not exist.
8293 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8294  switch (AbsFunction) {
8295  default:
8296  return 0;
8297 
8298  case Builtin::BI__builtin_abs:
8299  return Builtin::BI__builtin_labs;
8300  case Builtin::BI__builtin_labs:
8301  return Builtin::BI__builtin_llabs;
8302  case Builtin::BI__builtin_llabs:
8303  return 0;
8304 
8305  case Builtin::BI__builtin_fabsf:
8306  return Builtin::BI__builtin_fabs;
8307  case Builtin::BI__builtin_fabs:
8308  return Builtin::BI__builtin_fabsl;
8309  case Builtin::BI__builtin_fabsl:
8310  return 0;
8311 
8312  case Builtin::BI__builtin_cabsf:
8313  return Builtin::BI__builtin_cabs;
8314  case Builtin::BI__builtin_cabs:
8315  return Builtin::BI__builtin_cabsl;
8316  case Builtin::BI__builtin_cabsl:
8317  return 0;
8318 
8319  case Builtin::BIabs:
8320  return Builtin::BIlabs;
8321  case Builtin::BIlabs:
8322  return Builtin::BIllabs;
8323  case Builtin::BIllabs:
8324  return 0;
8325 
8326  case Builtin::BIfabsf:
8327  return Builtin::BIfabs;
8328  case Builtin::BIfabs:
8329  return Builtin::BIfabsl;
8330  case Builtin::BIfabsl:
8331  return 0;
8332 
8333  case Builtin::BIcabsf:
8334  return Builtin::BIcabs;
8335  case Builtin::BIcabs:
8336  return Builtin::BIcabsl;
8337  case Builtin::BIcabsl:
8338  return 0;
8339  }
8340 }
8341 
8342 // Returns the argument type of the absolute value function.
8344  unsigned AbsType) {
8345  if (AbsType == 0)
8346  return QualType();
8347 
8349  QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8350  if (Error != ASTContext::GE_None)
8351  return QualType();
8352 
8354  if (!FT)
8355  return QualType();
8356 
8357  if (FT->getNumParams() != 1)
8358  return QualType();
8359 
8360  return FT->getParamType(0);
8361 }
8362 
8363 // Returns the best absolute value function, or zero, based on type and
8364 // current absolute value function.
8365 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8366  unsigned AbsFunctionKind) {
8367  unsigned BestKind = 0;
8368  uint64_t ArgSize = Context.getTypeSize(ArgType);
8369  for (unsigned Kind = AbsFunctionKind; Kind != 0;
8371  QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8372  if (Context.getTypeSize(ParamType) >= ArgSize) {
8373  if (BestKind == 0)
8374  BestKind = Kind;
8375  else if (Context.hasSameType(ParamType, ArgType)) {
8376  BestKind = Kind;
8377  break;
8378  }
8379  }
8380  }
8381  return BestKind;
8382 }
8383 
8387  AVK_Complex
8388 };
8389 
8392  return AVK_Integer;
8393  if (T->isRealFloatingType())
8394  return AVK_Floating;
8395  if (T->isAnyComplexType())
8396  return AVK_Complex;
8397 
8398  llvm_unreachable("Type not integer, floating, or complex");
8399 }
8400 
8401 // Changes the absolute value function to a different type. Preserves whether
8402 // the function is a builtin.
8403 static unsigned changeAbsFunction(unsigned AbsKind,
8404  AbsoluteValueKind ValueKind) {
8405  switch (ValueKind) {
8406  case AVK_Integer:
8407  switch (AbsKind) {
8408  default:
8409  return 0;
8410  case Builtin::BI__builtin_fabsf:
8411  case Builtin::BI__builtin_fabs:
8412  case Builtin::BI__builtin_fabsl:
8413  case Builtin::BI__builtin_cabsf:
8414  case Builtin::BI__builtin_cabs:
8415  case Builtin::BI__builtin_cabsl:
8416  return Builtin::BI__builtin_abs;
8417  case Builtin::BIfabsf:
8418  case Builtin::BIfabs:
8419  case Builtin::BIfabsl:
8420  case Builtin::BIcabsf:
8421  case Builtin::BIcabs:
8422  case Builtin::BIcabsl:
8423  return Builtin::BIabs;
8424  }
8425  case AVK_Floating:
8426  switch (AbsKind) {
8427  default:
8428  return 0;
8429  case Builtin::BI__builtin_abs:
8430  case Builtin::BI__builtin_labs:
8431  case Builtin::BI__builtin_llabs:
8432  case Builtin::BI__builtin_cabsf:
8433  case Builtin::BI__builtin_cabs:
8434  case Builtin::BI__builtin_cabsl:
8435  return Builtin::BI__builtin_fabsf;
8436  case Builtin::BIabs:
8437  case Builtin::BIlabs:
8438  case Builtin::BIllabs:
8439  case Builtin::BIcabsf:
8440  case Builtin::BIcabs:
8441  case Builtin::BIcabsl:
8442  return Builtin::BIfabsf;
8443  }
8444  case AVK_Complex:
8445  switch (AbsKind) {
8446  default:
8447  return 0;
8448  case Builtin::BI__builtin_abs:
8449  case Builtin::BI__builtin_labs:
8450  case Builtin::BI__builtin_llabs:
8451  case Builtin::BI__builtin_fabsf:
8452  case Builtin::BI__builtin_fabs:
8453  case Builtin::BI__builtin_fabsl:
8454  return Builtin::BI__builtin_cabsf;
8455  case Builtin::BIabs:
8456  case Builtin::BIlabs:
8457  case Builtin::BIllabs:
8458  case Builtin::BIfabsf:
8459  case Builtin::BIfabs:
8460  case Builtin::BIfabsl:
8461  return Builtin::BIcabsf;
8462  }
8463  }
8464  llvm_unreachable("Unable to convert function");
8465 }
8466 
8467 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8468  const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8469  if (!FnInfo)
8470  return 0;
8471 
8472  switch (FDecl->getBuiltinID()) {
8473  default:
8474  return 0;
8475  case Builtin::BI__builtin_abs:
8476  case Builtin::BI__builtin_fabs:
8477  case Builtin::BI__builtin_fabsf:
8478  case Builtin::BI__builtin_fabsl:
8479  case Builtin::BI__builtin_labs:
8480  case Builtin::BI__builtin_llabs:
8481  case Builtin::BI__builtin_cabs:
8482  case Builtin::BI__builtin_cabsf:
8483  case Builtin::BI__builtin_cabsl:
8484  case Builtin::BIabs:
8485  case Builtin::BIlabs:
8486  case Builtin::BIllabs:
8487  case Builtin::BIfabs:
8488  case Builtin::BIfabsf:
8489  case Builtin::BIfabsl:
8490  case Builtin::BIcabs:
8491  case Builtin::BIcabsf:
8492  case Builtin::BIcabsl:
8493  return FDecl->getBuiltinID();
8494  }
8495  llvm_unreachable("Unknown Builtin type");
8496 }
8497 
8498 // If the replacement is valid, emit a note with replacement function.
8499 // Additionally, suggest including the proper header if not already included.
8501  unsigned AbsKind, QualType ArgType) {
8502  bool EmitHeaderHint = true;
8503  const char *HeaderName = nullptr;
8504  StringRef FunctionName;
8505  if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8506  FunctionName = "std::abs";
8507  if (ArgType->isIntegralOrEnumerationType()) {
8508  HeaderName = "cstdlib";
8509  } else if (ArgType->isRealFloatingType()) {
8510  HeaderName = "cmath";
8511  } else {
8512  llvm_unreachable("Invalid Type");
8513  }
8514 
8515  // Lookup all std::abs
8516  if (NamespaceDecl *Std = S.getStdNamespace()) {
8518  R.suppressDiagnostics();
8519  S.LookupQualifiedName(R, Std);
8520 
8521  for (const auto *I : R) {
8522  const FunctionDecl *FDecl = nullptr;
8523  if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8524  FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8525  } else {
8526  FDecl = dyn_cast<FunctionDecl>(I);
8527  }
8528  if (!FDecl)
8529  continue;
8530 
8531  // Found std::abs(), check that they are the right ones.
8532  if (FDecl->getNumParams() != 1)
8533  continue;
8534 
8535  // Check that the parameter type can handle the argument.
8536  QualType ParamType = FDecl->getParamDecl(0)->getType();
8537  if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8538  S.Context.getTypeSize(ArgType) <=
8539  S.Context.getTypeSize(ParamType)) {
8540  // Found a function, don't need the header hint.
8541  EmitHeaderHint = false;
8542  break;
8543  }
8544  }
8545  }
8546  } else {
8547  FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8548  HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8549 
8550  if (HeaderName) {
8551  DeclarationName DN(&S.Context.Idents.get(FunctionName));
8553  R.suppressDiagnostics();
8554  S.LookupName(R, S.getCurScope());
8555 
8556  if (R.isSingleResult()) {
8557  FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8558  if (FD && FD->getBuiltinID() == AbsKind) {
8559  EmitHeaderHint = false;
8560  } else {
8561  return;
8562  }
8563  } else if (!R.empty()) {
8564  return;
8565  }
8566  }
8567  }
8568 
8569  S.Diag(Loc, diag::note_replace_abs_function)
8570  << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8571 
8572  if (!HeaderName)
8573  return;
8574 
8575  if (!EmitHeaderHint)
8576  return;
8577 
8578  S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8579  << FunctionName;
8580 }
8581 
8582 template <std::size_t StrLen>
8583 static bool IsStdFunction(const FunctionDecl *FDecl,
8584  const char (&Str)[StrLen]) {
8585  if (!FDecl)
8586  return false;
8587  if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8588  return false;
8589  if (!FDecl->isInStdNamespace())
8590  return false;
8591 
8592  return true;
8593 }
8594 
8595 enum class MathCheck { NaN, Inf };
8596 static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
8597  auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
8598  return std::any_of(names.begin(), names.end(), [&](llvm::StringRef name) {
8599  return calleeName == name;
8600  });
8601  };
8602 
8603  switch (Check) {
8604  case MathCheck::NaN:
8605  return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
8606  "__builtin_nanf16", "__builtin_nanf128"});
8607  case MathCheck::Inf:
8608  return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
8609  "__builtin_inff16", "__builtin_inff128"});
8610  }
8611  llvm_unreachable("unknown MathCheck");
8612 }
8613 
8614 void Sema::CheckInfNaNFunction(const CallExpr *Call,
8615  const FunctionDecl *FDecl) {
8616  FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
8617  bool HasIdentifier = FDecl->getIdentifier() != nullptr;
8618  bool IsNaNOrIsUnordered =
8619  IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered");
8620  bool IsSpecialNaN =
8621  HasIdentifier && IsInfOrNanFunction(FDecl->getName(), MathCheck::NaN);
8622  if ((IsNaNOrIsUnordered || IsSpecialNaN) && FPO.getNoHonorNaNs()) {
8623  Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
8624  << 1 << 0 << Call->getSourceRange();
8625  } else {
8626  bool IsInfOrIsFinite =
8627  IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite");
8628  bool IsInfinityOrIsSpecialInf =
8629  HasIdentifier && ((FDecl->getName() == "infinity") ||
8631  if ((IsInfOrIsFinite || IsInfinityOrIsSpecialInf) && FPO.getNoHonorInfs())
8632  Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
8633  << 0 << 0 << Call->getSourceRange();
8634  }
8635 }
8636 
8637 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8638  const FunctionDecl *FDecl) {
8639  if (Call->getNumArgs() != 1)
8640  return;
8641 
8642  unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8643  bool IsStdAbs = IsStdFunction(FDecl, "abs");
8644  if (AbsKind == 0 && !IsStdAbs)
8645  return;
8646 
8647  QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8648  QualType ParamType = Call->getArg(0)->getType();
8649 
8650  // Unsigned types cannot be negative. Suggest removing the absolute value
8651  // function call.
8652  if (ArgType->isUnsignedIntegerType()) {
8653  StringRef FunctionName =
8654  IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8655  Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8656  Diag(Call->getExprLoc(), diag::note_remove_abs)
8657  << FunctionName
8658  << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8659  return;
8660  }
8661 
8662  // Taking the absolute value of a pointer is very suspicious, they probably
8663  // wanted to index into an array, dereference a pointer, call a function, etc.
8664  if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8665  unsigned DiagType = 0;
8666  if (ArgType->isFunctionType())
8667  DiagType = 1;
8668  else if (ArgType->isArrayType())
8669  DiagType = 2;
8670 
8671  Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8672  return;
8673  }
8674 
8675  // std::abs has overloads which prevent most of the absolute value problems
8676  // from occurring.
8677  if (IsStdAbs)
8678  return;
8679 
8680  AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8681  AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8682 
8683  // The argument and parameter are the same kind. Check if they are the right
8684  // size.
8685  if (ArgValueKind == ParamValueKind) {
8686  if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8687  return;
8688 
8689  unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8690  Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8691  << FDecl << ArgType << ParamType;
8692 
8693  if (NewAbsKind == 0)
8694  return;
8695 
8696  emitReplacement(*this, Call->getExprLoc(),
8697  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8698  return;
8699  }
8700 
8701  // ArgValueKind != ParamValueKind
8702  // The wrong type of absolute value function was used. Attempt to find the
8703  // proper one.
8704  unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8705  NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8706  if (NewAbsKind == 0)
8707  return;
8708 
8709  Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8710  << FDecl << ParamValueKind << ArgValueKind;
8711 
8712  emitReplacement(*this, Call->getExprLoc(),
8713  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8714 }
8715 
8716 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8717 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8718  const FunctionDecl *FDecl) {
8719  if (!Call || !FDecl) return;
8720 
8721  // Ignore template specializations and macros.
8722  if (inTemplateInstantiation()) return;
8723  if (Call->getExprLoc().isMacroID()) return;
8724 
8725  // Only care about the one template argument, two function parameter std::max
8726  if (Call->getNumArgs() != 2) return;
8727  if (!IsStdFunction(FDecl, "max")) return;
8728  const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8729  if (!ArgList) return;
8730  if (ArgList->size() != 1) return;
8731 
8732  // Check that template type argument is unsigned integer.
8733  const auto& TA = ArgList->get(0);
8734  if (TA.getKind() != TemplateArgument::Type) return;
8735  QualType ArgType = TA.getAsType();
8736  if (!ArgType->isUnsignedIntegerType()) return;
8737 
8738  // See if either argument is a literal zero.
8739  auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8740  const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8741  if (!MTE) return false;
8742  const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
8743  if (!Num) return false;
8744  if (Num->getValue() != 0) return false;
8745  return true;
8746  };
8747 
8748  const Expr *FirstArg = Call->getArg(0);
8749  const Expr *SecondArg = Call->getArg(1);
8750  const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8751  const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8752 
8753  // Only warn when exactly one argument is zero.
8754  if (IsFirstArgZero == IsSecondArgZero) return;
8755 
8756  SourceRange FirstRange = FirstArg->getSourceRange();
8757  SourceRange SecondRange = SecondArg->getSourceRange();
8758 
8759  SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8760 
8761  Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8762  << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8763 
8764  // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8765  SourceRange RemovalRange;
8766  if (IsFirstArgZero) {
8767  RemovalRange = SourceRange(FirstRange.getBegin(),
8768  SecondRange.getBegin().getLocWithOffset(-1));
8769  } else {
8770  RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8771  SecondRange.getEnd());
8772  }
8773 
8774  Diag(Call->getExprLoc(), diag::note_remove_max_call)
8775  << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8776  << FixItHint::CreateRemoval(RemovalRange);
8777 }
8778 
8779 //===--- CHECK: Standard memory functions ---------------------------------===//
8780 
8781 /// Takes the expression passed to the size_t parameter of functions
8782 /// such as memcmp, strncat, etc and warns if it's a comparison.
8783 ///
8784 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8786  IdentifierInfo *FnName,
8787  SourceLocation FnLoc,
8788  SourceLocation RParenLoc) {
8789  const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8790  if (!Size)
8791  return false;
8792 
8793  // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8794  if (!Size->isComparisonOp() && !Size->isLogicalOp())
8795  return false;
8796 
8797  SourceRange SizeRange = Size->getSourceRange();
8798  S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8799  << SizeRange << FnName;
8800  S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8801  << FnName
8803  S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8804  << FixItHint::CreateRemoval(RParenLoc);
8805  S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8806  << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8808  ")");
8809 
8810  return true;
8811 }
8812 
8813 /// Determine whether the given type is or contains a dynamic class type
8814 /// (e.g., whether it has a vtable).
8816  bool &IsContained) {
8817  // Look through array types while ignoring qualifiers.
8818  const Type *Ty = T->getBaseElementTypeUnsafe();
8819  IsContained = false;
8820 
8821  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8822  RD = RD ? RD->getDefinition() : nullptr;
8823  if (!RD || RD->isInvalidDecl())
8824  return nullptr;
8825 
8826  if (RD->isDynamicClass())
8827  return RD;
8828 
8829  // Check all the fields. If any bases were dynamic, the class is dynamic.
8830  // It's impossible for a class to transitively contain itself by value, so
8831  // infinite recursion is impossible.
8832  for (auto *FD : RD->fields()) {
8833  bool SubContained;
8834  if (const CXXRecordDecl *ContainedRD =
8835  getContainedDynamicClass(FD->getType(), SubContained)) {
8836  IsContained = true;
8837  return ContainedRD;
8838  }
8839  }
8840 
8841  return nullptr;
8842 }
8843 
8845  if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8846  if (Unary->getKind() == UETT_SizeOf)
8847  return Unary;
8848  return nullptr;
8849 }
8850 
8851 /// If E is a sizeof expression, returns its argument expression,
8852 /// otherwise returns NULL.
8853 static const Expr *getSizeOfExprArg(const Expr *E) {
8855  if (!SizeOf->isArgumentType())
8856  return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8857  return nullptr;
8858 }
8859 
8860 /// If E is a sizeof expression, returns its argument type.
8863  return SizeOf->getTypeOfArgument();
8864  return QualType();
8865 }
8866 
8867 namespace {
8868 
8869 struct SearchNonTrivialToInitializeField
8870  : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8871  using Super =
8873 
8874  SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8875 
8876  void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8877  SourceLocation SL) {
8878  if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8879  asDerived().visitArray(PDIK, AT, SL);
8880  return;
8881  }
8882 
8883  Super::visitWithKind(PDIK, FT, SL);
8884  }
8885 
8886  void visitARCStrong(QualType FT, SourceLocation SL) {
8887  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8888  }
8889  void visitARCWeak(QualType FT, SourceLocation SL) {
8890  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8891  }
8892  void visitStruct(QualType FT, SourceLocation SL) {
8893  for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8894  visit(FD->getType(), FD->getLocation());
8895  }
8896  void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8897  const ArrayType *AT, SourceLocation SL) {
8898  visit(getContext().getBaseElementType(AT), SL);
8899  }
8900  void visitTrivial(QualType FT, SourceLocation SL) {}
8901 
8902  static void diag(QualType RT, const Expr *E, Sema &S) {
8903  SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8904  }
8905 
8906  ASTContext &getContext() { return S.getASTContext(); }
8907 
8908  const Expr *E;
8909  Sema &S;
8910 };
8911 
8912 struct SearchNonTrivialToCopyField
8913  : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8915 
8916  SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8917 
8918  void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8919  SourceLocation SL) {
8920  if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8921  asDerived().visitArray(PCK, AT, SL);
8922  return;
8923  }
8924 
8925  Super::visitWithKind(PCK, FT, SL);
8926  }
8927 
8928  void visitARCStrong(QualType FT, SourceLocation SL) {
8929  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8930  }
8931  void visitARCWeak(QualType FT, SourceLocation SL) {
8932  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8933  }
8934  void visitStruct(QualType FT, SourceLocation SL) {
8935  for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8936  visit(FD->getType(), FD->getLocation());
8937  }
8938  void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8939  SourceLocation SL) {
8940  visit(getContext().getBaseElementType(AT), SL);
8941  }
8942  void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8943  SourceLocation SL) {}
8944  void visitTrivial(QualType FT, SourceLocation SL) {}
8945  void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8946 
8947  static void diag(QualType RT, const Expr *E, Sema &S) {
8948  SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8949  }
8950 
8951  ASTContext &getContext() { return S.getASTContext(); }
8952 
8953  const Expr *E;
8954  Sema &S;
8955 };
8956 
8957 }
8958 
8959 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8960 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8961  SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8962 
8963  if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8964  if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8965  return false;
8966 
8967  return doesExprLikelyComputeSize(BO->getLHS()) ||
8968  doesExprLikelyComputeSize(BO->getRHS());
8969  }
8970 
8971  return getAsSizeOfExpr(SizeofExpr) != nullptr;
8972 }
8973 
8974 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8975 ///
8976 /// \code
8977 /// #define MACRO 0
8978 /// foo(MACRO);
8979 /// foo(0);
8980 /// \endcode
8981 ///
8982 /// This should return true for the first call to foo, but not for the second
8983 /// (regardless of whether foo is a macro or function).
8985  SourceLocation CallLoc,
8986  SourceLocation ArgLoc) {
8987  if (!CallLoc.isMacroID())
8988  return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8989 
8990  return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8991  SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8992 }
8993 
8994 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8995 /// last two arguments transposed.
8996 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8997  if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8998  return;
8999 
9000  const Expr *SizeArg =
9001  Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9002 
9003  auto isLiteralZero = [](const Expr *E) {
9004  return (isa<IntegerLiteral>(E) &&
9005  cast<IntegerLiteral>(E)->getValue() == 0) ||
9006  (isa<CharacterLiteral>(E) &&
9007  cast<CharacterLiteral>(E)->getValue() == 0);
9008  };
9009 
9010  // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9011  SourceLocation CallLoc = Call->getRParenLoc();
9013  if (isLiteralZero(SizeArg) &&
9014  !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9015 
9016  SourceLocation DiagLoc = SizeArg->getExprLoc();
9017 
9018  // Some platforms #define bzero to __builtin_memset. See if this is the
9019  // case, and if so, emit a better diagnostic.
9020  if (BId == Builtin::BIbzero ||
9022  CallLoc, SM, S.getLangOpts()) == "bzero")) {
9023  S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9024  S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9025  } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9026  S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9027  S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9028  }
9029  return;
9030  }
9031 
9032  // If the second argument to a memset is a sizeof expression and the third
9033  // isn't, this is also likely an error. This should catch
9034  // 'memset(buf, sizeof(buf), 0xff)'.
9035  if (BId == Builtin::BImemset &&
9036  doesExprLikelyComputeSize(Call->getArg(1)) &&
9037  !doesExprLikelyComputeSize(Call->getArg(2))) {
9038  SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9039  S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9040  S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9041  return;
9042  }
9043 }
9044 
9045 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9046  unsigned BId,
9047  IdentifierInfo *FnName) {
9048  assert(BId != 0);
9049 
9050  // It is possible to have a non-standard definition of memset. Validate
9051  // we have enough arguments, and if not, abort further checking.
9052  unsigned ExpectedNumArgs =
9053  (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9054  if (Call->getNumArgs() < ExpectedNumArgs)
9055  return;
9056 
9057  unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9058  BId == Builtin::BIstrndup ? 1 : 2);
9059  unsigned LenArg =
9060  (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9061  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9062 
9063  if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9064  Call->getBeginLoc(), Call->getRParenLoc()))
9065  return;
9066 
9067  // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9068  CheckMemaccessSize(*this, BId, Call);
9069 
9070  // We have special checking when the length is a sizeof expression.
9071  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9072  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9073  llvm::FoldingSetNodeID SizeOfArgID;
9074 
9075  // Although widely used, 'bzero' is not a standard function. Be more strict
9076  // with the argument types before allowing diagnostics and only allow the
9077  // form bzero(ptr, sizeof(...)).
9078  QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9079  if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9080  return;
9081 
9082  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9083  const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9084  SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9085 
9086  QualType DestTy = Dest->getType();
9087  QualType PointeeTy;
9088  if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9089  PointeeTy = DestPtrTy->getPointeeType();
9090 
9091  // Never warn about void type pointers. This can be used to suppress
9092  // false positives.
9093  if (PointeeTy->isVoidType())
9094  continue;
9095 
9096  // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9097  // actually comparing the expressions for equality. Because computing the
9098  // expression IDs can be expensive, we only do this if the diagnostic is
9099  // enabled.
9100  if (SizeOfArg &&
9101  !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9102  SizeOfArg->getExprLoc())) {
9103  // We only compute IDs for expressions if the warning is enabled, and
9104  // cache the sizeof arg's ID.
9105  if (SizeOfArgID == llvm::FoldingSetNodeID())
9106  SizeOfArg->Profile(SizeOfArgID, Context, true);
9107  llvm::FoldingSetNodeID DestID;
9108  Dest->Profile(DestID, Context, true);
9109  if (DestID == SizeOfArgID) {
9110  // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9111  // over sizeof(src) as well.
9112  unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9113  StringRef ReadableName = FnName->getName();
9114 
9115  if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9116  if (UnaryOp->getOpcode() == UO_AddrOf)
9117  ActionIdx = 1; // If its an address-of operator, just remove it.
9118  if (!PointeeTy->isIncompleteType() &&
9119  (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9120  ActionIdx = 2; // If the pointee's size is sizeof(char),
9121  // suggest an explicit length.
9122 
9123  // If the function is defined as a builtin macro, do not show macro
9124  // expansion.
9125  SourceLocation SL = SizeOfArg->getExprLoc();
9126  SourceRange DSR = Dest->getSourceRange();
9127  SourceRange SSR = SizeOfArg->getSourceRange();
9128  SourceManager &SM = getSourceManager();
9129 
9130  if (SM.isMacroArgExpansion(SL)) {
9131  ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9132  SL = SM.getSpellingLoc(SL);
9133  DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9134  SM.getSpellingLoc(DSR.getEnd()));
9135  SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9136  SM.getSpellingLoc(SSR.getEnd()));
9137  }
9138 
9139  DiagRuntimeBehavior(SL, SizeOfArg,
9140  PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9141  << ReadableName
9142  << PointeeTy
9143  << DestTy
9144  << DSR
9145  << SSR);
9146  DiagRuntimeBehavior(SL, SizeOfArg,
9147  PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9148  << ActionIdx
9149  << SSR);
9150 
9151  break;
9152  }
9153  }
9154 
9155  // Also check for cases where the sizeof argument is the exact same
9156  // type as the memory argument, and where it points to a user-defined
9157  // record type.
9158  if (SizeOfArgTy != QualType()) {
9159  if (PointeeTy->isRecordType() &&
9160  Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9161  DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9162  PDiag(diag::warn_sizeof_pointer_type_memaccess)
9163  << FnName << SizeOfArgTy << ArgIdx
9164  << PointeeTy << Dest->getSourceRange()
9165  << LenExpr->getSourceRange());
9166  break;
9167  }
9168  }
9169  } else if (DestTy->isArrayType()) {
9170  PointeeTy = DestTy;
9171  }
9172 
9173  if (PointeeTy == QualType())
9174  continue;
9175 
9176  // Always complain about dynamic classes.
9177  bool IsContained;
9178  if (const CXXRecordDecl *ContainedRD =
9179  getContainedDynamicClass(PointeeTy, IsContained)) {
9180 
9181  unsigned OperationType = 0;
9182  const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9183  // "overwritten" if we're warning about the destination for any call
9184  // but memcmp; otherwise a verb appropriate to the call.
9185  if (ArgIdx != 0 || IsCmp) {
9186  if (BId == Builtin::BImemcpy)
9187  OperationType = 1;
9188  else if(BId == Builtin::BImemmove)
9189  OperationType = 2;
9190  else if (IsCmp)
9191  OperationType = 3;
9192  }
9193 
9194  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9195  PDiag(diag::warn_dyn_class_memaccess)
9196  << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9197  << IsContained << ContainedRD << OperationType
9198  << Call->getCallee()->getSourceRange());
9199  } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9200  BId != Builtin::BImemset)
9201  DiagRuntimeBehavior(
9202  Dest->getExprLoc(), Dest,
9203  PDiag(diag::warn_arc_object_memaccess)
9204  << ArgIdx << FnName << PointeeTy
9205  << Call->getCallee()->getSourceRange());
9206  else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9207  if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9208  RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9209  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9210  PDiag(diag::warn_cstruct_memaccess)
9211  << ArgIdx << FnName << PointeeTy << 0);
9212  SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9213  } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9214  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9215  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9216  PDiag(diag::warn_cstruct_memaccess)
9217  << ArgIdx << FnName << PointeeTy << 1);
9218  SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9219  } else {
9220  continue;
9221  }
9222  } else
9223  continue;
9224 
9225  DiagRuntimeBehavior(
9226  Dest->getExprLoc(), Dest,
9227  PDiag(diag::note_bad_memaccess_silence)
9228  << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9229  break;
9230  }
9231 }
9232 
9233 // A little helper routine: ignore addition and subtraction of integer literals.
9234 // This intentionally does not ignore all integer constant expressions because
9235 // we don't want to remove sizeof().
9236 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9237  Ex = Ex->IgnoreParenCasts();
9238 
9239  while (true) {
9240  const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9241  if (!BO || !BO->isAdditiveOp())
9242  break;
9243 
9244  const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9245  const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9246 
9247  if (isa<IntegerLiteral>(RHS))
9248  Ex = LHS;
9249  else if (isa<IntegerLiteral>(LHS))
9250  Ex = RHS;
9251  else
9252  break;
9253  }
9254 
9255  return Ex;
9256 }
9257 
9259  ASTContext &Context) {
9260  // Only handle constant-sized or VLAs, but not flexible members.
9261  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9262  // Only issue the FIXIT for arrays of size > 1.
9263  if (CAT->getZExtSize() <= 1)
9264  return false;
9265  } else if (!Ty->isVariableArrayType()) {
9266  return false;
9267  }
9268  return true;
9269 }
9270 
9271 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9272  IdentifierInfo *FnName) {
9273 
9274  // Don't crash if the user has the wrong number of arguments
9275  unsigned NumArgs = Call->getNumArgs();
9276  if ((NumArgs != 3) && (NumArgs != 4))
9277  return;
9278 
9279  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9280  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9281  const Expr *CompareWithSrc = nullptr;
9282 
9283  if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9284  Call->getBeginLoc(), Call->getRParenLoc()))
9285  return;
9286 
9287  // Look for 'strlcpy(dst, x, sizeof(x))'
9288  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9289  CompareWithSrc = Ex;
9290  else {
9291  // Look for 'strlcpy(dst, x, strlen(x))'
9292  if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9293  if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9294  SizeCall->getNumArgs() == 1)
9295  CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9296  }
9297  }
9298 
9299  if (!CompareWithSrc)
9300  return;
9301 
9302  // Determine if the argument to sizeof/strlen is equal to the source
9303  // argument. In principle there's all kinds of things you could do
9304  // here, for instance creating an == expression and evaluating it with
9305  // EvaluateAsBooleanCondition, but this uses a more direct technique:
9306  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9307  if (!SrcArgDRE)
9308  return;
9309 
9310  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9311  if (!CompareWithSrcDRE ||
9312  SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9313  return;
9314 
9315  const Expr *OriginalSizeArg = Call->getArg(2);
9316  Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9317  << OriginalSizeArg->getSourceRange() << FnName;
9318 
9319  // Output a FIXIT hint if the destination is an array (rather than a
9320  // pointer to an array). This could be enhanced to handle some
9321  // pointers if we know the actual size, like if DstArg is 'array+2'
9322  // we could say 'sizeof(array)-2'.
9323  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9324  if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9325  return;
9326 
9327  SmallString<128> sizeString;
9328  llvm::raw_svector_ostream OS(sizeString);
9329  OS << "sizeof(";
9330  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9331  OS << ")";
9332 
9333  Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9334  << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9335  OS.str());
9336 }
9337 
9338 /// Check if two expressions refer to the same declaration.
9339 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9340  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9341  if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9342  return D1->getDecl() == D2->getDecl();
9343  return false;
9344 }
9345 
9346 static const Expr *getStrlenExprArg(const Expr *E) {
9347  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9348  const FunctionDecl *FD = CE->getDirectCallee();
9349  if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9350  return nullptr;
9351  return CE->getArg(0)->IgnoreParenCasts();
9352  }
9353  return nullptr;
9354 }
9355 
9356 void Sema::CheckStrncatArguments(const CallExpr *CE,
9357  IdentifierInfo *FnName) {
9358  // Don't crash if the user has the wrong number of arguments.
9359  if (CE->getNumArgs() < 3)
9360  return;
9361  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9362  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9363  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9364 
9365  if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9366  CE->getRParenLoc()))
9367  return;
9368 
9369  // Identify common expressions, which are wrongly used as the size argument
9370  // to strncat and may lead to buffer overflows.
9371  unsigned PatternType = 0;
9372  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9373  // - sizeof(dst)
9374  if (referToTheSameDecl(SizeOfArg, DstArg))
9375  PatternType = 1;
9376  // - sizeof(src)
9377  else if (referToTheSameDecl(SizeOfArg, SrcArg))
9378  PatternType = 2;
9379  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9380  if (BE->getOpcode() == BO_Sub) {
9381  const Expr *L = BE->getLHS()->IgnoreParenCasts();
9382  const Expr *R = BE->getRHS()->IgnoreParenCasts();
9383  // - sizeof(dst) - strlen(dst)
9384  if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9386  PatternType = 1;
9387  // - sizeof(src) - (anything)
9388  else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9389  PatternType = 2;
9390  }
9391  }
9392 
9393  if (PatternType == 0)
9394  return;
9395 
9396  // Generate the diagnostic.
9397  SourceLocation SL = LenArg->getBeginLoc();
9398  SourceRange SR = LenArg->getSourceRange();
9399  SourceManager &SM = getSourceManager();
9400 
9401  // If the function is defined as a builtin macro, do not show macro expansion.
9402  if (SM.isMacroArgExpansion(SL)) {
9403  SL = SM.getSpellingLoc(SL);
9404  SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9405  SM.getSpellingLoc(SR.getEnd()));
9406  }
9407 
9408  // Check if the destination is an array (rather than a pointer to an array).
9409  QualType DstTy = DstArg->getType();
9410  bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9411  Context);
9412  if (!isKnownSizeArray) {
9413  if (PatternType == 1)
9414  Diag(SL, diag::warn_strncat_wrong_size) << SR;
9415  else
9416  Diag(SL, diag::warn_strncat_src_size) << SR;
9417  return;
9418  }
9419 
9420  if (PatternType == 1)
9421  Diag(SL, diag::warn_strncat_large_size) << SR;
9422  else
9423  Diag(SL, diag::warn_strncat_src_size) << SR;
9424 
9425  SmallString<128> sizeString;
9426  llvm::raw_svector_ostream OS(sizeString);
9427  OS << "sizeof(";
9428  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9429  OS << ") - ";
9430  OS << "strlen(";
9431  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9432  OS << ") - 1";
9433 
9434  Diag(SL, diag::note_strncat_wrong_size)
9435  << FixItHint::CreateReplacement(SR, OS.str());
9436 }
9437 
9438 namespace {
9439 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
9440  const UnaryOperator *UnaryExpr, const Decl *D) {
9441  if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
9442  S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
9443  << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
9444  return;
9445  }
9446 }
9447 
9448 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
9449  const UnaryOperator *UnaryExpr) {
9450  if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
9451  const Decl *D = Lvalue->getDecl();
9452  if (isa<DeclaratorDecl>(D))
9453  if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
9454  return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
9455  }
9456 
9457  if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
9458  return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
9459  Lvalue->getMemberDecl());
9460 }
9461 
9462 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
9463  const UnaryOperator *UnaryExpr) {
9464  const auto *Lambda = dyn_cast<LambdaExpr>(
9465  UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
9466  if (!Lambda)
9467  return;
9468 
9469  S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
9470  << CalleeName << 2 /*object: lambda expression*/;
9471 }
9472 
9473 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
9474  const DeclRefExpr *Lvalue) {
9475  const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
9476  if (Var == nullptr)
9477  return;
9478 
9479  S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
9480  << CalleeName << 0 /*object: */ << Var;
9481 }
9482 
9483 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
9484  const CastExpr *Cast) {
9485  SmallString<128> SizeString;
9486  llvm::raw_svector_ostream OS(SizeString);
9487 
9488  clang::CastKind Kind = Cast->getCastKind();
9489  if (Kind == clang::CK_BitCast &&
9490  !Cast->getSubExpr()->getType()->isFunctionPointerType())
9491  return;
9492  if (Kind == clang::CK_IntegralToPointer &&
9493  !isa<IntegerLiteral>(
9494  Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
9495  return;
9496 
9497  switch (Cast->getCastKind()) {
9498  case clang::CK_BitCast:
9499  case clang::CK_IntegralToPointer:
9500  case clang::CK_FunctionToPointerDecay:
9501  OS << '\'';
9502  Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
9503  OS << '\'';
9504  break;
9505  default:
9506  return;
9507  }
9508 
9509  S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
9510  << CalleeName << 0 /*object: */ << OS.str();
9511 }
9512 } // namespace
9513 
9514 void Sema::CheckFreeArguments(const CallExpr *E) {
9515  const std::string CalleeName =
9516  cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
9517 
9518  { // Prefer something that doesn't involve a cast to make things simpler.
9519  const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
9520  if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
9521  switch (UnaryExpr->getOpcode()) {
9522  case UnaryOperator::Opcode::UO_AddrOf:
9523  return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
9524  case UnaryOperator::Opcode::UO_Plus:
9525  return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
9526  default:
9527  break;
9528  }
9529 
9530  if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
9531  if (Lvalue->getType()->isArrayType())
9532  return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
9533 
9534  if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
9535  Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
9536  << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
9537  return;
9538  }
9539 
9540  if (isa<BlockExpr>(Arg)) {
9541  Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
9542  << CalleeName << 1 /*object: block*/;
9543  return;
9544  }
9545  }
9546  // Maybe the cast was important, check after the other cases.
9547  if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
9548  return CheckFreeArgumentsCast(*this, CalleeName, Cast);
9549 }
9550 
9551 void
9552 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9553  SourceLocation ReturnLoc,
9554  bool isObjCMethod,
9555  const AttrVec *Attrs,
9556  const FunctionDecl *FD) {
9557  // Check if the return value is null but should not be.
9558  if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9559  (!isObjCMethod && isNonNullType(lhsType))) &&
9560  CheckNonNullExpr(*this, RetValExp))
9561  Diag(ReturnLoc, diag::warn_null_ret)
9562  << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9563 
9564  // C++11 [basic.stc.dynamic.allocation]p4:
9565  // If an allocation function declared with a non-throwing
9566  // exception-specification fails to allocate storage, it shall return
9567  // a null pointer. Any other allocation function that fails to allocate
9568  // storage shall indicate failure only by throwing an exception [...]
9569  if (FD) {
9571  if (Op == OO_New || Op == OO_Array_New) {
9572  const FunctionProtoType *Proto
9573  = FD->getType()->castAs<FunctionProtoType>();
9574  if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9575  CheckNonNullExpr(*this, RetValExp))
9576  Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9577  << FD << getLangOpts().CPlusPlus11;
9578  }
9579  }
9580 
9581  if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
9582  Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
9583  }
9584 
9585  // PPC MMA non-pointer types are not allowed as return type. Checking the type
9586  // here prevent the user from using a PPC MMA type as trailing return type.
9587  if (Context.getTargetInfo().getTriple().isPPC64())
9588  PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
9589 }
9590 
9594  return;
9595 
9596  // Match and capture subexpressions such as "(float) X == 0.1".
9597  FloatingLiteral *FPLiteral;
9598  CastExpr *FPCast;
9599  auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
9600  FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
9601  FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
9602  return FPLiteral && FPCast;
9603  };
9604 
9605  if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
9606  auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
9607  auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
9608  if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
9609  TargetTy->isFloatingPoint()) {
9610  bool Lossy;
9611  llvm::APFloat TargetC = FPLiteral->getValue();
9612  TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
9613  llvm::APFloat::rmNearestTiesToEven, &Lossy);
9614  if (Lossy) {
9615  // If the literal cannot be represented in the source type, then a
9616  // check for == is always false and check for != is always true.
9617  Diag(Loc, diag::warn_float_compare_literal)
9618  << (Opcode == BO_EQ) << QualType(SourceTy, 0)
9619  << LHS->getSourceRange() << RHS->getSourceRange();
9620  return;
9621  }
9622  }
9623  }
9624 
9625  // Match a more general floating-point equality comparison (-Wfloat-equal).
9626  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9627  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9628 
9629  // Special case: check for x == x (which is OK).
9630  // Do not emit warnings for such cases.
9631  if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9632  if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9633  if (DRL->getDecl() == DRR->getDecl())
9634  return;
9635 
9636  // Special case: check for comparisons against literals that can be exactly
9637  // represented by APFloat. In such cases, do not emit a warning. This
9638  // is a heuristic: often comparison against such literals are used to
9639  // detect if a value in a variable has not changed. This clearly can
9640  // lead to false negatives.
9641  if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9642  if (FLL->isExact())
9643  return;
9644  } else
9645  if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9646  if (FLR->isExact())
9647  return;
9648 
9649  // Check for comparisons with builtin types.
9650  if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9651  if (CL->getBuiltinCallee())
9652  return;
9653 
9654  if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9655  if (CR->getBuiltinCallee())
9656  return;
9657 
9658  // Emit the diagnostic.
9659  Diag(Loc, diag::warn_floatingpoint_eq)
9660  << LHS->getSourceRange() << RHS->getSourceRange();
9661 }
9662 
9663 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9664 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9665 
9666 namespace {
9667 
9668 /// Structure recording the 'active' range of an integer-valued
9669 /// expression.
9670 struct IntRange {
9671  /// The number of bits active in the int. Note that this includes exactly one
9672  /// sign bit if !NonNegative.
9673  unsigned Width;
9674 
9675  /// True if the int is known not to have negative values. If so, all leading
9676  /// bits before Width are known zero, otherwise they are known to be the
9677  /// same as the MSB within Width.
9678  bool NonNegative;
9679 
9680  IntRange(unsigned Width, bool NonNegative)
9681  : Width(Width), NonNegative(NonNegative) {}
9682 
9683  /// Number of bits excluding the sign bit.
9684  unsigned valueBits() const {
9685  return NonNegative ? Width : Width - 1;
9686  }
9687 
9688  /// Returns the range of the bool type.
9689  static IntRange forBoolType() {
9690  return IntRange(1, true);
9691  }
9692 
9693  /// Returns the range of an opaque value of the given integral type.
9694  static IntRange forValueOfType(ASTContext &C, QualType T) {
9695  return forValueOfCanonicalType(C,
9697  }
9698 
9699  /// Returns the range of an opaque value of a canonical integral type.
9700  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9701  assert(T->isCanonicalUnqualified());
9702 
9703  if (const VectorType *VT = dyn_cast<VectorType>(T))
9704  T = VT->getElementType().getTypePtr();
9705  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9706  T = CT->getElementType().getTypePtr();
9707  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9708  T = AT->getValueType().getTypePtr();
9709 
9710  if (!C.getLangOpts().CPlusPlus) {
9711  // For enum types in C code, use the underlying datatype.
9712  if (const EnumType *ET = dyn_cast<EnumType>(T))
9713  T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9714  } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9715  // For enum types in C++, use the known bit width of the enumerators.
9716  EnumDecl *Enum = ET->getDecl();
9717  // In C++11, enums can have a fixed underlying type. Use this type to
9718  // compute the range.
9719  if (Enum->isFixed()) {
9720  return IntRange(C.getIntWidth(QualType(T, 0)),
9722  }
9723 
9724  unsigned NumPositive = Enum->getNumPositiveBits();
9725  unsigned NumNegative = Enum->getNumNegativeBits();
9726 
9727  if (NumNegative == 0)
9728  return IntRange(NumPositive, true/*NonNegative*/);
9729  else
9730  return IntRange(std::max(NumPositive + 1, NumNegative),
9731  false/*NonNegative*/);
9732  }
9733 
9734  if (const auto *EIT = dyn_cast<BitIntType>(T))
9735  return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9736 
9737  const BuiltinType *BT = cast<BuiltinType>(T);
9738  assert(BT->isInteger());
9739 
9740  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9741  }
9742 
9743  /// Returns the "target" range of a canonical integral type, i.e.
9744  /// the range of values expressible in the type.
9745  ///
9746  /// This matches forValueOfCanonicalType except that enums have the
9747  /// full range of their type, not the range of their enumerators.
9748  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9749  assert(T->isCanonicalUnqualified());
9750 
9751  if (const VectorType *VT = dyn_cast<VectorType>(T))
9752  T = VT->getElementType().getTypePtr();
9753  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9754  T = CT->getElementType().getTypePtr();
9755  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9756  T = AT->getValueType().getTypePtr();
9757  if (const EnumType *ET = dyn_cast<EnumType>(T))
9758  T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9759 
9760  if (const auto *EIT = dyn_cast<BitIntType>(T))
9761  return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9762 
9763  const BuiltinType *BT = cast<BuiltinType>(T);
9764  assert(BT->isInteger());
9765 
9766  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9767  }
9768 
9769  /// Returns the supremum of two ranges: i.e. their conservative merge.
9770  static IntRange join(IntRange L, IntRange R) {
9771  bool Unsigned = L.NonNegative && R.NonNegative;
9772  return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
9773  L.NonNegative && R.NonNegative);
9774  }
9775 
9776  /// Return the range of a bitwise-AND of the two ranges.
9777  static IntRange bit_and(IntRange L, IntRange R) {
9778  unsigned Bits = std::max(L.Width, R.Width);
9779  bool NonNegative = false;
9780  if (L.NonNegative) {
9781  Bits = std::min(Bits, L.Width);
9782  NonNegative = true;
9783  }
9784  if (R.NonNegative) {
9785  Bits = std::min(Bits, R.Width);
9786  NonNegative = true;
9787  }
9788  return IntRange(Bits, NonNegative);
9789  }
9790 
9791  /// Return the range of a sum of the two ranges.
9792  static IntRange sum(IntRange L, IntRange R) {
9793  bool Unsigned = L.NonNegative && R.NonNegative;
9794  return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
9795  Unsigned);
9796  }
9797 
9798  /// Return the range of a difference of the two ranges.
9799  static IntRange difference(IntRange L, IntRange R) {
9800  // We need a 1-bit-wider range if:
9801  // 1) LHS can be negative: least value can be reduced.
9802  // 2) RHS can be negative: greatest value can be increased.
9803  bool CanWiden = !L.NonNegative || !R.NonNegative;
9804  bool Unsigned = L.NonNegative && R.Width == 0;
9805  return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
9806  !Unsigned,
9807  Unsigned);
9808  }
9809 
9810  /// Return the range of a product of the two ranges.
9811  static IntRange product(IntRange L, IntRange R) {
9812  // If both LHS and RHS can be negative, we can form
9813  // -2^L * -2^R = 2^(L + R)
9814  // which requires L + R + 1 value bits to represent.
9815  bool CanWiden = !L.NonNegative && !R.NonNegative;
9816  bool Unsigned = L.NonNegative && R.NonNegative;
9817  return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
9818  Unsigned);
9819  }
9820 
9821  /// Return the range of a remainder operation between the two ranges.
9822  static IntRange rem(IntRange L, IntRange R) {
9823  // The result of a remainder can't be larger than the result of
9824  // either side. The sign of the result is the sign of the LHS.
9825  bool Unsigned = L.NonNegative;
9826  return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
9827  Unsigned);
9828  }
9829 };
9830 
9831 } // namespace
9832 
9833 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9834  unsigned MaxWidth) {
9835  if (value.isSigned() && value.isNegative())
9836  return IntRange(value.getSignificantBits(), false);
9837 
9838  if (value.getBitWidth() > MaxWidth)
9839  value = value.trunc(MaxWidth);
9840 
9841  // isNonNegative() just checks the sign bit without considering
9842  // signedness.
9843  return IntRange(value.getActiveBits(), true);
9844 }
9845 
9846 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9847  unsigned MaxWidth) {
9848  if (result.isInt())
9849  return GetValueRange(C, result.getInt(), MaxWidth);
9850 
9851  if (result.isVector()) {
9852  IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9853  for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9854  IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9855  R = IntRange::join(R, El);
9856  }
9857  return R;
9858  }
9859 
9860  if (result.isComplexInt()) {
9861  IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9862  IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9863  return IntRange::join(R, I);
9864  }
9865 
9866  // This can happen with lossless casts to intptr_t of "based" lvalues.
9867  // Assume it might use arbitrary bits.
9868  // FIXME: The only reason we need to pass the type in here is to get
9869  // the sign right on this one case. It would be nice if APValue
9870  // preserved this.
9871  assert(result.isLValue() || result.isAddrLabelDiff());
9872  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9873 }
9874 
9875 static QualType GetExprType(const Expr *E) {
9876  QualType Ty = E->getType();
9877  if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9878  Ty = AtomicRHS->getValueType();
9879  return Ty;
9880 }
9881 
9882 /// Pseudo-evaluate the given integer expression, estimating the
9883 /// range of values it might take.
9884 ///
9885 /// \param MaxWidth The width to which the value will be truncated.
9886 /// \param Approximate If \c true, return a likely range for the result: in
9887 /// particular, assume that arithmetic on narrower types doesn't leave
9888 /// those types. If \c false, return a range including all possible
9889 /// result values.
9890 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
9891  bool InConstantContext, bool Approximate) {
9892  E = E->IgnoreParens();
9893 
9894  // Try a full evaluation first.
9895  Expr::EvalResult result;
9896  if (E->EvaluateAsRValue(result, C, InConstantContext))
9897  return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9898 
9899  // I think we only want to look through implicit casts here; if the
9900  // user has an explicit widening cast, we should treat the value as
9901  // being of the new, wider type.
9902  if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9903  if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9904  return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
9905  Approximate);
9906 
9907  IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9908 
9909  bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9910  CE->getCastKind() == CK_BooleanToSignedIntegral;
9911 
9912  // Assume that non-integer casts can span the full range of the type.
9913  if (!isIntegerCast)
9914  return OutputTypeRange;
9915 
9916  IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
9917  std::min(MaxWidth, OutputTypeRange.Width),
9918  InConstantContext, Approximate);
9919 
9920  // Bail out if the subexpr's range is as wide as the cast type.
9921  if (SubRange.Width >= OutputTypeRange.Width)
9922  return OutputTypeRange;
9923 
9924  // Otherwise, we take the smaller width, and we're non-negative if
9925  // either the output type or the subexpr is.
9926  return IntRange(SubRange.Width,
9927  SubRange.NonNegative || OutputTypeRange.NonNegative);
9928  }
9929 
9930  if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9931  // If we can fold the condition, just take that operand.
9932  bool CondResult;
9933  if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9934  return GetExprRange(C,
9935  CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
9936  MaxWidth, InConstantContext, Approximate);
9937 
9938  // Otherwise, conservatively merge.
9939  // GetExprRange requires an integer expression, but a throw expression
9940  // results in a void type.
9941  Expr *E = CO->getTrueExpr();
9942  IntRange L = E->getType()->isVoidType()
9943  ? IntRange{0, true}
9944  : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
9945  E = CO->getFalseExpr();
9946  IntRange R = E->getType()->isVoidType()
9947  ? IntRange{0, true}
9948  : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
9949  return IntRange::join(L, R);
9950  }
9951 
9952  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9953  IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
9954 
9955  switch (BO->getOpcode()) {
9956  case BO_Cmp:
9957  llvm_unreachable("builtin <=> should have class type");
9958 
9959  // Boolean-valued operations are single-bit and positive.
9960  case BO_LAnd:
9961  case BO_LOr:
9962  case BO_LT:
9963  case BO_GT:
9964  case BO_LE:
9965  case BO_GE:
9966  case BO_EQ:
9967  case BO_NE:
9968  return IntRange::forBoolType();
9969 
9970  // The type of the assignments is the type of the LHS, so the RHS
9971  // is not necessarily the same type.
9972  case BO_MulAssign:
9973  case BO_DivAssign:
9974  case BO_RemAssign:
9975  case BO_AddAssign:
9976  case BO_SubAssign:
9977  case BO_XorAssign:
9978  case BO_OrAssign:
9979  // TODO: bitfields?
9980  return IntRange::forValueOfType(C, GetExprType(E));
9981 
9982  // Simple assignments just pass through the RHS, which will have
9983  // been coerced to the LHS type.
9984  case BO_Assign:
9985  // TODO: bitfields?
9986  return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
9987  Approximate);
9988 
9989  // Operations with opaque sources are black-listed.
9990  case BO_PtrMemD:
9991  case BO_PtrMemI:
9992  return IntRange::forValueOfType(C, GetExprType(E));
9993 
9994  // Bitwise-and uses the *infinum* of the two source ranges.
9995  case BO_And:
9996  case BO_AndAssign:
9997  Combine = IntRange::bit_and;
9998  break;
9999 
10000  // Left shift gets black-listed based on a judgement call.
10001  case BO_Shl:
10002  // ...except that we want to treat '1 << (blah)' as logically
10003  // positive. It's an important idiom.
10004  if (IntegerLiteral *I
10005  = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10006  if (I->getValue() == 1) {
10007  IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10008  return IntRange(R.Width, /*NonNegative*/ true);
10009  }
10010  }
10011  [[fallthrough]];
10012 
10013  case BO_ShlAssign:
10014  return IntRange::forValueOfType(C, GetExprType(E));
10015 
10016  // Right shift by a constant can narrow its left argument.
10017  case BO_Shr:
10018  case BO_ShrAssign: {
10019  IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10020  Approximate);
10021 
10022  // If the shift amount is a positive constant, drop the width by
10023  // that much.
10024  if (std::optional<llvm::APSInt> shift =
10025  BO->getRHS()->getIntegerConstantExpr(C)) {
10026  if (shift->isNonNegative()) {
10027  if (shift->uge(L.Width))
10028  L.Width = (L.NonNegative ? 0 : 1);
10029  else
10030  L.Width -= shift->getZExtValue();
10031  }
10032  }
10033 
10034  return L;
10035  }
10036 
10037  // Comma acts as its right operand.
10038  case BO_Comma:
10039  return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10040  Approximate);
10041 
10042  case BO_Add:
10043  if (!Approximate)
10044  Combine = IntRange::sum;
10045  break;
10046 
10047  case BO_Sub:
10048  if (BO->getLHS()->getType()->isPointerType())
10049  return IntRange::forValueOfType(C, GetExprType(E));
10050  if (!Approximate)
10051  Combine = IntRange::difference;
10052  break;
10053 
10054  case BO_Mul:
10055  if (!Approximate)
10056  Combine = IntRange::product;
10057  break;
10058 
10059  // The width of a division result is mostly determined by the size
10060  // of the LHS.
10061  case BO_Div: {
10062  // Don't 'pre-truncate' the operands.
10063  unsigned opWidth = C.getIntWidth(GetExprType(E));
10064  IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10065  Approximate);
10066 
10067  // If the divisor is constant, use that.
10068  if (std::optional<llvm::APSInt> divisor =
10069  BO->getRHS()->getIntegerConstantExpr(C)) {
10070  unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10071  if (log2 >= L.Width)
10072  L.Width = (L.NonNegative ? 0 : 1);
10073  else
10074  L.Width = std::min(L.Width - log2, MaxWidth);
10075  return L;
10076  }
10077 
10078  // Otherwise, just use the LHS's width.
10079  // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10080  // could be -1.
10081  IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10082  Approximate);
10083  return IntRange(L.Width, L.NonNegative && R.NonNegative);
10084  }
10085 
10086  case BO_Rem:
10087  Combine = IntRange::rem;
10088  break;
10089 
10090  // The default behavior is okay for these.
10091  case BO_Xor:
10092  case BO_Or:
10093  break;
10094  }
10095 
10096  // Combine the two ranges, but limit the result to the type in which we
10097  // performed the computation.
10098  QualType T = GetExprType(E);
10099  unsigned opWidth = C.getIntWidth(T);
10100  IntRange L =
10101  GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10102  IntRange R =
10103  GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10104  IntRange C = Combine(L, R);
10105  C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10106  C.Width = std::min(C.Width, MaxWidth);
10107  return C;
10108  }
10109 
10110  if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10111  switch (UO->getOpcode()) {
10112  // Boolean-valued operations are white-listed.
10113  case UO_LNot:
10114  return IntRange::forBoolType();
10115 
10116  // Operations with opaque sources are black-listed.
10117  case UO_Deref:
10118  case UO_AddrOf: // should be impossible
10119  return IntRange::forValueOfType(C, GetExprType(E));
10120 
10121  default:
10122  return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10123  Approximate);
10124  }
10125  }
10126 
10127  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10128  return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10129  Approximate);
10130 
10131  if (const auto *BitField = E->getSourceBitField())
10132  return IntRange(BitField->getBitWidthValue(C),
10133  BitField->getType()->isUnsignedIntegerOrEnumerationType());
10134 
10135  return IntRange::forValueOfType(C, GetExprType(E));
10136 }
10137 
10138 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10139  bool InConstantContext, bool Approximate) {
10140  return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10141  Approximate);
10142 }
10143 
10144 /// Checks whether the given value, which currently has the given
10145 /// source semantics, has the same value when coerced through the
10146 /// target semantics.
10147 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10148  const llvm::fltSemantics &Src,
10149  const llvm::fltSemantics &Tgt) {
10150  llvm::APFloat truncated = value;
10151 
10152  bool ignored;
10153  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10154  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10155 
10156  return truncated.bitwiseIsEqual(value);
10157 }
10158 
10159 /// Checks whether the given value, which currently has the given
10160 /// source semantics, has the same value when coerced through the
10161 /// target semantics.
10162 ///
10163 /// The value might be a vector of floats (or a complex number).
10164 static bool IsSameFloatAfterCast(const APValue &value,
10165  const llvm::fltSemantics &Src,
10166  const llvm::fltSemantics &Tgt) {
10167  if (value.isFloat())
10168  return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10169 
10170  if (value.isVector()) {
10171  for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10172  if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10173  return false;
10174  return true;
10175  }
10176 
10177  assert(value.isComplexFloat());
10178  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10179  IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10180 }
10181 
10182 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10183  bool IsListInit = false);
10184 
10185 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10186  // Suppress cases where we are comparing against an enum constant.
10187  if (const DeclRefExpr *DR =
10188  dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10189  if (isa<EnumConstantDecl>(DR->getDecl()))
10190  return true;
10191 
10192  // Suppress cases where the value is expanded from a macro, unless that macro
10193  // is how a language represents a boolean literal. This is the case in both C
10194  // and Objective-C.
10195  SourceLocation BeginLoc = E->getBeginLoc();
10196  if (BeginLoc.isMacroID()) {
10197  StringRef MacroName = Lexer::getImmediateMacroName(
10198  BeginLoc, S.getSourceManager(), S.getLangOpts());
10199  return MacroName != "YES" && MacroName != "NO" &&
10200  MacroName != "true" && MacroName != "false";
10201  }
10202 
10203  return false;
10204 }
10205 
10207  return E->getType()->isIntegerType() &&
10208  (!E->getType()->isSignedIntegerType() ||
10210 }
10211 
10212 namespace {
10213 /// The promoted range of values of a type. In general this has the
10214 /// following structure:
10215 ///
10216 /// |-----------| . . . |-----------|
10217 /// ^ ^ ^ ^
10218 /// Min HoleMin HoleMax Max
10219 ///
10220 /// ... where there is only a hole if a signed type is promoted to unsigned
10221 /// (in which case Min and Max are the smallest and largest representable
10222 /// values).
10223 struct PromotedRange {
10224  // Min, or HoleMax if there is a hole.
10225  llvm::APSInt PromotedMin;
10226  // Max, or HoleMin if there is a hole.
10227  llvm::APSInt PromotedMax;
10228 
10229  PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10230  if (R.Width == 0)
10231  PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10232  else if (R.Width >= BitWidth && !Unsigned) {
10233  // Promotion made the type *narrower*. This happens when promoting
10234  // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10235  // Treat all values of 'signed int' as being in range for now.
10236  PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10237  PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10238  } else {
10239  PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10240  .extOrTrunc(BitWidth);
10241  PromotedMin.setIsUnsigned(Unsigned);
10242 
10243  PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10244  .extOrTrunc(BitWidth);
10245  PromotedMax.setIsUnsigned(Unsigned);
10246  }
10247  }
10248 
10249  // Determine whether this range is contiguous (has no hole).
10250  bool isContiguous() const { return PromotedMin <= PromotedMax; }
10251 
10252  // Where a constant value is within the range.
10253  enum ComparisonResult {
10254  LT = 0x1,
10255  LE = 0x2,
10256  GT = 0x4,
10257  GE = 0x8,
10258  EQ = 0x10,
10259  NE = 0x20,
10260  InRangeFlag = 0x40,
10261 
10262  Less = LE | LT | NE,
10263  Min = LE | InRangeFlag,
10264  InRange = InRangeFlag,
10265  Max = GE | InRangeFlag,
10266  Greater = GE | GT | NE,
10267 
10268  OnlyValue = LE | GE | EQ | InRangeFlag,
10269  InHole = NE
10270  };
10271 
10272  ComparisonResult compare(const llvm::APSInt &Value) const {
10273  assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10274  Value.isUnsigned() == PromotedMin.isUnsigned());
10275  if (!isContiguous()) {
10276  assert(Value.isUnsigned() && "discontiguous range for signed compare");
10277  if (Value.isMinValue()) return Min;
10278  if (Value.isMaxValue()) return Max;
10279  if (Value >= PromotedMin) return InRange;
10280  if (Value <= PromotedMax) return InRange;
10281  return InHole;
10282  }
10283 
10284  switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10285  case -1: return Less;
10286  case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10287  case 1:
10288  switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10289  case -1: return InRange;
10290  case 0: return Max;
10291  case 1: return Greater;
10292  }
10293  }
10294 
10295  llvm_unreachable("impossible compare result");
10296  }
10297 
10298  static std::optional<StringRef>
10299  constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10300  if (Op == BO_Cmp) {
10301  ComparisonResult LTFlag = LT, GTFlag = GT;
10302  if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10303 
10304  if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10305  if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10306  if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10307  return std::nullopt;
10308  }
10309 
10310  ComparisonResult TrueFlag, FalseFlag;
10311  if (Op == BO_EQ) {
10312  TrueFlag = EQ;
10313  FalseFlag = NE;
10314  } else if (Op == BO_NE) {
10315  TrueFlag = NE;
10316  FalseFlag = EQ;
10317  } else {
10318  if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10319  TrueFlag = LT;
10320  FalseFlag = GE;
10321  } else {
10322  TrueFlag = GT;
10323  FalseFlag = LE;
10324  }
10325  if (Op == BO_GE || Op == BO_LE)
10326  std::swap(TrueFlag, FalseFlag);
10327  }
10328  if (R & TrueFlag)
10329  return StringRef("true");
10330  if (R & FalseFlag)
10331  return StringRef("false");
10332  return std::nullopt;
10333  }
10334 };
10335 }
10336 
10337 static bool HasEnumType(Expr *E) {
10338  // Strip off implicit integral promotions.
10339  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10340  if (ICE->getCastKind() != CK_IntegralCast &&
10341  ICE->getCastKind() != CK_NoOp)
10342  break;
10343  E = ICE->getSubExpr();
10344  }
10345 
10346  return E->getType()->isEnumeralType();
10347 }
10348 
10349 static int classifyConstantValue(Expr *Constant) {
10350  // The values of this enumeration are used in the diagnostics
10351  // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10352  enum ConstantValueKind {
10353  Miscellaneous = 0,
10354  LiteralTrue,
10355  LiteralFalse
10356  };
10357  if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10358  return BL->getValue() ? ConstantValueKind::LiteralTrue
10359  : ConstantValueKind::LiteralFalse;
10360  return ConstantValueKind::Miscellaneous;
10361 }
10362 
10364  Expr *Constant, Expr *Other,
10365  const llvm::APSInt &Value,
10366  bool RhsConstant) {
10367  if (S.inTemplateInstantiation())
10368  return false;
10369 
10370  Expr *OriginalOther = Other;
10371 
10372  Constant = Constant->IgnoreParenImpCasts();
10373  Other = Other->IgnoreParenImpCasts();
10374 
10375  // Suppress warnings on tautological comparisons between values of the same
10376  // enumeration type. There are only two ways we could warn on this:
10377  // - If the constant is outside the range of representable values of
10378  // the enumeration. In such a case, we should warn about the cast
10379  // to enumeration type, not about the comparison.
10380  // - If the constant is the maximum / minimum in-range value. For an
10381  // enumeratin type, such comparisons can be meaningful and useful.
10382  if (Constant->getType()->isEnumeralType() &&
10383  S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10384  return false;
10385 
10386  IntRange OtherValueRange = GetExprRange(
10387  S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
10388 
10389  QualType OtherT = Other->getType();
10390  if (const auto *AT = OtherT->getAs<AtomicType>())
10391  OtherT = AT->getValueType();
10392  IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
10393 
10394  // Special case for ObjC BOOL on targets where its a typedef for a signed char
10395  // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
10396  bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10397  S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
10398  OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10399 
10400  // Whether we're treating Other as being a bool because of the form of
10401  // expression despite it having another type (typically 'int' in C).
10402  bool OtherIsBooleanDespiteType =
10403  !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10404  if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10405  OtherTypeRange = OtherValueRange = IntRange::forBoolType();
10406 
10407  // Check if all values in the range of possible values of this expression
10408  // lead to the same comparison outcome.
10409  PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
10410  Value.isUnsigned());
10411  auto Cmp = OtherPromotedValueRange.compare(Value);
10412  auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10413  if (!Result)
10414  return false;
10415 
10416  // Also consider the range determined by the type alone. This allows us to
10417  // classify the warning under the proper diagnostic group.
10418  bool TautologicalTypeCompare = false;
10419  {
10420  PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
10421  Value.isUnsigned());
10422  auto TypeCmp = OtherPromotedTypeRange.compare(Value);
10423  if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
10424  RhsConstant)) {
10425  TautologicalTypeCompare = true;
10426  Cmp = TypeCmp;
10427  Result = TypeResult;
10428  }
10429  }
10430 
10431  // Don't warn if the non-constant operand actually always evaluates to the
10432  // same value.
10433  if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
10434  return false;
10435 
10436  // Suppress the diagnostic for an in-range comparison if the constant comes
10437  // from a macro or enumerator. We don't want to diagnose
10438  //
10439  // some_long_value <= INT_MAX
10440  //
10441  // when sizeof(int) == sizeof(long).
10442  bool InRange = Cmp & PromotedRange::InRangeFlag;
10443  if (InRange && IsEnumConstOrFromMacro(S, Constant))
10444  return false;
10445 
10446  // A comparison of an unsigned bit-field against 0 is really a type problem,
10447  // even though at the type level the bit-field might promote to 'signed int'.
10448  if (Other->refersToBitField() && InRange && Value == 0 &&
10449  Other->getType()->isUnsignedIntegerOrEnumerationType())
10450  TautologicalTypeCompare = true;
10451 
10452  // If this is a comparison to an enum constant, include that
10453  // constant in the diagnostic.
10454  const EnumConstantDecl *ED = nullptr;
10455  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10456  ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10457 
10458  // Should be enough for uint128 (39 decimal digits)
10459  SmallString<64> PrettySourceValue;
10460  llvm::raw_svector_ostream OS(PrettySourceValue);
10461  if (ED) {
10462  OS << '\'' << *ED << "' (" << Value << ")";
10463  } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10464  Constant->IgnoreParenImpCasts())) {
10465  OS << (BL->getValue() ? "YES" : "NO");
10466  } else {
10467  OS << Value;
10468  }
10469 
10470  if (!TautologicalTypeCompare) {
10471  S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
10472  << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
10473  << E->getOpcodeStr() << OS.str() << *Result
10474  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10475  return true;
10476  }
10477 
10478  if (IsObjCSignedCharBool) {
10479  S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10480  S.PDiag(diag::warn_tautological_compare_objc_bool)
10481  << OS.str() << *Result);
10482  return true;
10483  }
10484 
10485  // FIXME: We use a somewhat different formatting for the in-range cases and
10486  // cases involving boolean values for historical reasons. We should pick a
10487  // consistent way of presenting these diagnostics.
10488  if (!InRange || Other->isKnownToHaveBooleanValue()) {
10489 
10491  E->getOperatorLoc(), E,
10492  S.PDiag(!InRange ? diag::warn_out_of_range_compare
10493  : diag::warn_tautological_bool_compare)
10494  << OS.str() << classifyConstantValue(Constant) << OtherT
10495  << OtherIsBooleanDespiteType << *Result
10496  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10497  } else {
10498  bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
10499  unsigned Diag =
10500  (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10501  ? (HasEnumType(OriginalOther)
10502  ? diag::warn_unsigned_enum_always_true_comparison
10503  : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
10504  : diag::warn_unsigned_always_true_comparison)
10505  : diag::warn_tautological_constant_compare;
10506 
10507  S.Diag(E->getOperatorLoc(), Diag)
10508  << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10509  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10510  }
10511 
10512  return true;
10513 }
10514 
10515 /// Analyze the operands of the given comparison. Implements the
10516 /// fallback case from AnalyzeComparison.
10518  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10519  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10520 }
10521 
10522 /// Implements -Wsign-compare.
10523 ///
10524 /// \param E the binary operator to check for warnings
10526  // The type the comparison is being performed in.
10527  QualType T = E->getLHS()->getType();
10528 
10529  // Only analyze comparison operators where both sides have been converted to
10530  // the same type.
10531  if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10532  return AnalyzeImpConvsInComparison(S, E);
10533 
10534  // Don't analyze value-dependent comparisons directly.
10535  if (E->isValueDependent())
10536  return AnalyzeImpConvsInComparison(S, E);
10537 
10538  Expr *LHS = E->getLHS();
10539  Expr *RHS = E->getRHS();
10540 
10541  if (T->isIntegralType(S.Context)) {
10542  std::optional<llvm::APSInt> RHSValue =
10544  std::optional<llvm::APSInt> LHSValue =
10546 
10547  // We don't care about expressions whose result is a constant.
10548  if (RHSValue && LHSValue)
10549  return AnalyzeImpConvsInComparison(S, E);
10550 
10551  // We only care about expressions where just one side is literal
10552  if ((bool)RHSValue ^ (bool)LHSValue) {
10553  // Is the constant on the RHS or LHS?
10554  const bool RhsConstant = (bool)RHSValue;
10555  Expr *Const = RhsConstant ? RHS : LHS;
10556  Expr *Other = RhsConstant ? LHS : RHS;
10557  const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
10558 
10559  // Check whether an integer constant comparison results in a value
10560  // of 'true' or 'false'.
10561  if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10562  return AnalyzeImpConvsInComparison(S, E);
10563  }
10564  }
10565 
10567  // We don't do anything special if this isn't an unsigned integral
10568  // comparison: we're only interested in integral comparisons, and
10569  // signed comparisons only happen in cases we don't care to warn about.
10570  return AnalyzeImpConvsInComparison(S, E);
10571  }
10572 
10573  LHS = LHS->IgnoreParenImpCasts();
10574  RHS = RHS->IgnoreParenImpCasts();
10575 
10576  if (!S.getLangOpts().CPlusPlus) {
10577  // Avoid warning about comparison of integers with different signs when
10578  // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10579  // the type of `E`.
10580  if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10581  LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10582  if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10583  RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10584  }
10585 
10586  // Check to see if one of the (unmodified) operands is of different
10587  // signedness.
10588  Expr *signedOperand, *unsignedOperand;
10589  if (LHS->getType()->hasSignedIntegerRepresentation()) {
10590  assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10591  "unsigned comparison between two signed integer expressions?");
10592  signedOperand = LHS;
10593  unsignedOperand = RHS;
10594  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10595  signedOperand = RHS;
10596  unsignedOperand = LHS;
10597  } else {
10598  return AnalyzeImpConvsInComparison(S, E);
10599  }
10600 
10601  // Otherwise, calculate the effective range of the signed operand.
10602  IntRange signedRange =
10603  GetExprRange(S.Context, signedOperand, S.isConstantEvaluatedContext(),
10604  /*Approximate=*/true);
10605 
10606  // Go ahead and analyze implicit conversions in the operands. Note
10607  // that we skip the implicit conversions on both sides.
10608  AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10609  AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10610 
10611  // If the signed range is non-negative, -Wsign-compare won't fire.
10612  if (signedRange.NonNegative)
10613  return;
10614 
10615  // For (in)equality comparisons, if the unsigned operand is a
10616  // constant which cannot collide with a overflowed signed operand,
10617  // then reinterpreting the signed operand as unsigned will not
10618  // change the result of the comparison.
10619  if (E->isEqualityOp()) {
10620  unsigned comparisonWidth = S.Context.getIntWidth(T);
10621  IntRange unsignedRange =
10622  GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
10623  /*Approximate=*/true);
10624 
10625  // We should never be unable to prove that the unsigned operand is
10626  // non-negative.
10627  assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10628 
10629  if (unsignedRange.Width < comparisonWidth)
10630  return;
10631  }
10632 
10633  S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10634  S.PDiag(diag::warn_mixed_sign_comparison)
10635  << LHS->getType() << RHS->getType()
10636  << LHS->getSourceRange() << RHS->getSourceRange());
10637 }
10638 
10639 /// Analyzes an attempt to assign the given value to a bitfield.
10640 ///
10641 /// Returns true if there was something fishy about the attempt.
10642 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10643  SourceLocation InitLoc) {
10644  assert(Bitfield->isBitField());
10645  if (Bitfield->isInvalidDecl())
10646  return false;
10647 
10648  // White-list bool bitfields.
10649  QualType BitfieldType = Bitfield->getType();
10650  if (BitfieldType->isBooleanType())
10651  return false;
10652 
10653  if (BitfieldType->isEnumeralType()) {
10654  EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10655  // If the underlying enum type was not explicitly specified as an unsigned
10656  // type and the enum contain only positive values, MSVC++ will cause an
10657  // inconsistency by storing this as a signed type.
10658  if (S.getLangOpts().CPlusPlus11 &&
10659  !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10660  BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10661  BitfieldEnumDecl->getNumNegativeBits() == 0) {
10662  S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10663  << BitfieldEnumDecl;
10664  }
10665  }
10666 
10667  // Ignore value- or type-dependent expressions.
10668  if (Bitfield->getBitWidth()->isValueDependent() ||
10669  Bitfield->getBitWidth()->isTypeDependent() ||
10670  Init->isValueDependent() ||
10671  Init->isTypeDependent())
10672  return false;
10673 
10674  Expr *OriginalInit = Init->IgnoreParenImpCasts();
10675  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10676 
10677  Expr::EvalResult Result;
10678  if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10680  // The RHS is not constant. If the RHS has an enum type, make sure the
10681  // bitfield is wide enough to hold all the values of the enum without
10682  // truncation.
10683  if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10684  EnumDecl *ED = EnumTy->getDecl();
10685  bool SignedBitfield = BitfieldType->isSignedIntegerType();
10686 
10687  // Enum types are implicitly signed on Windows, so check if there are any
10688  // negative enumerators to see if the enum was intended to be signed or
10689  // not.
10690  bool SignedEnum = ED->getNumNegativeBits() > 0;
10691 
10692  // Check for surprising sign changes when assigning enum values to a
10693  // bitfield of different signedness. If the bitfield is signed and we
10694  // have exactly the right number of bits to store this unsigned enum,
10695  // suggest changing the enum to an unsigned type. This typically happens
10696  // on Windows where unfixed enums always use an underlying type of 'int'.
10697  unsigned DiagID = 0;
10698  if (SignedEnum && !SignedBitfield) {
10699  DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10700  } else if (SignedBitfield && !SignedEnum &&
10701  ED->getNumPositiveBits() == FieldWidth) {
10702  DiagID = diag::warn_signed_bitfield_enum_conversion;
10703  }
10704 
10705  if (DiagID) {
10706  S.Diag(InitLoc, DiagID) << Bitfield << ED;
10707  TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10708  SourceRange TypeRange =
10709  TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10710  S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10711  << SignedEnum << TypeRange;
10712  }
10713 
10714  // Compute the required bitwidth. If the enum has negative values, we need
10715  // one more bit than the normal number of positive bits to represent the
10716  // sign bit.
10717  unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10718  ED->getNumNegativeBits())
10719  : ED->getNumPositiveBits();
10720 
10721  // Check the bitwidth.
10722  if (BitsNeeded > FieldWidth) {
10723  Expr *WidthExpr = Bitfield->getBitWidth();
10724  S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10725  << Bitfield << ED;
10726  S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10727  << BitsNeeded << ED << WidthExpr->getSourceRange();
10728  }
10729  }
10730 
10731  return false;
10732  }
10733 
10734  llvm::APSInt Value = Result.Val.getInt();
10735 
10736  unsigned OriginalWidth = Value.getBitWidth();
10737 
10738  // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
10739  // false positives where the user is demonstrating they intend to use the
10740  // bit-field as a Boolean, check to see if the value is 1 and we're assigning
10741  // to a one-bit bit-field to see if the value came from a macro named 'true'.
10742  bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
10743  if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
10744  SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
10745  if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
10746  S.findMacroSpelling(MaybeMacroLoc, "true"))
10747  return false;
10748  }
10749 
10750  if (!Value.isSigned() || Value.isNegative())
10751  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10752  if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10753  OriginalWidth = Value.getSignificantBits();
10754 
10755  if (OriginalWidth <= FieldWidth)
10756  return false;
10757 
10758  // Compute the value which the bitfield will contain.
10759  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10760  TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10761 
10762  // Check whether the stored value is equal to the original value.
10763  TruncatedValue = TruncatedValue.extend(OriginalWidth);
10764  if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10765  return false;
10766 
10767  std::string PrettyValue = toString(Value, 10);
10768  std::string PrettyTrunc = toString(TruncatedValue, 10);
10769 
10770  S.Diag(InitLoc, OneAssignedToOneBitBitfield
10771  ? diag::warn_impcast_single_bit_bitield_precision_constant
10772  : diag::warn_impcast_bitfield_precision_constant)
10773  << PrettyValue << PrettyTrunc << OriginalInit->getType()
10774  << Init->getSourceRange();
10775 
10776  return true;
10777 }
10778 
10779 /// Analyze the given simple or compound assignment for warning-worthy
10780 /// operations.
10782  // Just recurse on the LHS.
10783  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10784 
10785  // We want to recurse on the RHS as normal unless we're assigning to
10786  // a bitfield.
10787  if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10788  if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10789  E->getOperatorLoc())) {
10790  // Recurse, ignoring any implicit conversions on the RHS.
10791  return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10792  E->getOperatorLoc());
10793  }
10794  }
10795 
10796  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10797 
10798  // Diagnose implicitly sequentially-consistent atomic assignment.
10799  if (E->getLHS()->getType()->isAtomicType())
10800  S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10801 }
10802 
10803 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
10804 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10805  SourceLocation CContext, unsigned diag,
10806  bool pruneControlFlow = false) {
10807  if (pruneControlFlow) {
10809  S.PDiag(diag)
10810  << SourceType << T << E->getSourceRange()
10811  << SourceRange(CContext));
10812  return;
10813  }
10814  S.Diag(E->getExprLoc(), diag)
10815  << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10816 }
10817 
10818 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
10819 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10820  SourceLocation CContext,
10821  unsigned diag, bool pruneControlFlow = false) {
10822  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10823 }
10824 
10825 /// Diagnose an implicit cast from a floating point value to an integer value.
10827  SourceLocation CContext) {
10828  const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10829  const bool PruneWarnings = S.inTemplateInstantiation();
10830 
10831  Expr *InnerE = E->IgnoreParenImpCasts();
10832  // We also want to warn on, e.g., "int i = -1.234"
10833  if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10834  if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10835  InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10836 
10837  const bool IsLiteral =
10838  isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10839 
10840  llvm::APFloat Value(0.0);
10841  bool IsConstant =
10843  if (!IsConstant) {
10844  if (S.ObjC().isSignedCharBool(T)) {
10846  E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10847  << E->getType());
10848  }
10849 
10850  return DiagnoseImpCast(S, E, T, CContext,
10851  diag::warn_impcast_float_integer, PruneWarnings);
10852  }
10853 
10854  bool isExact = false;
10855 
10856  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10858  llvm::APFloat::opStatus Result = Value.convertToInteger(
10859  IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10860 
10861  // FIXME: Force the precision of the source value down so we don't print
10862  // digits which are usually useless (we don't really care here if we
10863  // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10864  // would automatically print the shortest representation, but it's a bit
10865  // tricky to implement.
10866  SmallString<16> PrettySourceValue;
10867  unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10868  precision = (precision * 59 + 195) / 196;
10869  Value.toString(PrettySourceValue, precision);
10870 
10871  if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
10873  E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10874  << PrettySourceValue);
10875  }
10876 
10877  if (Result == llvm::APFloat::opOK && isExact) {
10878  if (IsLiteral) return;
10879  return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10880  PruneWarnings);
10881  }
10882 
10883  // Conversion of a floating-point value to a non-bool integer where the
10884  // integral part cannot be represented by the integer type is undefined.
10885  if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10886  return DiagnoseImpCast(
10887  S, E, T, CContext,
10888  IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10889  : diag::warn_impcast_float_to_integer_out_of_range,
10890  PruneWarnings);
10891 
10892  unsigned DiagID = 0;
10893  if (IsLiteral) {
10894  // Warn on floating point literal to integer.
10895  DiagID = diag::warn_impcast_literal_float_to_integer;
10896  } else if (IntegerValue == 0) {
10897  if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10898  return DiagnoseImpCast(S, E, T, CContext,
10899  diag::warn_impcast_float_integer, PruneWarnings);
10900  }
10901  // Warn on non-zero to zero conversion.
10902  DiagID = diag::warn_impcast_float_to_integer_zero;
10903  } else {
10904  if (IntegerValue.isUnsigned()) {
10905  if (!IntegerValue.isMaxValue()) {
10906  return DiagnoseImpCast(S, E, T, CContext,
10907  diag::warn_impcast_float_integer, PruneWarnings);
10908  }
10909  } else { // IntegerValue.isSigned()
10910  if (!IntegerValue.isMaxSignedValue() &&
10911  !IntegerValue.isMinSignedValue()) {
10912  return DiagnoseImpCast(S, E, T, CContext,
10913  diag::warn_impcast_float_integer, PruneWarnings);
10914  }
10915  }
10916  // Warn on evaluatable floating point expression to integer conversion.
10917  DiagID = diag::warn_impcast_float_to_integer;
10918  }
10919 
10920  SmallString<16> PrettyTargetValue;
10921  if (IsBool)
10922  PrettyTargetValue = Value.isZero() ? "false" : "true";
10923  else
10924  IntegerValue.toString(PrettyTargetValue);
10925 
10926  if (PruneWarnings) {
10928  S.PDiag(DiagID)
10929  << E->getType() << T.getUnqualifiedType()
10930  << PrettySourceValue << PrettyTargetValue
10931  << E->getSourceRange() << SourceRange(CContext));
10932  } else {
10933  S.Diag(E->getExprLoc(), DiagID)
10934  << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10935  << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10936  }
10937 }
10938 
10939 /// Analyze the given compound assignment for the possible losing of
10940 /// floating-point precision.
10942  assert(isa<CompoundAssignOperator>(E) &&
10943  "Must be compound assignment operation");
10944  // Recurse on the LHS and RHS in here
10945  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10946  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10947 
10948  if (E->getLHS()->getType()->isAtomicType())
10949  S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10950 
10951  // Now check the outermost expression
10952  const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10953  const auto *RBT = cast<CompoundAssignOperator>(E)
10954  ->getComputationResultType()
10955  ->getAs<BuiltinType>();
10956 
10957  // The below checks assume source is floating point.
10958  if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10959 
10960  // If source is floating point but target is an integer.
10961  if (ResultBT->isInteger())
10962  return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10963  E->getExprLoc(), diag::warn_impcast_float_integer);
10964 
10965  if (!ResultBT->isFloatingPoint())
10966  return;
10967 
10968  // If both source and target are floating points, warn about losing precision.
10970  QualType(ResultBT, 0), QualType(RBT, 0));
10971  if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10972  // warn about dropping FP rank.
10973  DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10974  diag::warn_impcast_float_result_precision);
10975 }
10976 
10977 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10978  IntRange Range) {
10979  if (!Range.Width) return "0";
10980 
10981  llvm::APSInt ValueInRange = Value;
10982  ValueInRange.setIsSigned(!Range.NonNegative);
10983  ValueInRange = ValueInRange.trunc(Range.Width);
10984  return toString(ValueInRange, 10);
10985 }
10986 
10987 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10988  if (!isa<ImplicitCastExpr>(Ex))
10989  return false;
10990 
10991  Expr *InnerE = Ex->IgnoreParenImpCasts();
10992  const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10993  const Type *Source =
10994  S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10995  if (Target->isDependentType())
10996  return false;
10997 
10998  const BuiltinType *FloatCandidateBT =
10999  dyn_cast<BuiltinType>(ToBool ? Source : Target);
11000  const Type *BoolCandidateType = ToBool ? Target : Source;
11001 
11002  return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11003  FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11004 }
11005 
11007  SourceLocation CC) {
11008  unsigned NumArgs = TheCall->getNumArgs();
11009  for (unsigned i = 0; i < NumArgs; ++i) {
11010  Expr *CurrA = TheCall->getArg(i);
11011  if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11012  continue;
11013 
11014  bool IsSwapped = ((i > 0) &&
11015  IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11016  IsSwapped |= ((i < (NumArgs - 1)) &&
11017  IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11018  if (IsSwapped) {
11019  // Warn on this floating-point to bool conversion.
11021  CurrA->getType(), CC,
11022  diag::warn_impcast_floating_point_to_bool);
11023  }
11024  }
11025 }
11026 
11028  SourceLocation CC) {
11029  if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11030  E->getExprLoc()))
11031  return;
11032 
11033  // Don't warn on functions which have return type nullptr_t.
11034  if (isa<CallExpr>(E))
11035  return;
11036 
11037  // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11038  const Expr *NewE = E->IgnoreParenImpCasts();
11039  bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
11040  bool HasNullPtrType = NewE->getType()->isNullPtrType();
11041  if (!IsGNUNullExpr && !HasNullPtrType)
11042  return;
11043 
11044  // Return if target type is a safe conversion.
11045  if (T->isAnyPointerType() || T->isBlockPointerType() ||
11047  return;
11048 
11050 
11051  // Venture through the macro stacks to get to the source of macro arguments.
11052  // The new location is a better location than the complete location that was
11053  // passed in.
11055  CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11056 
11057  // __null is usually wrapped in a macro. Go up a macro if that is the case.
11058  if (IsGNUNullExpr && Loc.isMacroID()) {
11059  StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11060  Loc, S.SourceMgr, S.getLangOpts());
11061  if (MacroName == "NULL")
11063  }
11064 
11065  // Only warn if the null and context location are in the same macro expansion.
11066  if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11067  return;
11068 
11069  S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11070  << HasNullPtrType << T << SourceRange(CC)
11073 }
11074 
11075 // Helper function to filter out cases for constant width constant conversion.
11076 // Don't warn on char array initialization or for non-decimal values.
11078  SourceLocation CC) {
11079  // If initializing from a constant, and the constant starts with '0',
11080  // then it is a binary, octal, or hexadecimal. Allow these constants
11081  // to fill all the bits, even if there is a sign change.
11082  if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11083  const char FirstLiteralCharacter =
11084  S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11085  if (FirstLiteralCharacter == '0')
11086  return false;
11087  }
11088 
11089  // If the CC location points to a '{', and the type is char, then assume
11090  // assume it is an array initialization.
11091  if (CC.isValid() && T->isCharType()) {
11092  const char FirstContextCharacter =
11094  if (FirstContextCharacter == '{')
11095  return false;
11096  }
11097 
11098  return true;
11099 }
11100 
11102  const auto *IL = dyn_cast<IntegerLiteral>(E);
11103  if (!IL) {
11104  if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11105  if (UO->getOpcode() == UO_Minus)
11106  return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11107  }
11108  }
11109 
11110  return IL;
11111 }
11112 
11114  E = E->IgnoreParenImpCasts();
11115  SourceLocation ExprLoc = E->getExprLoc();
11116 
11117  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11118  BinaryOperator::Opcode Opc = BO->getOpcode();
11119  Expr::EvalResult Result;
11120  // Do not diagnose unsigned shifts.
11121  if (Opc == BO_Shl) {
11122  const auto *LHS = getIntegerLiteral(BO->getLHS());
11123  const auto *RHS = getIntegerLiteral(BO->getRHS());
11124  if (LHS && LHS->getValue() == 0)
11125  S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11126  else if (!E->isValueDependent() && LHS && RHS &&
11127  RHS->getValue().isNonNegative() &&
11129  S.Diag(ExprLoc, diag::warn_left_shift_always)
11130  << (Result.Val.getInt() != 0);
11131  else if (E->getType()->isSignedIntegerType())
11132  S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11133  }
11134  }
11135 
11136  if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11137  const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11138  const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11139  if (!LHS || !RHS)
11140  return;
11141  if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11142  (RHS->getValue() == 0 || RHS->getValue() == 1))
11143  // Do not diagnose common idioms.
11144  return;
11145  if (LHS->getValue() != 0 && RHS->getValue() != 0)
11146  S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11147  }
11148 }
11149 
11151  bool *ICContext, bool IsListInit) {
11152  if (E->isTypeDependent() || E->isValueDependent()) return;
11153 
11154  const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
11155  const Type *Target = Context.getCanonicalType(T).getTypePtr();
11156  if (Source == Target) return;
11157  if (Target->isDependentType()) return;
11158 
11159  // If the conversion context location is invalid don't complain. We also
11160  // don't want to emit a warning if the issue occurs from the expansion of
11161  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11162  // delay this check as long as possible. Once we detect we are in that
11163  // scenario, we just return.
11164  if (CC.isInvalid())
11165  return;
11166 
11167  if (Source->isAtomicType())
11168  Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11169 
11170  // Diagnose implicit casts to bool.
11171  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11172  if (isa<StringLiteral>(E))
11173  // Warn on string literal to bool. Checks for string literals in logical
11174  // and expressions, for instance, assert(0 && "error here"), are
11175  // prevented by a check in AnalyzeImplicitConversions().
11176  return DiagnoseImpCast(*this, E, T, CC,
11177  diag::warn_impcast_string_literal_to_bool);
11178  if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11179  isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11180  // This covers the literal expressions that evaluate to Objective-C
11181  // objects.
11182  return DiagnoseImpCast(*this, E, T, CC,
11183  diag::warn_impcast_objective_c_literal_to_bool);
11184  }
11185  if (Source->isPointerType() || Source->canDecayToPointerType()) {
11186  // Warn on pointer to bool conversion that is always true.
11187  DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11188  SourceRange(CC));
11189  }
11190  }
11191 
11192  // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11193  // is a typedef for signed char (macOS), then that constant value has to be 1
11194  // or 0.
11195  if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
11196  Expr::EvalResult Result;
11197  if (E->EvaluateAsInt(Result, getASTContext(), Expr::SE_AllowSideEffects)) {
11198  if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11199  ObjC().adornBoolConversionDiagWithTernaryFixit(
11200  E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11201  << toString(Result.Val.getInt(), 10));
11202  }
11203  return;
11204  }
11205  }
11206 
11207  // Check implicit casts from Objective-C collection literals to specialized
11208  // collection types, e.g., NSArray<NSString *> *.
11209  if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11210  ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
11211  else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11212  ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
11213 
11214  // Strip vector types.
11215  if (isa<VectorType>(Source)) {
11216  if (Target->isSveVLSBuiltinType() &&
11217  (Context.areCompatibleSveTypes(QualType(Target, 0),
11218  QualType(Source, 0)) ||
11220  QualType(Source, 0))))
11221  return;
11222 
11223  if (Target->isRVVVLSBuiltinType() &&
11224  (Context.areCompatibleRVVTypes(QualType(Target, 0),
11225  QualType(Source, 0)) ||
11227  QualType(Source, 0))))
11228  return;
11229 
11230  if (!isa<VectorType>(Target)) {
11231  if (SourceMgr.isInSystemMacro(CC))
11232  return;
11233  return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
11234  } else if (getLangOpts().HLSL &&
11235  Target->castAs<VectorType>()->getNumElements() <
11236  Source->castAs<VectorType>()->getNumElements()) {
11237  // Diagnose vector truncation but don't return. We may also want to
11238  // diagnose an element conversion.
11239  DiagnoseImpCast(*this, E, T, CC,
11240  diag::warn_hlsl_impcast_vector_truncation);
11241  }
11242 
11243  // If the vector cast is cast between two vectors of the same size, it is
11244  // a bitcast, not a conversion, except under HLSL where it is a conversion.
11245  if (!getLangOpts().HLSL &&
11246  Context.getTypeSize(Source) == Context.getTypeSize(Target))
11247  return;
11248 
11249  Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11250  Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11251  }
11252  if (auto VecTy = dyn_cast<VectorType>(Target))
11253  Target = VecTy->getElementType().getTypePtr();
11254 
11255  // Strip complex types.
11256  if (isa<ComplexType>(Source)) {
11257  if (!isa<ComplexType>(Target)) {
11258  if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11259  return;
11260 
11261  return DiagnoseImpCast(*this, E, T, CC,
11262  getLangOpts().CPlusPlus
11263  ? diag::err_impcast_complex_scalar
11264  : diag::warn_impcast_complex_scalar);
11265  }
11266 
11267  Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11268  Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11269  }
11270 
11271  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11272  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11273 
11274  // Strip SVE vector types
11275  if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
11276  // Need the original target type for vector type checks
11277  const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
11278  // Handle conversion from scalable to fixed when msve-vector-bits is
11279  // specified
11280  if (Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),
11281  QualType(Source, 0)) ||
11282  Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
11283  QualType(Source, 0)))
11284  return;
11285 
11286  // If the vector cast is cast between two vectors of the same size, it is
11287  // a bitcast, not a conversion.
11288  if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
11289  return;
11290 
11291  Source = SourceBT->getSveEltType(Context).getTypePtr();
11292  }
11293 
11294  if (TargetBT && TargetBT->isSveVLSBuiltinType())
11295  Target = TargetBT->getSveEltType(Context).getTypePtr();
11296 
11297  // If the source is floating point...
11298  if (SourceBT && SourceBT->isFloatingPoint()) {
11299  // ...and the target is floating point...
11300  if (TargetBT && TargetBT->isFloatingPoint()) {
11301  // ...then warn if we're dropping FP rank.
11302 
11303  int Order = getASTContext().getFloatingTypeSemanticOrder(
11304  QualType(SourceBT, 0), QualType(TargetBT, 0));
11305  if (Order > 0) {
11306  // Don't warn about float constants that are precisely
11307  // representable in the target type.
11308  Expr::EvalResult result;
11309  if (E->EvaluateAsRValue(result, Context)) {
11310  // Value might be a float, a float vector, or a float complex.
11312  result.Val,
11313  Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11314  Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) {
11315  if (getLangOpts().SYCLIsDevice)
11316  SYCL().DiagIfDeviceCode(CC, diag::warn_imp_float_size_conversion);
11317  else
11318  DiagnoseImpCast(*this, E, T, CC,
11319  diag::warn_imp_float_size_conversion);
11320  return;
11321  }
11322  }
11323 
11324  if (SourceMgr.isInSystemMacro(CC))
11325  return;
11326  // If there is a precision conversion between floating point types when
11327  // -Wimplicit-float-size-conversion is passed but
11328  // -Wimplicit-float-conversion is not, make sure we emit at least a size
11329  // warning.
11330  if (Diags.isIgnored(diag::warn_impcast_float_precision, CC)) {
11331  if (getLangOpts().SYCLIsDevice)
11332  SYCL().DiagIfDeviceCode(CC, diag::warn_imp_float_size_conversion);
11333  else
11334  DiagnoseImpCast(*this, E, T, CC,
11335  diag::warn_imp_float_size_conversion);
11336  }
11337  DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
11338  }
11339  // ... or possibly if we're increasing rank, too
11340  else if (Order < 0) {
11341  if (SourceMgr.isInSystemMacro(CC))
11342  return;
11343 
11344  DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
11345  }
11346  return;
11347  }
11348 
11349  // If the target is integral, always warn.
11350  if (TargetBT && TargetBT->isInteger()) {
11351  if (SourceMgr.isInSystemMacro(CC))
11352  return;
11353 
11354  DiagnoseFloatingImpCast(*this, E, T, CC);
11355  }
11356 
11357  // Detect the case where a call result is converted from floating-point to
11358  // to bool, and the final argument to the call is converted from bool, to
11359  // discover this typo:
11360  //
11361  // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
11362  //
11363  // FIXME: This is an incredibly special case; is there some more general
11364  // way to detect this class of misplaced-parentheses bug?
11365  if (Target->isBooleanType() && isa<CallExpr>(E)) {
11366  // Check last argument of function call to see if it is an
11367  // implicit cast from a type matching the type the result
11368  // is being cast to.
11369  CallExpr *CEx = cast<CallExpr>(E);
11370  if (unsigned NumArgs = CEx->getNumArgs()) {
11371  Expr *LastA = CEx->getArg(NumArgs - 1);
11372  Expr *InnerE = LastA->IgnoreParenImpCasts();
11373  if (isa<ImplicitCastExpr>(LastA) &&
11374  InnerE->getType()->isBooleanType()) {
11375  // Warn on this floating-point to bool conversion
11376  DiagnoseImpCast(*this, E, T, CC,
11377  diag::warn_impcast_floating_point_to_bool);
11378  }
11379  }
11380  }
11381  return;
11382  }
11383 
11384  // Valid casts involving fixed point types should be accounted for here.
11385  if (Source->isFixedPointType()) {
11386  if (Target->isUnsaturatedFixedPointType()) {
11387  Expr::EvalResult Result;
11388  if (E->EvaluateAsFixedPoint(Result, Context, Expr::SE_AllowSideEffects,
11389  isConstantEvaluatedContext())) {
11390  llvm::APFixedPoint Value = Result.Val.getFixedPoint();
11391  llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
11392  llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
11393  if (Value > MaxVal || Value < MinVal) {
11394  DiagRuntimeBehavior(E->getExprLoc(), E,
11395  PDiag(diag::warn_impcast_fixed_point_range)
11396  << Value.toString() << T
11397  << E->getSourceRange()
11398  << clang::SourceRange(CC));
11399  return;
11400  }
11401  }
11402  } else if (Target->isIntegerType()) {
11403  Expr::EvalResult Result;
11404  if (!isConstantEvaluatedContext() &&
11405  E->EvaluateAsFixedPoint(Result, Context, Expr::SE_AllowSideEffects)) {
11406  llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
11407 
11408  bool Overflowed;
11409  llvm::APSInt IntResult = FXResult.convertToInt(
11410  Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
11411  &Overflowed);
11412 
11413  if (Overflowed) {
11414  DiagRuntimeBehavior(E->getExprLoc(), E,
11415  PDiag(diag::warn_impcast_fixed_point_range)
11416  << FXResult.toString() << T
11417  << E->getSourceRange()
11418  << clang::SourceRange(CC));
11419  return;
11420  }
11421  }
11422  }
11423  } else if (Target->isUnsaturatedFixedPointType()) {
11424  if (Source->isIntegerType()) {
11425  Expr::EvalResult Result;
11426  if (!isConstantEvaluatedContext() &&
11427  E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) {
11428  llvm::APSInt Value = Result.Val.getInt();
11429 
11430  bool Overflowed;
11431  llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
11432  Value, Context.getFixedPointSemantics(T), &Overflowed);
11433 
11434  if (Overflowed) {
11435  DiagRuntimeBehavior(E->getExprLoc(), E,
11436  PDiag(diag::warn_impcast_fixed_point_range)
11437  << toString(Value, /*Radix=*/10) << T
11438  << E->getSourceRange()
11439  << clang::SourceRange(CC));
11440  return;
11441  }
11442  }
11443  }
11444  }
11445 
11446  // If we are casting an integer type to a floating point type without
11447  // initialization-list syntax, we might lose accuracy if the floating
11448  // point type has a narrower significand than the integer type.
11449  if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11450  TargetBT->isFloatingType() && !IsListInit) {
11451  // Determine the number of precision bits in the source integer type.
11452  IntRange SourceRange =
11453  GetExprRange(Context, E, isConstantEvaluatedContext(),
11454  /*Approximate=*/true);
11455  unsigned int SourcePrecision = SourceRange.Width;
11456 
11457  // Determine the number of precision bits in the
11458  // target floating point type.
11459  unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11460  Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11461 
11462  if (SourcePrecision > 0 && TargetPrecision > 0 &&
11463  SourcePrecision > TargetPrecision) {
11464 
11465  if (std::optional<llvm::APSInt> SourceInt =
11466  E->getIntegerConstantExpr(Context)) {
11467  // If the source integer is a constant, convert it to the target
11468  // floating point type. Issue a warning if the value changes
11469  // during the whole conversion.
11470  llvm::APFloat TargetFloatValue(
11471  Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11472  llvm::APFloat::opStatus ConversionStatus =
11473  TargetFloatValue.convertFromAPInt(
11474  *SourceInt, SourceBT->isSignedInteger(),
11475  llvm::APFloat::rmNearestTiesToEven);
11476 
11477  if (ConversionStatus != llvm::APFloat::opOK) {
11478  SmallString<32> PrettySourceValue;
11479  SourceInt->toString(PrettySourceValue, 10);
11480  SmallString<32> PrettyTargetValue;
11481  TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11482 
11483  DiagRuntimeBehavior(
11484  E->getExprLoc(), E,
11485  PDiag(diag::warn_impcast_integer_float_precision_constant)
11486  << PrettySourceValue << PrettyTargetValue << E->getType() << T
11487  << E->getSourceRange() << clang::SourceRange(CC));
11488  }
11489  } else {
11490  // Otherwise, the implicit conversion may lose precision.
11491  DiagnoseImpCast(*this, E, T, CC,
11492  diag::warn_impcast_integer_float_precision);
11493  }
11494  }
11495  }
11496 
11497  DiagnoseNullConversion(*this, E, T, CC);
11498 
11499  DiscardMisalignedMemberAddress(Target, E);
11500 
11501  if (Target->isBooleanType())
11502  DiagnoseIntInBoolContext(*this, E);
11503 
11504  if (!Source->isIntegerType() || !Target->isIntegerType())
11505  return;
11506 
11507  // TODO: remove this early return once the false positives for constant->bool
11508  // in templates, macros, etc, are reduced or removed.
11509  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11510  return;
11511 
11512  if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
11513  !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11514  return ObjC().adornBoolConversionDiagWithTernaryFixit(
11515  E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11516  << E->getType());
11517  }
11518 
11519  IntRange SourceTypeRange =
11520  IntRange::forTargetOfCanonicalType(Context, Source);
11521  IntRange LikelySourceRange = GetExprRange(
11522  Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
11523  IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
11524 
11525  if (LikelySourceRange.Width > TargetRange.Width) {
11526  // If the source is a constant, use a default-on diagnostic.
11527  // TODO: this should happen for bitfield stores, too.
11528  Expr::EvalResult Result;
11529  if (E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects,
11530  isConstantEvaluatedContext())) {
11531  llvm::APSInt Value(32);
11532  Value = Result.Val.getInt();
11533 
11534  if (SourceMgr.isInSystemMacro(CC))
11535  return;
11536 
11537  std::string PrettySourceValue = toString(Value, 10);
11538  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11539 
11540  DiagRuntimeBehavior(E->getExprLoc(), E,
11541  PDiag(diag::warn_impcast_integer_precision_constant)
11542  << PrettySourceValue << PrettyTargetValue
11543  << E->getType() << T << E->getSourceRange()
11544  << SourceRange(CC));
11545  return;
11546  }
11547 
11548  // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11549  if (SourceMgr.isInSystemMacro(CC))
11550  return;
11551 
11552  if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
11553  return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
11554  /* pruneControlFlow */ true);
11555  return DiagnoseImpCast(*this, E, T, CC,
11556  diag::warn_impcast_integer_precision);
11557  }
11558 
11559  if (TargetRange.Width > SourceTypeRange.Width) {
11560  if (auto *UO = dyn_cast<UnaryOperator>(E))
11561  if (UO->getOpcode() == UO_Minus)
11562  if (Source->isUnsignedIntegerType()) {
11563  if (Target->isUnsignedIntegerType())
11564  return DiagnoseImpCast(*this, E, T, CC,
11565  diag::warn_impcast_high_order_zero_bits);
11566  if (Target->isSignedIntegerType())
11567  return DiagnoseImpCast(*this, E, T, CC,
11568  diag::warn_impcast_nonnegative_result);
11569  }
11570  }
11571 
11572  if (TargetRange.Width == LikelySourceRange.Width &&
11573  !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
11574  Source->isSignedIntegerType()) {
11575  // Warn when doing a signed to signed conversion, warn if the positive
11576  // source value is exactly the width of the target type, which will
11577  // cause a negative value to be stored.
11578 
11579  Expr::EvalResult Result;
11580  if (E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects) &&
11581  !SourceMgr.isInSystemMacro(CC)) {
11582  llvm::APSInt Value = Result.Val.getInt();
11583  if (isSameWidthConstantConversion(*this, E, T, CC)) {
11584  std::string PrettySourceValue = toString(Value, 10);
11585  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11586 
11587  Diag(E->getExprLoc(),
11588  PDiag(diag::warn_impcast_integer_precision_constant)
11589  << PrettySourceValue << PrettyTargetValue << E->getType() << T
11590  << E->getSourceRange() << SourceRange(CC));
11591  return;
11592  }
11593  }
11594 
11595  // Fall through for non-constants to give a sign conversion warning.
11596  }
11597 
11598  if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
11599  ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
11600  (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
11601  LikelySourceRange.Width == TargetRange.Width))) {
11602  if (SourceMgr.isInSystemMacro(CC))
11603  return;
11604 
11605  if (SourceBT && SourceBT->isInteger() && TargetBT &&
11606  TargetBT->isInteger() &&
11607  Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
11608  return;
11609  }
11610 
11611  unsigned DiagID = diag::warn_impcast_integer_sign;
11612 
11613  // Traditionally, gcc has warned about this under -Wsign-compare.
11614  // We also want to warn about it in -Wconversion.
11615  // So if -Wconversion is off, use a completely identical diagnostic
11616  // in the sign-compare group.
11617  // The conditional-checking code will
11618  if (ICContext) {
11619  DiagID = diag::warn_impcast_integer_sign_conditional;
11620  *ICContext = true;
11621  }
11622 
11623  return DiagnoseImpCast(*this, E, T, CC, DiagID);
11624  }
11625 
11626  // Diagnose conversions between different enumeration types.
11627  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11628  // type, to give us better diagnostics.
11629  QualType SourceType = E->getEnumCoercedType(Context);
11630  Source = Context.getCanonicalType(SourceType).getTypePtr();
11631 
11632  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11633  if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11634  if (SourceEnum->getDecl()->hasNameForLinkage() &&
11635  TargetEnum->getDecl()->hasNameForLinkage() &&
11636  SourceEnum != TargetEnum) {
11637  if (SourceMgr.isInSystemMacro(CC))
11638  return;
11639 
11640  return DiagnoseImpCast(*this, E, SourceType, T, CC,
11641  diag::warn_impcast_different_enum_types);
11642  }
11643 }
11644 
11646  SourceLocation CC, QualType T);
11647 
11649  SourceLocation CC, bool &ICContext) {
11650  E = E->IgnoreParenImpCasts();
11651  // Diagnose incomplete type for second or third operand in C.
11652  if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
11653  S.RequireCompleteExprType(E, diag::err_incomplete_type);
11654 
11655  if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
11656  return CheckConditionalOperator(S, CO, CC, T);
11657 
11658  AnalyzeImplicitConversions(S, E, CC);
11659  if (E->getType() != T)
11660  return S.CheckImplicitConversion(E, T, CC, &ICContext);
11661 }
11662 
11664  SourceLocation CC, QualType T) {
11665  AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11666 
11667  Expr *TrueExpr = E->getTrueExpr();
11668  if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
11669  TrueExpr = BCO->getCommon();
11670 
11671  bool Suspicious = false;
11672  CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
11673  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11674 
11675  if (T->isBooleanType())
11677 
11678  // If -Wconversion would have warned about either of the candidates
11679  // for a signedness conversion to the context type...
11680  if (!Suspicious) return;
11681 
11682  // ...but it's currently ignored...
11683  if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11684  return;
11685 
11686  // ...then check whether it would have warned about either of the
11687  // candidates for a signedness conversion to the condition type.
11688  if (E->getType() == T) return;
11689 
11690  Suspicious = false;
11691  S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
11692  &Suspicious);
11693  if (!Suspicious)
11694  S.CheckImplicitConversion(E->getFalseExpr()->IgnoreParenImpCasts(),
11695  E->getType(), CC, &Suspicious);
11696 }
11697 
11698 /// Check conversion of given expression to boolean.
11699 /// Input argument E is a logical expression.
11701  // Run the bool-like conversion checks only for C since there bools are
11702  // still not used as the return type from "boolean" operators or as the input
11703  // type for conditional operators.
11704  if (S.getLangOpts().CPlusPlus)
11705  return;
11707  return;
11709 }
11710 
11711 namespace {
11712 struct AnalyzeImplicitConversionsWorkItem {
11713  Expr *E;
11714  SourceLocation CC;
11715  bool IsListInit;
11716 };
11717 }
11718 
11719 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11720 /// that should be visited are added to WorkList.
11722  Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11724  Expr *OrigE = Item.E;
11725  SourceLocation CC = Item.CC;
11726 
11727  QualType T = OrigE->getType();
11728  Expr *E = OrigE->IgnoreParenImpCasts();
11729 
11730  // Propagate whether we are in a C++ list initialization expression.
11731  // If so, we do not issue warnings for implicit int-float conversion
11732  // precision loss, because C++11 narrowing already handles it.
11733  bool IsListInit = Item.IsListInit ||
11734  (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11735 
11736  if (E->isTypeDependent() || E->isValueDependent())
11737  return;
11738 
11739  Expr *SourceExpr = E;
11740  // Examine, but don't traverse into the source expression of an
11741  // OpaqueValueExpr, since it may have multiple parents and we don't want to
11742  // emit duplicate diagnostics. Its fine to examine the form or attempt to
11743  // evaluate it in the context of checking the specific conversion to T though.
11744  if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11745  if (auto *Src = OVE->getSourceExpr())
11746  SourceExpr = Src;
11747 
11748  if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11749  if (UO->getOpcode() == UO_Not &&
11750  UO->getSubExpr()->isKnownToHaveBooleanValue())
11751  S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11752  << OrigE->getSourceRange() << T->isBooleanType()
11753  << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11754 
11755  if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
11756  if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
11757  BO->getLHS()->isKnownToHaveBooleanValue() &&
11758  BO->getRHS()->isKnownToHaveBooleanValue() &&
11759  BO->getLHS()->HasSideEffects(S.Context) &&
11760  BO->getRHS()->HasSideEffects(S.Context)) {
11762  const LangOptions &LO = S.getLangOpts();
11763  SourceLocation BLoc = BO->getOperatorLoc();
11764  SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
11765  StringRef SR = clang::Lexer::getSourceText(
11766  clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
11767  // To reduce false positives, only issue the diagnostic if the operator
11768  // is explicitly spelled as a punctuator. This suppresses the diagnostic
11769  // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
11770  // in C, along with other macro spellings the user might invent.
11771  if (SR.str() == "&" || SR.str() == "|") {
11772 
11773  S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
11774  << (BO->getOpcode() == BO_And ? "&" : "|")
11775  << OrigE->getSourceRange()
11777  BO->getOperatorLoc(),
11778  (BO->getOpcode() == BO_And ? "&&" : "||"));
11779  S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
11780  }
11781  }
11782 
11783  // For conditional operators, we analyze the arguments as if they
11784  // were being fed directly into the output.
11785  if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
11786  CheckConditionalOperator(S, CO, CC, T);
11787  return;
11788  }
11789 
11790  // Check implicit argument conversions for function calls.
11791  if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11792  CheckImplicitArgumentConversions(S, Call, CC);
11793 
11794  // Go ahead and check any implicit conversions we might have skipped.
11795  // The non-canonical typecheck is just an optimization;
11796  // CheckImplicitConversion will filter out dead implicit conversions.
11797  if (SourceExpr->getType() != T)
11798  S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
11799 
11800  // Now continue drilling into this expression.
11801 
11802  if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11803  // The bound subexpressions in a PseudoObjectExpr are not reachable
11804  // as transitive children.
11805  // FIXME: Use a more uniform representation for this.
11806  for (auto *SE : POE->semantics())
11807  if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11808  WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11809  }
11810 
11811  // Skip past explicit casts.
11812  if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11813  E = CE->getSubExpr()->IgnoreParenImpCasts();
11814  if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11815  S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11816  WorkList.push_back({E, CC, IsListInit});
11817  return;
11818  }
11819 
11820  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11821  // Do a somewhat different check with comparison operators.
11822  if (BO->isComparisonOp())
11823  return AnalyzeComparison(S, BO);
11824 
11825  // And with simple assignments.
11826  if (BO->getOpcode() == BO_Assign)
11827  return AnalyzeAssignment(S, BO);
11828  // And with compound assignments.
11829  if (BO->isAssignmentOp())
11830  return AnalyzeCompoundAssignment(S, BO);
11831  }
11832 
11833  // These break the otherwise-useful invariant below. Fortunately,
11834  // we don't really need to recurse into them, because any internal
11835  // expressions should have been analyzed already when they were
11836  // built into statements.
11837  if (isa<StmtExpr>(E)) return;
11838 
11839  // Don't descend into unevaluated contexts.
11840  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11841 
11842  // Now just recurse over the expression's children.
11843  CC = E->getExprLoc();
11844  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11845  bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11846  for (Stmt *SubStmt : E->children()) {
11847  Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11848  if (!ChildExpr)
11849  continue;
11850 
11851  if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
11852  if (ChildExpr == CSE->getOperand())
11853  // Do not recurse over a CoroutineSuspendExpr's operand.
11854  // The operand is also a subexpression of getCommonExpr(), and
11855  // recursing into it directly would produce duplicate diagnostics.
11856  continue;
11857 
11858  if (IsLogicalAndOperator &&
11859  isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11860  // Ignore checking string literals that are in logical and operators.
11861  // This is a common pattern for asserts.
11862  continue;
11863  WorkList.push_back({ChildExpr, CC, IsListInit});
11864  }
11865 
11866  if (BO && BO->isLogicalOp()) {
11867  Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11868  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11869  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11870 
11871  SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11872  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11873  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11874  }
11875 
11876  if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11877  if (U->getOpcode() == UO_LNot) {
11878  ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11879  } else if (U->getOpcode() != UO_AddrOf) {
11880  if (U->getSubExpr()->getType()->isAtomicType())
11881  S.Diag(U->getSubExpr()->getBeginLoc(),
11882  diag::warn_atomic_implicit_seq_cst);
11883  }
11884  }
11885 }
11886 
11887 /// AnalyzeImplicitConversions - Find and report any interesting
11888 /// implicit conversions in the given expression. There are a couple
11889 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11891  bool IsListInit/*= false*/) {
11893  WorkList.push_back({OrigE, CC, IsListInit});
11894  while (!WorkList.empty())
11895  AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11896 }
11897 
11898 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11899 // Returns true when emitting a warning about taking the address of a reference.
11900 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11901  const PartialDiagnostic &PD) {
11902  E = E->IgnoreParenImpCasts();
11903 
11904  const FunctionDecl *FD = nullptr;
11905 
11906  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11907  if (!DRE->getDecl()->getType()->isReferenceType())
11908  return false;
11909  } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11910  if (!M->getMemberDecl()->getType()->isReferenceType())
11911  return false;
11912  } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11913  if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11914  return false;
11915  FD = Call->getDirectCallee();
11916  } else {
11917  return false;
11918  }
11919 
11920  SemaRef.Diag(E->getExprLoc(), PD);
11921 
11922  // If possible, point to location of function.
11923  if (FD) {
11924  SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11925  }
11926 
11927  return true;
11928 }
11929 
11930 // Returns true if the SourceLocation is expanded from any macro body.
11931 // Returns false if the SourceLocation is invalid, is from not in a macro
11932 // expansion, or is from expanded from a top-level macro argument.
11934  if (Loc.isInvalid())
11935  return false;
11936 
11937  while (Loc.isMacroID()) {
11938  if (SM.isMacroBodyExpansion(Loc))
11939  return true;
11940  Loc = SM.getImmediateMacroCallerLoc(Loc);
11941  }
11942 
11943  return false;
11944 }
11945 
11948  bool IsEqual, SourceRange Range) {
11949  if (!E)
11950  return;
11951 
11952  // Don't warn inside macros.
11953  if (E->getExprLoc().isMacroID()) {
11954  const SourceManager &SM = getSourceManager();
11955  if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11957  return;
11958  }
11959  E = E->IgnoreImpCasts();
11960 
11961  const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11962 
11963  if (isa<CXXThisExpr>(E)) {
11964  unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11965  : diag::warn_this_bool_conversion;
11966  Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11967  return;
11968  }
11969 
11970  bool IsAddressOf = false;
11971 
11972  if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
11973  if (UO->getOpcode() != UO_AddrOf)
11974  return;
11975  IsAddressOf = true;
11976  E = UO->getSubExpr();
11977  }
11978 
11979  if (IsAddressOf) {
11980  unsigned DiagID = IsCompare
11981  ? diag::warn_address_of_reference_null_compare
11982  : diag::warn_address_of_reference_bool_conversion;
11983  PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11984  << IsEqual;
11985  if (CheckForReference(*this, E, PD)) {
11986  return;
11987  }
11988  }
11989 
11990  auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11991  bool IsParam = isa<NonNullAttr>(NonnullAttr);
11992  std::string Str;
11993  llvm::raw_string_ostream S(Str);
11994  E->printPretty(S, nullptr, getPrintingPolicy());
11995  unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11996  : diag::warn_cast_nonnull_to_bool;
11997  Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11998  << E->getSourceRange() << Range << IsEqual;
11999  Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12000  };
12001 
12002  // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12003  if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12004  if (auto *Callee = Call->getDirectCallee()) {
12005  if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12006  ComplainAboutNonnullParamOrCall(A);
12007  return;
12008  }
12009  }
12010  }
12011 
12012  // Complain if we are converting a lambda expression to a boolean value
12013  // outside of instantiation.
12014  if (!inTemplateInstantiation()) {
12015  if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
12016  if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
12017  MRecordDecl && MRecordDecl->isLambda()) {
12018  Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
12019  << /*LambdaPointerConversionOperatorType=*/3
12020  << MRecordDecl->getSourceRange() << Range << IsEqual;
12021  return;
12022  }
12023  }
12024  }
12025 
12026  // Expect to find a single Decl. Skip anything more complicated.
12027  ValueDecl *D = nullptr;
12028  if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12029  D = R->getDecl();
12030  } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12031  D = M->getMemberDecl();
12032  }
12033 
12034  // Weak Decls can be null.
12035  if (!D || D->isWeak())
12036  return;
12037 
12038  // Check for parameter decl with nonnull attribute
12039  if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12040  if (getCurFunction() &&
12041  !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12042  if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12043  ComplainAboutNonnullParamOrCall(A);
12044  return;
12045  }
12046 
12047  if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12048  // Skip function template not specialized yet.
12050  return;
12051  auto ParamIter = llvm::find(FD->parameters(), PV);
12052  assert(ParamIter != FD->param_end());
12053  unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12054 
12055  for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12056  if (!NonNull->args_size()) {
12057  ComplainAboutNonnullParamOrCall(NonNull);
12058  return;
12059  }
12060 
12061  for (const ParamIdx &ArgNo : NonNull->args()) {
12062  if (ArgNo.getASTIndex() == ParamNo) {
12063  ComplainAboutNonnullParamOrCall(NonNull);
12064  return;
12065  }
12066  }
12067  }
12068  }
12069  }
12070  }
12071 
12072  QualType T = D->getType();
12073  const bool IsArray = T->isArrayType();
12074  const bool IsFunction = T->isFunctionType();
12075 
12076  // Address of function is used to silence the function warning.
12077  if (IsAddressOf && IsFunction) {
12078  return;
12079  }
12080 
12081  // Found nothing.
12082  if (!IsAddressOf && !IsFunction && !IsArray)
12083  return;
12084 
12085  // Pretty print the expression for the diagnostic.
12086  std::string Str;
12087  llvm::raw_string_ostream S(Str);
12088  E->printPretty(S, nullptr, getPrintingPolicy());
12089 
12090  unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12091  : diag::warn_impcast_pointer_to_bool;
12092  enum {
12093  AddressOf,
12094  FunctionPointer,
12095  ArrayPointer
12096  } DiagType;
12097  if (IsAddressOf)
12098  DiagType = AddressOf;
12099  else if (IsFunction)
12100  DiagType = FunctionPointer;
12101  else if (IsArray)
12102  DiagType = ArrayPointer;
12103  else
12104  llvm_unreachable("Could not determine diagnostic.");
12105  Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12106  << Range << IsEqual;
12107 
12108  if (!IsFunction)
12109  return;
12110 
12111  // Suggest '&' to silence the function warning.
12112  Diag(E->getExprLoc(), diag::note_function_warning_silence)
12114 
12115  // Check to see if '()' fixit should be emitted.
12116  QualType ReturnType;
12117  UnresolvedSet<4> NonTemplateOverloads;
12118  tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12119  if (ReturnType.isNull())
12120  return;
12121 
12122  if (IsCompare) {
12123  // There are two cases here. If there is null constant, the only suggest
12124  // for a pointer return type. If the null is 0, then suggest if the return
12125  // type is a pointer or an integer type.
12126  if (!ReturnType->isPointerType()) {
12127  if (NullKind == Expr::NPCK_ZeroExpression ||
12128  NullKind == Expr::NPCK_ZeroLiteral) {
12129  if (!ReturnType->isIntegerType())
12130  return;
12131  } else {
12132  return;
12133  }
12134  }
12135  } else { // !IsCompare
12136  // For function to bool, only suggest if the function pointer has bool
12137  // return type.
12138  if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12139  return;
12140  }
12141  Diag(E->getExprLoc(), diag::note_function_to_function_call)
12142  << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12143 }
12144 
12145 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12146  // Don't diagnose in unevaluated contexts.
12147  if (isUnevaluatedContext())
12148  return;
12149 
12150  // Don't diagnose for value- or type-dependent expressions.
12151  if (E->isTypeDependent() || E->isValueDependent())
12152  return;
12153 
12154  // Check for array bounds violations in cases where the check isn't triggered
12155  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12156  // ArraySubscriptExpr is on the RHS of a variable initialization.
12157  CheckArrayAccess(E);
12158 
12159  // This is not the right CC for (e.g.) a variable initialization.
12160  AnalyzeImplicitConversions(*this, E, CC);
12161 }
12162 
12163 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12164  ::CheckBoolLikeConversion(*this, E, CC);
12165 }
12166 
12167 void Sema::CheckForIntOverflow (const Expr *E) {
12168  // Use a work list to deal with nested struct initializers.
12169  SmallVector<const Expr *, 2> Exprs(1, E);
12170 
12171  do {
12172  const Expr *OriginalE = Exprs.pop_back_val();
12173  const Expr *E = OriginalE->IgnoreParenCasts();
12174 
12175  if (isa<BinaryOperator, UnaryOperator>(E)) {
12176  E->EvaluateForOverflow(Context);
12177  continue;
12178  }
12179 
12180  if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
12181  Exprs.append(InitList->inits().begin(), InitList->inits().end());
12182  else if (isa<ObjCBoxedExpr>(OriginalE))
12183  E->EvaluateForOverflow(Context);
12184  else if (const auto *Call = dyn_cast<CallExpr>(E))
12185  Exprs.append(Call->arg_begin(), Call->arg_end());
12186  else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
12187  Exprs.append(Message->arg_begin(), Message->arg_end());
12188  else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
12189  Exprs.append(Construct->arg_begin(), Construct->arg_end());
12190  else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
12191  Exprs.push_back(Temporary->getSubExpr());
12192  else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
12193  Exprs.push_back(Array->getIdx());
12194  else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
12195  Exprs.push_back(Compound->getInitializer());
12196  else if (const auto *New = dyn_cast<CXXNewExpr>(E);
12197  New && New->isArray()) {
12198  if (auto ArraySize = New->getArraySize())
12199  Exprs.push_back(*ArraySize);
12200  }
12201  } while (!Exprs.empty());
12202 }
12203 
12204 namespace {
12205 
12206 /// Visitor for expressions which looks for unsequenced operations on the
12207 /// same object.
12208 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12210 
12211  /// A tree of sequenced regions within an expression. Two regions are
12212  /// unsequenced if one is an ancestor or a descendent of the other. When we
12213  /// finish processing an expression with sequencing, such as a comma
12214  /// expression, we fold its tree nodes into its parent, since they are
12215  /// unsequenced with respect to nodes we will visit later.
12216  class SequenceTree {
12217  struct Value {
12218  explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12219  unsigned Parent : 31;
12220  LLVM_PREFERRED_TYPE(bool)
12221  unsigned Merged : 1;
12222  };
12223  SmallVector<Value, 8> Values;
12224 
12225  public:
12226  /// A region within an expression which may be sequenced with respect
12227  /// to some other region.
12228  class Seq {
12229  friend class SequenceTree;
12230 
12231  unsigned Index;
12232 
12233  explicit Seq(unsigned N) : Index(N) {}
12234 
12235  public:
12236  Seq() : Index(0) {}
12237  };
12238 
12239  SequenceTree() { Values.push_back(Value(0)); }
12240  Seq root() const { return Seq(0); }
12241 
12242  /// Create a new sequence of operations, which is an unsequenced
12243  /// subset of \p Parent. This sequence of operations is sequenced with
12244  /// respect to other children of \p Parent.
12245  Seq allocate(Seq Parent) {
12246  Values.push_back(Value(Parent.Index));
12247  return Seq(Values.size() - 1);
12248  }
12249 
12250  /// Merge a sequence of operations into its parent.
12251  void merge(Seq S) {
12252  Values[S.Index].Merged = true;
12253  }
12254 
12255  /// Determine whether two operations are unsequenced. This operation
12256  /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12257  /// should have been merged into its parent as appropriate.
12258  bool isUnsequenced(Seq Cur, Seq Old) {
12259  unsigned C = representative(Cur.Index);
12260  unsigned Target = representative(Old.Index);
12261  while (C >= Target) {
12262  if (C == Target)
12263  return true;
12264  C = Values[C].Parent;
12265  }
12266  return false;
12267  }
12268 
12269  private:
12270  /// Pick a representative for a sequence.
12271  unsigned representative(unsigned K) {
12272  if (Values[K].Merged)
12273  // Perform path compression as we go.
12274  return Values[K].Parent = representative(Values[K].Parent);
12275  return K;
12276  }
12277  };
12278 
12279  /// An object for which we can track unsequenced uses.
12280  using Object = const NamedDecl *;
12281 
12282  /// Different flavors of object usage which we track. We only track the
12283  /// least-sequenced usage of each kind.
12284  enum UsageKind {
12285  /// A read of an object. Multiple unsequenced reads are OK.
12286  UK_Use,
12287 
12288  /// A modification of an object which is sequenced before the value
12289  /// computation of the expression, such as ++n in C++.
12290  UK_ModAsValue,
12291 
12292  /// A modification of an object which is not sequenced before the value
12293  /// computation of the expression, such as n++.
12294  UK_ModAsSideEffect,
12295 
12296  UK_Count = UK_ModAsSideEffect + 1
12297  };
12298 
12299  /// Bundle together a sequencing region and the expression corresponding
12300  /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12301  struct Usage {
12302  const Expr *UsageExpr = nullptr;
12303  SequenceTree::Seq Seq;
12304 
12305  Usage() = default;
12306  };
12307 
12308  struct UsageInfo {
12309  Usage Uses[UK_Count];
12310 
12311  /// Have we issued a diagnostic for this object already?
12312  bool Diagnosed = false;
12313 
12314  UsageInfo();
12315  };
12316  using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12317 
12318  Sema &SemaRef;
12319 
12320  /// Sequenced regions within the expression.
12321  SequenceTree Tree;
12322 
12323  /// Declaration modifications and references which we have seen.
12324  UsageInfoMap UsageMap;
12325 
12326  /// The region we are currently within.
12327  SequenceTree::Seq Region;
12328 
12329  /// Filled in with declarations which were modified as a side-effect
12330  /// (that is, post-increment operations).
12331  SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12332 
12333  /// Expressions to check later. We defer checking these to reduce
12334  /// stack usage.
12336 
12337  /// RAII object wrapping the visitation of a sequenced subexpression of an
12338  /// expression. At the end of this process, the side-effects of the evaluation
12339  /// become sequenced with respect to the value computation of the result, so
12340  /// we downgrade any UK_ModAsSideEffect within the evaluation to
12341  /// UK_ModAsValue.
12342  struct SequencedSubexpression {
12343  SequencedSubexpression(SequenceChecker &Self)
12344  : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12345  Self.ModAsSideEffect = &ModAsSideEffect;
12346  }
12347 
12348  ~SequencedSubexpression() {
12349  for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12350  // Add a new usage with usage kind UK_ModAsValue, and then restore
12351  // the previous usage with UK_ModAsSideEffect (thus clearing it if
12352  // the previous one was empty).
12353  UsageInfo &UI = Self.UsageMap[M.first];
12354  auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12355  Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12356  SideEffectUsage = M.second;
12357  }
12358  Self.ModAsSideEffect = OldModAsSideEffect;
12359  }
12360 
12361  SequenceChecker &Self;
12362  SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12363  SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12364  };
12365 
12366  /// RAII object wrapping the visitation of a subexpression which we might
12367  /// choose to evaluate as a constant. If any subexpression is evaluated and
12368  /// found to be non-constant, this allows us to suppress the evaluation of
12369  /// the outer expression.
12370  class EvaluationTracker {
12371  public:
12372  EvaluationTracker(SequenceChecker &Self)
12373  : Self(Self), Prev(Self.EvalTracker) {
12374  Self.EvalTracker = this;
12375  }
12376 
12377  ~EvaluationTracker() {
12378  Self.EvalTracker = Prev;
12379  if (Prev)
12380  Prev->EvalOK &= EvalOK;
12381  }
12382 
12383  bool evaluate(const Expr *E, bool &Result) {
12384  if (!EvalOK || E->isValueDependent())
12385  return false;
12386  EvalOK = E->EvaluateAsBooleanCondition(
12387  Result, Self.SemaRef.Context,
12388  Self.SemaRef.isConstantEvaluatedContext());
12389  return EvalOK;
12390  }
12391 
12392  private:
12393  SequenceChecker &Self;
12394  EvaluationTracker *Prev;
12395  bool EvalOK = true;
12396  } *EvalTracker = nullptr;
12397 
12398  /// Find the object which is produced by the specified expression,
12399  /// if any.
12400  Object getObject(const Expr *E, bool Mod) const {
12401  E = E->IgnoreParenCasts();
12402  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12403  if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12404  return getObject(UO->getSubExpr(), Mod);
12405  } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12406  if (BO->getOpcode() == BO_Comma)
12407  return getObject(BO->getRHS(), Mod);
12408  if (Mod && BO->isAssignmentOp())
12409  return getObject(BO->getLHS(), Mod);
12410  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12411  // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12412  if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12413  return ME->getMemberDecl();
12414  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12415  // FIXME: If this is a reference, map through to its value.
12416  return DRE->getDecl();
12417  return nullptr;
12418  }
12419 
12420  /// Note that an object \p O was modified or used by an expression
12421  /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12422  /// the object \p O as obtained via the \p UsageMap.
12423  void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12424  // Get the old usage for the given object and usage kind.
12425  Usage &U = UI.Uses[UK];
12426  if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12427  // If we have a modification as side effect and are in a sequenced
12428  // subexpression, save the old Usage so that we can restore it later
12429  // in SequencedSubexpression::~SequencedSubexpression.
12430  if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12431  ModAsSideEffect->push_back(std::make_pair(O, U));
12432  // Then record the new usage with the current sequencing region.
12433  U.UsageExpr = UsageExpr;
12434  U.Seq = Region;
12435  }
12436  }
12437 
12438  /// Check whether a modification or use of an object \p O in an expression
12439  /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12440  /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12441  /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12442  /// usage and false we are checking for a mod-use unsequenced usage.
12443  void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12444  UsageKind OtherKind, bool IsModMod) {
12445  if (UI.Diagnosed)
12446  return;
12447 
12448  const Usage &U = UI.Uses[OtherKind];
12449  if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12450  return;
12451 
12452  const Expr *Mod = U.UsageExpr;
12453  const Expr *ModOrUse = UsageExpr;
12454  if (OtherKind == UK_Use)
12455  std::swap(Mod, ModOrUse);
12456 
12457  SemaRef.DiagRuntimeBehavior(
12458  Mod->getExprLoc(), {Mod, ModOrUse},
12459  SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12460  : diag::warn_unsequenced_mod_use)
12461  << O << SourceRange(ModOrUse->getExprLoc()));
12462  UI.Diagnosed = true;
12463  }
12464 
12465  // A note on note{Pre, Post}{Use, Mod}:
12466  //
12467  // (It helps to follow the algorithm with an expression such as
12468  // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12469  // operations before C++17 and both are well-defined in C++17).
12470  //
12471  // When visiting a node which uses/modify an object we first call notePreUse
12472  // or notePreMod before visiting its sub-expression(s). At this point the
12473  // children of the current node have not yet been visited and so the eventual
12474  // uses/modifications resulting from the children of the current node have not
12475  // been recorded yet.
12476  //
12477  // We then visit the children of the current node. After that notePostUse or
12478  // notePostMod is called. These will 1) detect an unsequenced modification
12479  // as side effect (as in "k++ + k") and 2) add a new usage with the
12480  // appropriate usage kind.
12481  //
12482  // We also have to be careful that some operation sequences modification as
12483  // side effect as well (for example: || or ,). To account for this we wrap
12484  // the visitation of such a sub-expression (for example: the LHS of || or ,)
12485  // with SequencedSubexpression. SequencedSubexpression is an RAII object
12486  // which record usages which are modifications as side effect, and then
12487  // downgrade them (or more accurately restore the previous usage which was a
12488  // modification as side effect) when exiting the scope of the sequenced
12489  // subexpression.
12490 
12491  void notePreUse(Object O, const Expr *UseExpr) {
12492  UsageInfo &UI = UsageMap[O];
12493  // Uses conflict with other modifications.
12494  checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12495  }
12496 
12497  void notePostUse(Object O, const Expr *UseExpr) {
12498  UsageInfo &UI = UsageMap[O];
12499  checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12500  /*IsModMod=*/false);
12501  addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12502  }
12503 
12504  void notePreMod(Object O, const Expr *ModExpr) {
12505  UsageInfo &UI = UsageMap[O];
12506  // Modifications conflict with other modifications and with uses.
12507  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12508  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12509  }
12510 
12511  void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12512  UsageInfo &UI = UsageMap[O];
12513  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12514  /*IsModMod=*/true);
12515  addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12516  }
12517 
12518 public:
12519  SequenceChecker(Sema &S, const Expr *E,
12521  : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12522  Visit(E);
12523  // Silence a -Wunused-private-field since WorkList is now unused.
12524  // TODO: Evaluate if it can be used, and if not remove it.
12525  (void)this->WorkList;
12526  }
12527 
12528  void VisitStmt(const Stmt *S) {
12529  // Skip all statements which aren't expressions for now.
12530  }
12531 
12532  void VisitExpr(const Expr *E) {
12533  // By default, just recurse to evaluated subexpressions.
12534  Base::VisitStmt(E);
12535  }
12536 
12537  void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
12538  for (auto *Sub : CSE->children()) {
12539  const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
12540  if (!ChildExpr)
12541  continue;
12542 
12543  if (ChildExpr == CSE->getOperand())
12544  // Do not recurse over a CoroutineSuspendExpr's operand.
12545  // The operand is also a subexpression of getCommonExpr(), and
12546  // recursing into it directly could confuse object management
12547  // for the sake of sequence tracking.
12548  continue;
12549 
12550  Visit(Sub);
12551  }
12552  }
12553 
12554  void VisitCastExpr(const CastExpr *E) {
12555  Object O = Object();
12556  if (E->getCastKind() == CK_LValueToRValue)
12557  O = getObject(E->getSubExpr(), false);
12558 
12559  if (O)
12560  notePreUse(O, E);
12561  VisitExpr(E);
12562  if (O)
12563  notePostUse(O, E);
12564  }
12565 
12566  void VisitSequencedExpressions(const Expr *SequencedBefore,
12567  const Expr *SequencedAfter) {
12568  SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12569  SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12570  SequenceTree::Seq OldRegion = Region;
12571 
12572  {
12573  SequencedSubexpression SeqBefore(*this);
12574  Region = BeforeRegion;
12575  Visit(SequencedBefore);
12576  }
12577 
12578  Region = AfterRegion;
12579  Visit(SequencedAfter);
12580 
12581  Region = OldRegion;
12582 
12583  Tree.merge(BeforeRegion);
12584  Tree.merge(AfterRegion);
12585  }
12586 
12587  void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12588  // C++17 [expr.sub]p1:
12589  // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12590  // expression E1 is sequenced before the expression E2.
12591  if (SemaRef.getLangOpts().CPlusPlus17)
12592  VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12593  else {
12594  Visit(ASE->getLHS());
12595  Visit(ASE->getRHS());
12596  }
12597  }
12598 
12599  void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12600  void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12601  void VisitBinPtrMem(const BinaryOperator *BO) {
12602  // C++17 [expr.mptr.oper]p4:
12603  // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12604  // the expression E1 is sequenced before the expression E2.
12605  if (SemaRef.getLangOpts().CPlusPlus17)
12606  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12607  else {
12608  Visit(BO->getLHS());
12609  Visit(BO->getRHS());
12610  }
12611  }
12612 
12613  void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12614  void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12615  void VisitBinShlShr(const BinaryOperator *BO) {
12616  // C++17 [expr.shift]p4:
12617  // The expression E1 is sequenced before the expression E2.
12618  if (SemaRef.getLangOpts().CPlusPlus17)
12619  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12620  else {
12621  Visit(BO->getLHS());
12622  Visit(BO->getRHS());
12623  }
12624  }
12625 
12626  void VisitBinComma(const BinaryOperator *BO) {
12627  // C++11 [expr.comma]p1:
12628  // Every value computation and side effect associated with the left
12629  // expression is sequenced before every value computation and side
12630  // effect associated with the right expression.
12631  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12632  }
12633 
12634  void VisitBinAssign(const BinaryOperator *BO) {
12635  SequenceTree::Seq RHSRegion;
12636  SequenceTree::Seq LHSRegion;
12637  if (SemaRef.getLangOpts().CPlusPlus17) {
12638  RHSRegion = Tree.allocate(Region);
12639  LHSRegion = Tree.allocate(Region);
12640  } else {
12641  RHSRegion = Region;
12642  LHSRegion = Region;
12643  }
12644  SequenceTree::Seq OldRegion = Region;
12645 
12646  // C++11 [expr.ass]p1:
12647  // [...] the assignment is sequenced after the value computation
12648  // of the right and left operands, [...]
12649  //
12650  // so check it before inspecting the operands and update the
12651  // map afterwards.
12652  Object O = getObject(BO->getLHS(), /*Mod=*/true);
12653  if (O)
12654  notePreMod(O, BO);
12655 
12656  if (SemaRef.getLangOpts().CPlusPlus17) {
12657  // C++17 [expr.ass]p1:
12658  // [...] The right operand is sequenced before the left operand. [...]
12659  {
12660  SequencedSubexpression SeqBefore(*this);
12661  Region = RHSRegion;
12662  Visit(BO->getRHS());
12663  }
12664 
12665  Region = LHSRegion;
12666  Visit(BO->getLHS());
12667 
12668  if (O && isa<CompoundAssignOperator>(BO))
12669  notePostUse(O, BO);
12670 
12671  } else {
12672  // C++11 does not specify any sequencing between the LHS and RHS.
12673  Region = LHSRegion;
12674  Visit(BO->getLHS());
12675 
12676  if (O && isa<CompoundAssignOperator>(BO))
12677  notePostUse(O, BO);
12678 
12679  Region = RHSRegion;
12680  Visit(BO->getRHS());
12681  }
12682 
12683  // C++11 [expr.ass]p1:
12684  // the assignment is sequenced [...] before the value computation of the
12685  // assignment expression.
12686  // C11 6.5.16/3 has no such rule.
12687  Region = OldRegion;
12688  if (O)
12689  notePostMod(O, BO,
12690  SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12691  : UK_ModAsSideEffect);
12692  if (SemaRef.getLangOpts().CPlusPlus17) {
12693  Tree.merge(RHSRegion);
12694  Tree.merge(LHSRegion);
12695  }
12696  }
12697 
12698  void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12699  VisitBinAssign(CAO);
12700  }
12701 
12702  void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12703  void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12704  void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12705  Object O = getObject(UO->getSubExpr(), true);
12706  if (!O)
12707  return VisitExpr(UO);
12708 
12709  notePreMod(O, UO);
12710  Visit(UO->getSubExpr());
12711  // C++11 [expr.pre.incr]p1:
12712  // the expression ++x is equivalent to x+=1
12713  notePostMod(O, UO,
12714  SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12715  : UK_ModAsSideEffect);
12716  }
12717 
12718  void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12719  void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12720  void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12721  Object O = getObject(UO->getSubExpr(), true);
12722  if (!O)
12723  return VisitExpr(UO);
12724 
12725  notePreMod(O, UO);
12726  Visit(UO->getSubExpr());
12727  notePostMod(O, UO, UK_ModAsSideEffect);
12728  }
12729 
12730  void VisitBinLOr(const BinaryOperator *BO) {
12731  // C++11 [expr.log.or]p2:
12732  // If the second expression is evaluated, every value computation and
12733  // side effect associated with the first expression is sequenced before
12734  // every value computation and side effect associated with the
12735  // second expression.
12736  SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12737  SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12738  SequenceTree::Seq OldRegion = Region;
12739 
12740  EvaluationTracker Eval(*this);
12741  {
12742  SequencedSubexpression Sequenced(*this);
12743  Region = LHSRegion;
12744  Visit(BO->getLHS());
12745  }
12746 
12747  // C++11 [expr.log.or]p1:
12748  // [...] the second operand is not evaluated if the first operand
12749  // evaluates to true.
12750  bool EvalResult = false;
12751  bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12752  bool ShouldVisitRHS = !EvalOK || !EvalResult;
12753  if (ShouldVisitRHS) {
12754  Region = RHSRegion;
12755  Visit(BO->getRHS());
12756  }
12757 
12758  Region = OldRegion;
12759  Tree.merge(LHSRegion);
12760  Tree.merge(RHSRegion);
12761  }
12762 
12763  void VisitBinLAnd(const BinaryOperator *BO) {
12764  // C++11 [expr.log.and]p2:
12765  // If the second expression is evaluated, every value computation and
12766  // side effect associated with the first expression is sequenced before
12767  // every value computation and side effect associated with the
12768  // second expression.
12769  SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12770  SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12771  SequenceTree::Seq OldRegion = Region;
12772 
12773  EvaluationTracker Eval(*this);
12774  {
12775  SequencedSubexpression Sequenced(*this);
12776  Region = LHSRegion;
12777  Visit(BO->getLHS());
12778  }
12779 
12780  // C++11 [expr.log.and]p1:
12781  // [...] the second operand is not evaluated if the first operand is false.
12782  bool EvalResult = false;
12783  bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12784  bool ShouldVisitRHS = !EvalOK || EvalResult;
12785  if (ShouldVisitRHS) {
12786  Region = RHSRegion;
12787  Visit(BO->getRHS());
12788  }
12789 
12790  Region = OldRegion;
12791  Tree.merge(LHSRegion);
12792  Tree.merge(RHSRegion);
12793  }
12794 
12795  void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12796  // C++11 [expr.cond]p1:
12797  // [...] Every value computation and side effect associated with the first
12798  // expression is sequenced before every value computation and side effect
12799  // associated with the second or third expression.
12800  SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12801 
12802  // No sequencing is specified between the true and false expression.
12803  // However since exactly one of both is going to be evaluated we can
12804  // consider them to be sequenced. This is needed to avoid warning on
12805  // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12806  // both the true and false expressions because we can't evaluate x.
12807  // This will still allow us to detect an expression like (pre C++17)
12808  // "(x ? y += 1 : y += 2) = y".
12809  //
12810  // We don't wrap the visitation of the true and false expression with
12811  // SequencedSubexpression because we don't want to downgrade modifications
12812  // as side effect in the true and false expressions after the visition
12813  // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12814  // not warn between the two "y++", but we should warn between the "y++"
12815  // and the "y".
12816  SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12817  SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12818  SequenceTree::Seq OldRegion = Region;
12819 
12820  EvaluationTracker Eval(*this);
12821  {
12822  SequencedSubexpression Sequenced(*this);
12823  Region = ConditionRegion;
12824  Visit(CO->getCond());
12825  }
12826 
12827  // C++11 [expr.cond]p1:
12828  // [...] The first expression is contextually converted to bool (Clause 4).
12829  // It is evaluated and if it is true, the result of the conditional
12830  // expression is the value of the second expression, otherwise that of the
12831  // third expression. Only one of the second and third expressions is
12832  // evaluated. [...]
12833  bool EvalResult = false;
12834  bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12835  bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
12836  bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
12837  if (ShouldVisitTrueExpr) {
12838  Region = TrueRegion;
12839  Visit(CO->getTrueExpr());
12840  }
12841  if (ShouldVisitFalseExpr) {
12842  Region = FalseRegion;
12843  Visit(CO->getFalseExpr());
12844  }
12845 
12846  Region = OldRegion;
12847  Tree.merge(ConditionRegion);
12848  Tree.merge(TrueRegion);
12849  Tree.merge(FalseRegion);
12850  }
12851 
12852  void VisitCallExpr(const CallExpr *CE) {
12853  // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12854 
12855  if (CE->isUnevaluatedBuiltinCall(Context))
12856  return;
12857 
12858  // C++11 [intro.execution]p15:
12859  // When calling a function [...], every value computation and side effect
12860  // associated with any argument expression, or with the postfix expression
12861  // designating the called function, is sequenced before execution of every
12862  // expression or statement in the body of the function [and thus before
12863  // the value computation of its result].
12864  SequencedSubexpression Sequenced(*this);
12865  SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
12866  // C++17 [expr.call]p5
12867  // The postfix-expression is sequenced before each expression in the
12868  // expression-list and any default argument. [...]
12869  SequenceTree::Seq CalleeRegion;
12870  SequenceTree::Seq OtherRegion;
12871  if (SemaRef.getLangOpts().CPlusPlus17) {
12872  CalleeRegion = Tree.allocate(Region);
12873  OtherRegion = Tree.allocate(Region);
12874  } else {
12875  CalleeRegion = Region;
12876  OtherRegion = Region;
12877  }
12878  SequenceTree::Seq OldRegion = Region;
12879 
12880  // Visit the callee expression first.
12881  Region = CalleeRegion;
12882  if (SemaRef.getLangOpts().CPlusPlus17) {
12883  SequencedSubexpression Sequenced(*this);
12884  Visit(CE->getCallee());
12885  } else {
12886  Visit(CE->getCallee());
12887  }
12888 
12889  // Then visit the argument expressions.
12890  Region = OtherRegion;
12891  for (const Expr *Argument : CE->arguments())
12892  Visit(Argument);
12893 
12894  Region = OldRegion;
12895  if (SemaRef.getLangOpts().CPlusPlus17) {
12896  Tree.merge(CalleeRegion);
12897  Tree.merge(OtherRegion);
12898  }
12899  });
12900  }
12901 
12902  void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
12903  // C++17 [over.match.oper]p2:
12904  // [...] the operator notation is first transformed to the equivalent
12905  // function-call notation as summarized in Table 12 (where @ denotes one
12906  // of the operators covered in the specified subclause). However, the
12907  // operands are sequenced in the order prescribed for the built-in
12908  // operator (Clause 8).
12909  //
12910  // From the above only overloaded binary operators and overloaded call
12911  // operators have sequencing rules in C++17 that we need to handle
12912  // separately.
12913  if (!SemaRef.getLangOpts().CPlusPlus17 ||
12914  (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
12915  return VisitCallExpr(CXXOCE);
12916 
12917  enum {
12918  NoSequencing,
12919  LHSBeforeRHS,
12920  RHSBeforeLHS,
12921  LHSBeforeRest
12922  } SequencingKind;
12923  switch (CXXOCE->getOperator()) {
12924  case OO_Equal:
12925  case OO_PlusEqual:
12926  case OO_MinusEqual:
12927  case OO_StarEqual:
12928  case OO_SlashEqual:
12929  case OO_PercentEqual:
12930  case OO_CaretEqual:
12931  case OO_AmpEqual:
12932  case OO_PipeEqual:
12933  case OO_LessLessEqual:
12934  case OO_GreaterGreaterEqual:
12935  SequencingKind = RHSBeforeLHS;
12936  break;
12937 
12938  case OO_LessLess:
12939  case OO_GreaterGreater:
12940  case OO_AmpAmp:
12941  case OO_PipePipe:
12942  case OO_Comma:
12943  case OO_ArrowStar:
12944  case OO_Subscript:
12945  SequencingKind = LHSBeforeRHS;
12946  break;
12947 
12948  case OO_Call:
12949  SequencingKind = LHSBeforeRest;
12950  break;
12951 
12952  default:
12953  SequencingKind = NoSequencing;
12954  break;
12955  }
12956 
12957  if (SequencingKind == NoSequencing)
12958  return VisitCallExpr(CXXOCE);
12959 
12960  // This is a call, so all subexpressions are sequenced before the result.
12961  SequencedSubexpression Sequenced(*this);
12962 
12963  SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
12964  assert(SemaRef.getLangOpts().CPlusPlus17 &&
12965  "Should only get there with C++17 and above!");
12966  assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
12967  "Should only get there with an overloaded binary operator"
12968  " or an overloaded call operator!");
12969 
12970  if (SequencingKind == LHSBeforeRest) {
12971  assert(CXXOCE->getOperator() == OO_Call &&
12972  "We should only have an overloaded call operator here!");
12973 
12974  // This is very similar to VisitCallExpr, except that we only have the
12975  // C++17 case. The postfix-expression is the first argument of the
12976  // CXXOperatorCallExpr. The expressions in the expression-list, if any,
12977  // are in the following arguments.
12978  //
12979  // Note that we intentionally do not visit the callee expression since
12980  // it is just a decayed reference to a function.
12981  SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
12982  SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
12983  SequenceTree::Seq OldRegion = Region;
12984 
12985  assert(CXXOCE->getNumArgs() >= 1 &&
12986  "An overloaded call operator must have at least one argument"
12987  " for the postfix-expression!");
12988  const Expr *PostfixExpr = CXXOCE->getArgs()[0];
12989  llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
12990  CXXOCE->getNumArgs() - 1);
12991 
12992  // Visit the postfix-expression first.
12993  {
12994  Region = PostfixExprRegion;
12995  SequencedSubexpression Sequenced(*this);
12996  Visit(PostfixExpr);
12997  }
12998 
12999  // Then visit the argument expressions.
13000  Region = ArgsRegion;
13001  for (const Expr *Arg : Args)
13002  Visit(Arg);
13003 
13004  Region = OldRegion;
13005  Tree.merge(PostfixExprRegion);
13006  Tree.merge(ArgsRegion);
13007  } else {
13008  assert(CXXOCE->getNumArgs() == 2 &&
13009  "Should only have two arguments here!");
13010  assert((SequencingKind == LHSBeforeRHS ||
13011  SequencingKind == RHSBeforeLHS) &&
13012  "Unexpected sequencing kind!");
13013 
13014  // We do not visit the callee expression since it is just a decayed
13015  // reference to a function.
13016  const Expr *E1 = CXXOCE->getArg(0);
13017  const Expr *E2 = CXXOCE->getArg(1);
13018  if (SequencingKind == RHSBeforeLHS)
13019  std::swap(E1, E2);
13020 
13021  return VisitSequencedExpressions(E1, E2);
13022  }
13023  });
13024  }
13025 
13026  void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13027  // This is a call, so all subexpressions are sequenced before the result.
13028  SequencedSubexpression Sequenced(*this);
13029 
13030  if (!CCE->isListInitialization())
13031  return VisitExpr(CCE);
13032 
13033  // In C++11, list initializations are sequenced.
13034  SequenceExpressionsInOrder(
13035  llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
13036  }
13037 
13038  void VisitInitListExpr(const InitListExpr *ILE) {
13039  if (!SemaRef.getLangOpts().CPlusPlus11)
13040  return VisitExpr(ILE);
13041 
13042  // In C++11, list initializations are sequenced.
13043  SequenceExpressionsInOrder(ILE->inits());
13044  }
13045 
13046  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
13047  // C++20 parenthesized list initializations are sequenced. See C++20
13048  // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
13049  SequenceExpressionsInOrder(PLIE->getInitExprs());
13050  }
13051 
13052 private:
13053  void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
13055  SequenceTree::Seq Parent = Region;
13056  for (const Expr *E : ExpressionList) {
13057  if (!E)
13058  continue;
13059  Region = Tree.allocate(Parent);
13060  Elts.push_back(Region);
13061  Visit(E);
13062  }
13063 
13064  // Forget that the initializers are sequenced.
13065  Region = Parent;
13066  for (unsigned I = 0; I < Elts.size(); ++I)
13067  Tree.merge(Elts[I]);
13068  }
13069 };
13070 
13071 SequenceChecker::UsageInfo::UsageInfo() = default;
13072 
13073 } // namespace
13074 
13075 void Sema::CheckUnsequencedOperations(const Expr *E) {
13077  WorkList.push_back(E);
13078  while (!WorkList.empty()) {
13079  const Expr *Item = WorkList.pop_back_val();
13080  SequenceChecker(*this, Item, WorkList);
13081  }
13082 }
13083 
13084 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13085  bool IsConstexpr) {
13086  llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
13087  IsConstexpr || isa<ConstantExpr>(E));
13088  CheckImplicitConversions(E, CheckLoc);
13089  if (!E->isInstantiationDependent())
13090  CheckUnsequencedOperations(E);
13091  if (!IsConstexpr && !E->isValueDependent())
13092  CheckForIntOverflow(E);
13093  DiagnoseMisalignedMembers();
13094 }
13095 
13096 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13097  FieldDecl *BitField,
13098  Expr *Init) {
13099  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13100 }
13101 
13103  SourceLocation Loc) {
13104  if (!PType->isVariablyModifiedType())
13105  return;
13106  if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13107  diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13108  return;
13109  }
13110  if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13111  diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13112  return;
13113  }
13114  if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13115  diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13116  return;
13117  }
13118 
13119  const ArrayType *AT = S.Context.getAsArrayType(PType);
13120  if (!AT)
13121  return;
13122 
13125  return;
13126  }
13127 
13128  S.Diag(Loc, diag::err_array_star_in_function_definition);
13129 }
13130 
13132  bool CheckParameterNames) {
13133  bool HasInvalidParm = false;
13134  for (ParmVarDecl *Param : Parameters) {
13135  assert(Param && "null in a parameter list");
13136  // C99 6.7.5.3p4: the parameters in a parameter type list in a
13137  // function declarator that is part of a function definition of
13138  // that function shall not have incomplete type.
13139  //
13140  // C++23 [dcl.fct.def.general]/p2
13141  // The type of a parameter [...] for a function definition
13142  // shall not be a (possibly cv-qualified) class type that is incomplete
13143  // or abstract within the function body unless the function is deleted.
13144  if (!Param->isInvalidDecl() &&
13145  (RequireCompleteType(Param->getLocation(), Param->getType(),
13146  diag::err_typecheck_decl_incomplete_type) ||
13147  RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
13148  diag::err_abstract_type_in_decl,
13149  AbstractParamType))) {
13150  Param->setInvalidDecl();
13151  HasInvalidParm = true;
13152  }
13153 
13154  // C99 6.9.1p5: If the declarator includes a parameter type list, the
13155  // declaration of each parameter shall include an identifier.
13156  if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13157  !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13158  // Diagnose this as an extension in C17 and earlier.
13159  if (!getLangOpts().C23)
13160  Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
13161  }
13162 
13163  // C99 6.7.5.3p12:
13164  // If the function declarator is not part of a definition of that
13165  // function, parameters may have incomplete type and may use the [*]
13166  // notation in their sequences of declarator specifiers to specify
13167  // variable length array types.
13168  QualType PType = Param->getOriginalType();
13169  // FIXME: This diagnostic should point the '[*]' if source-location
13170  // information is added for it.
13171  diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13172 
13173  // If the parameter is a c++ class type and it has to be destructed in the
13174  // callee function, declare the destructor so that it can be called by the
13175  // callee function. Do not perform any direct access check on the dtor here.
13176  if (!Param->isInvalidDecl()) {
13177  if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13178  if (!ClassDecl->isInvalidDecl() &&
13179  !ClassDecl->hasIrrelevantDestructor() &&
13180  !ClassDecl->isDependentContext() &&
13181  ClassDecl->isParamDestroyedInCallee()) {
13182  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13183  MarkFunctionReferenced(Param->getLocation(), Destructor);
13184  DiagnoseUseOfDecl(Destructor, Param->getLocation());
13185  }
13186  }
13187  }
13188 
13189  // Parameters with the pass_object_size attribute only need to be marked
13190  // constant at function definitions. Because we lack information about
13191  // whether we're on a declaration or definition when we're instantiating the
13192  // attribute, we need to check for constness here.
13193  if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13194  if (!Param->getType().isConstQualified())
13195  Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13196  << Attr->getSpelling() << 1;
13197 
13198  // Check for parameter names shadowing fields from the class.
13199  if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13200  // The owning context for the parameter should be the function, but we
13201  // want to see if this function's declaration context is a record.
13202  DeclContext *DC = Param->getDeclContext();
13203  if (DC && DC->isFunctionOrMethod()) {
13204  if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13205  CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13206  RD, /*DeclIsField*/ false);
13207  }
13208  }
13209 
13210  if (!Param->isInvalidDecl() &&
13211  Param->getOriginalType()->isWebAssemblyTableType()) {
13212  Param->setInvalidDecl();
13213  HasInvalidParm = true;
13214  Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
13215  }
13216  }
13217 
13218  return HasInvalidParm;
13219 }
13220 
13221 std::optional<std::pair<
13223  *E,
13224  ASTContext
13225  &Ctx);
13226 
13227 /// Compute the alignment and offset of the base class object given the
13228 /// derived-to-base cast expression and the alignment and offset of the derived
13229 /// class object.
13230 static std::pair<CharUnits, CharUnits>
13232  CharUnits BaseAlignment, CharUnits Offset,
13233  ASTContext &Ctx) {
13234  for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13235  ++PathI) {
13236  const CXXBaseSpecifier *Base = *PathI;
13237  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13238  if (Base->isVirtual()) {
13239  // The complete object may have a lower alignment than the non-virtual
13240  // alignment of the base, in which case the base may be misaligned. Choose
13241  // the smaller of the non-virtual alignment and BaseAlignment, which is a
13242  // conservative lower bound of the complete object alignment.
13243  CharUnits NonVirtualAlignment =
13245  BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13246  Offset = CharUnits::Zero();
13247  } else {
13248  const ASTRecordLayout &RL =
13249  Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13250  Offset += RL.getBaseClassOffset(BaseDecl);
13251  }
13252  DerivedType = Base->getType();
13253  }
13254 
13255  return std::make_pair(BaseAlignment, Offset);
13256 }
13257 
13258 /// Compute the alignment and offset of a binary additive operator.
13259 static std::optional<std::pair<CharUnits, CharUnits>>
13261  bool IsSub, ASTContext &Ctx) {
13262  QualType PointeeType = PtrE->getType()->getPointeeType();
13263 
13264  if (!PointeeType->isConstantSizeType())
13265  return std::nullopt;
13266 
13267  auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13268 
13269  if (!P)
13270  return std::nullopt;
13271 
13272  CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13273  if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13274  CharUnits Offset = EltSize * IdxRes->getExtValue();
13275  if (IsSub)
13276  Offset = -Offset;
13277  return std::make_pair(P->first, P->second + Offset);
13278  }
13279 
13280  // If the integer expression isn't a constant expression, compute the lower
13281  // bound of the alignment using the alignment and offset of the pointer
13282  // expression and the element size.
13283  return std::make_pair(
13284  P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13285  CharUnits::Zero());
13286 }
13287 
13288 /// This helper function takes an lvalue expression and returns the alignment of
13289 /// a VarDecl and a constant offset from the VarDecl.
13290 std::optional<std::pair<
13291  CharUnits,
13293  ASTContext &Ctx) {
13294  E = E->IgnoreParens();
13295  switch (E->getStmtClass()) {
13296  default:
13297  break;
13298  case Stmt::CStyleCastExprClass:
13299  case Stmt::CXXStaticCastExprClass:
13300  case Stmt::ImplicitCastExprClass: {
13301  auto *CE = cast<CastExpr>(E);
13302  const Expr *From = CE->getSubExpr();
13303  switch (CE->getCastKind()) {
13304  default:
13305  break;
13306  case CK_NoOp:
13307  return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13308  case CK_UncheckedDerivedToBase:
13309  case CK_DerivedToBase: {
13310  auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13311  if (!P)
13312  break;
13313  return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13314  P->second, Ctx);
13315  }
13316  }
13317  break;
13318  }
13319  case Stmt::ArraySubscriptExprClass: {
13320  auto *ASE = cast<ArraySubscriptExpr>(E);
13321  return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13322  false, Ctx);
13323  }
13324  case Stmt::DeclRefExprClass: {
13325  if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13326  // FIXME: If VD is captured by copy or is an escaping __block variable,
13327  // use the alignment of VD's type.
13328  if (!VD->getType()->isReferenceType()) {
13329  // Dependent alignment cannot be resolved -> bail out.
13330  if (VD->hasDependentAlignment())
13331  break;
13332  return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13333  }
13334  if (VD->hasInit())
13335  return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13336  }
13337  break;
13338  }
13339  case Stmt::MemberExprClass: {
13340  auto *ME = cast<MemberExpr>(E);
13341  auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13342  if (!FD || FD->getType()->isReferenceType() ||
13343  FD->getParent()->isInvalidDecl())
13344  break;
13345  std::optional<std::pair<CharUnits, CharUnits>> P;
13346  if (ME->isArrow())
13347  P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
13348  else
13349  P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13350  if (!P)
13351  break;
13352  const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13353  uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13354  return std::make_pair(P->first,
13355  P->second + CharUnits::fromQuantity(Offset));
13356  }
13357  case Stmt::UnaryOperatorClass: {
13358  auto *UO = cast<UnaryOperator>(E);
13359  switch (UO->getOpcode()) {
13360  default:
13361  break;
13362  case UO_Deref:
13363  return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13364  }
13365  break;
13366  }
13367  case Stmt::BinaryOperatorClass: {
13368  auto *BO = cast<BinaryOperator>(E);
13369  auto Opcode = BO->getOpcode();
13370  switch (Opcode) {
13371  default:
13372  break;
13373  case BO_Comma:
13374  return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13375  }
13376  break;
13377  }
13378  }
13379  return std::nullopt;
13380 }
13381 
13382 /// This helper function takes a pointer expression and returns the alignment of
13383 /// a VarDecl and a constant offset from the VarDecl.
13384 std::optional<std::pair<
13386  *E,
13387  ASTContext
13388  &Ctx) {
13389  E = E->IgnoreParens();
13390  switch (E->getStmtClass()) {
13391  default:
13392  break;
13393  case Stmt::CStyleCastExprClass:
13394  case Stmt::CXXStaticCastExprClass:
13395  case Stmt::ImplicitCastExprClass: {
13396  auto *CE = cast<CastExpr>(E);
13397  const Expr *From = CE->getSubExpr();
13398  switch (CE->getCastKind()) {
13399  default:
13400  break;
13401  case CK_NoOp:
13402  return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13403  case CK_ArrayToPointerDecay:
13404  return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13405  case CK_UncheckedDerivedToBase:
13406  case CK_DerivedToBase: {
13407  auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13408  if (!P)
13409  break;
13411  CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13412  }
13413  }
13414  break;
13415  }
13416  case Stmt::CXXThisExprClass: {
13417  auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13418  CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
13419  return std::make_pair(Alignment, CharUnits::Zero());
13420  }
13421  case Stmt::UnaryOperatorClass: {
13422  auto *UO = cast<UnaryOperator>(E);
13423  if (UO->getOpcode() == UO_AddrOf)
13425  break;
13426  }
13427  case Stmt::BinaryOperatorClass: {
13428  auto *BO = cast<BinaryOperator>(E);
13429  auto Opcode = BO->getOpcode();
13430  switch (Opcode) {
13431  default:
13432  break;
13433  case BO_Add:
13434  case BO_Sub: {
13435  const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13436  if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13437  std::swap(LHS, RHS);
13438  return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13439  Ctx);
13440  }
13441  case BO_Comma:
13442  return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13443  }
13444  break;
13445  }
13446  }
13447  return std::nullopt;
13448 }
13449 
13451  // See if we can compute the alignment of a VarDecl and an offset from it.
13452  std::optional<std::pair<CharUnits, CharUnits>> P =
13454 
13455  if (P)
13456  return P->first.alignmentAtOffset(P->second);
13457 
13458  // If that failed, return the type's alignment.
13460 }
13461 
13463  // This is actually a lot of work to potentially be doing on every
13464  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13465  if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13466  return;
13467 
13468  // Ignore dependent types.
13469  if (T->isDependentType() || Op->getType()->isDependentType())
13470  return;
13471 
13472  // Require that the destination be a pointer type.
13473  const PointerType *DestPtr = T->getAs<PointerType>();
13474  if (!DestPtr) return;
13475 
13476  // If the destination has alignment 1, we're done.
13477  QualType DestPointee = DestPtr->getPointeeType();
13478  if (DestPointee->isIncompleteType()) return;
13479  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13480  if (DestAlign.isOne()) return;
13481 
13482  // Require that the source be a pointer type.
13483  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13484  if (!SrcPtr) return;
13485  QualType SrcPointee = SrcPtr->getPointeeType();
13486 
13487  // Explicitly allow casts from cv void*. We already implicitly
13488  // allowed casts to cv void*, since they have alignment 1.
13489  // Also allow casts involving incomplete types, which implicitly
13490  // includes 'void'.
13491  if (SrcPointee->isIncompleteType()) return;
13492 
13493  CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13494 
13495  if (SrcAlign >= DestAlign) return;
13496 
13497  Diag(TRange.getBegin(), diag::warn_cast_align)
13498  << Op->getType() << T
13499  << static_cast<unsigned>(SrcAlign.getQuantity())
13500  << static_cast<unsigned>(DestAlign.getQuantity())
13501  << TRange << Op->getSourceRange();
13502 }
13503 
13504 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13505  const ArraySubscriptExpr *ASE,
13506  bool AllowOnePastEnd, bool IndexNegated) {
13507  // Already diagnosed by the constant evaluator.
13508  if (isConstantEvaluatedContext())
13509  return;
13510 
13511  IndexExpr = IndexExpr->IgnoreParenImpCasts();
13512  if (IndexExpr->isValueDependent())
13513  return;
13514 
13515  const Type *EffectiveType =
13516  BaseExpr->getType()->getPointeeOrArrayElementType();
13517  BaseExpr = BaseExpr->IgnoreParenCasts();
13518  const ConstantArrayType *ArrayTy =
13519  Context.getAsConstantArrayType(BaseExpr->getType());
13520 
13522  StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
13523 
13524  const Type *BaseType =
13525  ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
13526  bool IsUnboundedArray =
13527  BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
13528  Context, StrictFlexArraysLevel,
13529  /*IgnoreTemplateOrMacroSubstitution=*/true);
13530  if (EffectiveType->isDependentType() ||
13531  (!IsUnboundedArray && BaseType->isDependentType()))
13532  return;
13533 
13534  Expr::EvalResult Result;
13535  if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13536  return;
13537 
13538  llvm::APSInt index = Result.Val.getInt();
13539  if (IndexNegated) {
13540  index.setIsUnsigned(false);
13541  index = -index;
13542  }
13543 
13544  if (IsUnboundedArray) {
13545  if (EffectiveType->isFunctionType())
13546  return;
13547  if (index.isUnsigned() || !index.isNegative()) {
13548  const auto &ASTC = getASTContext();
13549  unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
13550  EffectiveType->getCanonicalTypeInternal().getAddressSpace());
13551  if (index.getBitWidth() < AddrBits)
13552  index = index.zext(AddrBits);
13553  std::optional<CharUnits> ElemCharUnits =
13554  ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
13555  // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
13556  // pointer) bounds-checking isn't meaningful.
13557  if (!ElemCharUnits || ElemCharUnits->isZero())
13558  return;
13559  llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
13560  // If index has more active bits than address space, we already know
13561  // we have a bounds violation to warn about. Otherwise, compute
13562  // address of (index + 1)th element, and warn about bounds violation
13563  // only if that address exceeds address space.
13564  if (index.getActiveBits() <= AddrBits) {
13565  bool Overflow;
13566  llvm::APInt Product(index);
13567  Product += 1;
13568  Product = Product.umul_ov(ElemBytes, Overflow);
13569  if (!Overflow && Product.getActiveBits() <= AddrBits)
13570  return;
13571  }
13572 
13573  // Need to compute max possible elements in address space, since that
13574  // is included in diag message.
13575  llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
13576  MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
13577  MaxElems += 1;
13578  ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
13579  MaxElems = MaxElems.udiv(ElemBytes);
13580 
13581  unsigned DiagID =
13582  ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
13583  : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
13584 
13585  // Diag message shows element size in bits and in "bytes" (platform-
13586  // dependent CharUnits)
13587  DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13588  PDiag(DiagID)
13589  << toString(index, 10, true) << AddrBits
13590  << (unsigned)ASTC.toBits(*ElemCharUnits)
13591  << toString(ElemBytes, 10, false)
13592  << toString(MaxElems, 10, false)
13593  << (unsigned)MaxElems.getLimitedValue(~0U)
13594  << IndexExpr->getSourceRange());
13595 
13596  const NamedDecl *ND = nullptr;
13597  // Try harder to find a NamedDecl to point at in the note.
13598  while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
13599  BaseExpr = ASE->getBase()->IgnoreParenCasts();
13600  if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13601  ND = DRE->getDecl();
13602  if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
13603  ND = ME->getMemberDecl();
13604 
13605  if (ND)
13606  DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13607  PDiag(diag::note_array_declared_here) << ND);
13608  }
13609  return;
13610  }
13611 
13612  if (index.isUnsigned() || !index.isNegative()) {
13613  // It is possible that the type of the base expression after
13614  // IgnoreParenCasts is incomplete, even though the type of the base
13615  // expression before IgnoreParenCasts is complete (see PR39746 for an
13616  // example). In this case we have no information about whether the array
13617  // access exceeds the array bounds. However we can still diagnose an array
13618  // access which precedes the array bounds.
13619  if (BaseType->isIncompleteType())
13620  return;
13621 
13622  llvm::APInt size = ArrayTy->getSize();
13623 
13624  if (BaseType != EffectiveType) {
13625  // Make sure we're comparing apples to apples when comparing index to
13626  // size.
13627  uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13628  uint64_t array_typesize = Context.getTypeSize(BaseType);
13629 
13630  // Handle ptrarith_typesize being zero, such as when casting to void*.
13631  // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
13632  if (!ptrarith_typesize)
13633  ptrarith_typesize = Context.getCharWidth();
13634 
13635  if (ptrarith_typesize != array_typesize) {
13636  // There's a cast to a different size type involved.
13637  uint64_t ratio = array_typesize / ptrarith_typesize;
13638 
13639  // TODO: Be smarter about handling cases where array_typesize is not a
13640  // multiple of ptrarith_typesize.
13641  if (ptrarith_typesize * ratio == array_typesize)
13642  size *= llvm::APInt(size.getBitWidth(), ratio);
13643  }
13644  }
13645 
13646  if (size.getBitWidth() > index.getBitWidth())
13647  index = index.zext(size.getBitWidth());
13648  else if (size.getBitWidth() < index.getBitWidth())
13649  size = size.zext(index.getBitWidth());
13650 
13651  // For array subscripting the index must be less than size, but for pointer
13652  // arithmetic also allow the index (offset) to be equal to size since
13653  // computing the next address after the end of the array is legal and
13654  // commonly done e.g. in C++ iterators and range-based for loops.
13655  if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13656  return;
13657 
13658  // Suppress the warning if the subscript expression (as identified by the
13659  // ']' location) and the index expression are both from macro expansions
13660  // within a system header.
13661  if (ASE) {
13662  SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13663  ASE->getRBracketLoc());
13664  if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13665  SourceLocation IndexLoc =
13666  SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13667  if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13668  return;
13669  }
13670  }
13671 
13672  unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
13673  : diag::warn_ptr_arith_exceeds_bounds;
13674  unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
13675  QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
13676 
13677  DiagRuntimeBehavior(
13678  BaseExpr->getBeginLoc(), BaseExpr,
13679  PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
13680  << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
13681  } else {
13682  unsigned DiagID = diag::warn_array_index_precedes_bounds;
13683  if (!ASE) {
13684  DiagID = diag::warn_ptr_arith_precedes_bounds;
13685  if (index.isNegative()) index = -index;
13686  }
13687 
13688  DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13689  PDiag(DiagID) << toString(index, 10, true)
13690  << IndexExpr->getSourceRange());
13691  }
13692 
13693  const NamedDecl *ND = nullptr;
13694  // Try harder to find a NamedDecl to point at in the note.
13695  while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
13696  BaseExpr = ASE->getBase()->IgnoreParenCasts();
13697  if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13698  ND = DRE->getDecl();
13699  if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
13700  ND = ME->getMemberDecl();
13701 
13702  if (ND)
13703  DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13704  PDiag(diag::note_array_declared_here) << ND);
13705 }
13706 
13707 void Sema::CheckArrayAccess(const Expr *expr) {
13708  int AllowOnePastEnd = 0;
13709  while (expr) {
13710  expr = expr->IgnoreParenImpCasts();
13711  switch (expr->getStmtClass()) {
13712  case Stmt::ArraySubscriptExprClass: {
13713  const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13714  CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13715  AllowOnePastEnd > 0);
13716  expr = ASE->getBase();
13717  break;
13718  }
13719  case Stmt::MemberExprClass: {
13720  expr = cast<MemberExpr>(expr)->getBase();
13721  break;
13722  }
13723  case Stmt::ArraySectionExprClass: {
13724  const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
13725  // FIXME: We should probably be checking all of the elements to the
13726  // 'length' here as well.
13727  if (ASE->getLowerBound())
13728  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13729  /*ASE=*/nullptr, AllowOnePastEnd > 0);
13730  return;
13731  }
13732  case Stmt::UnaryOperatorClass: {
13733  // Only unwrap the * and & unary operators
13734  const UnaryOperator *UO = cast<UnaryOperator>(expr);
13735  expr = UO->getSubExpr();
13736  switch (UO->getOpcode()) {
13737  case UO_AddrOf:
13738  AllowOnePastEnd++;
13739  break;
13740  case UO_Deref:
13741  AllowOnePastEnd--;
13742  break;
13743  default:
13744  return;
13745  }
13746  break;
13747  }
13748  case Stmt::ConditionalOperatorClass: {
13749  const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13750  if (const Expr *lhs = cond->getLHS())
13751  CheckArrayAccess(lhs);
13752  if (const Expr *rhs = cond->getRHS())
13753  CheckArrayAccess(rhs);
13754  return;
13755  }
13756  case Stmt::CXXOperatorCallExprClass: {
13757  const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13758  for (const auto *Arg : OCE->arguments())
13759  CheckArrayAccess(Arg);
13760  return;
13761  }
13762  default:
13763  return;
13764  }
13765  }
13766 }
13767 
13769  Expr *RHS, bool isProperty) {
13770  // Check if RHS is an Objective-C object literal, which also can get
13771  // immediately zapped in a weak reference. Note that we explicitly
13772  // allow ObjCStringLiterals, since those are designed to never really die.
13773  RHS = RHS->IgnoreParenImpCasts();
13774 
13775  // This enum needs to match with the 'select' in
13776  // warn_objc_arc_literal_assign (off-by-1).
13779  return false;
13780 
13781  S.Diag(Loc, diag::warn_arc_literal_assign)
13782  << (unsigned) Kind
13783  << (isProperty ? 0 : 1)
13784  << RHS->getSourceRange();
13785 
13786  return true;
13787 }
13788 
13791  Expr *RHS, bool isProperty) {
13792  // Strip off any implicit cast added to get to the one ARC-specific.
13793  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13794  if (cast->getCastKind() == CK_ARCConsumeObject) {
13795  S.Diag(Loc, diag::warn_arc_retained_assign)
13797  << (isProperty ? 0 : 1)
13798  << RHS->getSourceRange();
13799  return true;
13800  }
13801  RHS = cast->getSubExpr();
13802  }
13803 
13804  if (LT == Qualifiers::OCL_Weak &&
13805  checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13806  return true;
13807 
13808  return false;
13809 }
13810 
13812  QualType LHS, Expr *RHS) {
13814 
13816  return false;
13817 
13818  if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13819  return true;
13820 
13821  return false;
13822 }
13823 
13825  Expr *LHS, Expr *RHS) {
13826  QualType LHSType;
13827  // PropertyRef on LHS type need be directly obtained from
13828  // its declaration as it has a PseudoType.
13829  ObjCPropertyRefExpr *PRE
13830  = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13831  if (PRE && !PRE->isImplicitProperty()) {
13832  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13833  if (PD)
13834  LHSType = PD->getType();
13835  }
13836 
13837  if (LHSType.isNull())
13838  LHSType = LHS->getType();
13839 
13841 
13842  if (LT == Qualifiers::OCL_Weak) {
13843  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13844  getCurFunction()->markSafeWeakUse(LHS);
13845  }
13846 
13847  if (checkUnsafeAssigns(Loc, LHSType, RHS))
13848  return;
13849 
13850  // FIXME. Check for other life times.
13851  if (LT != Qualifiers::OCL_None)
13852  return;
13853 
13854  if (PRE) {
13855  if (PRE->isImplicitProperty())
13856  return;
13857  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13858  if (!PD)
13859  return;
13860 
13861  unsigned Attributes = PD->getPropertyAttributes();
13862  if (Attributes & ObjCPropertyAttribute::kind_assign) {
13863  // when 'assign' attribute was not explicitly specified
13864  // by user, ignore it and rely on property type itself
13865  // for lifetime info.
13866  unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13867  if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
13868  LHSType->isObjCRetainableType())
13869  return;
13870 
13871  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13872  if (cast->getCastKind() == CK_ARCConsumeObject) {
13873  Diag(Loc, diag::warn_arc_retained_property_assign)
13874  << RHS->getSourceRange();
13875  return;
13876  }
13877  RHS = cast->getSubExpr();
13878  }
13879  } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
13880  if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13881  return;
13882  }
13883  }
13884 }
13885 
13886 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13887 
13888 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13889  SourceLocation StmtLoc,
13890  const NullStmt *Body) {
13891  // Do not warn if the body is a macro that expands to nothing, e.g:
13892  //
13893  // #define CALL(x)
13894  // if (condition)
13895  // CALL(0);
13896  if (Body->hasLeadingEmptyMacro())
13897  return false;
13898 
13899  // Get line numbers of statement and body.
13900  bool StmtLineInvalid;
13901  unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13902  &StmtLineInvalid);
13903  if (StmtLineInvalid)
13904  return false;
13905 
13906  bool BodyLineInvalid;
13907  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13908  &BodyLineInvalid);
13909  if (BodyLineInvalid)
13910  return false;
13911 
13912  // Warn if null statement and body are on the same line.
13913  if (StmtLine != BodyLine)
13914  return false;
13915 
13916  return true;
13917 }
13918 
13920  const Stmt *Body,
13921  unsigned DiagID) {
13922  // Since this is a syntactic check, don't emit diagnostic for template
13923  // instantiations, this just adds noise.
13924  if (CurrentInstantiationScope)
13925  return;
13926 
13927  // The body should be a null statement.
13928  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13929  if (!NBody)
13930  return;
13931 
13932  // Do the usual checks.
13933  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13934  return;
13935 
13936  Diag(NBody->getSemiLoc(), DiagID);
13937  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13938 }
13939 
13941  const Stmt *PossibleBody) {
13942  assert(!CurrentInstantiationScope); // Ensured by caller
13943 
13944  SourceLocation StmtLoc;
13945  const Stmt *Body;
13946  unsigned DiagID;
13947  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13948  StmtLoc = FS->getRParenLoc();
13949  Body = FS->getBody();
13950  DiagID = diag::warn_empty_for_body;
13951  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13952  StmtLoc = WS->getRParenLoc();
13953  Body = WS->getBody();
13954  DiagID = diag::warn_empty_while_body;
13955  } else
13956  return; // Neither `for' nor `while'.
13957 
13958  // The body should be a null statement.
13959  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13960  if (!NBody)
13961  return;
13962 
13963  // Skip expensive checks if diagnostic is disabled.
13964  if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13965  return;
13966 
13967  // Do the usual checks.
13968  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13969  return;
13970 
13971  // `for(...);' and `while(...);' are popular idioms, so in order to keep
13972  // noise level low, emit diagnostics only if for/while is followed by a
13973  // CompoundStmt, e.g.:
13974  // for (int i = 0; i < n; i++);
13975  // {
13976  // a(i);
13977  // }
13978  // or if for/while is followed by a statement with more indentation
13979  // than for/while itself:
13980  // for (int i = 0; i < n; i++);
13981  // a(i);
13982  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13983  if (!ProbableTypo) {
13984  bool BodyColInvalid;
13985  unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13986  PossibleBody->getBeginLoc(), &BodyColInvalid);
13987  if (BodyColInvalid)
13988  return;
13989 
13990  bool StmtColInvalid;
13991  unsigned StmtCol =
13992  SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13993  if (StmtColInvalid)
13994  return;
13995 
13996  if (BodyCol > StmtCol)
13997  ProbableTypo = true;
13998  }
13999 
14000  if (ProbableTypo) {
14001  Diag(NBody->getSemiLoc(), DiagID);
14002  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14003  }
14004 }
14005 
14006 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14007 
14008 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14009  SourceLocation OpLoc) {
14010  if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14011  return;
14012 
14013  if (inTemplateInstantiation())
14014  return;
14015 
14016  // Strip parens and casts away.
14017  LHSExpr = LHSExpr->IgnoreParenImpCasts();
14018  RHSExpr = RHSExpr->IgnoreParenImpCasts();
14019 
14020  // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
14021  // which we can treat as an inlined std::move
14022  if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
14023  CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
14024  RHSExpr = CE->getArg(0);
14025  else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
14026  CXXSCE && CXXSCE->isXValue())
14027  RHSExpr = CXXSCE->getSubExpr();
14028  else
14029  return;
14030 
14031  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14032  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14033 
14034  // Two DeclRefExpr's, check that the decls are the same.
14035  if (LHSDeclRef && RHSDeclRef) {
14036  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14037  return;
14038  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14039  RHSDeclRef->getDecl()->getCanonicalDecl())
14040  return;
14041 
14042  auto D = Diag(OpLoc, diag::warn_self_move)
14043  << LHSExpr->getType() << LHSExpr->getSourceRange()
14044  << RHSExpr->getSourceRange();
14045  if (const FieldDecl *F =
14046  getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl()))
14047  D << 1 << F
14048  << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14049  else
14050  D << 0;
14051  return;
14052  }
14053 
14054  // Member variables require a different approach to check for self moves.
14055  // MemberExpr's are the same if every nested MemberExpr refers to the same
14056  // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14057  // the base Expr's are CXXThisExpr's.
14058  const Expr *LHSBase = LHSExpr;
14059  const Expr *RHSBase = RHSExpr;
14060  const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14061  const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14062  if (!LHSME || !RHSME)
14063  return;
14064 
14065  while (LHSME && RHSME) {
14066  if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14067  RHSME->getMemberDecl()->getCanonicalDecl())
14068  return;
14069 
14070  LHSBase = LHSME->getBase();
14071  RHSBase = RHSME->getBase();
14072  LHSME = dyn_cast<MemberExpr>(LHSBase);
14073  RHSME = dyn_cast<MemberExpr>(RHSBase);
14074  }
14075 
14076  LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14077  RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14078  if (LHSDeclRef && RHSDeclRef) {
14079  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14080  return;
14081  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14082  RHSDeclRef->getDecl()->getCanonicalDecl())
14083  return;
14084 
14085  Diag(OpLoc, diag::warn_self_move)
14086  << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
14087  << RHSExpr->getSourceRange();
14088  return;
14089  }
14090 
14091  if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14092  Diag(OpLoc, diag::warn_self_move)
14093  << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
14094  << RHSExpr->getSourceRange();
14095 }
14096 
14097 //===--- Layout compatibility ----------------------------------------------//
14098 
14099 static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
14100 
14101 /// Check if two enumeration types are layout-compatible.
14102 static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
14103  const EnumDecl *ED2) {
14104  // C++11 [dcl.enum] p8:
14105  // Two enumeration types are layout-compatible if they have the same
14106  // underlying type.
14107  return ED1->isComplete() && ED2->isComplete() &&
14108  C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14109 }
14110 
14111 /// Check if two fields are layout-compatible.
14112 /// Can be used on union members, which are exempt from alignment requirement
14113 /// of common initial sequence.
14114 static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
14115  const FieldDecl *Field2,
14116  bool AreUnionMembers = false) {
14117  [[maybe_unused]] const Type *Field1Parent =
14118  Field1->getParent()->getTypeForDecl();
14119  [[maybe_unused]] const Type *Field2Parent =
14120  Field2->getParent()->getTypeForDecl();
14121  assert(((Field1Parent->isStructureOrClassType() &&
14122  Field2Parent->isStructureOrClassType()) ||
14123  (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
14124  "Can't evaluate layout compatibility between a struct field and a "
14125  "union field.");
14126  assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
14127  (AreUnionMembers && Field1Parent->isUnionType())) &&
14128  "AreUnionMembers should be 'true' for union fields (only).");
14129 
14130  if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14131  return false;
14132 
14133  if (Field1->isBitField() != Field2->isBitField())
14134  return false;
14135 
14136  if (Field1->isBitField()) {
14137  // Make sure that the bit-fields are the same length.
14138  unsigned Bits1 = Field1->getBitWidthValue(C);
14139  unsigned Bits2 = Field2->getBitWidthValue(C);
14140 
14141  if (Bits1 != Bits2)
14142  return false;
14143  }
14144 
14145  if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
14146  Field2->hasAttr<clang::NoUniqueAddressAttr>())
14147  return false;
14148 
14149  if (!AreUnionMembers &&
14150  Field1->getMaxAlignment() != Field2->getMaxAlignment())
14151  return false;
14152 
14153  return true;
14154 }
14155 
14156 /// Check if two standard-layout structs are layout-compatible.
14157 /// (C++11 [class.mem] p17)
14158 static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
14159  const RecordDecl *RD2) {
14160  // Get to the class where the fields are declared
14161  if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
14162  RD1 = D1CXX->getStandardLayoutBaseWithFields();
14163 
14164  if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
14165  RD2 = D2CXX->getStandardLayoutBaseWithFields();
14166 
14167  // Check the fields.
14168  return llvm::equal(RD1->fields(), RD2->fields(),
14169  [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
14170  return isLayoutCompatible(C, F1, F2);
14171  });
14172 }
14173 
14174 /// Check if two standard-layout unions are layout-compatible.
14175 /// (C++11 [class.mem] p18)
14176 static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
14177  const RecordDecl *RD2) {
14179  for (auto *Field2 : RD2->fields())
14180  UnmatchedFields.insert(Field2);
14181 
14182  for (auto *Field1 : RD1->fields()) {
14183  auto I = UnmatchedFields.begin();
14184  auto E = UnmatchedFields.end();
14185 
14186  for ( ; I != E; ++I) {
14187  if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
14188  bool Result = UnmatchedFields.erase(*I);
14189  (void) Result;
14190  assert(Result);
14191  break;
14192  }
14193  }
14194  if (I == E)
14195  return false;
14196  }
14197 
14198  return UnmatchedFields.empty();
14199 }
14200 
14201 static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
14202  const RecordDecl *RD2) {
14203  if (RD1->isUnion() != RD2->isUnion())
14204  return false;
14205 
14206  if (RD1->isUnion())
14207  return isLayoutCompatibleUnion(C, RD1, RD2);
14208  else
14209  return isLayoutCompatibleStruct(C, RD1, RD2);
14210 }
14211 
14212 /// Check if two types are layout-compatible in C++11 sense.
14213 static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
14214  if (T1.isNull() || T2.isNull())
14215  return false;
14216 
14217  // C++20 [basic.types] p11:
14218  // Two types cv1 T1 and cv2 T2 are layout-compatible types
14219  // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
14220  // or layout-compatible standard-layout class types (11.4).
14223 
14224  if (C.hasSameType(T1, T2))
14225  return true;
14226 
14227  const Type::TypeClass TC1 = T1->getTypeClass();
14228  const Type::TypeClass TC2 = T2->getTypeClass();
14229 
14230  if (TC1 != TC2)
14231  return false;
14232 
14233  if (TC1 == Type::Enum) {
14234  return isLayoutCompatible(C,
14235  cast<EnumType>(T1)->getDecl(),
14236  cast<EnumType>(T2)->getDecl());
14237  } else if (TC1 == Type::Record) {
14238  if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14239  return false;
14240 
14241  return isLayoutCompatible(C,
14242  cast<RecordType>(T1)->getDecl(),
14243  cast<RecordType>(T2)->getDecl());
14244  }
14245 
14246  return false;
14247 }
14248 
14250  return isLayoutCompatible(getASTContext(), T1, T2);
14251 }
14252 
14253 //===-------------- Pointer interconvertibility ----------------------------//
14254 
14256  const TypeSourceInfo *Derived) {
14257  QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
14258  QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
14259 
14260  if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
14261  getASTContext().hasSameType(BaseT, DerivedT))
14262  return true;
14263 
14264  if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
14265  return false;
14266 
14267  // Per [basic.compound]/4.3, containing object has to be standard-layout.
14268  if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
14269  return true;
14270 
14271  return false;
14272 }
14273 
14274 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14275 
14276 /// Given a type tag expression find the type tag itself.
14277 ///
14278 /// \param TypeExpr Type tag expression, as it appears in user's code.
14279 ///
14280 /// \param VD Declaration of an identifier that appears in a type tag.
14281 ///
14282 /// \param MagicValue Type tag magic value.
14283 ///
14284 /// \param isConstantEvaluated whether the evalaution should be performed in
14285 
14286 /// constant context.
14287 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14288  const ValueDecl **VD, uint64_t *MagicValue,
14289  bool isConstantEvaluated) {
14290  while(true) {
14291  if (!TypeExpr)
14292  return false;
14293 
14294  TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14295 
14296  switch (TypeExpr->getStmtClass()) {
14297  case Stmt::UnaryOperatorClass: {
14298  const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14299  if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14300  TypeExpr = UO->getSubExpr();
14301  continue;
14302  }
14303  return false;
14304  }
14305 
14306  case Stmt::DeclRefExprClass: {
14307  const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14308  *VD = DRE->getDecl();
14309  return true;
14310  }
14311 
14312  case Stmt::IntegerLiteralClass: {
14313  const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14314  llvm::APInt MagicValueAPInt = IL->getValue();
14315  if (MagicValueAPInt.getActiveBits() <= 64) {
14316  *MagicValue = MagicValueAPInt.getZExtValue();
14317  return true;
14318  } else
14319  return false;
14320  }
14321 
14322  case Stmt::BinaryConditionalOperatorClass:
14323  case Stmt::ConditionalOperatorClass: {
14324  const AbstractConditionalOperator *ACO =
14325  cast<AbstractConditionalOperator>(TypeExpr);
14326  bool Result;
14327  if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14328  isConstantEvaluated)) {
14329  if (Result)
14330  TypeExpr = ACO->getTrueExpr();
14331  else
14332  TypeExpr = ACO->getFalseExpr();
14333  continue;
14334  }
14335  return false;
14336  }
14337 
14338  case Stmt::BinaryOperatorClass: {
14339  const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14340  if (BO->getOpcode() == BO_Comma) {
14341  TypeExpr = BO->getRHS();
14342  continue;
14343  }
14344  return false;
14345  }
14346 
14347  default:
14348  return false;
14349  }
14350  }
14351 }
14352 
14353 /// Retrieve the C type corresponding to type tag TypeExpr.
14354 ///
14355 /// \param TypeExpr Expression that specifies a type tag.
14356 ///
14357 /// \param MagicValues Registered magic values.
14358 ///
14359 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14360 /// kind.
14361 ///
14362 /// \param TypeInfo Information about the corresponding C type.
14363 ///
14364 /// \param isConstantEvaluated whether the evalaution should be performed in
14365 /// constant context.
14366 ///
14367 /// \returns true if the corresponding C type was found.
14368 static bool GetMatchingCType(
14369  const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14370  const ASTContext &Ctx,
14371  const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14372  *MagicValues,
14373  bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14374  bool isConstantEvaluated) {
14375  FoundWrongKind = false;
14376 
14377  // Variable declaration that has type_tag_for_datatype attribute.
14378  const ValueDecl *VD = nullptr;
14379 
14380  uint64_t MagicValue;
14381 
14382  if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14383  return false;
14384 
14385  if (VD) {
14386  if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14387  if (I->getArgumentKind() != ArgumentKind) {
14388  FoundWrongKind = true;
14389  return false;
14390  }
14391  TypeInfo.Type = I->getMatchingCType();
14392  TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14393  TypeInfo.MustBeNull = I->getMustBeNull();
14394  return true;
14395  }
14396  return false;
14397  }
14398 
14399  if (!MagicValues)
14400  return false;
14401 
14402  llvm::DenseMap<Sema::TypeTagMagicValue,
14403  Sema::TypeTagData>::const_iterator I =
14404  MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14405  if (I == MagicValues->end())
14406  return false;
14407 
14408  TypeInfo = I->second;
14409  return true;
14410 }
14411 
14413  uint64_t MagicValue, QualType Type,
14414  bool LayoutCompatible,
14415  bool MustBeNull) {
14416  if (!TypeTagForDatatypeMagicValues)
14417  TypeTagForDatatypeMagicValues.reset(
14418  new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14419 
14420  TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14421  (*TypeTagForDatatypeMagicValues)[Magic] =
14422  TypeTagData(Type, LayoutCompatible, MustBeNull);
14423 }
14424 
14425 static bool IsSameCharType(QualType T1, QualType T2) {
14426  const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14427  if (!BT1)
14428  return false;
14429 
14430  const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14431  if (!BT2)
14432  return false;
14433 
14434  BuiltinType::Kind T1Kind = BT1->getKind();
14435  BuiltinType::Kind T2Kind = BT2->getKind();
14436 
14437  return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
14438  (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
14439  (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14440  (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14441 }
14442 
14443 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14444  const ArrayRef<const Expr *> ExprArgs,
14445  SourceLocation CallSiteLoc) {
14446  const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14447  bool IsPointerAttr = Attr->getIsPointer();
14448 
14449  // Retrieve the argument representing the 'type_tag'.
14450  unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14451  if (TypeTagIdxAST >= ExprArgs.size()) {
14452  Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14453  << 0 << Attr->getTypeTagIdx().getSourceIndex();
14454  return;
14455  }
14456  const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14457  bool FoundWrongKind;
14458  TypeTagData TypeInfo;
14459  if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14460  TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14461  TypeInfo, isConstantEvaluatedContext())) {
14462  if (FoundWrongKind)
14463  Diag(TypeTagExpr->getExprLoc(),
14464  diag::warn_type_tag_for_datatype_wrong_kind)
14465  << TypeTagExpr->getSourceRange();
14466  return;
14467  }
14468 
14469  // Retrieve the argument representing the 'arg_idx'.
14470  unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14471  if (ArgumentIdxAST >= ExprArgs.size()) {
14472  Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14473  << 1 << Attr->getArgumentIdx().getSourceIndex();
14474  return;
14475  }
14476  const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14477  if (IsPointerAttr) {
14478  // Skip implicit cast of pointer to `void *' (as a function argument).
14479  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14480  if (ICE->getType()->isVoidPointerType() &&
14481  ICE->getCastKind() == CK_BitCast)
14482  ArgumentExpr = ICE->getSubExpr();
14483  }
14484  QualType ArgumentType = ArgumentExpr->getType();
14485 
14486  // Passing a `void*' pointer shouldn't trigger a warning.
14487  if (IsPointerAttr && ArgumentType->isVoidPointerType())
14488  return;
14489 
14490  if (TypeInfo.MustBeNull) {
14491  // Type tag with matching void type requires a null pointer.
14492  if (!ArgumentExpr->isNullPointerConstant(Context,
14494  Diag(ArgumentExpr->getExprLoc(),
14495  diag::warn_type_safety_null_pointer_required)
14496  << ArgumentKind->getName()
14497  << ArgumentExpr->getSourceRange()
14498  << TypeTagExpr->getSourceRange();
14499  }
14500  return;
14501  }
14502 
14503  QualType RequiredType = TypeInfo.Type;
14504  if (IsPointerAttr)
14505  RequiredType = Context.getPointerType(RequiredType);
14506 
14507  bool mismatch = false;
14508  if (!TypeInfo.LayoutCompatible) {
14509  mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14510 
14511  // C++11 [basic.fundamental] p1:
14512  // Plain char, signed char, and unsigned char are three distinct types.
14513  //
14514  // But we treat plain `char' as equivalent to `signed char' or `unsigned
14515  // char' depending on the current char signedness mode.
14516  if (mismatch)
14517  if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14518  RequiredType->getPointeeType())) ||
14519  (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14520  mismatch = false;
14521  } else
14522  if (IsPointerAttr)
14523  mismatch = !isLayoutCompatible(Context,
14524  ArgumentType->getPointeeType(),
14525  RequiredType->getPointeeType());
14526  else
14527  mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14528 
14529  if (mismatch)
14530  Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14531  << ArgumentType << ArgumentKind
14532  << TypeInfo.LayoutCompatible << RequiredType
14533  << ArgumentExpr->getSourceRange()
14534  << TypeTagExpr->getSourceRange();
14535 }
14536 
14537 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14538  CharUnits Alignment) {
14539  MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14540 }
14541 
14543  for (MisalignedMember &m : MisalignedMembers) {
14544  const NamedDecl *ND = m.RD;
14545  if (ND->getName().empty()) {
14546  if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14547  ND = TD;
14548  }
14549  Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14550  << m.MD << ND << m.E->getSourceRange();
14551  }
14552  MisalignedMembers.clear();
14553 }
14554 
14556  E = E->IgnoreParens();
14557  if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
14558  return;
14559  if (isa<UnaryOperator>(E) &&
14560  cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14561  auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14562  if (isa<MemberExpr>(Op)) {
14563  auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14564  if (MA != MisalignedMembers.end() &&
14565  (T->isDependentType() || T->isIntegerType() ||
14567  Context.getTypeAlignInChars(
14568  T->getPointeeType()) <= MA->Alignment))))
14569  MisalignedMembers.erase(MA);
14570  }
14571  }
14572 }
14573 
14575  Expr *E,
14576  llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14577  Action) {
14578  const auto *ME = dyn_cast<MemberExpr>(E);
14579  if (!ME)
14580  return;
14581 
14582  // No need to check expressions with an __unaligned-qualified type.
14583  if (E->getType().getQualifiers().hasUnaligned())
14584  return;
14585 
14586  // For a chain of MemberExpr like "a.b.c.d" this list
14587  // will keep FieldDecl's like [d, c, b].
14588  SmallVector<FieldDecl *, 4> ReverseMemberChain;
14589  const MemberExpr *TopME = nullptr;
14590  bool AnyIsPacked = false;
14591  do {
14592  QualType BaseType = ME->getBase()->getType();
14593  if (BaseType->isDependentType())
14594  return;
14595  if (ME->isArrow())
14596  BaseType = BaseType->getPointeeType();
14597  RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14598  if (RD->isInvalidDecl())
14599  return;
14600 
14601  ValueDecl *MD = ME->getMemberDecl();
14602  auto *FD = dyn_cast<FieldDecl>(MD);
14603  // We do not care about non-data members.
14604  if (!FD || FD->isInvalidDecl())
14605  return;
14606 
14607  AnyIsPacked =
14608  AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14609  ReverseMemberChain.push_back(FD);
14610 
14611  TopME = ME;
14612  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14613  } while (ME);
14614  assert(TopME && "We did not compute a topmost MemberExpr!");
14615 
14616  // Not the scope of this diagnostic.
14617  if (!AnyIsPacked)
14618  return;
14619 
14620  const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14621  const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14622  // TODO: The innermost base of the member expression may be too complicated.
14623  // For now, just disregard these cases. This is left for future
14624  // improvement.
14625  if (!DRE && !isa<CXXThisExpr>(TopBase))
14626  return;
14627 
14628  // Alignment expected by the whole expression.
14629  CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14630 
14631  // No need to do anything else with this case.
14632  if (ExpectedAlignment.isOne())
14633  return;
14634 
14635  // Synthesize offset of the whole access.
14636  CharUnits Offset;
14637  for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
14638  Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
14639 
14640  // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14641  CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14642  ReverseMemberChain.back()->getParent()->getTypeForDecl());
14643 
14644  // The base expression of the innermost MemberExpr may give
14645  // stronger guarantees than the class containing the member.
14646  if (DRE && !TopME->isArrow()) {
14647  const ValueDecl *VD = DRE->getDecl();
14648  if (!VD->getType()->isReferenceType())
14649  CompleteObjectAlignment =
14650  std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14651  }
14652 
14653  // Check if the synthesized offset fulfills the alignment.
14654  if (Offset % ExpectedAlignment != 0 ||
14655  // It may fulfill the offset it but the effective alignment may still be
14656  // lower than the expected expression alignment.
14657  CompleteObjectAlignment < ExpectedAlignment) {
14658  // If this happens, we want to determine a sensible culprit of this.
14659  // Intuitively, watching the chain of member expressions from right to
14660  // left, we start with the required alignment (as required by the field
14661  // type) but some packed attribute in that chain has reduced the alignment.
14662  // It may happen that another packed structure increases it again. But if
14663  // we are here such increase has not been enough. So pointing the first
14664  // FieldDecl that either is packed or else its RecordDecl is,
14665  // seems reasonable.
14666  FieldDecl *FD = nullptr;
14667  CharUnits Alignment;
14668  for (FieldDecl *FDI : ReverseMemberChain) {
14669  if (FDI->hasAttr<PackedAttr>() ||
14670  FDI->getParent()->hasAttr<PackedAttr>()) {
14671  FD = FDI;
14672  Alignment = std::min(
14673  Context.getTypeAlignInChars(FD->getType()),
14674  Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14675  break;
14676  }
14677  }
14678  assert(FD && "We did not find a packed FieldDecl!");
14679  Action(E, FD->getParent(), FD, Alignment);
14680  }
14681 }
14682 
14683 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14684  using namespace std::placeholders;
14685 
14686  RefersToMemberWithReducedAlignment(
14687  rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14688  _2, _3, _4));
14689 }
14690 
14692  if (checkArgCount(TheCall, 1))
14693  return true;
14694 
14695  ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
14696  if (A.isInvalid())
14697  return true;
14698 
14699  TheCall->setArg(0, A.get());
14700  QualType TyA = A.get()->getType();
14701 
14702  if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
14703  return true;
14704 
14705  TheCall->setType(TyA);
14706  return false;
14707 }
14708 
14709 bool Sema::BuiltinElementwiseMath(CallExpr *TheCall) {
14710  QualType Res;
14711  if (BuiltinVectorMath(TheCall, Res))
14712  return true;
14713  TheCall->setType(Res);
14714  return false;
14715 }
14716 
14718  QualType Res;
14719  if (BuiltinVectorMath(TheCall, Res))
14720  return true;
14721 
14722  if (auto *VecTy0 = Res->getAs<VectorType>())
14723  TheCall->setType(VecTy0->getElementType());
14724  else
14725  TheCall->setType(Res);
14726 
14727  return false;
14728 }
14729 
14731  if (checkArgCount(TheCall, 2))
14732  return true;
14733 
14734  ExprResult A = TheCall->getArg(0);
14735  ExprResult B = TheCall->getArg(1);
14736  // Do standard promotions between the two arguments, returning their common
14737  // type.
14738  Res = UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
14739  if (A.isInvalid() || B.isInvalid())
14740  return true;
14741 
14742  QualType TyA = A.get()->getType();
14743  QualType TyB = B.get()->getType();
14744 
14745  if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
14746  return Diag(A.get()->getBeginLoc(),
14747  diag::err_typecheck_call_different_arg_types)
14748  << TyA << TyB;
14749 
14750  if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
14751  return true;
14752 
14753  TheCall->setArg(0, A.get());
14754  TheCall->setArg(1, B.get());
14755  return false;
14756 }
14757 
14759  bool CheckForFloatArgs) {
14760  if (checkArgCount(TheCall, 3))
14761  return true;
14762 
14763  Expr *Args[3];
14764  for (int I = 0; I < 3; ++I) {
14765  ExprResult Converted = UsualUnaryConversions(TheCall->getArg(I));
14766  if (Converted.isInvalid())
14767  return true;
14768  Args[I] = Converted.get();
14769  }
14770 
14771  if (CheckForFloatArgs) {
14772  int ArgOrdinal = 1;
14773  for (Expr *Arg : Args) {
14774  if (checkFPMathBuiltinElementType(*this, Arg->getBeginLoc(),
14775  Arg->getType(), ArgOrdinal++))
14776  return true;
14777  }
14778  } else {
14779  int ArgOrdinal = 1;
14780  for (Expr *Arg : Args) {
14781  if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
14782  ArgOrdinal++))
14783  return true;
14784  }
14785  }
14786 
14787  for (int I = 1; I < 3; ++I) {
14788  if (Args[0]->getType().getCanonicalType() !=
14789  Args[I]->getType().getCanonicalType()) {
14790  return Diag(Args[0]->getBeginLoc(),
14791  diag::err_typecheck_call_different_arg_types)
14792  << Args[0]->getType() << Args[I]->getType();
14793  }
14794 
14795  TheCall->setArg(I, Args[I]);
14796  }
14797 
14798  TheCall->setType(Args[0]->getType());
14799  return false;
14800 }
14801 
14802 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
14803  if (checkArgCount(TheCall, 1))
14804  return true;
14805 
14806  ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
14807  if (A.isInvalid())
14808  return true;
14809 
14810  TheCall->setArg(0, A.get());
14811  return false;
14812 }
14813 
14814 bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
14815  if (checkArgCount(TheCall, 1))
14816  return true;
14817 
14818  ExprResult Arg = TheCall->getArg(0);
14819  QualType TyArg = Arg.get()->getType();
14820 
14821  if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
14822  return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14823  << 1 << /*vector, integer or floating point ty*/ 0 << TyArg;
14824 
14825  TheCall->setType(TyArg);
14826  return false;
14827 }
14828 
14829 ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
14830  ExprResult CallResult) {
14831  if (checkArgCount(TheCall, 1))
14832  return ExprError();
14833 
14834  ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
14835  if (MatrixArg.isInvalid())
14836  return MatrixArg;
14837  Expr *Matrix = MatrixArg.get();
14838 
14839  auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
14840  if (!MType) {
14841  Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14842  << 1 << /* matrix ty*/ 1 << Matrix->getType();
14843  return ExprError();
14844  }
14845 
14846  // Create returned matrix type by swapping rows and columns of the argument
14847  // matrix type.
14848  QualType ResultType = Context.getConstantMatrixType(
14849  MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
14850 
14851  // Change the return type to the type of the returned matrix.
14852  TheCall->setType(ResultType);
14853 
14854  // Update call argument to use the possibly converted matrix argument.
14855  TheCall->setArg(0, Matrix);
14856  return CallResult;
14857 }
14858 
14859 // Get and verify the matrix dimensions.
14860 static std::optional<unsigned>
14862  SourceLocation ErrorPos;
14863  std::optional<llvm::APSInt> Value =
14864  Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
14865  if (!Value) {
14866  S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
14867  << Name;
14868  return {};
14869  }
14870  uint64_t Dim = Value->getZExtValue();
14872  S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
14874  return {};
14875  }
14876  return Dim;
14877 }
14878 
14879 ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
14880  ExprResult CallResult) {
14881  if (!getLangOpts().MatrixTypes) {
14882  Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
14883  return ExprError();
14884  }
14885 
14886  if (checkArgCount(TheCall, 4))
14887  return ExprError();
14888 
14889  unsigned PtrArgIdx = 0;
14890  Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
14891  Expr *RowsExpr = TheCall->getArg(1);
14892  Expr *ColumnsExpr = TheCall->getArg(2);
14893  Expr *StrideExpr = TheCall->getArg(3);
14894 
14895  bool ArgError = false;
14896 
14897  // Check pointer argument.
14898  {
14899  ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
14900  if (PtrConv.isInvalid())
14901  return PtrConv;
14902  PtrExpr = PtrConv.get();
14903  TheCall->setArg(0, PtrExpr);
14904  if (PtrExpr->isTypeDependent()) {
14905  TheCall->setType(Context.DependentTy);
14906  return TheCall;
14907  }
14908  }
14909 
14910  auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
14911  QualType ElementTy;
14912  if (!PtrTy) {
14913  Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14914  << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
14915  ArgError = true;
14916  } else {
14917  ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
14918 
14919  if (!ConstantMatrixType::isValidElementType(ElementTy)) {
14920  Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14921  << PtrArgIdx + 1 << /* pointer to element ty*/ 2
14922  << PtrExpr->getType();
14923  ArgError = true;
14924  }
14925  }
14926 
14927  // Apply default Lvalue conversions and convert the expression to size_t.
14928  auto ApplyArgumentConversions = [this](Expr *E) {
14929  ExprResult Conv = DefaultLvalueConversion(E);
14930  if (Conv.isInvalid())
14931  return Conv;
14932 
14933  return tryConvertExprToType(Conv.get(), Context.getSizeType());
14934  };
14935 
14936  // Apply conversion to row and column expressions.
14937  ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
14938  if (!RowsConv.isInvalid()) {
14939  RowsExpr = RowsConv.get();
14940  TheCall->setArg(1, RowsExpr);
14941  } else
14942  RowsExpr = nullptr;
14943 
14944  ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
14945  if (!ColumnsConv.isInvalid()) {
14946  ColumnsExpr = ColumnsConv.get();
14947  TheCall->setArg(2, ColumnsExpr);
14948  } else
14949  ColumnsExpr = nullptr;
14950 
14951  // If any part of the result matrix type is still pending, just use
14952  // Context.DependentTy, until all parts are resolved.
14953  if ((RowsExpr && RowsExpr->isTypeDependent()) ||
14954  (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
14955  TheCall->setType(Context.DependentTy);
14956  return CallResult;
14957  }
14958 
14959  // Check row and column dimensions.
14960  std::optional<unsigned> MaybeRows;
14961  if (RowsExpr)
14962  MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
14963 
14964  std::optional<unsigned> MaybeColumns;
14965  if (ColumnsExpr)
14966  MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
14967 
14968  // Check stride argument.
14969  ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
14970  if (StrideConv.isInvalid())
14971  return ExprError();
14972  StrideExpr = StrideConv.get();
14973  TheCall->setArg(3, StrideExpr);
14974 
14975  if (MaybeRows) {
14976  if (std::optional<llvm::APSInt> Value =
14977  StrideExpr->getIntegerConstantExpr(Context)) {
14978  uint64_t Stride = Value->getZExtValue();
14979  if (Stride < *MaybeRows) {
14980  Diag(StrideExpr->getBeginLoc(),
14981  diag::err_builtin_matrix_stride_too_small);
14982  ArgError = true;
14983  }
14984  }
14985  }
14986 
14987  if (ArgError || !MaybeRows || !MaybeColumns)
14988  return ExprError();
14989 
14990  TheCall->setType(
14991  Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
14992  return CallResult;
14993 }
14994 
14995 ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
14996  ExprResult CallResult) {
14997  if (checkArgCount(TheCall, 3))
14998  return ExprError();
14999 
15000  unsigned PtrArgIdx = 1;
15001  Expr *MatrixExpr = TheCall->getArg(0);
15002  Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15003  Expr *StrideExpr = TheCall->getArg(2);
15004 
15005  bool ArgError = false;
15006 
15007  {
15008  ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15009  if (MatrixConv.isInvalid())
15010  return MatrixConv;
15011  MatrixExpr = MatrixConv.get();
15012  TheCall->setArg(0, MatrixExpr);
15013  }
15014  if (MatrixExpr->isTypeDependent()) {
15015  TheCall->setType(Context.DependentTy);
15016  return TheCall;
15017  }
15018 
15019  auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15020  if (!MatrixTy) {
15021  Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
15022  << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
15023  ArgError = true;
15024  }
15025 
15026  {
15027  ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15028  if (PtrConv.isInvalid())
15029  return PtrConv;
15030  PtrExpr = PtrConv.get();
15031  TheCall->setArg(1, PtrExpr);
15032  if (PtrExpr->isTypeDependent()) {
15033  TheCall->setType(Context.DependentTy);
15034  return TheCall;
15035  }
15036  }
15037 
15038  // Check pointer argument.
15039  auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15040  if (!PtrTy) {
15041  Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
15042  << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
15043  ArgError = true;
15044  } else {
15045  QualType ElementTy = PtrTy->getPointeeType();
15046  if (ElementTy.isConstQualified()) {
15047  Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15048  ArgError = true;
15049  }
15050  ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15051  if (MatrixTy &&
15052  !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15053  Diag(PtrExpr->getBeginLoc(),
15054  diag::err_builtin_matrix_pointer_arg_mismatch)
15055  << ElementTy << MatrixTy->getElementType();
15056  ArgError = true;
15057  }
15058  }
15059 
15060  // Apply default Lvalue conversions and convert the stride expression to
15061  // size_t.
15062  {
15063  ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15064  if (StrideConv.isInvalid())
15065  return StrideConv;
15066 
15067  StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15068  if (StrideConv.isInvalid())
15069  return StrideConv;
15070  StrideExpr = StrideConv.get();
15071  TheCall->setArg(2, StrideExpr);
15072  }
15073 
15074  // Check stride argument.
15075  if (MatrixTy) {
15076  if (std::optional<llvm::APSInt> Value =
15077  StrideExpr->getIntegerConstantExpr(Context)) {
15078  uint64_t Stride = Value->getZExtValue();
15079  if (Stride < MatrixTy->getNumRows()) {
15080  Diag(StrideExpr->getBeginLoc(),
15081  diag::err_builtin_matrix_stride_too_small);
15082  ArgError = true;
15083  }
15084  }
15085  }
15086 
15087  if (ArgError)
15088  return ExprError();
15089 
15090  return CallResult;
15091 }
15092 
15094  const NamedDecl *Callee) {
15095  // This warning does not make sense in code that has no runtime behavior.
15096  if (isUnevaluatedContext())
15097  return;
15098 
15099  const NamedDecl *Caller = getCurFunctionOrMethodDecl();
15100 
15101  if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
15102  return;
15103 
15104  // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
15105  // all TCBs the callee is a part of.
15106  llvm::StringSet<> CalleeTCBs;
15107  for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
15108  CalleeTCBs.insert(A->getTCBName());
15109  for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
15110  CalleeTCBs.insert(A->getTCBName());
15111 
15112  // Go through the TCBs the caller is a part of and emit warnings if Caller
15113  // is in a TCB that the Callee is not.
15114  for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
15115  StringRef CallerTCB = A->getTCBName();
15116  if (CalleeTCBs.count(CallerTCB) == 0) {
15117  this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
15118  << Callee << CallerTCB;
15119  }
15120  }
15121 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3346
NodeId Parent
Definition: ASTDiff.cpp:191
SyntaxTree::Impl & Tree
Definition: ASTDiff.cpp:192
int Depth
Definition: ASTDiff.cpp:190
ASTImporterLookupTable & LT
StringRef P
Provides definitions for the various language-specific address spaces.
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
Defines the Diagnostic-related interfaces.
const Decl * D
enum clang::sema::@1659::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition: XCore.cpp:632
llvm::APSInt APSInt
Definition: Compiler.cpp:22
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1171
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Offset
Definition: Format.cpp:3003
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
LangStandard::Kind Std
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
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.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
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 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Pseudo-evaluate the given integer expression, estimating the range of values it might take.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
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,...
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
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...
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers=false)
static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth)
static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool)
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.
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static QualType GetExprType(const Expr *E)
static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, SourceLocation CC)
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool isKnownToHaveUnsignedValue(Expr *E)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static llvm::APSInt getSYCLAllocaDefaultSize(const ASTContext &Ctx, const VarDecl *VD)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static bool checkIntelFPGARegArgument(Sema &S, QualType ArgType, SourceLocation &Loc)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool IsSameCharType(QualType T1, QualType T2)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
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).
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static int classifyConstantValue(Expr *Constant)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static bool requiresParensToAddCast(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
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 ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool IsEnumConstOrFromMacro(Sema &S, Expr *E)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static const Expr * getStrlenExprArg(const Expr *E)
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.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
MathCheck
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
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 std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static bool HasEnumType(Expr *E)
static bool checkFPMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
SourceLocation End
std::string Label
__DEVICE__ int min(int __a, int __b)
__DEVICE__ int max(int __a, int __b)
__device__ int
__device__ __2f16 float __ockl_bool s
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isVector() const
Definition: APValue.h:407
unsigned getStructNumFields() const
Definition: APValue.h:542
APFloat & getFloat()
Definition: APValue.h:437
bool isComplexInt() const
Definition: APValue.h:404
ValueKind getKind() const
Definition: APValue.h:395
bool isFloat() const
Definition: APValue.h:402
APSInt & getComplexIntReal()
Definition: APValue.h:453
bool isComplexFloat() const
Definition: APValue.h:405
unsigned getVectorLength() const
Definition: APValue.h:505
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isLValue() const
Definition: APValue.h:406
APValue & getStructField(unsigned i)
Definition: APValue.h:551
APFloat & getComplexFloatImag()
Definition: APValue.h:477
bool isInt() const
Definition: APValue.h:401
APSInt & getInt()
Definition: APValue.h:423
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
bool isAddrLabelDiff() const
Definition: APValue.h:412
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getRecordType(const RecordDecl *Decl) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2633
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2649
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1147
IdentifierTable & Idents
Definition: ASTContext.h:660
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2830
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
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 ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1120
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1121
CanQualType IntTy
Definition: ASTContext.h:1128
TypeInfoChars getTypeInfoInChars(const Type *T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2680
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2399
CanQualType BuiltinFnTy
Definition: ASTContext.h:1149
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
QualType getExceptionObjectType(QualType T) const
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1129
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
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:1620
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
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 TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:780
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
@ GE_None
No error.
Definition: ASTContext.h:2301
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2403
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:218
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4217
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4395
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4401
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4407
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition: Expr.h:6957
Expr * getBase()
Get base of the array section.
Definition: Expr.h:7023
Expr * getLowerBound()
Get lower bound of array section.
Definition: Expr.h:7027
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2726
SourceLocation getRBracketLoc() const
Definition: Expr.h:2774
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2755
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3576
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3590
QualType getElementType() const
Definition: Type.h:3588
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6660
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:6801
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6767
Attr - This represents one attribute.
Definition: Attr.h:46
const char * getSpelling() const
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6385
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:6400
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3912
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:4044
SourceLocation getExprLoc() const
Definition: Expr.h:3952
bool isEqualityOp() const
Definition: Expr.h:4009
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3997
Opcode getOpcode() const
Definition: Expr.h:3956
Expr * getRHS() const
Definition: Expr.h:3963
Expr * getLHS() const
Definition: Expr.h:3961
A fixed int type of a specified bitwidth.
Definition: Type.h:7643
Pointer to a block type.
Definition: Type.h:3407
This class is used for builtin types like 'int'.
Definition: Type.h:3029
bool isInteger() const
Definition: Type.h:3094
bool isFloatingPoint() const
Definition: Type.h:3106
bool isSignedInteger() const
Definition: Type.h:3098
bool isUnsignedInteger() const
Definition: Type.h:3102
Kind getKind() const
Definition: Type.h:3081
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition: Builtins.h:268
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
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:222
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3843
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1628
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1686
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getExprLoc() const LLVM_READONLY
Definition: ExprCXX.h:151
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:111
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4953
ArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:4993
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1230
bool isDynamicClass() const
Definition: DeclCXX.h:586
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2882
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3063
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3086
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1693
arg_iterator arg_begin()
Definition: Expr.h:3126
arg_iterator arg_end()
Definition: Expr.h:3129
bool isCallToStdMove() const
Definition: Expr.cpp:3573
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1702
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3060
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3073
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition: Expr.h:3163
arg_range arguments()
Definition: Expr.h:3121
SourceLocation getRParenLoc() const
Definition: Expr.h:3197
Expr * getCallee()
Definition: Expr.h:3032
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3052
Decl * getCalleeDecl()
Definition: Expr.h:3046
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition: Expr.cpp:1639
void setCallee(Expr *F)
Definition: Expr.h:3034
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3550
path_iterator path_begin()
Definition: Expr.h:3620
CastKind getCastKind() const
Definition: Expr.h:3594
Expr * getSubExpr()
Definition: Expr.h:3600
path_iterator path_end()
Definition: Expr.h:3621
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition: Type.h:3144
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4164
Declaration of a C++20 concept.
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4255
Expr * getLHS() const
Definition: Expr.h:4289
Expr * getRHS() const
Definition: Expr.h:4290
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3614
QualType desugar() const
Definition: Type.h:3715
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3670
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4229
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition: Type.h:4263
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4258
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4575
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:5070
child_range children()
Definition: ExprCXX.h:5169
Expr * getOperand() const
Definition: ExprCXX.h:5139
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
ValueDecl * getDecl()
Definition: Expr.h:1333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
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:488
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1352
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1457
SourceLocation getLocation() const
Definition: Expr.h:1341
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:425
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:537
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1178
bool isInvalidDecl() const
Definition: DeclBase.h:595
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
SourceLocation getLocation() const
Definition: DeclBase.h:446
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool hasAttr() const
Definition: DeclBase.h:584
T * getAttr() const
Definition: DeclBase.h:580
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
The name of a declaration.
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1974
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:761
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1083
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1094
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:922
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3275
Represents an enum.
Definition: Decl.h:3845
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4042
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4064
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4005
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4021
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4031
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6001
This represents one expression.
Definition: Expr.h:110
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,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:671
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition: Expr.h:668
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3127
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3122
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3110
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
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...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3118
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4159
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
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...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3114
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:3619
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3102
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:797
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:806
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:809
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:799
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...
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:3998
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isFlexibleArrayMemberLike(ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition: Expr.cpp:206
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
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...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition: Expr.cpp:226
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:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition: Type.h:4123
Represents a member of a struct/union/class.
Definition: Decl.h:3031
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3122
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4582
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3248
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3135
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:72
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:135
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:124
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:98
llvm::APFloat getValue() const
Definition: Expr.h:1652
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2786
Represents a function declaration or definition.
Definition: Decl.h:1933
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4389
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3703
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3622
param_iterator param_end()
Definition: Decl.h:2660
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3721
QualType getReturnType() const
Definition: Decl.h:2718
param_iterator param_begin()
Definition: Decl.h:2659
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3081
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4168
bool isStatic() const
Definition: Decl.h:2802
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3983
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2647
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3969
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3682
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2670
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5012
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5272
unsigned getNumParams() const
Definition: Type.h:5265
QualType getParamType(unsigned i) const
Definition: Type.h:5267
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5389
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5276
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5384
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4318
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4610
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4606
QualType getReturnType() const
Definition: Type.h:4640
@ SME_PStateSMEnabledMask
Definition: Type.h:4584
@ SME_PStateSMCompatibleMask
Definition: Type.h:4585
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3727
Describes an C or C++ initializer list.
Definition: Expr.h:5070
ArrayRef< Expr * > inits()
Definition: Expr.h:5110
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:480
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1060
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:499
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1107
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:850
Represents the results of name lookup.
Definition: Lookup.h:46
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4214
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3239
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3322
Expr * getBase() const
Definition: Expr.h:3316
bool isArrow() const
Definition: Expr.h:3423
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1916
Represent a C++ namespace.
Definition: Decl.h:548
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1569
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1583
SourceLocation getSemiLoc() const
Definition: Stmt.h:1580
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
QualType getType() const
Definition: DeclObjC.h:803
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:826
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:617
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:706
bool isImplicitProperty() const
Definition: ExprObjC.h:703
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:254
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2187
Represents a parameter to a function.
Definition: Decl.h:1723
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3197
QualType getPointeeType() const
Definition: Type.h:3207
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6528
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4955
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7844
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2751
PrimitiveDefaultInitializeKind
Definition: Type.h:1463
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1221
bool isTrivialType(const ASTContext &Context) const
Return true if this is a trivial type per (C++0x [basic.types]p9)
Definition: Type.cpp:2653
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7760
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7886
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1101
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7800
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition: Type.cpp:2604
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition: Type.h:7812
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7854
void removeLocalVolatile()
Definition: Type.h:7876
void removeLocalConst()
Definition: Type.h:7868
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7833
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7881
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1448
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
bool hasUnaligned() const
Definition: Type.h:498
Represents a struct/union/class.
Definition: Decl.h:4146
field_range fields() const
Definition: Decl.h:4352
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5975
RecordDecl * getDecl() const
Definition: Type.h:5985
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition: Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition: Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition: Scope.h:128
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition: SemaARM.h:35
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition: SemaARM.h:36
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:64
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
bool isSignedCharBool(QualType Ty)
Definition: SemaObjC.cpp:2308
void adornBoolConversionDiagWithTernaryFixit(Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
Definition: SemaObjC.cpp:2313
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:601
@ KernelCallVariadicFunction
Definition: SemaSYCL.h:340
static bool isSyclType(QualType Ty, SYCLTypeAttr::SYCLType TypeName)
Check whether Ty corresponds to a SYCL type of name TypeName.
Definition: SemaSYCL.cpp:76
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
SemaObjC & ObjC()
Definition: Sema.h:1169
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9036
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9044
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9081
VariadicCallType
Definition: Sema.h:2353
@ VariadicDoesNotApply
Definition: Sema.h:2358
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
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 isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
bool FormatStringHasSArg(const StringLiteral *FExpr)
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, bool IsVariadic, FormatStringInfo *FSI)
Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo parameter with the Format...
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
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...
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1609
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:852
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14057
ASTContext & Context
Definition: Sema.h:962
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:820
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15633
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:763
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:729
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:868
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
AtomicArgumentOrder
Definition: Sema.h:2295
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
bool IsLayoutCompatible(QualType T1, QualType T2) const
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:8988
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6474
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
Definition: Sema.h:960
const LangOptions & getLangOpts() const
Definition: Sema.h:553
static const uint64_t MaximumAlignment
Definition: Sema.h:891
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall)
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:997
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3360
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition: Sema.h:2273
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2279
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
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...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:708
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res)
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1102
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
@ VAK_Invalid
Definition: Sema.h:7580
@ VAK_Valid
Definition: Sema.h:7576
@ VAK_ValidInCXX11
Definition: Sema.h:7577
@ VAK_MSVCUndefined
Definition: Sema.h:7579
@ VAK_Undefined
Definition: Sema.h:7578
FormatArgumentPassingKind
Definition: Sema.h:2197
@ FAPK_Fixed
Definition: Sema.h:2198
@ FAPK_Variadic
Definition: Sema.h:2199
@ FAPK_VAList
Definition: Sema.h:2200
SourceManager & getSourceManager() const
Definition: Sema.h:558
bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20783
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13535
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, bool CheckForFloatArgs=true)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
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 DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20067
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
bool isConstantEvaluatedContext() const
Definition: Sema.h:2189
ASTContext & getASTContext() const
Definition: Sema.h:560
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8999
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:965
DiagnosticsEngine & Diags
Definition: Sema.h:964
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9666
FormatStringType
Definition: Sema.h:2226
@ FST_NSString
Definition: Sema.h:2229
@ FST_Syslog
Definition: Sema.h:2236
@ FST_Printf
Definition: Sema.h:2228
@ FST_FreeBSDKPrintf
Definition: Sema.h:2233
@ FST_Scanf
Definition: Sema.h:2227
@ FST_OSLog
Definition: Sema.h:2235
@ FST_OSTrace
Definition: Sema.h:2234
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:601
bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4507
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition: Stmt.cpp:287
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1959
bool isUTF8() const
Definition: Expr.h:1904
bool isWide() const
Definition: Expr.h:1903
bool isPascal() const
Definition: Expr.h:1908
unsigned getLength() const
Definition: Expr.h:1895
StringLiteralKind getKind() const
Definition: Expr.h:1898
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:1384
bool isUTF32() const
Definition: Expr.h:1906
unsigned getByteLength() const
Definition: Expr.h:1894
StringRef getString() const
Definition: Expr.h:1855
bool isUTF16() const
Definition: Expr.h:1905
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:1960
bool isOrdinary() const
Definition: Expr.h:1902
unsigned getCharByteWidth() const
Definition: Expr.h:1896
bool isUnion() const
Definition: Decl.h:3768
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual bool validatePointerAuthKey(const llvm::APSInt &value) const
Determine whether the given pointer-authentication key is valid.
Definition: TargetInfo.cpp:973
virtual bool supportsCpuSupports() const
Definition: TargetInfo.h:1513
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1533
virtual bool supportsCpuInit() const
Definition: TargetInfo.h:1515
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:992
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
IntType getSizeType() const
Definition: TargetInfo.h:371
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1519
virtual bool supportsCpuIs() const
Definition: TargetInfo.h:1514
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
Definition: TargetInfo.h:1672
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1487
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm....
Definition: TargetInfo.h:1721
A template argument list.
Definition: DeclTemplate.h:244
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:265
Represents a template argument.
Definition: TemplateBase.h:61
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
const Type * getTypeForDecl() const
Definition: Decl.h:3392
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5707
A container of type source information.
Definition: Type.h:7731
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7742
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBlockPointerType() const
Definition: Type.h:8027
bool isVoidType() const
Definition: Type.h:8347
bool isBooleanType() const
Definition: Type.h:8475
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8525
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isFloat16Type() const
Definition: Type.h:8356
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2217
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8505
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:2021
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2352
bool isArrayType() const
Definition: Type.h:8085
bool isCharType() const
Definition: Type.cpp:2089
bool isFunctionPointerType() const
Definition: Type.h:8053
bool isPointerType() const
Definition: Type.h:8013
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8387
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8635
bool isReferenceType() const
Definition: Type.h:8031
bool isEnumeralType() const
Definition: Type.h:8117
bool isScalarType() const
Definition: Type.h:8446
bool isVariableArrayType() const
Definition: Type.h:8097
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2510
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8462
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2236
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2548
bool isImageType() const
Definition: Type.h:8248
bool isPipeType() const
Definition: Type.h:8265
bool isBitIntType() const
Definition: Type.h:8269
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8316
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8109
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2701
bool isAnyComplexType() const
Definition: Type.h:8121
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8400
bool isHalfType() const
Definition: Type.h:8351
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2186
QualType getCanonicalTypeInternal() const
Definition: Type.h:2984
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2467
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8518
bool isMemberPointerType() const
Definition: Type.h:8067
bool isAtomicType() const
Definition: Type.h:8168
bool isFunctionProtoType() const
Definition: Type.h:2528
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2973
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2719
bool isObjCObjectType() const
Definition: Type.h:8159
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8621
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8481
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2439
bool isEventT() const
Definition: Type.h:8232
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:8009
bool isObjCObjectPointerType() const
Definition: Type.h:8155
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2258
bool isStructureOrClassType() const
Definition: Type.cpp:657
bool isVectorType() const
Definition: Type.h:8125
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isFloatingType() const
Definition: Type.cpp:2249
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:2196
bool isAnyPointerType() const
Definition: Type.h:8021
TypeClass getTypeClass() const
Definition: Type.h:2334
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2360
bool isSamplerT() const
Definition: Type.h:8228
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8568
bool isNullPtrType() const
Definition: Type.h:8380
bool isRecordType() const
Definition: Type.h:8113
bool isObjCRetainableType() const
Definition: Type.cpp:4961
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4699
bool isUnionType() const
Definition: Type.cpp:671
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2479
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition: Type.cpp:2536
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3410
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2630
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2240
Opcode getOpcode() const
Definition: Expr.h:2280
Expr * getSubExpr() const
Definition: Expr.h:2285
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2362
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3324
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:668
QualType getType() const
Definition: Decl.h:679
Represents a variable declaration or definition.
Definition: Decl.h:880
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2543
Represents a GCC generic vector type.
Definition: Type.h:4031
unsigned getNumElements() const
Definition: Type.h:4046
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2589
MatchKind
How well a given conversion specifier matches its argument.
Definition: FormatString.h:271
@ NoMatch
The conversion specifier and the argument types are incompatible.
Definition: FormatString.h:274
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
Definition: FormatString.h:286
@ Match
The conversion specifier and the argument type are compatible.
Definition: FormatString.h:277
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
Definition: FormatString.h:288
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition: larchintrin.h:181
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.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
ComparisonResult
Indicates the result of a tentative comparison.
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:221
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
llvm::APFloat APFloat
Definition: Floating.h:23
bool GT(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1111
llvm::APInt APInt
Definition: Integral.h:29
bool Call(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition: Interp.h:2578
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1089
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1103
bool InRange(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1130
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1665
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2051
bool EQ(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1058
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1118
std::string toString(const til::SExpr *E)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
std::shared_ptr< MatchComputation< T > > Generator
Definition: RewriteRule.h:65
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:66
@ CPlusPlus
Definition: LangStandard.h:56
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ NonNull
Values of this type can never be null.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition: IgnoreExpr.h:137
BinaryOperatorKind
@ SC_Register
Definition: Specifiers.h:257
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition: IgnoreExpr.h:125
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition: SemaARM.cpp:548
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition: IgnoreExpr.h:34
CastKind
CastKind - The kind of operation required for a conversion.
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
for(const auto &A :T->param_types())
const FunctionProtoType * T
StringLiteralKind
Definition: Expr.h:1749
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition: JsonSupport.h:21
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_Win64
Definition: Specifiers.h:285
@ CC_C
Definition: Specifiers.h:279
@ CC_X86_64SysV
Definition: Specifiers.h:286
@ Generic
not a target-specific vector type
U cast(CodeGen::Address addr)
Definition: Address.h:325
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:124
unsigned long uint64_t
long int64_t
int int32_t
float __ovld __cnfn distance(float, float)
Returns the distance between p0 and p1.
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
Extra information about a function prototype.
Definition: Type.h:5097
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned AnonymousTagLocations
When printing an anonymous tag name, also print the location of that entity (e.g.,...
unsigned Indentation
The number of spaces to use to indent each line.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12718
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12835
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition: Sema.h:12861
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition: Sema.h:12851
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12816
FormatArgumentPassingKind ArgPassingKind
Definition: Sema.h:2208
#define log2(__x)
Definition: tgmath.h:970