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"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed bit-precise integer args larger than 128 bits to mul
329   // function until we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_bit_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class ScanfDiagnosticFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   // Accepts the argument index (relative to the first destination index) of the
414   // argument whose size we want.
415   using ComputeSizeFunction =
416       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
417 
418   // Accepts the argument index (relative to the first destination index), the
419   // destination size, and the source size).
420   using DiagnoseFunction =
421       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
422 
423   ComputeSizeFunction ComputeSizeArgument;
424   DiagnoseFunction Diagnose;
425 
426 public:
427   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
428                                DiagnoseFunction Diagnose)
429       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
430 
431   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
432                             const char *StartSpecifier,
433                             unsigned specifierLen) override {
434     if (!FS.consumesDataArgument())
435       return true;
436 
437     unsigned NulByte = 0;
438     switch ((FS.getConversionSpecifier().getKind())) {
439     default:
440       return true;
441     case analyze_format_string::ConversionSpecifier::sArg:
442     case analyze_format_string::ConversionSpecifier::ScanListArg:
443       NulByte = 1;
444       break;
445     case analyze_format_string::ConversionSpecifier::cArg:
446       break;
447     }
448 
449     auto OptionalFW = FS.getFieldWidth();
450     if (OptionalFW.getHowSpecified() !=
451         analyze_format_string::OptionalAmount::HowSpecified::Constant)
452       return true;
453 
454     unsigned SourceSize = OptionalFW.getConstantAmount() + NulByte;
455 
456     auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
457     if (!DestSizeAPS)
458       return true;
459 
460     unsigned DestSize = DestSizeAPS->getZExtValue();
461 
462     if (DestSize < SourceSize)
463       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
464 
465     return true;
466   }
467 };
468 
469 class EstimateSizeFormatHandler
470     : public analyze_format_string::FormatStringHandler {
471   size_t Size;
472 
473 public:
474   EstimateSizeFormatHandler(StringRef Format)
475       : Size(std::min(Format.find(0), Format.size()) +
476              1 /* null byte always written by sprintf */) {}
477 
478   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
479                              const char *, unsigned SpecifierLen) override {
480 
481     const size_t FieldWidth = computeFieldWidth(FS);
482     const size_t Precision = computePrecision(FS);
483 
484     // The actual format.
485     switch (FS.getConversionSpecifier().getKind()) {
486     // Just a char.
487     case analyze_format_string::ConversionSpecifier::cArg:
488     case analyze_format_string::ConversionSpecifier::CArg:
489       Size += std::max(FieldWidth, (size_t)1);
490       break;
491     // Just an integer.
492     case analyze_format_string::ConversionSpecifier::dArg:
493     case analyze_format_string::ConversionSpecifier::DArg:
494     case analyze_format_string::ConversionSpecifier::iArg:
495     case analyze_format_string::ConversionSpecifier::oArg:
496     case analyze_format_string::ConversionSpecifier::OArg:
497     case analyze_format_string::ConversionSpecifier::uArg:
498     case analyze_format_string::ConversionSpecifier::UArg:
499     case analyze_format_string::ConversionSpecifier::xArg:
500     case analyze_format_string::ConversionSpecifier::XArg:
501       Size += std::max(FieldWidth, Precision);
502       break;
503 
504     // %g style conversion switches between %f or %e style dynamically.
505     // %f always takes less space, so default to it.
506     case analyze_format_string::ConversionSpecifier::gArg:
507     case analyze_format_string::ConversionSpecifier::GArg:
508 
509     // Floating point number in the form '[+]ddd.ddd'.
510     case analyze_format_string::ConversionSpecifier::fArg:
511     case analyze_format_string::ConversionSpecifier::FArg:
512       Size += std::max(FieldWidth, 1 /* integer part */ +
513                                        (Precision ? 1 + Precision
514                                                   : 0) /* period + decimal */);
515       break;
516 
517     // Floating point number in the form '[-]d.ddde[+-]dd'.
518     case analyze_format_string::ConversionSpecifier::eArg:
519     case analyze_format_string::ConversionSpecifier::EArg:
520       Size +=
521           std::max(FieldWidth,
522                    1 /* integer part */ +
523                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
524                        1 /* e or E letter */ + 2 /* exponent */);
525       break;
526 
527     // Floating point number in the form '[-]0xh.hhhhp±dd'.
528     case analyze_format_string::ConversionSpecifier::aArg:
529     case analyze_format_string::ConversionSpecifier::AArg:
530       Size +=
531           std::max(FieldWidth,
532                    2 /* 0x */ + 1 /* integer part */ +
533                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
534                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
535       break;
536 
537     // Just a string.
538     case analyze_format_string::ConversionSpecifier::sArg:
539     case analyze_format_string::ConversionSpecifier::SArg:
540       Size += FieldWidth;
541       break;
542 
543     // Just a pointer in the form '0xddd'.
544     case analyze_format_string::ConversionSpecifier::pArg:
545       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
546       break;
547 
548     // A plain percent.
549     case analyze_format_string::ConversionSpecifier::PercentArg:
550       Size += 1;
551       break;
552 
553     default:
554       break;
555     }
556 
557     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
558 
559     if (FS.hasAlternativeForm()) {
560       switch (FS.getConversionSpecifier().getKind()) {
561       default:
562         break;
563       // Force a leading '0'.
564       case analyze_format_string::ConversionSpecifier::oArg:
565         Size += 1;
566         break;
567       // Force a leading '0x'.
568       case analyze_format_string::ConversionSpecifier::xArg:
569       case analyze_format_string::ConversionSpecifier::XArg:
570         Size += 2;
571         break;
572       // Force a period '.' before decimal, even if precision is 0.
573       case analyze_format_string::ConversionSpecifier::aArg:
574       case analyze_format_string::ConversionSpecifier::AArg:
575       case analyze_format_string::ConversionSpecifier::eArg:
576       case analyze_format_string::ConversionSpecifier::EArg:
577       case analyze_format_string::ConversionSpecifier::fArg:
578       case analyze_format_string::ConversionSpecifier::FArg:
579       case analyze_format_string::ConversionSpecifier::gArg:
580       case analyze_format_string::ConversionSpecifier::GArg:
581         Size += (Precision ? 0 : 1);
582         break;
583       }
584     }
585     assert(SpecifierLen <= Size && "no underflow");
586     Size -= SpecifierLen;
587     return true;
588   }
589 
590   size_t getSizeLowerBound() const { return Size; }
591 
592 private:
593   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
594     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
595     size_t FieldWidth = 0;
596     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
597       FieldWidth = FW.getConstantAmount();
598     return FieldWidth;
599   }
600 
601   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
602     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
603     size_t Precision = 0;
604 
605     // See man 3 printf for default precision value based on the specifier.
606     switch (FW.getHowSpecified()) {
607     case analyze_format_string::OptionalAmount::NotSpecified:
608       switch (FS.getConversionSpecifier().getKind()) {
609       default:
610         break;
611       case analyze_format_string::ConversionSpecifier::dArg: // %d
612       case analyze_format_string::ConversionSpecifier::DArg: // %D
613       case analyze_format_string::ConversionSpecifier::iArg: // %i
614         Precision = 1;
615         break;
616       case analyze_format_string::ConversionSpecifier::oArg: // %d
617       case analyze_format_string::ConversionSpecifier::OArg: // %D
618       case analyze_format_string::ConversionSpecifier::uArg: // %d
619       case analyze_format_string::ConversionSpecifier::UArg: // %D
620       case analyze_format_string::ConversionSpecifier::xArg: // %d
621       case analyze_format_string::ConversionSpecifier::XArg: // %D
622         Precision = 1;
623         break;
624       case analyze_format_string::ConversionSpecifier::fArg: // %f
625       case analyze_format_string::ConversionSpecifier::FArg: // %F
626       case analyze_format_string::ConversionSpecifier::eArg: // %e
627       case analyze_format_string::ConversionSpecifier::EArg: // %E
628       case analyze_format_string::ConversionSpecifier::gArg: // %g
629       case analyze_format_string::ConversionSpecifier::GArg: // %G
630         Precision = 6;
631         break;
632       case analyze_format_string::ConversionSpecifier::pArg: // %d
633         Precision = 1;
634         break;
635       }
636       break;
637     case analyze_format_string::OptionalAmount::Constant:
638       Precision = FW.getConstantAmount();
639       break;
640     default:
641       break;
642     }
643     return Precision;
644   }
645 };
646 
647 } // namespace
648 
649 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
650                                                CallExpr *TheCall) {
651   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
652       isConstantEvaluated())
653     return;
654 
655   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
656   if (!BuiltinID)
657     return;
658 
659   const TargetInfo &TI = getASTContext().getTargetInfo();
660   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
661 
662   auto ComputeExplicitObjectSizeArgument =
663       [&](unsigned Index) -> Optional<llvm::APSInt> {
664     Expr::EvalResult Result;
665     Expr *SizeArg = TheCall->getArg(Index);
666     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
667       return llvm::None;
668     return Result.Val.getInt();
669   };
670 
671   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
672     // If the parameter has a pass_object_size attribute, then we should use its
673     // (potentially) more strict checking mode. Otherwise, conservatively assume
674     // type 0.
675     int BOSType = 0;
676     // This check can fail for variadic functions.
677     if (Index < FD->getNumParams()) {
678       if (const auto *POS =
679               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
680         BOSType = POS->getType();
681     }
682 
683     const Expr *ObjArg = TheCall->getArg(Index);
684     uint64_t Result;
685     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
686       return llvm::None;
687 
688     // Get the object size in the target's size_t width.
689     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
690   };
691 
692   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
693     Expr *ObjArg = TheCall->getArg(Index);
694     uint64_t Result;
695     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
696       return llvm::None;
697     // Add 1 for null byte.
698     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
699   };
700 
701   Optional<llvm::APSInt> SourceSize;
702   Optional<llvm::APSInt> DestinationSize;
703   unsigned DiagID = 0;
704   bool IsChkVariant = false;
705 
706   auto GetFunctionName = [&]() {
707     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
708     // Skim off the details of whichever builtin was called to produce a better
709     // diagnostic, as it's unlikely that the user wrote the __builtin
710     // explicitly.
711     if (IsChkVariant) {
712       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
713       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
714     } else if (FunctionName.startswith("__builtin_")) {
715       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
716     }
717     return FunctionName;
718   };
719 
720   switch (BuiltinID) {
721   default:
722     return;
723   case Builtin::BI__builtin_strcpy:
724   case Builtin::BIstrcpy: {
725     DiagID = diag::warn_fortify_strlen_overflow;
726     SourceSize = ComputeStrLenArgument(1);
727     DestinationSize = ComputeSizeArgument(0);
728     break;
729   }
730 
731   case Builtin::BI__builtin___strcpy_chk: {
732     DiagID = diag::warn_fortify_strlen_overflow;
733     SourceSize = ComputeStrLenArgument(1);
734     DestinationSize = ComputeExplicitObjectSizeArgument(2);
735     IsChkVariant = true;
736     break;
737   }
738 
739   case Builtin::BIscanf:
740   case Builtin::BIfscanf:
741   case Builtin::BIsscanf: {
742     unsigned FormatIndex = 1;
743     unsigned DataIndex = 2;
744     if (BuiltinID == Builtin::BIscanf) {
745       FormatIndex = 0;
746       DataIndex = 1;
747     }
748 
749     const auto *FormatExpr =
750         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
751 
752     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
753     if (!Format)
754       return;
755 
756     if (!Format->isAscii() && !Format->isUTF8())
757       return;
758 
759     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
760                         unsigned SourceSize) {
761       DiagID = diag::warn_fortify_scanf_overflow;
762       unsigned Index = ArgIndex + DataIndex;
763       StringRef FunctionName = GetFunctionName();
764       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
765                           PDiag(DiagID) << FunctionName << (Index + 1)
766                                         << DestSize << SourceSize);
767     };
768 
769     StringRef FormatStrRef = Format->getString();
770     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
771       return ComputeSizeArgument(Index + DataIndex);
772     };
773     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
774     const char *FormatBytes = FormatStrRef.data();
775     const ConstantArrayType *T =
776         Context.getAsConstantArrayType(Format->getType());
777     assert(T && "String literal not of constant array type!");
778     size_t TypeSize = T->getSize().getZExtValue();
779 
780     // In case there's a null byte somewhere.
781     size_t StrLen =
782         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
783 
784     analyze_format_string::ParseScanfString(H, FormatBytes,
785                                             FormatBytes + StrLen, getLangOpts(),
786                                             Context.getTargetInfo());
787 
788     // Unlike the other cases, in this one we have already issued the diagnostic
789     // here, so no need to continue (because unlike the other cases, here the
790     // diagnostic refers to the argument number).
791     return;
792   }
793 
794   case Builtin::BIsprintf:
795   case Builtin::BI__builtin___sprintf_chk: {
796     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
797     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
798 
799     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
800 
801       if (!Format->isAscii() && !Format->isUTF8())
802         return;
803 
804       StringRef FormatStrRef = Format->getString();
805       EstimateSizeFormatHandler H(FormatStrRef);
806       const char *FormatBytes = FormatStrRef.data();
807       const ConstantArrayType *T =
808           Context.getAsConstantArrayType(Format->getType());
809       assert(T && "String literal not of constant array type!");
810       size_t TypeSize = T->getSize().getZExtValue();
811 
812       // In case there's a null byte somewhere.
813       size_t StrLen =
814           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
815       if (!analyze_format_string::ParsePrintfString(
816               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
817               Context.getTargetInfo(), false)) {
818         DiagID = diag::warn_fortify_source_format_overflow;
819         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
820                          .extOrTrunc(SizeTypeWidth);
821         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
822           DestinationSize = ComputeExplicitObjectSizeArgument(2);
823           IsChkVariant = true;
824         } else {
825           DestinationSize = ComputeSizeArgument(0);
826         }
827         break;
828       }
829     }
830     return;
831   }
832   case Builtin::BI__builtin___memcpy_chk:
833   case Builtin::BI__builtin___memmove_chk:
834   case Builtin::BI__builtin___memset_chk:
835   case Builtin::BI__builtin___strlcat_chk:
836   case Builtin::BI__builtin___strlcpy_chk:
837   case Builtin::BI__builtin___strncat_chk:
838   case Builtin::BI__builtin___strncpy_chk:
839   case Builtin::BI__builtin___stpncpy_chk:
840   case Builtin::BI__builtin___memccpy_chk:
841   case Builtin::BI__builtin___mempcpy_chk: {
842     DiagID = diag::warn_builtin_chk_overflow;
843     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
844     DestinationSize =
845         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
846     IsChkVariant = true;
847     break;
848   }
849 
850   case Builtin::BI__builtin___snprintf_chk:
851   case Builtin::BI__builtin___vsnprintf_chk: {
852     DiagID = diag::warn_builtin_chk_overflow;
853     SourceSize = ComputeExplicitObjectSizeArgument(1);
854     DestinationSize = ComputeExplicitObjectSizeArgument(3);
855     IsChkVariant = true;
856     break;
857   }
858 
859   case Builtin::BIstrncat:
860   case Builtin::BI__builtin_strncat:
861   case Builtin::BIstrncpy:
862   case Builtin::BI__builtin_strncpy:
863   case Builtin::BIstpncpy:
864   case Builtin::BI__builtin_stpncpy: {
865     // Whether these functions overflow depends on the runtime strlen of the
866     // string, not just the buffer size, so emitting the "always overflow"
867     // diagnostic isn't quite right. We should still diagnose passing a buffer
868     // size larger than the destination buffer though; this is a runtime abort
869     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
870     DiagID = diag::warn_fortify_source_size_mismatch;
871     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
872     DestinationSize = ComputeSizeArgument(0);
873     break;
874   }
875 
876   case Builtin::BImemcpy:
877   case Builtin::BI__builtin_memcpy:
878   case Builtin::BImemmove:
879   case Builtin::BI__builtin_memmove:
880   case Builtin::BImemset:
881   case Builtin::BI__builtin_memset:
882   case Builtin::BImempcpy:
883   case Builtin::BI__builtin_mempcpy: {
884     DiagID = diag::warn_fortify_source_overflow;
885     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
886     DestinationSize = ComputeSizeArgument(0);
887     break;
888   }
889   case Builtin::BIsnprintf:
890   case Builtin::BI__builtin_snprintf:
891   case Builtin::BIvsnprintf:
892   case Builtin::BI__builtin_vsnprintf: {
893     DiagID = diag::warn_fortify_source_size_mismatch;
894     SourceSize = ComputeExplicitObjectSizeArgument(1);
895     DestinationSize = ComputeSizeArgument(0);
896     break;
897   }
898   }
899 
900   if (!SourceSize || !DestinationSize ||
901       SourceSize.getValue().ule(DestinationSize.getValue()))
902     return;
903 
904   StringRef FunctionName = GetFunctionName();
905 
906   SmallString<16> DestinationStr;
907   SmallString<16> SourceStr;
908   DestinationSize->toString(DestinationStr, /*Radix=*/10);
909   SourceSize->toString(SourceStr, /*Radix=*/10);
910   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
911                       PDiag(DiagID)
912                           << FunctionName << DestinationStr << SourceStr);
913 }
914 
915 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
916                                      Scope::ScopeFlags NeededScopeFlags,
917                                      unsigned DiagID) {
918   // Scopes aren't available during instantiation. Fortunately, builtin
919   // functions cannot be template args so they cannot be formed through template
920   // instantiation. Therefore checking once during the parse is sufficient.
921   if (SemaRef.inTemplateInstantiation())
922     return false;
923 
924   Scope *S = SemaRef.getCurScope();
925   while (S && !S->isSEHExceptScope())
926     S = S->getParent();
927   if (!S || !(S->getFlags() & NeededScopeFlags)) {
928     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
929     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
930         << DRE->getDecl()->getIdentifier();
931     return true;
932   }
933 
934   return false;
935 }
936 
937 static inline bool isBlockPointer(Expr *Arg) {
938   return Arg->getType()->isBlockPointerType();
939 }
940 
941 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
942 /// void*, which is a requirement of device side enqueue.
943 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
944   const BlockPointerType *BPT =
945       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
946   ArrayRef<QualType> Params =
947       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
948   unsigned ArgCounter = 0;
949   bool IllegalParams = false;
950   // Iterate through the block parameters until either one is found that is not
951   // a local void*, or the block is valid.
952   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
953        I != E; ++I, ++ArgCounter) {
954     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
955         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
956             LangAS::opencl_local) {
957       // Get the location of the error. If a block literal has been passed
958       // (BlockExpr) then we can point straight to the offending argument,
959       // else we just point to the variable reference.
960       SourceLocation ErrorLoc;
961       if (isa<BlockExpr>(BlockArg)) {
962         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
963         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
964       } else if (isa<DeclRefExpr>(BlockArg)) {
965         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
966       }
967       S.Diag(ErrorLoc,
968              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
969       IllegalParams = true;
970     }
971   }
972 
973   return IllegalParams;
974 }
975 
976 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
977   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
978     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
979         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
980     return true;
981   }
982   return false;
983 }
984 
985 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
986   if (checkArgCount(S, TheCall, 2))
987     return true;
988 
989   if (checkOpenCLSubgroupExt(S, TheCall))
990     return true;
991 
992   // First argument is an ndrange_t type.
993   Expr *NDRangeArg = TheCall->getArg(0);
994   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
995     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
996         << TheCall->getDirectCallee() << "'ndrange_t'";
997     return true;
998   }
999 
1000   Expr *BlockArg = TheCall->getArg(1);
1001   if (!isBlockPointer(BlockArg)) {
1002     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1003         << TheCall->getDirectCallee() << "block";
1004     return true;
1005   }
1006   return checkOpenCLBlockArgs(S, BlockArg);
1007 }
1008 
1009 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1010 /// get_kernel_work_group_size
1011 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1012 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1013   if (checkArgCount(S, TheCall, 1))
1014     return true;
1015 
1016   Expr *BlockArg = TheCall->getArg(0);
1017   if (!isBlockPointer(BlockArg)) {
1018     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1019         << TheCall->getDirectCallee() << "block";
1020     return true;
1021   }
1022   return checkOpenCLBlockArgs(S, BlockArg);
1023 }
1024 
1025 /// Diagnose integer type and any valid implicit conversion to it.
1026 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1027                                       const QualType &IntType);
1028 
1029 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1030                                             unsigned Start, unsigned End) {
1031   bool IllegalParams = false;
1032   for (unsigned I = Start; I <= End; ++I)
1033     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1034                                               S.Context.getSizeType());
1035   return IllegalParams;
1036 }
1037 
1038 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1039 /// 'local void*' parameter of passed block.
1040 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1041                                            Expr *BlockArg,
1042                                            unsigned NumNonVarArgs) {
1043   const BlockPointerType *BPT =
1044       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1045   unsigned NumBlockParams =
1046       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1047   unsigned TotalNumArgs = TheCall->getNumArgs();
1048 
1049   // For each argument passed to the block, a corresponding uint needs to
1050   // be passed to describe the size of the local memory.
1051   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1052     S.Diag(TheCall->getBeginLoc(),
1053            diag::err_opencl_enqueue_kernel_local_size_args);
1054     return true;
1055   }
1056 
1057   // Check that the sizes of the local memory are specified by integers.
1058   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1059                                          TotalNumArgs - 1);
1060 }
1061 
1062 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1063 /// overload formats specified in Table 6.13.17.1.
1064 /// int enqueue_kernel(queue_t queue,
1065 ///                    kernel_enqueue_flags_t flags,
1066 ///                    const ndrange_t ndrange,
1067 ///                    void (^block)(void))
1068 /// int enqueue_kernel(queue_t queue,
1069 ///                    kernel_enqueue_flags_t flags,
1070 ///                    const ndrange_t ndrange,
1071 ///                    uint num_events_in_wait_list,
1072 ///                    clk_event_t *event_wait_list,
1073 ///                    clk_event_t *event_ret,
1074 ///                    void (^block)(void))
1075 /// int enqueue_kernel(queue_t queue,
1076 ///                    kernel_enqueue_flags_t flags,
1077 ///                    const ndrange_t ndrange,
1078 ///                    void (^block)(local void*, ...),
1079 ///                    uint size0, ...)
1080 /// int enqueue_kernel(queue_t queue,
1081 ///                    kernel_enqueue_flags_t flags,
1082 ///                    const ndrange_t ndrange,
1083 ///                    uint num_events_in_wait_list,
1084 ///                    clk_event_t *event_wait_list,
1085 ///                    clk_event_t *event_ret,
1086 ///                    void (^block)(local void*, ...),
1087 ///                    uint size0, ...)
1088 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1089   unsigned NumArgs = TheCall->getNumArgs();
1090 
1091   if (NumArgs < 4) {
1092     S.Diag(TheCall->getBeginLoc(),
1093            diag::err_typecheck_call_too_few_args_at_least)
1094         << 0 << 4 << NumArgs;
1095     return true;
1096   }
1097 
1098   Expr *Arg0 = TheCall->getArg(0);
1099   Expr *Arg1 = TheCall->getArg(1);
1100   Expr *Arg2 = TheCall->getArg(2);
1101   Expr *Arg3 = TheCall->getArg(3);
1102 
1103   // First argument always needs to be a queue_t type.
1104   if (!Arg0->getType()->isQueueT()) {
1105     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1106            diag::err_opencl_builtin_expected_type)
1107         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1108     return true;
1109   }
1110 
1111   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1112   if (!Arg1->getType()->isIntegerType()) {
1113     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1114            diag::err_opencl_builtin_expected_type)
1115         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1116     return true;
1117   }
1118 
1119   // Third argument is always an ndrange_t type.
1120   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1121     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1122            diag::err_opencl_builtin_expected_type)
1123         << TheCall->getDirectCallee() << "'ndrange_t'";
1124     return true;
1125   }
1126 
1127   // With four arguments, there is only one form that the function could be
1128   // called in: no events and no variable arguments.
1129   if (NumArgs == 4) {
1130     // check that the last argument is the right block type.
1131     if (!isBlockPointer(Arg3)) {
1132       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1133           << TheCall->getDirectCallee() << "block";
1134       return true;
1135     }
1136     // we have a block type, check the prototype
1137     const BlockPointerType *BPT =
1138         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1139     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1140       S.Diag(Arg3->getBeginLoc(),
1141              diag::err_opencl_enqueue_kernel_blocks_no_args);
1142       return true;
1143     }
1144     return false;
1145   }
1146   // we can have block + varargs.
1147   if (isBlockPointer(Arg3))
1148     return (checkOpenCLBlockArgs(S, Arg3) ||
1149             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1150   // last two cases with either exactly 7 args or 7 args and varargs.
1151   if (NumArgs >= 7) {
1152     // check common block argument.
1153     Expr *Arg6 = TheCall->getArg(6);
1154     if (!isBlockPointer(Arg6)) {
1155       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1156           << TheCall->getDirectCallee() << "block";
1157       return true;
1158     }
1159     if (checkOpenCLBlockArgs(S, Arg6))
1160       return true;
1161 
1162     // Forth argument has to be any integer type.
1163     if (!Arg3->getType()->isIntegerType()) {
1164       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1165              diag::err_opencl_builtin_expected_type)
1166           << TheCall->getDirectCallee() << "integer";
1167       return true;
1168     }
1169     // check remaining common arguments.
1170     Expr *Arg4 = TheCall->getArg(4);
1171     Expr *Arg5 = TheCall->getArg(5);
1172 
1173     // Fifth argument is always passed as a pointer to clk_event_t.
1174     if (!Arg4->isNullPointerConstant(S.Context,
1175                                      Expr::NPC_ValueDependentIsNotNull) &&
1176         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1177       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1178              diag::err_opencl_builtin_expected_type)
1179           << TheCall->getDirectCallee()
1180           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1181       return true;
1182     }
1183 
1184     // Sixth argument is always passed as a pointer to clk_event_t.
1185     if (!Arg5->isNullPointerConstant(S.Context,
1186                                      Expr::NPC_ValueDependentIsNotNull) &&
1187         !(Arg5->getType()->isPointerType() &&
1188           Arg5->getType()->getPointeeType()->isClkEventT())) {
1189       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1190              diag::err_opencl_builtin_expected_type)
1191           << TheCall->getDirectCallee()
1192           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1193       return true;
1194     }
1195 
1196     if (NumArgs == 7)
1197       return false;
1198 
1199     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1200   }
1201 
1202   // None of the specific case has been detected, give generic error
1203   S.Diag(TheCall->getBeginLoc(),
1204          diag::err_opencl_enqueue_kernel_incorrect_args);
1205   return true;
1206 }
1207 
1208 /// Returns OpenCL access qual.
1209 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1210     return D->getAttr<OpenCLAccessAttr>();
1211 }
1212 
1213 /// Returns true if pipe element type is different from the pointer.
1214 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1215   const Expr *Arg0 = Call->getArg(0);
1216   // First argument type should always be pipe.
1217   if (!Arg0->getType()->isPipeType()) {
1218     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1219         << Call->getDirectCallee() << Arg0->getSourceRange();
1220     return true;
1221   }
1222   OpenCLAccessAttr *AccessQual =
1223       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1224   // Validates the access qualifier is compatible with the call.
1225   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1226   // read_only and write_only, and assumed to be read_only if no qualifier is
1227   // specified.
1228   switch (Call->getDirectCallee()->getBuiltinID()) {
1229   case Builtin::BIread_pipe:
1230   case Builtin::BIreserve_read_pipe:
1231   case Builtin::BIcommit_read_pipe:
1232   case Builtin::BIwork_group_reserve_read_pipe:
1233   case Builtin::BIsub_group_reserve_read_pipe:
1234   case Builtin::BIwork_group_commit_read_pipe:
1235   case Builtin::BIsub_group_commit_read_pipe:
1236     if (!(!AccessQual || AccessQual->isReadOnly())) {
1237       S.Diag(Arg0->getBeginLoc(),
1238              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1239           << "read_only" << Arg0->getSourceRange();
1240       return true;
1241     }
1242     break;
1243   case Builtin::BIwrite_pipe:
1244   case Builtin::BIreserve_write_pipe:
1245   case Builtin::BIcommit_write_pipe:
1246   case Builtin::BIwork_group_reserve_write_pipe:
1247   case Builtin::BIsub_group_reserve_write_pipe:
1248   case Builtin::BIwork_group_commit_write_pipe:
1249   case Builtin::BIsub_group_commit_write_pipe:
1250     if (!(AccessQual && AccessQual->isWriteOnly())) {
1251       S.Diag(Arg0->getBeginLoc(),
1252              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1253           << "write_only" << Arg0->getSourceRange();
1254       return true;
1255     }
1256     break;
1257   default:
1258     break;
1259   }
1260   return false;
1261 }
1262 
1263 /// Returns true if pipe element type is different from the pointer.
1264 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1265   const Expr *Arg0 = Call->getArg(0);
1266   const Expr *ArgIdx = Call->getArg(Idx);
1267   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1268   const QualType EltTy = PipeTy->getElementType();
1269   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1270   // The Idx argument should be a pointer and the type of the pointer and
1271   // the type of pipe element should also be the same.
1272   if (!ArgTy ||
1273       !S.Context.hasSameType(
1274           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1275     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1276         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1277         << ArgIdx->getType() << ArgIdx->getSourceRange();
1278     return true;
1279   }
1280   return false;
1281 }
1282 
1283 // Performs semantic analysis for the read/write_pipe call.
1284 // \param S Reference to the semantic analyzer.
1285 // \param Call A pointer to the builtin call.
1286 // \return True if a semantic error has been found, false otherwise.
1287 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1288   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1289   // functions have two forms.
1290   switch (Call->getNumArgs()) {
1291   case 2:
1292     if (checkOpenCLPipeArg(S, Call))
1293       return true;
1294     // The call with 2 arguments should be
1295     // read/write_pipe(pipe T, T*).
1296     // Check packet type T.
1297     if (checkOpenCLPipePacketType(S, Call, 1))
1298       return true;
1299     break;
1300 
1301   case 4: {
1302     if (checkOpenCLPipeArg(S, Call))
1303       return true;
1304     // The call with 4 arguments should be
1305     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1306     // Check reserve_id_t.
1307     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1308       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1309           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1310           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1311       return true;
1312     }
1313 
1314     // Check the index.
1315     const Expr *Arg2 = Call->getArg(2);
1316     if (!Arg2->getType()->isIntegerType() &&
1317         !Arg2->getType()->isUnsignedIntegerType()) {
1318       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1319           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1320           << Arg2->getType() << Arg2->getSourceRange();
1321       return true;
1322     }
1323 
1324     // Check packet type T.
1325     if (checkOpenCLPipePacketType(S, Call, 3))
1326       return true;
1327   } break;
1328   default:
1329     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1330         << Call->getDirectCallee() << Call->getSourceRange();
1331     return true;
1332   }
1333 
1334   return false;
1335 }
1336 
1337 // Performs a semantic analysis on the {work_group_/sub_group_
1338 //        /_}reserve_{read/write}_pipe
1339 // \param S Reference to the semantic analyzer.
1340 // \param Call The call to the builtin function to be analyzed.
1341 // \return True if a semantic error was found, false otherwise.
1342 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1343   if (checkArgCount(S, Call, 2))
1344     return true;
1345 
1346   if (checkOpenCLPipeArg(S, Call))
1347     return true;
1348 
1349   // Check the reserve size.
1350   if (!Call->getArg(1)->getType()->isIntegerType() &&
1351       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1352     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1353         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1354         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1355     return true;
1356   }
1357 
1358   // Since return type of reserve_read/write_pipe built-in function is
1359   // reserve_id_t, which is not defined in the builtin def file , we used int
1360   // as return type and need to override the return type of these functions.
1361   Call->setType(S.Context.OCLReserveIDTy);
1362 
1363   return false;
1364 }
1365 
1366 // Performs a semantic analysis on {work_group_/sub_group_
1367 //        /_}commit_{read/write}_pipe
1368 // \param S Reference to the semantic analyzer.
1369 // \param Call The call to the builtin function to be analyzed.
1370 // \return True if a semantic error was found, false otherwise.
1371 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1372   if (checkArgCount(S, Call, 2))
1373     return true;
1374 
1375   if (checkOpenCLPipeArg(S, Call))
1376     return true;
1377 
1378   // Check reserve_id_t.
1379   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1380     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1381         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1382         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1383     return true;
1384   }
1385 
1386   return false;
1387 }
1388 
1389 // Performs a semantic analysis on the call to built-in Pipe
1390 //        Query Functions.
1391 // \param S Reference to the semantic analyzer.
1392 // \param Call The call to the builtin function to be analyzed.
1393 // \return True if a semantic error was found, false otherwise.
1394 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1395   if (checkArgCount(S, Call, 1))
1396     return true;
1397 
1398   if (!Call->getArg(0)->getType()->isPipeType()) {
1399     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1400         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1401     return true;
1402   }
1403 
1404   return false;
1405 }
1406 
1407 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1408 // Performs semantic analysis for the to_global/local/private call.
1409 // \param S Reference to the semantic analyzer.
1410 // \param BuiltinID ID of the builtin function.
1411 // \param Call A pointer to the builtin call.
1412 // \return True if a semantic error has been found, false otherwise.
1413 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1414                                     CallExpr *Call) {
1415   if (checkArgCount(S, Call, 1))
1416     return true;
1417 
1418   auto RT = Call->getArg(0)->getType();
1419   if (!RT->isPointerType() || RT->getPointeeType()
1420       .getAddressSpace() == LangAS::opencl_constant) {
1421     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1422         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1423     return true;
1424   }
1425 
1426   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1427     S.Diag(Call->getArg(0)->getBeginLoc(),
1428            diag::warn_opencl_generic_address_space_arg)
1429         << Call->getDirectCallee()->getNameInfo().getAsString()
1430         << Call->getArg(0)->getSourceRange();
1431   }
1432 
1433   RT = RT->getPointeeType();
1434   auto Qual = RT.getQualifiers();
1435   switch (BuiltinID) {
1436   case Builtin::BIto_global:
1437     Qual.setAddressSpace(LangAS::opencl_global);
1438     break;
1439   case Builtin::BIto_local:
1440     Qual.setAddressSpace(LangAS::opencl_local);
1441     break;
1442   case Builtin::BIto_private:
1443     Qual.setAddressSpace(LangAS::opencl_private);
1444     break;
1445   default:
1446     llvm_unreachable("Invalid builtin function");
1447   }
1448   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1449       RT.getUnqualifiedType(), Qual)));
1450 
1451   return false;
1452 }
1453 
1454 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1455   if (checkArgCount(S, TheCall, 1))
1456     return ExprError();
1457 
1458   // Compute __builtin_launder's parameter type from the argument.
1459   // The parameter type is:
1460   //  * The type of the argument if it's not an array or function type,
1461   //  Otherwise,
1462   //  * The decayed argument type.
1463   QualType ParamTy = [&]() {
1464     QualType ArgTy = TheCall->getArg(0)->getType();
1465     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1466       return S.Context.getPointerType(Ty->getElementType());
1467     if (ArgTy->isFunctionType()) {
1468       return S.Context.getPointerType(ArgTy);
1469     }
1470     return ArgTy;
1471   }();
1472 
1473   TheCall->setType(ParamTy);
1474 
1475   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1476     if (!ParamTy->isPointerType())
1477       return 0;
1478     if (ParamTy->isFunctionPointerType())
1479       return 1;
1480     if (ParamTy->isVoidPointerType())
1481       return 2;
1482     return llvm::Optional<unsigned>{};
1483   }();
1484   if (DiagSelect.hasValue()) {
1485     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1486         << DiagSelect.getValue() << TheCall->getSourceRange();
1487     return ExprError();
1488   }
1489 
1490   // We either have an incomplete class type, or we have a class template
1491   // whose instantiation has not been forced. Example:
1492   //
1493   //   template <class T> struct Foo { T value; };
1494   //   Foo<int> *p = nullptr;
1495   //   auto *d = __builtin_launder(p);
1496   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1497                             diag::err_incomplete_type))
1498     return ExprError();
1499 
1500   assert(ParamTy->getPointeeType()->isObjectType() &&
1501          "Unhandled non-object pointer case");
1502 
1503   InitializedEntity Entity =
1504       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1505   ExprResult Arg =
1506       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1507   if (Arg.isInvalid())
1508     return ExprError();
1509   TheCall->setArg(0, Arg.get());
1510 
1511   return TheCall;
1512 }
1513 
1514 // Emit an error and return true if the current architecture is not in the list
1515 // of supported architectures.
1516 static bool
1517 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1518                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1519   llvm::Triple::ArchType CurArch =
1520       S.getASTContext().getTargetInfo().getTriple().getArch();
1521   if (llvm::is_contained(SupportedArchs, CurArch))
1522     return false;
1523   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1524       << TheCall->getSourceRange();
1525   return true;
1526 }
1527 
1528 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1529                                  SourceLocation CallSiteLoc);
1530 
1531 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1532                                       CallExpr *TheCall) {
1533   switch (TI.getTriple().getArch()) {
1534   default:
1535     // Some builtins don't require additional checking, so just consider these
1536     // acceptable.
1537     return false;
1538   case llvm::Triple::arm:
1539   case llvm::Triple::armeb:
1540   case llvm::Triple::thumb:
1541   case llvm::Triple::thumbeb:
1542     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1543   case llvm::Triple::aarch64:
1544   case llvm::Triple::aarch64_32:
1545   case llvm::Triple::aarch64_be:
1546     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1547   case llvm::Triple::bpfeb:
1548   case llvm::Triple::bpfel:
1549     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1550   case llvm::Triple::hexagon:
1551     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1552   case llvm::Triple::mips:
1553   case llvm::Triple::mipsel:
1554   case llvm::Triple::mips64:
1555   case llvm::Triple::mips64el:
1556     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1557   case llvm::Triple::systemz:
1558     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1559   case llvm::Triple::x86:
1560   case llvm::Triple::x86_64:
1561     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1562   case llvm::Triple::ppc:
1563   case llvm::Triple::ppcle:
1564   case llvm::Triple::ppc64:
1565   case llvm::Triple::ppc64le:
1566     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1567   case llvm::Triple::amdgcn:
1568     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1569   case llvm::Triple::riscv32:
1570   case llvm::Triple::riscv64:
1571     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1572   }
1573 }
1574 
1575 ExprResult
1576 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1577                                CallExpr *TheCall) {
1578   ExprResult TheCallResult(TheCall);
1579 
1580   // Find out if any arguments are required to be integer constant expressions.
1581   unsigned ICEArguments = 0;
1582   ASTContext::GetBuiltinTypeError Error;
1583   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1584   if (Error != ASTContext::GE_None)
1585     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1586 
1587   // If any arguments are required to be ICE's, check and diagnose.
1588   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1589     // Skip arguments not required to be ICE's.
1590     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1591 
1592     llvm::APSInt Result;
1593     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1594       return true;
1595     ICEArguments &= ~(1 << ArgNo);
1596   }
1597 
1598   switch (BuiltinID) {
1599   case Builtin::BI__builtin___CFStringMakeConstantString:
1600     assert(TheCall->getNumArgs() == 1 &&
1601            "Wrong # arguments to builtin CFStringMakeConstantString");
1602     if (CheckObjCString(TheCall->getArg(0)))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_ms_va_start:
1606   case Builtin::BI__builtin_stdarg_start:
1607   case Builtin::BI__builtin_va_start:
1608     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1609       return ExprError();
1610     break;
1611   case Builtin::BI__va_start: {
1612     switch (Context.getTargetInfo().getTriple().getArch()) {
1613     case llvm::Triple::aarch64:
1614     case llvm::Triple::arm:
1615     case llvm::Triple::thumb:
1616       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1617         return ExprError();
1618       break;
1619     default:
1620       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1621         return ExprError();
1622       break;
1623     }
1624     break;
1625   }
1626 
1627   // The acquire, release, and no fence variants are ARM and AArch64 only.
1628   case Builtin::BI_interlockedbittestandset_acq:
1629   case Builtin::BI_interlockedbittestandset_rel:
1630   case Builtin::BI_interlockedbittestandset_nf:
1631   case Builtin::BI_interlockedbittestandreset_acq:
1632   case Builtin::BI_interlockedbittestandreset_rel:
1633   case Builtin::BI_interlockedbittestandreset_nf:
1634     if (CheckBuiltinTargetSupport(
1635             *this, BuiltinID, TheCall,
1636             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1637       return ExprError();
1638     break;
1639 
1640   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1641   case Builtin::BI_bittest64:
1642   case Builtin::BI_bittestandcomplement64:
1643   case Builtin::BI_bittestandreset64:
1644   case Builtin::BI_bittestandset64:
1645   case Builtin::BI_interlockedbittestandreset64:
1646   case Builtin::BI_interlockedbittestandset64:
1647     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1648                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1649                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1650       return ExprError();
1651     break;
1652 
1653   case Builtin::BI__builtin_isgreater:
1654   case Builtin::BI__builtin_isgreaterequal:
1655   case Builtin::BI__builtin_isless:
1656   case Builtin::BI__builtin_islessequal:
1657   case Builtin::BI__builtin_islessgreater:
1658   case Builtin::BI__builtin_isunordered:
1659     if (SemaBuiltinUnorderedCompare(TheCall))
1660       return ExprError();
1661     break;
1662   case Builtin::BI__builtin_fpclassify:
1663     if (SemaBuiltinFPClassification(TheCall, 6))
1664       return ExprError();
1665     break;
1666   case Builtin::BI__builtin_isfinite:
1667   case Builtin::BI__builtin_isinf:
1668   case Builtin::BI__builtin_isinf_sign:
1669   case Builtin::BI__builtin_isnan:
1670   case Builtin::BI__builtin_isnormal:
1671   case Builtin::BI__builtin_signbit:
1672   case Builtin::BI__builtin_signbitf:
1673   case Builtin::BI__builtin_signbitl:
1674     if (SemaBuiltinFPClassification(TheCall, 1))
1675       return ExprError();
1676     break;
1677   case Builtin::BI__builtin_shufflevector:
1678     return SemaBuiltinShuffleVector(TheCall);
1679     // TheCall will be freed by the smart pointer here, but that's fine, since
1680     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1681   case Builtin::BI__builtin_prefetch:
1682     if (SemaBuiltinPrefetch(TheCall))
1683       return ExprError();
1684     break;
1685   case Builtin::BI__builtin_alloca_with_align:
1686     if (SemaBuiltinAllocaWithAlign(TheCall))
1687       return ExprError();
1688     LLVM_FALLTHROUGH;
1689   case Builtin::BI__builtin_alloca:
1690     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1691         << TheCall->getDirectCallee();
1692     break;
1693   case Builtin::BI__arithmetic_fence:
1694     if (SemaBuiltinArithmeticFence(TheCall))
1695       return ExprError();
1696     break;
1697   case Builtin::BI__assume:
1698   case Builtin::BI__builtin_assume:
1699     if (SemaBuiltinAssume(TheCall))
1700       return ExprError();
1701     break;
1702   case Builtin::BI__builtin_assume_aligned:
1703     if (SemaBuiltinAssumeAligned(TheCall))
1704       return ExprError();
1705     break;
1706   case Builtin::BI__builtin_dynamic_object_size:
1707   case Builtin::BI__builtin_object_size:
1708     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1709       return ExprError();
1710     break;
1711   case Builtin::BI__builtin_longjmp:
1712     if (SemaBuiltinLongjmp(TheCall))
1713       return ExprError();
1714     break;
1715   case Builtin::BI__builtin_setjmp:
1716     if (SemaBuiltinSetjmp(TheCall))
1717       return ExprError();
1718     break;
1719   case Builtin::BI__builtin_classify_type:
1720     if (checkArgCount(*this, TheCall, 1)) return true;
1721     TheCall->setType(Context.IntTy);
1722     break;
1723   case Builtin::BI__builtin_complex:
1724     if (SemaBuiltinComplex(TheCall))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_constant_p: {
1728     if (checkArgCount(*this, TheCall, 1)) return true;
1729     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1730     if (Arg.isInvalid()) return true;
1731     TheCall->setArg(0, Arg.get());
1732     TheCall->setType(Context.IntTy);
1733     break;
1734   }
1735   case Builtin::BI__builtin_launder:
1736     return SemaBuiltinLaunder(*this, TheCall);
1737   case Builtin::BI__sync_fetch_and_add:
1738   case Builtin::BI__sync_fetch_and_add_1:
1739   case Builtin::BI__sync_fetch_and_add_2:
1740   case Builtin::BI__sync_fetch_and_add_4:
1741   case Builtin::BI__sync_fetch_and_add_8:
1742   case Builtin::BI__sync_fetch_and_add_16:
1743   case Builtin::BI__sync_fetch_and_sub:
1744   case Builtin::BI__sync_fetch_and_sub_1:
1745   case Builtin::BI__sync_fetch_and_sub_2:
1746   case Builtin::BI__sync_fetch_and_sub_4:
1747   case Builtin::BI__sync_fetch_and_sub_8:
1748   case Builtin::BI__sync_fetch_and_sub_16:
1749   case Builtin::BI__sync_fetch_and_or:
1750   case Builtin::BI__sync_fetch_and_or_1:
1751   case Builtin::BI__sync_fetch_and_or_2:
1752   case Builtin::BI__sync_fetch_and_or_4:
1753   case Builtin::BI__sync_fetch_and_or_8:
1754   case Builtin::BI__sync_fetch_and_or_16:
1755   case Builtin::BI__sync_fetch_and_and:
1756   case Builtin::BI__sync_fetch_and_and_1:
1757   case Builtin::BI__sync_fetch_and_and_2:
1758   case Builtin::BI__sync_fetch_and_and_4:
1759   case Builtin::BI__sync_fetch_and_and_8:
1760   case Builtin::BI__sync_fetch_and_and_16:
1761   case Builtin::BI__sync_fetch_and_xor:
1762   case Builtin::BI__sync_fetch_and_xor_1:
1763   case Builtin::BI__sync_fetch_and_xor_2:
1764   case Builtin::BI__sync_fetch_and_xor_4:
1765   case Builtin::BI__sync_fetch_and_xor_8:
1766   case Builtin::BI__sync_fetch_and_xor_16:
1767   case Builtin::BI__sync_fetch_and_nand:
1768   case Builtin::BI__sync_fetch_and_nand_1:
1769   case Builtin::BI__sync_fetch_and_nand_2:
1770   case Builtin::BI__sync_fetch_and_nand_4:
1771   case Builtin::BI__sync_fetch_and_nand_8:
1772   case Builtin::BI__sync_fetch_and_nand_16:
1773   case Builtin::BI__sync_add_and_fetch:
1774   case Builtin::BI__sync_add_and_fetch_1:
1775   case Builtin::BI__sync_add_and_fetch_2:
1776   case Builtin::BI__sync_add_and_fetch_4:
1777   case Builtin::BI__sync_add_and_fetch_8:
1778   case Builtin::BI__sync_add_and_fetch_16:
1779   case Builtin::BI__sync_sub_and_fetch:
1780   case Builtin::BI__sync_sub_and_fetch_1:
1781   case Builtin::BI__sync_sub_and_fetch_2:
1782   case Builtin::BI__sync_sub_and_fetch_4:
1783   case Builtin::BI__sync_sub_and_fetch_8:
1784   case Builtin::BI__sync_sub_and_fetch_16:
1785   case Builtin::BI__sync_and_and_fetch:
1786   case Builtin::BI__sync_and_and_fetch_1:
1787   case Builtin::BI__sync_and_and_fetch_2:
1788   case Builtin::BI__sync_and_and_fetch_4:
1789   case Builtin::BI__sync_and_and_fetch_8:
1790   case Builtin::BI__sync_and_and_fetch_16:
1791   case Builtin::BI__sync_or_and_fetch:
1792   case Builtin::BI__sync_or_and_fetch_1:
1793   case Builtin::BI__sync_or_and_fetch_2:
1794   case Builtin::BI__sync_or_and_fetch_4:
1795   case Builtin::BI__sync_or_and_fetch_8:
1796   case Builtin::BI__sync_or_and_fetch_16:
1797   case Builtin::BI__sync_xor_and_fetch:
1798   case Builtin::BI__sync_xor_and_fetch_1:
1799   case Builtin::BI__sync_xor_and_fetch_2:
1800   case Builtin::BI__sync_xor_and_fetch_4:
1801   case Builtin::BI__sync_xor_and_fetch_8:
1802   case Builtin::BI__sync_xor_and_fetch_16:
1803   case Builtin::BI__sync_nand_and_fetch:
1804   case Builtin::BI__sync_nand_and_fetch_1:
1805   case Builtin::BI__sync_nand_and_fetch_2:
1806   case Builtin::BI__sync_nand_and_fetch_4:
1807   case Builtin::BI__sync_nand_and_fetch_8:
1808   case Builtin::BI__sync_nand_and_fetch_16:
1809   case Builtin::BI__sync_val_compare_and_swap:
1810   case Builtin::BI__sync_val_compare_and_swap_1:
1811   case Builtin::BI__sync_val_compare_and_swap_2:
1812   case Builtin::BI__sync_val_compare_and_swap_4:
1813   case Builtin::BI__sync_val_compare_and_swap_8:
1814   case Builtin::BI__sync_val_compare_and_swap_16:
1815   case Builtin::BI__sync_bool_compare_and_swap:
1816   case Builtin::BI__sync_bool_compare_and_swap_1:
1817   case Builtin::BI__sync_bool_compare_and_swap_2:
1818   case Builtin::BI__sync_bool_compare_and_swap_4:
1819   case Builtin::BI__sync_bool_compare_and_swap_8:
1820   case Builtin::BI__sync_bool_compare_and_swap_16:
1821   case Builtin::BI__sync_lock_test_and_set:
1822   case Builtin::BI__sync_lock_test_and_set_1:
1823   case Builtin::BI__sync_lock_test_and_set_2:
1824   case Builtin::BI__sync_lock_test_and_set_4:
1825   case Builtin::BI__sync_lock_test_and_set_8:
1826   case Builtin::BI__sync_lock_test_and_set_16:
1827   case Builtin::BI__sync_lock_release:
1828   case Builtin::BI__sync_lock_release_1:
1829   case Builtin::BI__sync_lock_release_2:
1830   case Builtin::BI__sync_lock_release_4:
1831   case Builtin::BI__sync_lock_release_8:
1832   case Builtin::BI__sync_lock_release_16:
1833   case Builtin::BI__sync_swap:
1834   case Builtin::BI__sync_swap_1:
1835   case Builtin::BI__sync_swap_2:
1836   case Builtin::BI__sync_swap_4:
1837   case Builtin::BI__sync_swap_8:
1838   case Builtin::BI__sync_swap_16:
1839     return SemaBuiltinAtomicOverloaded(TheCallResult);
1840   case Builtin::BI__sync_synchronize:
1841     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1842         << TheCall->getCallee()->getSourceRange();
1843     break;
1844   case Builtin::BI__builtin_nontemporal_load:
1845   case Builtin::BI__builtin_nontemporal_store:
1846     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1847   case Builtin::BI__builtin_memcpy_inline: {
1848     clang::Expr *SizeOp = TheCall->getArg(2);
1849     // We warn about copying to or from `nullptr` pointers when `size` is
1850     // greater than 0. When `size` is value dependent we cannot evaluate its
1851     // value so we bail out.
1852     if (SizeOp->isValueDependent())
1853       break;
1854     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1855       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1856       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1857     }
1858     break;
1859   }
1860 #define BUILTIN(ID, TYPE, ATTRS)
1861 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1862   case Builtin::BI##ID: \
1863     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1864 #include "clang/Basic/Builtins.def"
1865   case Builtin::BI__annotation:
1866     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__builtin_annotation:
1870     if (SemaBuiltinAnnotation(*this, TheCall))
1871       return ExprError();
1872     break;
1873   case Builtin::BI__builtin_addressof:
1874     if (SemaBuiltinAddressof(*this, TheCall))
1875       return ExprError();
1876     break;
1877   case Builtin::BI__builtin_is_aligned:
1878   case Builtin::BI__builtin_align_up:
1879   case Builtin::BI__builtin_align_down:
1880     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1881       return ExprError();
1882     break;
1883   case Builtin::BI__builtin_add_overflow:
1884   case Builtin::BI__builtin_sub_overflow:
1885   case Builtin::BI__builtin_mul_overflow:
1886     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1887       return ExprError();
1888     break;
1889   case Builtin::BI__builtin_operator_new:
1890   case Builtin::BI__builtin_operator_delete: {
1891     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1892     ExprResult Res =
1893         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1894     if (Res.isInvalid())
1895       CorrectDelayedTyposInExpr(TheCallResult.get());
1896     return Res;
1897   }
1898   case Builtin::BI__builtin_dump_struct: {
1899     // We first want to ensure we are called with 2 arguments
1900     if (checkArgCount(*this, TheCall, 2))
1901       return ExprError();
1902     // Ensure that the first argument is of type 'struct XX *'
1903     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1904     const QualType PtrArgType = PtrArg->getType();
1905     if (!PtrArgType->isPointerType() ||
1906         !PtrArgType->getPointeeType()->isRecordType()) {
1907       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1908           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1909           << "structure pointer";
1910       return ExprError();
1911     }
1912 
1913     // Ensure that the second argument is of type 'FunctionType'
1914     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1915     const QualType FnPtrArgType = FnPtrArg->getType();
1916     if (!FnPtrArgType->isPointerType()) {
1917       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1918           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1919           << FnPtrArgType << "'int (*)(const char *, ...)'";
1920       return ExprError();
1921     }
1922 
1923     const auto *FuncType =
1924         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1925 
1926     if (!FuncType) {
1927       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1928           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1929           << FnPtrArgType << "'int (*)(const char *, ...)'";
1930       return ExprError();
1931     }
1932 
1933     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1934       if (!FT->getNumParams()) {
1935         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1936             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1937             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1938         return ExprError();
1939       }
1940       QualType PT = FT->getParamType(0);
1941       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1942           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1943           !PT->getPointeeType().isConstQualified()) {
1944         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1945             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1946             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1947         return ExprError();
1948       }
1949     }
1950 
1951     TheCall->setType(Context.IntTy);
1952     break;
1953   }
1954   case Builtin::BI__builtin_expect_with_probability: {
1955     // We first want to ensure we are called with 3 arguments
1956     if (checkArgCount(*this, TheCall, 3))
1957       return ExprError();
1958     // then check probability is constant float in range [0.0, 1.0]
1959     const Expr *ProbArg = TheCall->getArg(2);
1960     SmallVector<PartialDiagnosticAt, 8> Notes;
1961     Expr::EvalResult Eval;
1962     Eval.Diag = &Notes;
1963     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1964         !Eval.Val.isFloat()) {
1965       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1966           << ProbArg->getSourceRange();
1967       for (const PartialDiagnosticAt &PDiag : Notes)
1968         Diag(PDiag.first, PDiag.second);
1969       return ExprError();
1970     }
1971     llvm::APFloat Probability = Eval.Val.getFloat();
1972     bool LoseInfo = false;
1973     Probability.convert(llvm::APFloat::IEEEdouble(),
1974                         llvm::RoundingMode::Dynamic, &LoseInfo);
1975     if (!(Probability >= llvm::APFloat(0.0) &&
1976           Probability <= llvm::APFloat(1.0))) {
1977       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1978           << ProbArg->getSourceRange();
1979       return ExprError();
1980     }
1981     break;
1982   }
1983   case Builtin::BI__builtin_preserve_access_index:
1984     if (SemaBuiltinPreserveAI(*this, TheCall))
1985       return ExprError();
1986     break;
1987   case Builtin::BI__builtin_call_with_static_chain:
1988     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1989       return ExprError();
1990     break;
1991   case Builtin::BI__exception_code:
1992   case Builtin::BI_exception_code:
1993     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1994                                  diag::err_seh___except_block))
1995       return ExprError();
1996     break;
1997   case Builtin::BI__exception_info:
1998   case Builtin::BI_exception_info:
1999     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2000                                  diag::err_seh___except_filter))
2001       return ExprError();
2002     break;
2003   case Builtin::BI__GetExceptionInfo:
2004     if (checkArgCount(*this, TheCall, 1))
2005       return ExprError();
2006 
2007     if (CheckCXXThrowOperand(
2008             TheCall->getBeginLoc(),
2009             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2010             TheCall))
2011       return ExprError();
2012 
2013     TheCall->setType(Context.VoidPtrTy);
2014     break;
2015   // OpenCL v2.0, s6.13.16 - Pipe functions
2016   case Builtin::BIread_pipe:
2017   case Builtin::BIwrite_pipe:
2018     // Since those two functions are declared with var args, we need a semantic
2019     // check for the argument.
2020     if (SemaBuiltinRWPipe(*this, TheCall))
2021       return ExprError();
2022     break;
2023   case Builtin::BIreserve_read_pipe:
2024   case Builtin::BIreserve_write_pipe:
2025   case Builtin::BIwork_group_reserve_read_pipe:
2026   case Builtin::BIwork_group_reserve_write_pipe:
2027     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2028       return ExprError();
2029     break;
2030   case Builtin::BIsub_group_reserve_read_pipe:
2031   case Builtin::BIsub_group_reserve_write_pipe:
2032     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2033         SemaBuiltinReserveRWPipe(*this, TheCall))
2034       return ExprError();
2035     break;
2036   case Builtin::BIcommit_read_pipe:
2037   case Builtin::BIcommit_write_pipe:
2038   case Builtin::BIwork_group_commit_read_pipe:
2039   case Builtin::BIwork_group_commit_write_pipe:
2040     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2041       return ExprError();
2042     break;
2043   case Builtin::BIsub_group_commit_read_pipe:
2044   case Builtin::BIsub_group_commit_write_pipe:
2045     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2046         SemaBuiltinCommitRWPipe(*this, TheCall))
2047       return ExprError();
2048     break;
2049   case Builtin::BIget_pipe_num_packets:
2050   case Builtin::BIget_pipe_max_packets:
2051     if (SemaBuiltinPipePackets(*this, TheCall))
2052       return ExprError();
2053     break;
2054   case Builtin::BIto_global:
2055   case Builtin::BIto_local:
2056   case Builtin::BIto_private:
2057     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2058       return ExprError();
2059     break;
2060   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2061   case Builtin::BIenqueue_kernel:
2062     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2063       return ExprError();
2064     break;
2065   case Builtin::BIget_kernel_work_group_size:
2066   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2067     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2068       return ExprError();
2069     break;
2070   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2071   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2072     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2073       return ExprError();
2074     break;
2075   case Builtin::BI__builtin_os_log_format:
2076     Cleanup.setExprNeedsCleanups(true);
2077     LLVM_FALLTHROUGH;
2078   case Builtin::BI__builtin_os_log_format_buffer_size:
2079     if (SemaBuiltinOSLogFormat(TheCall))
2080       return ExprError();
2081     break;
2082   case Builtin::BI__builtin_frame_address:
2083   case Builtin::BI__builtin_return_address: {
2084     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2085       return ExprError();
2086 
2087     // -Wframe-address warning if non-zero passed to builtin
2088     // return/frame address.
2089     Expr::EvalResult Result;
2090     if (!TheCall->getArg(0)->isValueDependent() &&
2091         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2092         Result.Val.getInt() != 0)
2093       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2094           << ((BuiltinID == Builtin::BI__builtin_return_address)
2095                   ? "__builtin_return_address"
2096                   : "__builtin_frame_address")
2097           << TheCall->getSourceRange();
2098     break;
2099   }
2100 
2101   // __builtin_elementwise_abs restricts the element type to signed integers or
2102   // floating point types only.
2103   case Builtin::BI__builtin_elementwise_abs: {
2104     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2105       return ExprError();
2106 
2107     QualType ArgTy = TheCall->getArg(0)->getType();
2108     QualType EltTy = ArgTy;
2109 
2110     if (auto *VecTy = EltTy->getAs<VectorType>())
2111       EltTy = VecTy->getElementType();
2112     if (EltTy->isUnsignedIntegerType()) {
2113       Diag(TheCall->getArg(0)->getBeginLoc(),
2114            diag::err_builtin_invalid_arg_type)
2115           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2116       return ExprError();
2117     }
2118     break;
2119   }
2120 
2121   // __builtin_elementwise_ceil restricts the element type to floating point
2122   // types only.
2123   case Builtin::BI__builtin_elementwise_ceil: {
2124     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2125       return ExprError();
2126 
2127     QualType ArgTy = TheCall->getArg(0)->getType();
2128     QualType EltTy = ArgTy;
2129 
2130     if (auto *VecTy = EltTy->getAs<VectorType>())
2131       EltTy = VecTy->getElementType();
2132     if (!EltTy->isFloatingType()) {
2133       Diag(TheCall->getArg(0)->getBeginLoc(),
2134            diag::err_builtin_invalid_arg_type)
2135           << 1 << /* float ty*/ 5 << ArgTy;
2136 
2137       return ExprError();
2138     }
2139     break;
2140   }
2141 
2142   case Builtin::BI__builtin_elementwise_min:
2143   case Builtin::BI__builtin_elementwise_max:
2144     if (SemaBuiltinElementwiseMath(TheCall))
2145       return ExprError();
2146     break;
2147   case Builtin::BI__builtin_reduce_max:
2148   case Builtin::BI__builtin_reduce_min:
2149     if (SemaBuiltinReduceMath(TheCall))
2150       return ExprError();
2151     break;
2152   case Builtin::BI__builtin_matrix_transpose:
2153     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2154 
2155   case Builtin::BI__builtin_matrix_column_major_load:
2156     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2157 
2158   case Builtin::BI__builtin_matrix_column_major_store:
2159     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2160 
2161   case Builtin::BI__builtin_get_device_side_mangled_name: {
2162     auto Check = [](CallExpr *TheCall) {
2163       if (TheCall->getNumArgs() != 1)
2164         return false;
2165       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2166       if (!DRE)
2167         return false;
2168       auto *D = DRE->getDecl();
2169       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2170         return false;
2171       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2172              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2173     };
2174     if (!Check(TheCall)) {
2175       Diag(TheCall->getBeginLoc(),
2176            diag::err_hip_invalid_args_builtin_mangled_name);
2177       return ExprError();
2178     }
2179   }
2180   }
2181 
2182   // Since the target specific builtins for each arch overlap, only check those
2183   // of the arch we are compiling for.
2184   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2185     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2186       assert(Context.getAuxTargetInfo() &&
2187              "Aux Target Builtin, but not an aux target?");
2188 
2189       if (CheckTSBuiltinFunctionCall(
2190               *Context.getAuxTargetInfo(),
2191               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2192         return ExprError();
2193     } else {
2194       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2195                                      TheCall))
2196         return ExprError();
2197     }
2198   }
2199 
2200   return TheCallResult;
2201 }
2202 
2203 // Get the valid immediate range for the specified NEON type code.
2204 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2205   NeonTypeFlags Type(t);
2206   int IsQuad = ForceQuad ? true : Type.isQuad();
2207   switch (Type.getEltType()) {
2208   case NeonTypeFlags::Int8:
2209   case NeonTypeFlags::Poly8:
2210     return shift ? 7 : (8 << IsQuad) - 1;
2211   case NeonTypeFlags::Int16:
2212   case NeonTypeFlags::Poly16:
2213     return shift ? 15 : (4 << IsQuad) - 1;
2214   case NeonTypeFlags::Int32:
2215     return shift ? 31 : (2 << IsQuad) - 1;
2216   case NeonTypeFlags::Int64:
2217   case NeonTypeFlags::Poly64:
2218     return shift ? 63 : (1 << IsQuad) - 1;
2219   case NeonTypeFlags::Poly128:
2220     return shift ? 127 : (1 << IsQuad) - 1;
2221   case NeonTypeFlags::Float16:
2222     assert(!shift && "cannot shift float types!");
2223     return (4 << IsQuad) - 1;
2224   case NeonTypeFlags::Float32:
2225     assert(!shift && "cannot shift float types!");
2226     return (2 << IsQuad) - 1;
2227   case NeonTypeFlags::Float64:
2228     assert(!shift && "cannot shift float types!");
2229     return (1 << IsQuad) - 1;
2230   case NeonTypeFlags::BFloat16:
2231     assert(!shift && "cannot shift float types!");
2232     return (4 << IsQuad) - 1;
2233   }
2234   llvm_unreachable("Invalid NeonTypeFlag!");
2235 }
2236 
2237 /// getNeonEltType - Return the QualType corresponding to the elements of
2238 /// the vector type specified by the NeonTypeFlags.  This is used to check
2239 /// the pointer arguments for Neon load/store intrinsics.
2240 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2241                                bool IsPolyUnsigned, bool IsInt64Long) {
2242   switch (Flags.getEltType()) {
2243   case NeonTypeFlags::Int8:
2244     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2245   case NeonTypeFlags::Int16:
2246     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2247   case NeonTypeFlags::Int32:
2248     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2249   case NeonTypeFlags::Int64:
2250     if (IsInt64Long)
2251       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2252     else
2253       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2254                                 : Context.LongLongTy;
2255   case NeonTypeFlags::Poly8:
2256     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2257   case NeonTypeFlags::Poly16:
2258     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2259   case NeonTypeFlags::Poly64:
2260     if (IsInt64Long)
2261       return Context.UnsignedLongTy;
2262     else
2263       return Context.UnsignedLongLongTy;
2264   case NeonTypeFlags::Poly128:
2265     break;
2266   case NeonTypeFlags::Float16:
2267     return Context.HalfTy;
2268   case NeonTypeFlags::Float32:
2269     return Context.FloatTy;
2270   case NeonTypeFlags::Float64:
2271     return Context.DoubleTy;
2272   case NeonTypeFlags::BFloat16:
2273     return Context.BFloat16Ty;
2274   }
2275   llvm_unreachable("Invalid NeonTypeFlag!");
2276 }
2277 
2278 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2279   // Range check SVE intrinsics that take immediate values.
2280   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2281 
2282   switch (BuiltinID) {
2283   default:
2284     return false;
2285 #define GET_SVE_IMMEDIATE_CHECK
2286 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2287 #undef GET_SVE_IMMEDIATE_CHECK
2288   }
2289 
2290   // Perform all the immediate checks for this builtin call.
2291   bool HasError = false;
2292   for (auto &I : ImmChecks) {
2293     int ArgNum, CheckTy, ElementSizeInBits;
2294     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2295 
2296     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2297 
2298     // Function that checks whether the operand (ArgNum) is an immediate
2299     // that is one of the predefined values.
2300     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2301                                    int ErrDiag) -> bool {
2302       // We can't check the value of a dependent argument.
2303       Expr *Arg = TheCall->getArg(ArgNum);
2304       if (Arg->isTypeDependent() || Arg->isValueDependent())
2305         return false;
2306 
2307       // Check constant-ness first.
2308       llvm::APSInt Imm;
2309       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2310         return true;
2311 
2312       if (!CheckImm(Imm.getSExtValue()))
2313         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2314       return false;
2315     };
2316 
2317     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2318     case SVETypeFlags::ImmCheck0_31:
2319       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2320         HasError = true;
2321       break;
2322     case SVETypeFlags::ImmCheck0_13:
2323       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2324         HasError = true;
2325       break;
2326     case SVETypeFlags::ImmCheck1_16:
2327       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2328         HasError = true;
2329       break;
2330     case SVETypeFlags::ImmCheck0_7:
2331       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2332         HasError = true;
2333       break;
2334     case SVETypeFlags::ImmCheckExtract:
2335       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2336                                       (2048 / ElementSizeInBits) - 1))
2337         HasError = true;
2338       break;
2339     case SVETypeFlags::ImmCheckShiftRight:
2340       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2341         HasError = true;
2342       break;
2343     case SVETypeFlags::ImmCheckShiftRightNarrow:
2344       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2345                                       ElementSizeInBits / 2))
2346         HasError = true;
2347       break;
2348     case SVETypeFlags::ImmCheckShiftLeft:
2349       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2350                                       ElementSizeInBits - 1))
2351         HasError = true;
2352       break;
2353     case SVETypeFlags::ImmCheckLaneIndex:
2354       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2355                                       (128 / (1 * ElementSizeInBits)) - 1))
2356         HasError = true;
2357       break;
2358     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2359       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2360                                       (128 / (2 * ElementSizeInBits)) - 1))
2361         HasError = true;
2362       break;
2363     case SVETypeFlags::ImmCheckLaneIndexDot:
2364       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2365                                       (128 / (4 * ElementSizeInBits)) - 1))
2366         HasError = true;
2367       break;
2368     case SVETypeFlags::ImmCheckComplexRot90_270:
2369       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2370                               diag::err_rotation_argument_to_cadd))
2371         HasError = true;
2372       break;
2373     case SVETypeFlags::ImmCheckComplexRotAll90:
2374       if (CheckImmediateInSet(
2375               [](int64_t V) {
2376                 return V == 0 || V == 90 || V == 180 || V == 270;
2377               },
2378               diag::err_rotation_argument_to_cmla))
2379         HasError = true;
2380       break;
2381     case SVETypeFlags::ImmCheck0_1:
2382       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2383         HasError = true;
2384       break;
2385     case SVETypeFlags::ImmCheck0_2:
2386       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2387         HasError = true;
2388       break;
2389     case SVETypeFlags::ImmCheck0_3:
2390       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2391         HasError = true;
2392       break;
2393     }
2394   }
2395 
2396   return HasError;
2397 }
2398 
2399 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2400                                         unsigned BuiltinID, CallExpr *TheCall) {
2401   llvm::APSInt Result;
2402   uint64_t mask = 0;
2403   unsigned TV = 0;
2404   int PtrArgNum = -1;
2405   bool HasConstPtr = false;
2406   switch (BuiltinID) {
2407 #define GET_NEON_OVERLOAD_CHECK
2408 #include "clang/Basic/arm_neon.inc"
2409 #include "clang/Basic/arm_fp16.inc"
2410 #undef GET_NEON_OVERLOAD_CHECK
2411   }
2412 
2413   // For NEON intrinsics which are overloaded on vector element type, validate
2414   // the immediate which specifies which variant to emit.
2415   unsigned ImmArg = TheCall->getNumArgs()-1;
2416   if (mask) {
2417     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2418       return true;
2419 
2420     TV = Result.getLimitedValue(64);
2421     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2422       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2423              << TheCall->getArg(ImmArg)->getSourceRange();
2424   }
2425 
2426   if (PtrArgNum >= 0) {
2427     // Check that pointer arguments have the specified type.
2428     Expr *Arg = TheCall->getArg(PtrArgNum);
2429     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2430       Arg = ICE->getSubExpr();
2431     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2432     QualType RHSTy = RHS.get()->getType();
2433 
2434     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2435     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2436                           Arch == llvm::Triple::aarch64_32 ||
2437                           Arch == llvm::Triple::aarch64_be;
2438     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2439     QualType EltTy =
2440         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2441     if (HasConstPtr)
2442       EltTy = EltTy.withConst();
2443     QualType LHSTy = Context.getPointerType(EltTy);
2444     AssignConvertType ConvTy;
2445     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2446     if (RHS.isInvalid())
2447       return true;
2448     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2449                                  RHS.get(), AA_Assigning))
2450       return true;
2451   }
2452 
2453   // For NEON intrinsics which take an immediate value as part of the
2454   // instruction, range check them here.
2455   unsigned i = 0, l = 0, u = 0;
2456   switch (BuiltinID) {
2457   default:
2458     return false;
2459   #define GET_NEON_IMMEDIATE_CHECK
2460   #include "clang/Basic/arm_neon.inc"
2461   #include "clang/Basic/arm_fp16.inc"
2462   #undef GET_NEON_IMMEDIATE_CHECK
2463   }
2464 
2465   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2466 }
2467 
2468 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2469   switch (BuiltinID) {
2470   default:
2471     return false;
2472   #include "clang/Basic/arm_mve_builtin_sema.inc"
2473   }
2474 }
2475 
2476 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2477                                        CallExpr *TheCall) {
2478   bool Err = false;
2479   switch (BuiltinID) {
2480   default:
2481     return false;
2482 #include "clang/Basic/arm_cde_builtin_sema.inc"
2483   }
2484 
2485   if (Err)
2486     return true;
2487 
2488   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2489 }
2490 
2491 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2492                                         const Expr *CoprocArg, bool WantCDE) {
2493   if (isConstantEvaluated())
2494     return false;
2495 
2496   // We can't check the value of a dependent argument.
2497   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2498     return false;
2499 
2500   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2501   int64_t CoprocNo = CoprocNoAP.getExtValue();
2502   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2503 
2504   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2505   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2506 
2507   if (IsCDECoproc != WantCDE)
2508     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2509            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2510 
2511   return false;
2512 }
2513 
2514 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2515                                         unsigned MaxWidth) {
2516   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2517           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2518           BuiltinID == ARM::BI__builtin_arm_strex ||
2519           BuiltinID == ARM::BI__builtin_arm_stlex ||
2520           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2521           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2522           BuiltinID == AArch64::BI__builtin_arm_strex ||
2523           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2524          "unexpected ARM builtin");
2525   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2526                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2527                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2528                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2529 
2530   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2531 
2532   // Ensure that we have the proper number of arguments.
2533   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2534     return true;
2535 
2536   // Inspect the pointer argument of the atomic builtin.  This should always be
2537   // a pointer type, whose element is an integral scalar or pointer type.
2538   // Because it is a pointer type, we don't have to worry about any implicit
2539   // casts here.
2540   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2541   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2542   if (PointerArgRes.isInvalid())
2543     return true;
2544   PointerArg = PointerArgRes.get();
2545 
2546   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2547   if (!pointerType) {
2548     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2549         << PointerArg->getType() << PointerArg->getSourceRange();
2550     return true;
2551   }
2552 
2553   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2554   // task is to insert the appropriate casts into the AST. First work out just
2555   // what the appropriate type is.
2556   QualType ValType = pointerType->getPointeeType();
2557   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2558   if (IsLdrex)
2559     AddrType.addConst();
2560 
2561   // Issue a warning if the cast is dodgy.
2562   CastKind CastNeeded = CK_NoOp;
2563   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2564     CastNeeded = CK_BitCast;
2565     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2566         << PointerArg->getType() << Context.getPointerType(AddrType)
2567         << AA_Passing << PointerArg->getSourceRange();
2568   }
2569 
2570   // Finally, do the cast and replace the argument with the corrected version.
2571   AddrType = Context.getPointerType(AddrType);
2572   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2573   if (PointerArgRes.isInvalid())
2574     return true;
2575   PointerArg = PointerArgRes.get();
2576 
2577   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2578 
2579   // In general, we allow ints, floats and pointers to be loaded and stored.
2580   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2581       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2582     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2583         << PointerArg->getType() << PointerArg->getSourceRange();
2584     return true;
2585   }
2586 
2587   // But ARM doesn't have instructions to deal with 128-bit versions.
2588   if (Context.getTypeSize(ValType) > MaxWidth) {
2589     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2590     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2591         << PointerArg->getType() << PointerArg->getSourceRange();
2592     return true;
2593   }
2594 
2595   switch (ValType.getObjCLifetime()) {
2596   case Qualifiers::OCL_None:
2597   case Qualifiers::OCL_ExplicitNone:
2598     // okay
2599     break;
2600 
2601   case Qualifiers::OCL_Weak:
2602   case Qualifiers::OCL_Strong:
2603   case Qualifiers::OCL_Autoreleasing:
2604     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2605         << ValType << PointerArg->getSourceRange();
2606     return true;
2607   }
2608 
2609   if (IsLdrex) {
2610     TheCall->setType(ValType);
2611     return false;
2612   }
2613 
2614   // Initialize the argument to be stored.
2615   ExprResult ValArg = TheCall->getArg(0);
2616   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2617       Context, ValType, /*consume*/ false);
2618   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2619   if (ValArg.isInvalid())
2620     return true;
2621   TheCall->setArg(0, ValArg.get());
2622 
2623   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2624   // but the custom checker bypasses all default analysis.
2625   TheCall->setType(Context.IntTy);
2626   return false;
2627 }
2628 
2629 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2630                                        CallExpr *TheCall) {
2631   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2632       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2633       BuiltinID == ARM::BI__builtin_arm_strex ||
2634       BuiltinID == ARM::BI__builtin_arm_stlex) {
2635     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2636   }
2637 
2638   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2639     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2640       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2641   }
2642 
2643   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2644       BuiltinID == ARM::BI__builtin_arm_wsr64)
2645     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2646 
2647   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2648       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2649       BuiltinID == ARM::BI__builtin_arm_wsr ||
2650       BuiltinID == ARM::BI__builtin_arm_wsrp)
2651     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2652 
2653   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2654     return true;
2655   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2656     return true;
2657   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2658     return true;
2659 
2660   // For intrinsics which take an immediate value as part of the instruction,
2661   // range check them here.
2662   // FIXME: VFP Intrinsics should error if VFP not present.
2663   switch (BuiltinID) {
2664   default: return false;
2665   case ARM::BI__builtin_arm_ssat:
2666     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2667   case ARM::BI__builtin_arm_usat:
2668     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2669   case ARM::BI__builtin_arm_ssat16:
2670     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2671   case ARM::BI__builtin_arm_usat16:
2672     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2673   case ARM::BI__builtin_arm_vcvtr_f:
2674   case ARM::BI__builtin_arm_vcvtr_d:
2675     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2676   case ARM::BI__builtin_arm_dmb:
2677   case ARM::BI__builtin_arm_dsb:
2678   case ARM::BI__builtin_arm_isb:
2679   case ARM::BI__builtin_arm_dbg:
2680     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2681   case ARM::BI__builtin_arm_cdp:
2682   case ARM::BI__builtin_arm_cdp2:
2683   case ARM::BI__builtin_arm_mcr:
2684   case ARM::BI__builtin_arm_mcr2:
2685   case ARM::BI__builtin_arm_mrc:
2686   case ARM::BI__builtin_arm_mrc2:
2687   case ARM::BI__builtin_arm_mcrr:
2688   case ARM::BI__builtin_arm_mcrr2:
2689   case ARM::BI__builtin_arm_mrrc:
2690   case ARM::BI__builtin_arm_mrrc2:
2691   case ARM::BI__builtin_arm_ldc:
2692   case ARM::BI__builtin_arm_ldcl:
2693   case ARM::BI__builtin_arm_ldc2:
2694   case ARM::BI__builtin_arm_ldc2l:
2695   case ARM::BI__builtin_arm_stc:
2696   case ARM::BI__builtin_arm_stcl:
2697   case ARM::BI__builtin_arm_stc2:
2698   case ARM::BI__builtin_arm_stc2l:
2699     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2700            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2701                                         /*WantCDE*/ false);
2702   }
2703 }
2704 
2705 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2706                                            unsigned BuiltinID,
2707                                            CallExpr *TheCall) {
2708   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2709       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2710       BuiltinID == AArch64::BI__builtin_arm_strex ||
2711       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2712     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2713   }
2714 
2715   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2716     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2717       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2718       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2719       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2720   }
2721 
2722   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2723       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2724     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2725 
2726   // Memory Tagging Extensions (MTE) Intrinsics
2727   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2728       BuiltinID == AArch64::BI__builtin_arm_addg ||
2729       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2730       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2731       BuiltinID == AArch64::BI__builtin_arm_stg ||
2732       BuiltinID == AArch64::BI__builtin_arm_subp) {
2733     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2734   }
2735 
2736   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2737       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2738       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2739       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2740     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2741 
2742   // Only check the valid encoding range. Any constant in this range would be
2743   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2744   // an exception for incorrect registers. This matches MSVC behavior.
2745   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2746       BuiltinID == AArch64::BI_WriteStatusReg)
2747     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2748 
2749   if (BuiltinID == AArch64::BI__getReg)
2750     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2751 
2752   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2753     return true;
2754 
2755   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2756     return true;
2757 
2758   // For intrinsics which take an immediate value as part of the instruction,
2759   // range check them here.
2760   unsigned i = 0, l = 0, u = 0;
2761   switch (BuiltinID) {
2762   default: return false;
2763   case AArch64::BI__builtin_arm_dmb:
2764   case AArch64::BI__builtin_arm_dsb:
2765   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2766   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2767   }
2768 
2769   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2770 }
2771 
2772 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2773   if (Arg->getType()->getAsPlaceholderType())
2774     return false;
2775 
2776   // The first argument needs to be a record field access.
2777   // If it is an array element access, we delay decision
2778   // to BPF backend to check whether the access is a
2779   // field access or not.
2780   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2781           isa<MemberExpr>(Arg->IgnoreParens()) ||
2782           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2783 }
2784 
2785 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2786                             QualType VectorTy, QualType EltTy) {
2787   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2788   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2789     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2790         << Call->getSourceRange() << VectorEltTy << EltTy;
2791     return false;
2792   }
2793   return true;
2794 }
2795 
2796 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2797   QualType ArgType = Arg->getType();
2798   if (ArgType->getAsPlaceholderType())
2799     return false;
2800 
2801   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2802   // format:
2803   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2804   //   2. <type> var;
2805   //      __builtin_preserve_type_info(var, flag);
2806   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2807       !isa<UnaryOperator>(Arg->IgnoreParens()))
2808     return false;
2809 
2810   // Typedef type.
2811   if (ArgType->getAs<TypedefType>())
2812     return true;
2813 
2814   // Record type or Enum type.
2815   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2816   if (const auto *RT = Ty->getAs<RecordType>()) {
2817     if (!RT->getDecl()->getDeclName().isEmpty())
2818       return true;
2819   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2820     if (!ET->getDecl()->getDeclName().isEmpty())
2821       return true;
2822   }
2823 
2824   return false;
2825 }
2826 
2827 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2828   QualType ArgType = Arg->getType();
2829   if (ArgType->getAsPlaceholderType())
2830     return false;
2831 
2832   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2833   // format:
2834   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2835   //                                 flag);
2836   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2837   if (!UO)
2838     return false;
2839 
2840   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2841   if (!CE)
2842     return false;
2843   if (CE->getCastKind() != CK_IntegralToPointer &&
2844       CE->getCastKind() != CK_NullToPointer)
2845     return false;
2846 
2847   // The integer must be from an EnumConstantDecl.
2848   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2849   if (!DR)
2850     return false;
2851 
2852   const EnumConstantDecl *Enumerator =
2853       dyn_cast<EnumConstantDecl>(DR->getDecl());
2854   if (!Enumerator)
2855     return false;
2856 
2857   // The type must be EnumType.
2858   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2859   const auto *ET = Ty->getAs<EnumType>();
2860   if (!ET)
2861     return false;
2862 
2863   // The enum value must be supported.
2864   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2865 }
2866 
2867 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2868                                        CallExpr *TheCall) {
2869   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2870           BuiltinID == BPF::BI__builtin_btf_type_id ||
2871           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2872           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2873          "unexpected BPF builtin");
2874 
2875   if (checkArgCount(*this, TheCall, 2))
2876     return true;
2877 
2878   // The second argument needs to be a constant int
2879   Expr *Arg = TheCall->getArg(1);
2880   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2881   diag::kind kind;
2882   if (!Value) {
2883     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2884       kind = diag::err_preserve_field_info_not_const;
2885     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2886       kind = diag::err_btf_type_id_not_const;
2887     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2888       kind = diag::err_preserve_type_info_not_const;
2889     else
2890       kind = diag::err_preserve_enum_value_not_const;
2891     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2892     return true;
2893   }
2894 
2895   // The first argument
2896   Arg = TheCall->getArg(0);
2897   bool InvalidArg = false;
2898   bool ReturnUnsignedInt = true;
2899   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2900     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2901       InvalidArg = true;
2902       kind = diag::err_preserve_field_info_not_field;
2903     }
2904   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2905     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2906       InvalidArg = true;
2907       kind = diag::err_preserve_type_info_invalid;
2908     }
2909   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2910     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2911       InvalidArg = true;
2912       kind = diag::err_preserve_enum_value_invalid;
2913     }
2914     ReturnUnsignedInt = false;
2915   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2916     ReturnUnsignedInt = false;
2917   }
2918 
2919   if (InvalidArg) {
2920     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2921     return true;
2922   }
2923 
2924   if (ReturnUnsignedInt)
2925     TheCall->setType(Context.UnsignedIntTy);
2926   else
2927     TheCall->setType(Context.UnsignedLongTy);
2928   return false;
2929 }
2930 
2931 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2932   struct ArgInfo {
2933     uint8_t OpNum;
2934     bool IsSigned;
2935     uint8_t BitWidth;
2936     uint8_t Align;
2937   };
2938   struct BuiltinInfo {
2939     unsigned BuiltinID;
2940     ArgInfo Infos[2];
2941   };
2942 
2943   static BuiltinInfo Infos[] = {
2944     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2945     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2946     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2947     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2948     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2949     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2950     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2951     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2952     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2953     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2954     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2955 
2956     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2959     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2960     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2961     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2962     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2964     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2965     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2966     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2967 
2968     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2969     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2970     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2971     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2972     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2973     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2974     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2975     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2976     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2977     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2978     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2979     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2980     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2981     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2982     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2983     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2984     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2985     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2986     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2987     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2988     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2989     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2990     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2991     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2992     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2993     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2994     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2995     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2996     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2997     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2998     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2999     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3000     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3001     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3002     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3003     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3004     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3005     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3006     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3007     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3008     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3009     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3010     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3011     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3012     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3013     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3014     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3015     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3016     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3017     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3018     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3019     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3020                                                       {{ 1, false, 6,  0 }} },
3021     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3022     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3023     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3024     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3025     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3026     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3027     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3028                                                       {{ 1, false, 5,  0 }} },
3029     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3030     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3031     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3032     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3033     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3034     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3035                                                        { 2, false, 5,  0 }} },
3036     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3037                                                        { 2, false, 6,  0 }} },
3038     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3039                                                        { 3, false, 5,  0 }} },
3040     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3041                                                        { 3, false, 6,  0 }} },
3042     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3043     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3044     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3045     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3046     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3047     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3048     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3049     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3050     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3051     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3052     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3053     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3054     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3055     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3056     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3057     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3058                                                       {{ 2, false, 4,  0 },
3059                                                        { 3, false, 5,  0 }} },
3060     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3061                                                       {{ 2, false, 4,  0 },
3062                                                        { 3, false, 5,  0 }} },
3063     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3064                                                       {{ 2, false, 4,  0 },
3065                                                        { 3, false, 5,  0 }} },
3066     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3067                                                       {{ 2, false, 4,  0 },
3068                                                        { 3, false, 5,  0 }} },
3069     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3070     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3071     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3072     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3073     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3074     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3075     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3076     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3077     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3078     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3079     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3080                                                        { 2, false, 5,  0 }} },
3081     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3082                                                        { 2, false, 6,  0 }} },
3083     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3084     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3085     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3086     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3087     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3088     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3089     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3090     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3091     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3092                                                       {{ 1, false, 4,  0 }} },
3093     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3094     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3095                                                       {{ 1, false, 4,  0 }} },
3096     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3097     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3098     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3099     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3100     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3101     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3102     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3103     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3104     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3105     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3106     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3107     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3108     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3109     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3110     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3111     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3112     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3113     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3114     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3115     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3116                                                       {{ 3, false, 1,  0 }} },
3117     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3118     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3119     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3120     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3121                                                       {{ 3, false, 1,  0 }} },
3122     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3123     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3124     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3125     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3126                                                       {{ 3, false, 1,  0 }} },
3127   };
3128 
3129   // Use a dynamically initialized static to sort the table exactly once on
3130   // first run.
3131   static const bool SortOnce =
3132       (llvm::sort(Infos,
3133                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3134                    return LHS.BuiltinID < RHS.BuiltinID;
3135                  }),
3136        true);
3137   (void)SortOnce;
3138 
3139   const BuiltinInfo *F = llvm::partition_point(
3140       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3141   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3142     return false;
3143 
3144   bool Error = false;
3145 
3146   for (const ArgInfo &A : F->Infos) {
3147     // Ignore empty ArgInfo elements.
3148     if (A.BitWidth == 0)
3149       continue;
3150 
3151     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3152     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3153     if (!A.Align) {
3154       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3155     } else {
3156       unsigned M = 1 << A.Align;
3157       Min *= M;
3158       Max *= M;
3159       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3160       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3161     }
3162   }
3163   return Error;
3164 }
3165 
3166 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3167                                            CallExpr *TheCall) {
3168   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3169 }
3170 
3171 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3172                                         unsigned BuiltinID, CallExpr *TheCall) {
3173   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3174          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3175 }
3176 
3177 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3178                                CallExpr *TheCall) {
3179 
3180   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3181       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3182     if (!TI.hasFeature("dsp"))
3183       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3184   }
3185 
3186   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3187       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3188     if (!TI.hasFeature("dspr2"))
3189       return Diag(TheCall->getBeginLoc(),
3190                   diag::err_mips_builtin_requires_dspr2);
3191   }
3192 
3193   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3194       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3195     if (!TI.hasFeature("msa"))
3196       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3197   }
3198 
3199   return false;
3200 }
3201 
3202 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3203 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3204 // ordering for DSP is unspecified. MSA is ordered by the data format used
3205 // by the underlying instruction i.e., df/m, df/n and then by size.
3206 //
3207 // FIXME: The size tests here should instead be tablegen'd along with the
3208 //        definitions from include/clang/Basic/BuiltinsMips.def.
3209 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3210 //        be too.
3211 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3212   unsigned i = 0, l = 0, u = 0, m = 0;
3213   switch (BuiltinID) {
3214   default: return false;
3215   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3216   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3217   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3218   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3219   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3220   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3221   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3222   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3223   // df/m field.
3224   // These intrinsics take an unsigned 3 bit immediate.
3225   case Mips::BI__builtin_msa_bclri_b:
3226   case Mips::BI__builtin_msa_bnegi_b:
3227   case Mips::BI__builtin_msa_bseti_b:
3228   case Mips::BI__builtin_msa_sat_s_b:
3229   case Mips::BI__builtin_msa_sat_u_b:
3230   case Mips::BI__builtin_msa_slli_b:
3231   case Mips::BI__builtin_msa_srai_b:
3232   case Mips::BI__builtin_msa_srari_b:
3233   case Mips::BI__builtin_msa_srli_b:
3234   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3235   case Mips::BI__builtin_msa_binsli_b:
3236   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3237   // These intrinsics take an unsigned 4 bit immediate.
3238   case Mips::BI__builtin_msa_bclri_h:
3239   case Mips::BI__builtin_msa_bnegi_h:
3240   case Mips::BI__builtin_msa_bseti_h:
3241   case Mips::BI__builtin_msa_sat_s_h:
3242   case Mips::BI__builtin_msa_sat_u_h:
3243   case Mips::BI__builtin_msa_slli_h:
3244   case Mips::BI__builtin_msa_srai_h:
3245   case Mips::BI__builtin_msa_srari_h:
3246   case Mips::BI__builtin_msa_srli_h:
3247   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3248   case Mips::BI__builtin_msa_binsli_h:
3249   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3250   // These intrinsics take an unsigned 5 bit immediate.
3251   // The first block of intrinsics actually have an unsigned 5 bit field,
3252   // not a df/n field.
3253   case Mips::BI__builtin_msa_cfcmsa:
3254   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3255   case Mips::BI__builtin_msa_clei_u_b:
3256   case Mips::BI__builtin_msa_clei_u_h:
3257   case Mips::BI__builtin_msa_clei_u_w:
3258   case Mips::BI__builtin_msa_clei_u_d:
3259   case Mips::BI__builtin_msa_clti_u_b:
3260   case Mips::BI__builtin_msa_clti_u_h:
3261   case Mips::BI__builtin_msa_clti_u_w:
3262   case Mips::BI__builtin_msa_clti_u_d:
3263   case Mips::BI__builtin_msa_maxi_u_b:
3264   case Mips::BI__builtin_msa_maxi_u_h:
3265   case Mips::BI__builtin_msa_maxi_u_w:
3266   case Mips::BI__builtin_msa_maxi_u_d:
3267   case Mips::BI__builtin_msa_mini_u_b:
3268   case Mips::BI__builtin_msa_mini_u_h:
3269   case Mips::BI__builtin_msa_mini_u_w:
3270   case Mips::BI__builtin_msa_mini_u_d:
3271   case Mips::BI__builtin_msa_addvi_b:
3272   case Mips::BI__builtin_msa_addvi_h:
3273   case Mips::BI__builtin_msa_addvi_w:
3274   case Mips::BI__builtin_msa_addvi_d:
3275   case Mips::BI__builtin_msa_bclri_w:
3276   case Mips::BI__builtin_msa_bnegi_w:
3277   case Mips::BI__builtin_msa_bseti_w:
3278   case Mips::BI__builtin_msa_sat_s_w:
3279   case Mips::BI__builtin_msa_sat_u_w:
3280   case Mips::BI__builtin_msa_slli_w:
3281   case Mips::BI__builtin_msa_srai_w:
3282   case Mips::BI__builtin_msa_srari_w:
3283   case Mips::BI__builtin_msa_srli_w:
3284   case Mips::BI__builtin_msa_srlri_w:
3285   case Mips::BI__builtin_msa_subvi_b:
3286   case Mips::BI__builtin_msa_subvi_h:
3287   case Mips::BI__builtin_msa_subvi_w:
3288   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3289   case Mips::BI__builtin_msa_binsli_w:
3290   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3291   // These intrinsics take an unsigned 6 bit immediate.
3292   case Mips::BI__builtin_msa_bclri_d:
3293   case Mips::BI__builtin_msa_bnegi_d:
3294   case Mips::BI__builtin_msa_bseti_d:
3295   case Mips::BI__builtin_msa_sat_s_d:
3296   case Mips::BI__builtin_msa_sat_u_d:
3297   case Mips::BI__builtin_msa_slli_d:
3298   case Mips::BI__builtin_msa_srai_d:
3299   case Mips::BI__builtin_msa_srari_d:
3300   case Mips::BI__builtin_msa_srli_d:
3301   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3302   case Mips::BI__builtin_msa_binsli_d:
3303   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3304   // These intrinsics take a signed 5 bit immediate.
3305   case Mips::BI__builtin_msa_ceqi_b:
3306   case Mips::BI__builtin_msa_ceqi_h:
3307   case Mips::BI__builtin_msa_ceqi_w:
3308   case Mips::BI__builtin_msa_ceqi_d:
3309   case Mips::BI__builtin_msa_clti_s_b:
3310   case Mips::BI__builtin_msa_clti_s_h:
3311   case Mips::BI__builtin_msa_clti_s_w:
3312   case Mips::BI__builtin_msa_clti_s_d:
3313   case Mips::BI__builtin_msa_clei_s_b:
3314   case Mips::BI__builtin_msa_clei_s_h:
3315   case Mips::BI__builtin_msa_clei_s_w:
3316   case Mips::BI__builtin_msa_clei_s_d:
3317   case Mips::BI__builtin_msa_maxi_s_b:
3318   case Mips::BI__builtin_msa_maxi_s_h:
3319   case Mips::BI__builtin_msa_maxi_s_w:
3320   case Mips::BI__builtin_msa_maxi_s_d:
3321   case Mips::BI__builtin_msa_mini_s_b:
3322   case Mips::BI__builtin_msa_mini_s_h:
3323   case Mips::BI__builtin_msa_mini_s_w:
3324   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3325   // These intrinsics take an unsigned 8 bit immediate.
3326   case Mips::BI__builtin_msa_andi_b:
3327   case Mips::BI__builtin_msa_nori_b:
3328   case Mips::BI__builtin_msa_ori_b:
3329   case Mips::BI__builtin_msa_shf_b:
3330   case Mips::BI__builtin_msa_shf_h:
3331   case Mips::BI__builtin_msa_shf_w:
3332   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3333   case Mips::BI__builtin_msa_bseli_b:
3334   case Mips::BI__builtin_msa_bmnzi_b:
3335   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3336   // df/n format
3337   // These intrinsics take an unsigned 4 bit immediate.
3338   case Mips::BI__builtin_msa_copy_s_b:
3339   case Mips::BI__builtin_msa_copy_u_b:
3340   case Mips::BI__builtin_msa_insve_b:
3341   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3342   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3343   // These intrinsics take an unsigned 3 bit immediate.
3344   case Mips::BI__builtin_msa_copy_s_h:
3345   case Mips::BI__builtin_msa_copy_u_h:
3346   case Mips::BI__builtin_msa_insve_h:
3347   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3348   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3349   // These intrinsics take an unsigned 2 bit immediate.
3350   case Mips::BI__builtin_msa_copy_s_w:
3351   case Mips::BI__builtin_msa_copy_u_w:
3352   case Mips::BI__builtin_msa_insve_w:
3353   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3354   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3355   // These intrinsics take an unsigned 1 bit immediate.
3356   case Mips::BI__builtin_msa_copy_s_d:
3357   case Mips::BI__builtin_msa_copy_u_d:
3358   case Mips::BI__builtin_msa_insve_d:
3359   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3360   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3361   // Memory offsets and immediate loads.
3362   // These intrinsics take a signed 10 bit immediate.
3363   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3364   case Mips::BI__builtin_msa_ldi_h:
3365   case Mips::BI__builtin_msa_ldi_w:
3366   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3367   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3368   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3369   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3370   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3371   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3372   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3373   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3374   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3375   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3376   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3377   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3378   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3379   }
3380 
3381   if (!m)
3382     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3383 
3384   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3385          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3386 }
3387 
3388 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3389 /// advancing the pointer over the consumed characters. The decoded type is
3390 /// returned. If the decoded type represents a constant integer with a
3391 /// constraint on its value then Mask is set to that value. The type descriptors
3392 /// used in Str are specific to PPC MMA builtins and are documented in the file
3393 /// defining the PPC builtins.
3394 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3395                                         unsigned &Mask) {
3396   bool RequireICE = false;
3397   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3398   switch (*Str++) {
3399   case 'V':
3400     return Context.getVectorType(Context.UnsignedCharTy, 16,
3401                                  VectorType::VectorKind::AltiVecVector);
3402   case 'i': {
3403     char *End;
3404     unsigned size = strtoul(Str, &End, 10);
3405     assert(End != Str && "Missing constant parameter constraint");
3406     Str = End;
3407     Mask = size;
3408     return Context.IntTy;
3409   }
3410   case 'W': {
3411     char *End;
3412     unsigned size = strtoul(Str, &End, 10);
3413     assert(End != Str && "Missing PowerPC MMA type size");
3414     Str = End;
3415     QualType Type;
3416     switch (size) {
3417   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3418     case size: Type = Context.Id##Ty; break;
3419   #include "clang/Basic/PPCTypes.def"
3420     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3421     }
3422     bool CheckVectorArgs = false;
3423     while (!CheckVectorArgs) {
3424       switch (*Str++) {
3425       case '*':
3426         Type = Context.getPointerType(Type);
3427         break;
3428       case 'C':
3429         Type = Type.withConst();
3430         break;
3431       default:
3432         CheckVectorArgs = true;
3433         --Str;
3434         break;
3435       }
3436     }
3437     return Type;
3438   }
3439   default:
3440     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3441   }
3442 }
3443 
3444 static bool isPPC_64Builtin(unsigned BuiltinID) {
3445   // These builtins only work on PPC 64bit targets.
3446   switch (BuiltinID) {
3447   case PPC::BI__builtin_divde:
3448   case PPC::BI__builtin_divdeu:
3449   case PPC::BI__builtin_bpermd:
3450   case PPC::BI__builtin_ppc_ldarx:
3451   case PPC::BI__builtin_ppc_stdcx:
3452   case PPC::BI__builtin_ppc_tdw:
3453   case PPC::BI__builtin_ppc_trapd:
3454   case PPC::BI__builtin_ppc_cmpeqb:
3455   case PPC::BI__builtin_ppc_setb:
3456   case PPC::BI__builtin_ppc_mulhd:
3457   case PPC::BI__builtin_ppc_mulhdu:
3458   case PPC::BI__builtin_ppc_maddhd:
3459   case PPC::BI__builtin_ppc_maddhdu:
3460   case PPC::BI__builtin_ppc_maddld:
3461   case PPC::BI__builtin_ppc_load8r:
3462   case PPC::BI__builtin_ppc_store8r:
3463   case PPC::BI__builtin_ppc_insert_exp:
3464   case PPC::BI__builtin_ppc_extract_sig:
3465   case PPC::BI__builtin_ppc_addex:
3466   case PPC::BI__builtin_darn:
3467   case PPC::BI__builtin_darn_raw:
3468   case PPC::BI__builtin_ppc_compare_and_swaplp:
3469   case PPC::BI__builtin_ppc_fetch_and_addlp:
3470   case PPC::BI__builtin_ppc_fetch_and_andlp:
3471   case PPC::BI__builtin_ppc_fetch_and_orlp:
3472   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3473     return true;
3474   }
3475   return false;
3476 }
3477 
3478 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3479                              StringRef FeatureToCheck, unsigned DiagID,
3480                              StringRef DiagArg = "") {
3481   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3482     return false;
3483 
3484   if (DiagArg.empty())
3485     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3486   else
3487     S.Diag(TheCall->getBeginLoc(), DiagID)
3488         << DiagArg << TheCall->getSourceRange();
3489 
3490   return true;
3491 }
3492 
3493 /// Returns true if the argument consists of one contiguous run of 1s with any
3494 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3495 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3496 /// since all 1s are not contiguous.
3497 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3498   llvm::APSInt Result;
3499   // We can't check the value of a dependent argument.
3500   Expr *Arg = TheCall->getArg(ArgNum);
3501   if (Arg->isTypeDependent() || Arg->isValueDependent())
3502     return false;
3503 
3504   // Check constant-ness first.
3505   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3506     return true;
3507 
3508   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3509   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3510     return false;
3511 
3512   return Diag(TheCall->getBeginLoc(),
3513               diag::err_argument_not_contiguous_bit_field)
3514          << ArgNum << Arg->getSourceRange();
3515 }
3516 
3517 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3518                                        CallExpr *TheCall) {
3519   unsigned i = 0, l = 0, u = 0;
3520   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3521   llvm::APSInt Result;
3522 
3523   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3524     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3525            << TheCall->getSourceRange();
3526 
3527   switch (BuiltinID) {
3528   default: return false;
3529   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3530   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3531     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3532            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3533   case PPC::BI__builtin_altivec_dss:
3534     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3535   case PPC::BI__builtin_tbegin:
3536   case PPC::BI__builtin_tend:
3537     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3538            SemaFeatureCheck(*this, TheCall, "htm",
3539                             diag::err_ppc_builtin_requires_htm);
3540   case PPC::BI__builtin_tsr:
3541     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3542            SemaFeatureCheck(*this, TheCall, "htm",
3543                             diag::err_ppc_builtin_requires_htm);
3544   case PPC::BI__builtin_tabortwc:
3545   case PPC::BI__builtin_tabortdc:
3546     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3547            SemaFeatureCheck(*this, TheCall, "htm",
3548                             diag::err_ppc_builtin_requires_htm);
3549   case PPC::BI__builtin_tabortwci:
3550   case PPC::BI__builtin_tabortdci:
3551     return SemaFeatureCheck(*this, TheCall, "htm",
3552                             diag::err_ppc_builtin_requires_htm) ||
3553            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3554             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3555   case PPC::BI__builtin_tabort:
3556   case PPC::BI__builtin_tcheck:
3557   case PPC::BI__builtin_treclaim:
3558   case PPC::BI__builtin_trechkpt:
3559   case PPC::BI__builtin_tendall:
3560   case PPC::BI__builtin_tresume:
3561   case PPC::BI__builtin_tsuspend:
3562   case PPC::BI__builtin_get_texasr:
3563   case PPC::BI__builtin_get_texasru:
3564   case PPC::BI__builtin_get_tfhar:
3565   case PPC::BI__builtin_get_tfiar:
3566   case PPC::BI__builtin_set_texasr:
3567   case PPC::BI__builtin_set_texasru:
3568   case PPC::BI__builtin_set_tfhar:
3569   case PPC::BI__builtin_set_tfiar:
3570   case PPC::BI__builtin_ttest:
3571     return SemaFeatureCheck(*this, TheCall, "htm",
3572                             diag::err_ppc_builtin_requires_htm);
3573   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3574   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3575   // extended double representation.
3576   case PPC::BI__builtin_unpack_longdouble:
3577     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3578       return true;
3579     LLVM_FALLTHROUGH;
3580   case PPC::BI__builtin_pack_longdouble:
3581     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3582       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3583              << "ibmlongdouble";
3584     return false;
3585   case PPC::BI__builtin_altivec_dst:
3586   case PPC::BI__builtin_altivec_dstt:
3587   case PPC::BI__builtin_altivec_dstst:
3588   case PPC::BI__builtin_altivec_dststt:
3589     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3590   case PPC::BI__builtin_vsx_xxpermdi:
3591   case PPC::BI__builtin_vsx_xxsldwi:
3592     return SemaBuiltinVSX(TheCall);
3593   case PPC::BI__builtin_divwe:
3594   case PPC::BI__builtin_divweu:
3595   case PPC::BI__builtin_divde:
3596   case PPC::BI__builtin_divdeu:
3597     return SemaFeatureCheck(*this, TheCall, "extdiv",
3598                             diag::err_ppc_builtin_only_on_arch, "7");
3599   case PPC::BI__builtin_bpermd:
3600     return SemaFeatureCheck(*this, TheCall, "bpermd",
3601                             diag::err_ppc_builtin_only_on_arch, "7");
3602   case PPC::BI__builtin_unpack_vector_int128:
3603     return SemaFeatureCheck(*this, TheCall, "vsx",
3604                             diag::err_ppc_builtin_only_on_arch, "7") ||
3605            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3606   case PPC::BI__builtin_pack_vector_int128:
3607     return SemaFeatureCheck(*this, TheCall, "vsx",
3608                             diag::err_ppc_builtin_only_on_arch, "7");
3609   case PPC::BI__builtin_altivec_vgnb:
3610      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3611   case PPC::BI__builtin_altivec_vec_replace_elt:
3612   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3613     QualType VecTy = TheCall->getArg(0)->getType();
3614     QualType EltTy = TheCall->getArg(1)->getType();
3615     unsigned Width = Context.getIntWidth(EltTy);
3616     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3617            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3618   }
3619   case PPC::BI__builtin_vsx_xxeval:
3620      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3621   case PPC::BI__builtin_altivec_vsldbi:
3622      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3623   case PPC::BI__builtin_altivec_vsrdbi:
3624      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3625   case PPC::BI__builtin_vsx_xxpermx:
3626      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3627   case PPC::BI__builtin_ppc_tw:
3628   case PPC::BI__builtin_ppc_tdw:
3629     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3630   case PPC::BI__builtin_ppc_cmpeqb:
3631   case PPC::BI__builtin_ppc_setb:
3632   case PPC::BI__builtin_ppc_maddhd:
3633   case PPC::BI__builtin_ppc_maddhdu:
3634   case PPC::BI__builtin_ppc_maddld:
3635     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3636                             diag::err_ppc_builtin_only_on_arch, "9");
3637   case PPC::BI__builtin_ppc_cmprb:
3638     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3639                             diag::err_ppc_builtin_only_on_arch, "9") ||
3640            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3641   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3642   // be a constant that represents a contiguous bit field.
3643   case PPC::BI__builtin_ppc_rlwnm:
3644     return SemaValueIsRunOfOnes(TheCall, 2);
3645   case PPC::BI__builtin_ppc_rlwimi:
3646   case PPC::BI__builtin_ppc_rldimi:
3647     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3648            SemaValueIsRunOfOnes(TheCall, 3);
3649   case PPC::BI__builtin_ppc_extract_exp:
3650   case PPC::BI__builtin_ppc_extract_sig:
3651   case PPC::BI__builtin_ppc_insert_exp:
3652     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3653                             diag::err_ppc_builtin_only_on_arch, "9");
3654   case PPC::BI__builtin_ppc_addex: {
3655     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3656                          diag::err_ppc_builtin_only_on_arch, "9") ||
3657         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3658       return true;
3659     // Output warning for reserved values 1 to 3.
3660     int ArgValue =
3661         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3662     if (ArgValue != 0)
3663       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3664           << ArgValue;
3665     return false;
3666   }
3667   case PPC::BI__builtin_ppc_mtfsb0:
3668   case PPC::BI__builtin_ppc_mtfsb1:
3669     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3670   case PPC::BI__builtin_ppc_mtfsf:
3671     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3672   case PPC::BI__builtin_ppc_mtfsfi:
3673     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3674            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3675   case PPC::BI__builtin_ppc_alignx:
3676     return SemaBuiltinConstantArgPower2(TheCall, 0);
3677   case PPC::BI__builtin_ppc_rdlam:
3678     return SemaValueIsRunOfOnes(TheCall, 2);
3679   case PPC::BI__builtin_ppc_icbt:
3680   case PPC::BI__builtin_ppc_sthcx:
3681   case PPC::BI__builtin_ppc_stbcx:
3682   case PPC::BI__builtin_ppc_lharx:
3683   case PPC::BI__builtin_ppc_lbarx:
3684     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3685                             diag::err_ppc_builtin_only_on_arch, "8");
3686   case PPC::BI__builtin_vsx_ldrmb:
3687   case PPC::BI__builtin_vsx_strmb:
3688     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3689                             diag::err_ppc_builtin_only_on_arch, "8") ||
3690            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3691   case PPC::BI__builtin_altivec_vcntmbb:
3692   case PPC::BI__builtin_altivec_vcntmbh:
3693   case PPC::BI__builtin_altivec_vcntmbw:
3694   case PPC::BI__builtin_altivec_vcntmbd:
3695     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3696   case PPC::BI__builtin_darn:
3697   case PPC::BI__builtin_darn_raw:
3698   case PPC::BI__builtin_darn_32:
3699     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3700                             diag::err_ppc_builtin_only_on_arch, "9");
3701   case PPC::BI__builtin_vsx_xxgenpcvbm:
3702   case PPC::BI__builtin_vsx_xxgenpcvhm:
3703   case PPC::BI__builtin_vsx_xxgenpcvwm:
3704   case PPC::BI__builtin_vsx_xxgenpcvdm:
3705     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3706   case PPC::BI__builtin_ppc_compare_exp_uo:
3707   case PPC::BI__builtin_ppc_compare_exp_lt:
3708   case PPC::BI__builtin_ppc_compare_exp_gt:
3709   case PPC::BI__builtin_ppc_compare_exp_eq:
3710     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3711                             diag::err_ppc_builtin_only_on_arch, "9") ||
3712            SemaFeatureCheck(*this, TheCall, "vsx",
3713                             diag::err_ppc_builtin_requires_vsx);
3714   case PPC::BI__builtin_ppc_test_data_class: {
3715     // Check if the first argument of the __builtin_ppc_test_data_class call is
3716     // valid. The argument must be either a 'float' or a 'double'.
3717     QualType ArgType = TheCall->getArg(0)->getType();
3718     if (ArgType != QualType(Context.FloatTy) &&
3719         ArgType != QualType(Context.DoubleTy))
3720       return Diag(TheCall->getBeginLoc(),
3721                   diag::err_ppc_invalid_test_data_class_type);
3722     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3723                             diag::err_ppc_builtin_only_on_arch, "9") ||
3724            SemaFeatureCheck(*this, TheCall, "vsx",
3725                             diag::err_ppc_builtin_requires_vsx) ||
3726            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3727   }
3728   case PPC::BI__builtin_ppc_load8r:
3729   case PPC::BI__builtin_ppc_store8r:
3730     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3731                             diag::err_ppc_builtin_only_on_arch, "7");
3732 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3733   case PPC::BI__builtin_##Name:                                                \
3734     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3735 #include "clang/Basic/BuiltinsPPC.def"
3736   }
3737   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3738 }
3739 
3740 // Check if the given type is a non-pointer PPC MMA type. This function is used
3741 // in Sema to prevent invalid uses of restricted PPC MMA types.
3742 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3743   if (Type->isPointerType() || Type->isArrayType())
3744     return false;
3745 
3746   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3747 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3748   if (false
3749 #include "clang/Basic/PPCTypes.def"
3750      ) {
3751     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3752     return true;
3753   }
3754   return false;
3755 }
3756 
3757 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3758                                           CallExpr *TheCall) {
3759   // position of memory order and scope arguments in the builtin
3760   unsigned OrderIndex, ScopeIndex;
3761   switch (BuiltinID) {
3762   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3763   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3764   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3765   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3766     OrderIndex = 2;
3767     ScopeIndex = 3;
3768     break;
3769   case AMDGPU::BI__builtin_amdgcn_fence:
3770     OrderIndex = 0;
3771     ScopeIndex = 1;
3772     break;
3773   default:
3774     return false;
3775   }
3776 
3777   ExprResult Arg = TheCall->getArg(OrderIndex);
3778   auto ArgExpr = Arg.get();
3779   Expr::EvalResult ArgResult;
3780 
3781   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3782     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3783            << ArgExpr->getType();
3784   auto Ord = ArgResult.Val.getInt().getZExtValue();
3785 
3786   // Check validity of memory ordering as per C11 / C++11's memody model.
3787   // Only fence needs check. Atomic dec/inc allow all memory orders.
3788   if (!llvm::isValidAtomicOrderingCABI(Ord))
3789     return Diag(ArgExpr->getBeginLoc(),
3790                 diag::warn_atomic_op_has_invalid_memory_order)
3791            << ArgExpr->getSourceRange();
3792   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3793   case llvm::AtomicOrderingCABI::relaxed:
3794   case llvm::AtomicOrderingCABI::consume:
3795     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3796       return Diag(ArgExpr->getBeginLoc(),
3797                   diag::warn_atomic_op_has_invalid_memory_order)
3798              << ArgExpr->getSourceRange();
3799     break;
3800   case llvm::AtomicOrderingCABI::acquire:
3801   case llvm::AtomicOrderingCABI::release:
3802   case llvm::AtomicOrderingCABI::acq_rel:
3803   case llvm::AtomicOrderingCABI::seq_cst:
3804     break;
3805   }
3806 
3807   Arg = TheCall->getArg(ScopeIndex);
3808   ArgExpr = Arg.get();
3809   Expr::EvalResult ArgResult1;
3810   // Check that sync scope is a constant literal
3811   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3812     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3813            << ArgExpr->getType();
3814 
3815   return false;
3816 }
3817 
3818 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3819   llvm::APSInt Result;
3820 
3821   // We can't check the value of a dependent argument.
3822   Expr *Arg = TheCall->getArg(ArgNum);
3823   if (Arg->isTypeDependent() || Arg->isValueDependent())
3824     return false;
3825 
3826   // Check constant-ness first.
3827   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3828     return true;
3829 
3830   int64_t Val = Result.getSExtValue();
3831   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3832     return false;
3833 
3834   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3835          << Arg->getSourceRange();
3836 }
3837 
3838 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3839                                          unsigned BuiltinID,
3840                                          CallExpr *TheCall) {
3841   // CodeGenFunction can also detect this, but this gives a better error
3842   // message.
3843   bool FeatureMissing = false;
3844   SmallVector<StringRef> ReqFeatures;
3845   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3846   Features.split(ReqFeatures, ',');
3847 
3848   // Check if each required feature is included
3849   for (StringRef F : ReqFeatures) {
3850     if (TI.hasFeature(F))
3851       continue;
3852 
3853     // If the feature is 64bit, alter the string so it will print better in
3854     // the diagnostic.
3855     if (F == "64bit")
3856       F = "RV64";
3857 
3858     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3859     F.consume_front("experimental-");
3860     std::string FeatureStr = F.str();
3861     FeatureStr[0] = std::toupper(FeatureStr[0]);
3862 
3863     // Error message
3864     FeatureMissing = true;
3865     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3866         << TheCall->getSourceRange() << StringRef(FeatureStr);
3867   }
3868 
3869   if (FeatureMissing)
3870     return true;
3871 
3872   switch (BuiltinID) {
3873   case RISCVVector::BI__builtin_rvv_vsetvli:
3874     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3875            CheckRISCVLMUL(TheCall, 2);
3876   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3877     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3878            CheckRISCVLMUL(TheCall, 1);
3879   }
3880 
3881   return false;
3882 }
3883 
3884 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3885                                            CallExpr *TheCall) {
3886   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3887     Expr *Arg = TheCall->getArg(0);
3888     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3889       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3890         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3891                << Arg->getSourceRange();
3892   }
3893 
3894   // For intrinsics which take an immediate value as part of the instruction,
3895   // range check them here.
3896   unsigned i = 0, l = 0, u = 0;
3897   switch (BuiltinID) {
3898   default: return false;
3899   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3900   case SystemZ::BI__builtin_s390_verimb:
3901   case SystemZ::BI__builtin_s390_verimh:
3902   case SystemZ::BI__builtin_s390_verimf:
3903   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3904   case SystemZ::BI__builtin_s390_vfaeb:
3905   case SystemZ::BI__builtin_s390_vfaeh:
3906   case SystemZ::BI__builtin_s390_vfaef:
3907   case SystemZ::BI__builtin_s390_vfaebs:
3908   case SystemZ::BI__builtin_s390_vfaehs:
3909   case SystemZ::BI__builtin_s390_vfaefs:
3910   case SystemZ::BI__builtin_s390_vfaezb:
3911   case SystemZ::BI__builtin_s390_vfaezh:
3912   case SystemZ::BI__builtin_s390_vfaezf:
3913   case SystemZ::BI__builtin_s390_vfaezbs:
3914   case SystemZ::BI__builtin_s390_vfaezhs:
3915   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3916   case SystemZ::BI__builtin_s390_vfisb:
3917   case SystemZ::BI__builtin_s390_vfidb:
3918     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3919            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3920   case SystemZ::BI__builtin_s390_vftcisb:
3921   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3922   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3923   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3924   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3925   case SystemZ::BI__builtin_s390_vstrcb:
3926   case SystemZ::BI__builtin_s390_vstrch:
3927   case SystemZ::BI__builtin_s390_vstrcf:
3928   case SystemZ::BI__builtin_s390_vstrczb:
3929   case SystemZ::BI__builtin_s390_vstrczh:
3930   case SystemZ::BI__builtin_s390_vstrczf:
3931   case SystemZ::BI__builtin_s390_vstrcbs:
3932   case SystemZ::BI__builtin_s390_vstrchs:
3933   case SystemZ::BI__builtin_s390_vstrcfs:
3934   case SystemZ::BI__builtin_s390_vstrczbs:
3935   case SystemZ::BI__builtin_s390_vstrczhs:
3936   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3937   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3938   case SystemZ::BI__builtin_s390_vfminsb:
3939   case SystemZ::BI__builtin_s390_vfmaxsb:
3940   case SystemZ::BI__builtin_s390_vfmindb:
3941   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3942   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3943   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3944   case SystemZ::BI__builtin_s390_vclfnhs:
3945   case SystemZ::BI__builtin_s390_vclfnls:
3946   case SystemZ::BI__builtin_s390_vcfn:
3947   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3948   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3949   }
3950   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3951 }
3952 
3953 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3954 /// This checks that the target supports __builtin_cpu_supports and
3955 /// that the string argument is constant and valid.
3956 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3957                                    CallExpr *TheCall) {
3958   Expr *Arg = TheCall->getArg(0);
3959 
3960   // Check if the argument is a string literal.
3961   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3962     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3963            << Arg->getSourceRange();
3964 
3965   // Check the contents of the string.
3966   StringRef Feature =
3967       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3968   if (!TI.validateCpuSupports(Feature))
3969     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3970            << Arg->getSourceRange();
3971   return false;
3972 }
3973 
3974 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3975 /// This checks that the target supports __builtin_cpu_is and
3976 /// that the string argument is constant and valid.
3977 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3978   Expr *Arg = TheCall->getArg(0);
3979 
3980   // Check if the argument is a string literal.
3981   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3982     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3983            << Arg->getSourceRange();
3984 
3985   // Check the contents of the string.
3986   StringRef Feature =
3987       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3988   if (!TI.validateCpuIs(Feature))
3989     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3990            << Arg->getSourceRange();
3991   return false;
3992 }
3993 
3994 // Check if the rounding mode is legal.
3995 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3996   // Indicates if this instruction has rounding control or just SAE.
3997   bool HasRC = false;
3998 
3999   unsigned ArgNum = 0;
4000   switch (BuiltinID) {
4001   default:
4002     return false;
4003   case X86::BI__builtin_ia32_vcvttsd2si32:
4004   case X86::BI__builtin_ia32_vcvttsd2si64:
4005   case X86::BI__builtin_ia32_vcvttsd2usi32:
4006   case X86::BI__builtin_ia32_vcvttsd2usi64:
4007   case X86::BI__builtin_ia32_vcvttss2si32:
4008   case X86::BI__builtin_ia32_vcvttss2si64:
4009   case X86::BI__builtin_ia32_vcvttss2usi32:
4010   case X86::BI__builtin_ia32_vcvttss2usi64:
4011   case X86::BI__builtin_ia32_vcvttsh2si32:
4012   case X86::BI__builtin_ia32_vcvttsh2si64:
4013   case X86::BI__builtin_ia32_vcvttsh2usi32:
4014   case X86::BI__builtin_ia32_vcvttsh2usi64:
4015     ArgNum = 1;
4016     break;
4017   case X86::BI__builtin_ia32_maxpd512:
4018   case X86::BI__builtin_ia32_maxps512:
4019   case X86::BI__builtin_ia32_minpd512:
4020   case X86::BI__builtin_ia32_minps512:
4021   case X86::BI__builtin_ia32_maxph512:
4022   case X86::BI__builtin_ia32_minph512:
4023     ArgNum = 2;
4024     break;
4025   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4026   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4027   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4028   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4029   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4030   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4031   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4032   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4033   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4034   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4035   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4036   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4037   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4038   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4039   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4040   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4041   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4042   case X86::BI__builtin_ia32_exp2pd_mask:
4043   case X86::BI__builtin_ia32_exp2ps_mask:
4044   case X86::BI__builtin_ia32_getexppd512_mask:
4045   case X86::BI__builtin_ia32_getexpps512_mask:
4046   case X86::BI__builtin_ia32_getexpph512_mask:
4047   case X86::BI__builtin_ia32_rcp28pd_mask:
4048   case X86::BI__builtin_ia32_rcp28ps_mask:
4049   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4050   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4051   case X86::BI__builtin_ia32_vcomisd:
4052   case X86::BI__builtin_ia32_vcomiss:
4053   case X86::BI__builtin_ia32_vcomish:
4054   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4055     ArgNum = 3;
4056     break;
4057   case X86::BI__builtin_ia32_cmppd512_mask:
4058   case X86::BI__builtin_ia32_cmpps512_mask:
4059   case X86::BI__builtin_ia32_cmpsd_mask:
4060   case X86::BI__builtin_ia32_cmpss_mask:
4061   case X86::BI__builtin_ia32_cmpsh_mask:
4062   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4063   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4064   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4065   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4066   case X86::BI__builtin_ia32_getexpss128_round_mask:
4067   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4068   case X86::BI__builtin_ia32_getmantpd512_mask:
4069   case X86::BI__builtin_ia32_getmantps512_mask:
4070   case X86::BI__builtin_ia32_getmantph512_mask:
4071   case X86::BI__builtin_ia32_maxsd_round_mask:
4072   case X86::BI__builtin_ia32_maxss_round_mask:
4073   case X86::BI__builtin_ia32_maxsh_round_mask:
4074   case X86::BI__builtin_ia32_minsd_round_mask:
4075   case X86::BI__builtin_ia32_minss_round_mask:
4076   case X86::BI__builtin_ia32_minsh_round_mask:
4077   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4078   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4079   case X86::BI__builtin_ia32_reducepd512_mask:
4080   case X86::BI__builtin_ia32_reduceps512_mask:
4081   case X86::BI__builtin_ia32_reduceph512_mask:
4082   case X86::BI__builtin_ia32_rndscalepd_mask:
4083   case X86::BI__builtin_ia32_rndscaleps_mask:
4084   case X86::BI__builtin_ia32_rndscaleph_mask:
4085   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4086   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4087     ArgNum = 4;
4088     break;
4089   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4090   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4091   case X86::BI__builtin_ia32_fixupimmps512_mask:
4092   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4093   case X86::BI__builtin_ia32_fixupimmsd_mask:
4094   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4095   case X86::BI__builtin_ia32_fixupimmss_mask:
4096   case X86::BI__builtin_ia32_fixupimmss_maskz:
4097   case X86::BI__builtin_ia32_getmantsd_round_mask:
4098   case X86::BI__builtin_ia32_getmantss_round_mask:
4099   case X86::BI__builtin_ia32_getmantsh_round_mask:
4100   case X86::BI__builtin_ia32_rangepd512_mask:
4101   case X86::BI__builtin_ia32_rangeps512_mask:
4102   case X86::BI__builtin_ia32_rangesd128_round_mask:
4103   case X86::BI__builtin_ia32_rangess128_round_mask:
4104   case X86::BI__builtin_ia32_reducesd_mask:
4105   case X86::BI__builtin_ia32_reducess_mask:
4106   case X86::BI__builtin_ia32_reducesh_mask:
4107   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4108   case X86::BI__builtin_ia32_rndscaless_round_mask:
4109   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4110     ArgNum = 5;
4111     break;
4112   case X86::BI__builtin_ia32_vcvtsd2si64:
4113   case X86::BI__builtin_ia32_vcvtsd2si32:
4114   case X86::BI__builtin_ia32_vcvtsd2usi32:
4115   case X86::BI__builtin_ia32_vcvtsd2usi64:
4116   case X86::BI__builtin_ia32_vcvtss2si32:
4117   case X86::BI__builtin_ia32_vcvtss2si64:
4118   case X86::BI__builtin_ia32_vcvtss2usi32:
4119   case X86::BI__builtin_ia32_vcvtss2usi64:
4120   case X86::BI__builtin_ia32_vcvtsh2si32:
4121   case X86::BI__builtin_ia32_vcvtsh2si64:
4122   case X86::BI__builtin_ia32_vcvtsh2usi32:
4123   case X86::BI__builtin_ia32_vcvtsh2usi64:
4124   case X86::BI__builtin_ia32_sqrtpd512:
4125   case X86::BI__builtin_ia32_sqrtps512:
4126   case X86::BI__builtin_ia32_sqrtph512:
4127     ArgNum = 1;
4128     HasRC = true;
4129     break;
4130   case X86::BI__builtin_ia32_addph512:
4131   case X86::BI__builtin_ia32_divph512:
4132   case X86::BI__builtin_ia32_mulph512:
4133   case X86::BI__builtin_ia32_subph512:
4134   case X86::BI__builtin_ia32_addpd512:
4135   case X86::BI__builtin_ia32_addps512:
4136   case X86::BI__builtin_ia32_divpd512:
4137   case X86::BI__builtin_ia32_divps512:
4138   case X86::BI__builtin_ia32_mulpd512:
4139   case X86::BI__builtin_ia32_mulps512:
4140   case X86::BI__builtin_ia32_subpd512:
4141   case X86::BI__builtin_ia32_subps512:
4142   case X86::BI__builtin_ia32_cvtsi2sd64:
4143   case X86::BI__builtin_ia32_cvtsi2ss32:
4144   case X86::BI__builtin_ia32_cvtsi2ss64:
4145   case X86::BI__builtin_ia32_cvtusi2sd64:
4146   case X86::BI__builtin_ia32_cvtusi2ss32:
4147   case X86::BI__builtin_ia32_cvtusi2ss64:
4148   case X86::BI__builtin_ia32_vcvtusi2sh:
4149   case X86::BI__builtin_ia32_vcvtusi642sh:
4150   case X86::BI__builtin_ia32_vcvtsi2sh:
4151   case X86::BI__builtin_ia32_vcvtsi642sh:
4152     ArgNum = 2;
4153     HasRC = true;
4154     break;
4155   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4156   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4157   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4158   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4159   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4160   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4161   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4162   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4163   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4164   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4165   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4166   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4167   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4168   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4169   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4170   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4171   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4172   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4173   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4174   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4175   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4176   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4177   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4178   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4179   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4180   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4181   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4182   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4183   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4184     ArgNum = 3;
4185     HasRC = true;
4186     break;
4187   case X86::BI__builtin_ia32_addsh_round_mask:
4188   case X86::BI__builtin_ia32_addss_round_mask:
4189   case X86::BI__builtin_ia32_addsd_round_mask:
4190   case X86::BI__builtin_ia32_divsh_round_mask:
4191   case X86::BI__builtin_ia32_divss_round_mask:
4192   case X86::BI__builtin_ia32_divsd_round_mask:
4193   case X86::BI__builtin_ia32_mulsh_round_mask:
4194   case X86::BI__builtin_ia32_mulss_round_mask:
4195   case X86::BI__builtin_ia32_mulsd_round_mask:
4196   case X86::BI__builtin_ia32_subsh_round_mask:
4197   case X86::BI__builtin_ia32_subss_round_mask:
4198   case X86::BI__builtin_ia32_subsd_round_mask:
4199   case X86::BI__builtin_ia32_scalefph512_mask:
4200   case X86::BI__builtin_ia32_scalefpd512_mask:
4201   case X86::BI__builtin_ia32_scalefps512_mask:
4202   case X86::BI__builtin_ia32_scalefsd_round_mask:
4203   case X86::BI__builtin_ia32_scalefss_round_mask:
4204   case X86::BI__builtin_ia32_scalefsh_round_mask:
4205   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4206   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4207   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4208   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4209   case X86::BI__builtin_ia32_sqrtss_round_mask:
4210   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4211   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4212   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4213   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4214   case X86::BI__builtin_ia32_vfmaddss3_mask:
4215   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4216   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4217   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4218   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4219   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4220   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4221   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4222   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4223   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4224   case X86::BI__builtin_ia32_vfmaddps512_mask:
4225   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4226   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4227   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4228   case X86::BI__builtin_ia32_vfmaddph512_mask:
4229   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4230   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4231   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4232   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4233   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4234   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4235   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4236   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4237   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4238   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4239   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4240   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4241   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4242   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4243   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4244   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4245   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4246   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4247   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4248   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4249   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4250   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4251   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4252   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4253   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4254   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4255   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4256   case X86::BI__builtin_ia32_vfmulcsh_mask:
4257   case X86::BI__builtin_ia32_vfmulcph512_mask:
4258   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4259   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4260     ArgNum = 4;
4261     HasRC = true;
4262     break;
4263   }
4264 
4265   llvm::APSInt Result;
4266 
4267   // We can't check the value of a dependent argument.
4268   Expr *Arg = TheCall->getArg(ArgNum);
4269   if (Arg->isTypeDependent() || Arg->isValueDependent())
4270     return false;
4271 
4272   // Check constant-ness first.
4273   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4274     return true;
4275 
4276   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4277   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4278   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4279   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4280   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4281       Result == 8/*ROUND_NO_EXC*/ ||
4282       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4283       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4284     return false;
4285 
4286   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4287          << Arg->getSourceRange();
4288 }
4289 
4290 // Check if the gather/scatter scale is legal.
4291 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4292                                              CallExpr *TheCall) {
4293   unsigned ArgNum = 0;
4294   switch (BuiltinID) {
4295   default:
4296     return false;
4297   case X86::BI__builtin_ia32_gatherpfdpd:
4298   case X86::BI__builtin_ia32_gatherpfdps:
4299   case X86::BI__builtin_ia32_gatherpfqpd:
4300   case X86::BI__builtin_ia32_gatherpfqps:
4301   case X86::BI__builtin_ia32_scatterpfdpd:
4302   case X86::BI__builtin_ia32_scatterpfdps:
4303   case X86::BI__builtin_ia32_scatterpfqpd:
4304   case X86::BI__builtin_ia32_scatterpfqps:
4305     ArgNum = 3;
4306     break;
4307   case X86::BI__builtin_ia32_gatherd_pd:
4308   case X86::BI__builtin_ia32_gatherd_pd256:
4309   case X86::BI__builtin_ia32_gatherq_pd:
4310   case X86::BI__builtin_ia32_gatherq_pd256:
4311   case X86::BI__builtin_ia32_gatherd_ps:
4312   case X86::BI__builtin_ia32_gatherd_ps256:
4313   case X86::BI__builtin_ia32_gatherq_ps:
4314   case X86::BI__builtin_ia32_gatherq_ps256:
4315   case X86::BI__builtin_ia32_gatherd_q:
4316   case X86::BI__builtin_ia32_gatherd_q256:
4317   case X86::BI__builtin_ia32_gatherq_q:
4318   case X86::BI__builtin_ia32_gatherq_q256:
4319   case X86::BI__builtin_ia32_gatherd_d:
4320   case X86::BI__builtin_ia32_gatherd_d256:
4321   case X86::BI__builtin_ia32_gatherq_d:
4322   case X86::BI__builtin_ia32_gatherq_d256:
4323   case X86::BI__builtin_ia32_gather3div2df:
4324   case X86::BI__builtin_ia32_gather3div2di:
4325   case X86::BI__builtin_ia32_gather3div4df:
4326   case X86::BI__builtin_ia32_gather3div4di:
4327   case X86::BI__builtin_ia32_gather3div4sf:
4328   case X86::BI__builtin_ia32_gather3div4si:
4329   case X86::BI__builtin_ia32_gather3div8sf:
4330   case X86::BI__builtin_ia32_gather3div8si:
4331   case X86::BI__builtin_ia32_gather3siv2df:
4332   case X86::BI__builtin_ia32_gather3siv2di:
4333   case X86::BI__builtin_ia32_gather3siv4df:
4334   case X86::BI__builtin_ia32_gather3siv4di:
4335   case X86::BI__builtin_ia32_gather3siv4sf:
4336   case X86::BI__builtin_ia32_gather3siv4si:
4337   case X86::BI__builtin_ia32_gather3siv8sf:
4338   case X86::BI__builtin_ia32_gather3siv8si:
4339   case X86::BI__builtin_ia32_gathersiv8df:
4340   case X86::BI__builtin_ia32_gathersiv16sf:
4341   case X86::BI__builtin_ia32_gatherdiv8df:
4342   case X86::BI__builtin_ia32_gatherdiv16sf:
4343   case X86::BI__builtin_ia32_gathersiv8di:
4344   case X86::BI__builtin_ia32_gathersiv16si:
4345   case X86::BI__builtin_ia32_gatherdiv8di:
4346   case X86::BI__builtin_ia32_gatherdiv16si:
4347   case X86::BI__builtin_ia32_scatterdiv2df:
4348   case X86::BI__builtin_ia32_scatterdiv2di:
4349   case X86::BI__builtin_ia32_scatterdiv4df:
4350   case X86::BI__builtin_ia32_scatterdiv4di:
4351   case X86::BI__builtin_ia32_scatterdiv4sf:
4352   case X86::BI__builtin_ia32_scatterdiv4si:
4353   case X86::BI__builtin_ia32_scatterdiv8sf:
4354   case X86::BI__builtin_ia32_scatterdiv8si:
4355   case X86::BI__builtin_ia32_scattersiv2df:
4356   case X86::BI__builtin_ia32_scattersiv2di:
4357   case X86::BI__builtin_ia32_scattersiv4df:
4358   case X86::BI__builtin_ia32_scattersiv4di:
4359   case X86::BI__builtin_ia32_scattersiv4sf:
4360   case X86::BI__builtin_ia32_scattersiv4si:
4361   case X86::BI__builtin_ia32_scattersiv8sf:
4362   case X86::BI__builtin_ia32_scattersiv8si:
4363   case X86::BI__builtin_ia32_scattersiv8df:
4364   case X86::BI__builtin_ia32_scattersiv16sf:
4365   case X86::BI__builtin_ia32_scatterdiv8df:
4366   case X86::BI__builtin_ia32_scatterdiv16sf:
4367   case X86::BI__builtin_ia32_scattersiv8di:
4368   case X86::BI__builtin_ia32_scattersiv16si:
4369   case X86::BI__builtin_ia32_scatterdiv8di:
4370   case X86::BI__builtin_ia32_scatterdiv16si:
4371     ArgNum = 4;
4372     break;
4373   }
4374 
4375   llvm::APSInt Result;
4376 
4377   // We can't check the value of a dependent argument.
4378   Expr *Arg = TheCall->getArg(ArgNum);
4379   if (Arg->isTypeDependent() || Arg->isValueDependent())
4380     return false;
4381 
4382   // Check constant-ness first.
4383   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4384     return true;
4385 
4386   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4387     return false;
4388 
4389   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4390          << Arg->getSourceRange();
4391 }
4392 
4393 enum { TileRegLow = 0, TileRegHigh = 7 };
4394 
4395 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4396                                              ArrayRef<int> ArgNums) {
4397   for (int ArgNum : ArgNums) {
4398     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4399       return true;
4400   }
4401   return false;
4402 }
4403 
4404 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4405                                         ArrayRef<int> ArgNums) {
4406   // Because the max number of tile register is TileRegHigh + 1, so here we use
4407   // each bit to represent the usage of them in bitset.
4408   std::bitset<TileRegHigh + 1> ArgValues;
4409   for (int ArgNum : ArgNums) {
4410     Expr *Arg = TheCall->getArg(ArgNum);
4411     if (Arg->isTypeDependent() || Arg->isValueDependent())
4412       continue;
4413 
4414     llvm::APSInt Result;
4415     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4416       return true;
4417     int ArgExtValue = Result.getExtValue();
4418     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4419            "Incorrect tile register num.");
4420     if (ArgValues.test(ArgExtValue))
4421       return Diag(TheCall->getBeginLoc(),
4422                   diag::err_x86_builtin_tile_arg_duplicate)
4423              << TheCall->getArg(ArgNum)->getSourceRange();
4424     ArgValues.set(ArgExtValue);
4425   }
4426   return false;
4427 }
4428 
4429 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4430                                                 ArrayRef<int> ArgNums) {
4431   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4432          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4433 }
4434 
4435 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4436   switch (BuiltinID) {
4437   default:
4438     return false;
4439   case X86::BI__builtin_ia32_tileloadd64:
4440   case X86::BI__builtin_ia32_tileloaddt164:
4441   case X86::BI__builtin_ia32_tilestored64:
4442   case X86::BI__builtin_ia32_tilezero:
4443     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4444   case X86::BI__builtin_ia32_tdpbssd:
4445   case X86::BI__builtin_ia32_tdpbsud:
4446   case X86::BI__builtin_ia32_tdpbusd:
4447   case X86::BI__builtin_ia32_tdpbuud:
4448   case X86::BI__builtin_ia32_tdpbf16ps:
4449     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4450   }
4451 }
4452 static bool isX86_32Builtin(unsigned BuiltinID) {
4453   // These builtins only work on x86-32 targets.
4454   switch (BuiltinID) {
4455   case X86::BI__builtin_ia32_readeflags_u32:
4456   case X86::BI__builtin_ia32_writeeflags_u32:
4457     return true;
4458   }
4459 
4460   return false;
4461 }
4462 
4463 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4464                                        CallExpr *TheCall) {
4465   if (BuiltinID == X86::BI__builtin_cpu_supports)
4466     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4467 
4468   if (BuiltinID == X86::BI__builtin_cpu_is)
4469     return SemaBuiltinCpuIs(*this, TI, TheCall);
4470 
4471   // Check for 32-bit only builtins on a 64-bit target.
4472   const llvm::Triple &TT = TI.getTriple();
4473   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4474     return Diag(TheCall->getCallee()->getBeginLoc(),
4475                 diag::err_32_bit_builtin_64_bit_tgt);
4476 
4477   // If the intrinsic has rounding or SAE make sure its valid.
4478   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4479     return true;
4480 
4481   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4482   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4483     return true;
4484 
4485   // If the intrinsic has a tile arguments, make sure they are valid.
4486   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4487     return true;
4488 
4489   // For intrinsics which take an immediate value as part of the instruction,
4490   // range check them here.
4491   int i = 0, l = 0, u = 0;
4492   switch (BuiltinID) {
4493   default:
4494     return false;
4495   case X86::BI__builtin_ia32_vec_ext_v2si:
4496   case X86::BI__builtin_ia32_vec_ext_v2di:
4497   case X86::BI__builtin_ia32_vextractf128_pd256:
4498   case X86::BI__builtin_ia32_vextractf128_ps256:
4499   case X86::BI__builtin_ia32_vextractf128_si256:
4500   case X86::BI__builtin_ia32_extract128i256:
4501   case X86::BI__builtin_ia32_extractf64x4_mask:
4502   case X86::BI__builtin_ia32_extracti64x4_mask:
4503   case X86::BI__builtin_ia32_extractf32x8_mask:
4504   case X86::BI__builtin_ia32_extracti32x8_mask:
4505   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4506   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4507   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4508   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4509     i = 1; l = 0; u = 1;
4510     break;
4511   case X86::BI__builtin_ia32_vec_set_v2di:
4512   case X86::BI__builtin_ia32_vinsertf128_pd256:
4513   case X86::BI__builtin_ia32_vinsertf128_ps256:
4514   case X86::BI__builtin_ia32_vinsertf128_si256:
4515   case X86::BI__builtin_ia32_insert128i256:
4516   case X86::BI__builtin_ia32_insertf32x8:
4517   case X86::BI__builtin_ia32_inserti32x8:
4518   case X86::BI__builtin_ia32_insertf64x4:
4519   case X86::BI__builtin_ia32_inserti64x4:
4520   case X86::BI__builtin_ia32_insertf64x2_256:
4521   case X86::BI__builtin_ia32_inserti64x2_256:
4522   case X86::BI__builtin_ia32_insertf32x4_256:
4523   case X86::BI__builtin_ia32_inserti32x4_256:
4524     i = 2; l = 0; u = 1;
4525     break;
4526   case X86::BI__builtin_ia32_vpermilpd:
4527   case X86::BI__builtin_ia32_vec_ext_v4hi:
4528   case X86::BI__builtin_ia32_vec_ext_v4si:
4529   case X86::BI__builtin_ia32_vec_ext_v4sf:
4530   case X86::BI__builtin_ia32_vec_ext_v4di:
4531   case X86::BI__builtin_ia32_extractf32x4_mask:
4532   case X86::BI__builtin_ia32_extracti32x4_mask:
4533   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4534   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4535     i = 1; l = 0; u = 3;
4536     break;
4537   case X86::BI_mm_prefetch:
4538   case X86::BI__builtin_ia32_vec_ext_v8hi:
4539   case X86::BI__builtin_ia32_vec_ext_v8si:
4540     i = 1; l = 0; u = 7;
4541     break;
4542   case X86::BI__builtin_ia32_sha1rnds4:
4543   case X86::BI__builtin_ia32_blendpd:
4544   case X86::BI__builtin_ia32_shufpd:
4545   case X86::BI__builtin_ia32_vec_set_v4hi:
4546   case X86::BI__builtin_ia32_vec_set_v4si:
4547   case X86::BI__builtin_ia32_vec_set_v4di:
4548   case X86::BI__builtin_ia32_shuf_f32x4_256:
4549   case X86::BI__builtin_ia32_shuf_f64x2_256:
4550   case X86::BI__builtin_ia32_shuf_i32x4_256:
4551   case X86::BI__builtin_ia32_shuf_i64x2_256:
4552   case X86::BI__builtin_ia32_insertf64x2_512:
4553   case X86::BI__builtin_ia32_inserti64x2_512:
4554   case X86::BI__builtin_ia32_insertf32x4:
4555   case X86::BI__builtin_ia32_inserti32x4:
4556     i = 2; l = 0; u = 3;
4557     break;
4558   case X86::BI__builtin_ia32_vpermil2pd:
4559   case X86::BI__builtin_ia32_vpermil2pd256:
4560   case X86::BI__builtin_ia32_vpermil2ps:
4561   case X86::BI__builtin_ia32_vpermil2ps256:
4562     i = 3; l = 0; u = 3;
4563     break;
4564   case X86::BI__builtin_ia32_cmpb128_mask:
4565   case X86::BI__builtin_ia32_cmpw128_mask:
4566   case X86::BI__builtin_ia32_cmpd128_mask:
4567   case X86::BI__builtin_ia32_cmpq128_mask:
4568   case X86::BI__builtin_ia32_cmpb256_mask:
4569   case X86::BI__builtin_ia32_cmpw256_mask:
4570   case X86::BI__builtin_ia32_cmpd256_mask:
4571   case X86::BI__builtin_ia32_cmpq256_mask:
4572   case X86::BI__builtin_ia32_cmpb512_mask:
4573   case X86::BI__builtin_ia32_cmpw512_mask:
4574   case X86::BI__builtin_ia32_cmpd512_mask:
4575   case X86::BI__builtin_ia32_cmpq512_mask:
4576   case X86::BI__builtin_ia32_ucmpb128_mask:
4577   case X86::BI__builtin_ia32_ucmpw128_mask:
4578   case X86::BI__builtin_ia32_ucmpd128_mask:
4579   case X86::BI__builtin_ia32_ucmpq128_mask:
4580   case X86::BI__builtin_ia32_ucmpb256_mask:
4581   case X86::BI__builtin_ia32_ucmpw256_mask:
4582   case X86::BI__builtin_ia32_ucmpd256_mask:
4583   case X86::BI__builtin_ia32_ucmpq256_mask:
4584   case X86::BI__builtin_ia32_ucmpb512_mask:
4585   case X86::BI__builtin_ia32_ucmpw512_mask:
4586   case X86::BI__builtin_ia32_ucmpd512_mask:
4587   case X86::BI__builtin_ia32_ucmpq512_mask:
4588   case X86::BI__builtin_ia32_vpcomub:
4589   case X86::BI__builtin_ia32_vpcomuw:
4590   case X86::BI__builtin_ia32_vpcomud:
4591   case X86::BI__builtin_ia32_vpcomuq:
4592   case X86::BI__builtin_ia32_vpcomb:
4593   case X86::BI__builtin_ia32_vpcomw:
4594   case X86::BI__builtin_ia32_vpcomd:
4595   case X86::BI__builtin_ia32_vpcomq:
4596   case X86::BI__builtin_ia32_vec_set_v8hi:
4597   case X86::BI__builtin_ia32_vec_set_v8si:
4598     i = 2; l = 0; u = 7;
4599     break;
4600   case X86::BI__builtin_ia32_vpermilpd256:
4601   case X86::BI__builtin_ia32_roundps:
4602   case X86::BI__builtin_ia32_roundpd:
4603   case X86::BI__builtin_ia32_roundps256:
4604   case X86::BI__builtin_ia32_roundpd256:
4605   case X86::BI__builtin_ia32_getmantpd128_mask:
4606   case X86::BI__builtin_ia32_getmantpd256_mask:
4607   case X86::BI__builtin_ia32_getmantps128_mask:
4608   case X86::BI__builtin_ia32_getmantps256_mask:
4609   case X86::BI__builtin_ia32_getmantpd512_mask:
4610   case X86::BI__builtin_ia32_getmantps512_mask:
4611   case X86::BI__builtin_ia32_getmantph128_mask:
4612   case X86::BI__builtin_ia32_getmantph256_mask:
4613   case X86::BI__builtin_ia32_getmantph512_mask:
4614   case X86::BI__builtin_ia32_vec_ext_v16qi:
4615   case X86::BI__builtin_ia32_vec_ext_v16hi:
4616     i = 1; l = 0; u = 15;
4617     break;
4618   case X86::BI__builtin_ia32_pblendd128:
4619   case X86::BI__builtin_ia32_blendps:
4620   case X86::BI__builtin_ia32_blendpd256:
4621   case X86::BI__builtin_ia32_shufpd256:
4622   case X86::BI__builtin_ia32_roundss:
4623   case X86::BI__builtin_ia32_roundsd:
4624   case X86::BI__builtin_ia32_rangepd128_mask:
4625   case X86::BI__builtin_ia32_rangepd256_mask:
4626   case X86::BI__builtin_ia32_rangepd512_mask:
4627   case X86::BI__builtin_ia32_rangeps128_mask:
4628   case X86::BI__builtin_ia32_rangeps256_mask:
4629   case X86::BI__builtin_ia32_rangeps512_mask:
4630   case X86::BI__builtin_ia32_getmantsd_round_mask:
4631   case X86::BI__builtin_ia32_getmantss_round_mask:
4632   case X86::BI__builtin_ia32_getmantsh_round_mask:
4633   case X86::BI__builtin_ia32_vec_set_v16qi:
4634   case X86::BI__builtin_ia32_vec_set_v16hi:
4635     i = 2; l = 0; u = 15;
4636     break;
4637   case X86::BI__builtin_ia32_vec_ext_v32qi:
4638     i = 1; l = 0; u = 31;
4639     break;
4640   case X86::BI__builtin_ia32_cmpps:
4641   case X86::BI__builtin_ia32_cmpss:
4642   case X86::BI__builtin_ia32_cmppd:
4643   case X86::BI__builtin_ia32_cmpsd:
4644   case X86::BI__builtin_ia32_cmpps256:
4645   case X86::BI__builtin_ia32_cmppd256:
4646   case X86::BI__builtin_ia32_cmpps128_mask:
4647   case X86::BI__builtin_ia32_cmppd128_mask:
4648   case X86::BI__builtin_ia32_cmpps256_mask:
4649   case X86::BI__builtin_ia32_cmppd256_mask:
4650   case X86::BI__builtin_ia32_cmpps512_mask:
4651   case X86::BI__builtin_ia32_cmppd512_mask:
4652   case X86::BI__builtin_ia32_cmpsd_mask:
4653   case X86::BI__builtin_ia32_cmpss_mask:
4654   case X86::BI__builtin_ia32_vec_set_v32qi:
4655     i = 2; l = 0; u = 31;
4656     break;
4657   case X86::BI__builtin_ia32_permdf256:
4658   case X86::BI__builtin_ia32_permdi256:
4659   case X86::BI__builtin_ia32_permdf512:
4660   case X86::BI__builtin_ia32_permdi512:
4661   case X86::BI__builtin_ia32_vpermilps:
4662   case X86::BI__builtin_ia32_vpermilps256:
4663   case X86::BI__builtin_ia32_vpermilpd512:
4664   case X86::BI__builtin_ia32_vpermilps512:
4665   case X86::BI__builtin_ia32_pshufd:
4666   case X86::BI__builtin_ia32_pshufd256:
4667   case X86::BI__builtin_ia32_pshufd512:
4668   case X86::BI__builtin_ia32_pshufhw:
4669   case X86::BI__builtin_ia32_pshufhw256:
4670   case X86::BI__builtin_ia32_pshufhw512:
4671   case X86::BI__builtin_ia32_pshuflw:
4672   case X86::BI__builtin_ia32_pshuflw256:
4673   case X86::BI__builtin_ia32_pshuflw512:
4674   case X86::BI__builtin_ia32_vcvtps2ph:
4675   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4676   case X86::BI__builtin_ia32_vcvtps2ph256:
4677   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4678   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4679   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4680   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4681   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4682   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4683   case X86::BI__builtin_ia32_rndscaleps_mask:
4684   case X86::BI__builtin_ia32_rndscalepd_mask:
4685   case X86::BI__builtin_ia32_rndscaleph_mask:
4686   case X86::BI__builtin_ia32_reducepd128_mask:
4687   case X86::BI__builtin_ia32_reducepd256_mask:
4688   case X86::BI__builtin_ia32_reducepd512_mask:
4689   case X86::BI__builtin_ia32_reduceps128_mask:
4690   case X86::BI__builtin_ia32_reduceps256_mask:
4691   case X86::BI__builtin_ia32_reduceps512_mask:
4692   case X86::BI__builtin_ia32_reduceph128_mask:
4693   case X86::BI__builtin_ia32_reduceph256_mask:
4694   case X86::BI__builtin_ia32_reduceph512_mask:
4695   case X86::BI__builtin_ia32_prold512:
4696   case X86::BI__builtin_ia32_prolq512:
4697   case X86::BI__builtin_ia32_prold128:
4698   case X86::BI__builtin_ia32_prold256:
4699   case X86::BI__builtin_ia32_prolq128:
4700   case X86::BI__builtin_ia32_prolq256:
4701   case X86::BI__builtin_ia32_prord512:
4702   case X86::BI__builtin_ia32_prorq512:
4703   case X86::BI__builtin_ia32_prord128:
4704   case X86::BI__builtin_ia32_prord256:
4705   case X86::BI__builtin_ia32_prorq128:
4706   case X86::BI__builtin_ia32_prorq256:
4707   case X86::BI__builtin_ia32_fpclasspd128_mask:
4708   case X86::BI__builtin_ia32_fpclasspd256_mask:
4709   case X86::BI__builtin_ia32_fpclassps128_mask:
4710   case X86::BI__builtin_ia32_fpclassps256_mask:
4711   case X86::BI__builtin_ia32_fpclassps512_mask:
4712   case X86::BI__builtin_ia32_fpclasspd512_mask:
4713   case X86::BI__builtin_ia32_fpclassph128_mask:
4714   case X86::BI__builtin_ia32_fpclassph256_mask:
4715   case X86::BI__builtin_ia32_fpclassph512_mask:
4716   case X86::BI__builtin_ia32_fpclasssd_mask:
4717   case X86::BI__builtin_ia32_fpclassss_mask:
4718   case X86::BI__builtin_ia32_fpclasssh_mask:
4719   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4720   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4721   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4722   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4723   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4724   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4725   case X86::BI__builtin_ia32_kshiftliqi:
4726   case X86::BI__builtin_ia32_kshiftlihi:
4727   case X86::BI__builtin_ia32_kshiftlisi:
4728   case X86::BI__builtin_ia32_kshiftlidi:
4729   case X86::BI__builtin_ia32_kshiftriqi:
4730   case X86::BI__builtin_ia32_kshiftrihi:
4731   case X86::BI__builtin_ia32_kshiftrisi:
4732   case X86::BI__builtin_ia32_kshiftridi:
4733     i = 1; l = 0; u = 255;
4734     break;
4735   case X86::BI__builtin_ia32_vperm2f128_pd256:
4736   case X86::BI__builtin_ia32_vperm2f128_ps256:
4737   case X86::BI__builtin_ia32_vperm2f128_si256:
4738   case X86::BI__builtin_ia32_permti256:
4739   case X86::BI__builtin_ia32_pblendw128:
4740   case X86::BI__builtin_ia32_pblendw256:
4741   case X86::BI__builtin_ia32_blendps256:
4742   case X86::BI__builtin_ia32_pblendd256:
4743   case X86::BI__builtin_ia32_palignr128:
4744   case X86::BI__builtin_ia32_palignr256:
4745   case X86::BI__builtin_ia32_palignr512:
4746   case X86::BI__builtin_ia32_alignq512:
4747   case X86::BI__builtin_ia32_alignd512:
4748   case X86::BI__builtin_ia32_alignd128:
4749   case X86::BI__builtin_ia32_alignd256:
4750   case X86::BI__builtin_ia32_alignq128:
4751   case X86::BI__builtin_ia32_alignq256:
4752   case X86::BI__builtin_ia32_vcomisd:
4753   case X86::BI__builtin_ia32_vcomiss:
4754   case X86::BI__builtin_ia32_shuf_f32x4:
4755   case X86::BI__builtin_ia32_shuf_f64x2:
4756   case X86::BI__builtin_ia32_shuf_i32x4:
4757   case X86::BI__builtin_ia32_shuf_i64x2:
4758   case X86::BI__builtin_ia32_shufpd512:
4759   case X86::BI__builtin_ia32_shufps:
4760   case X86::BI__builtin_ia32_shufps256:
4761   case X86::BI__builtin_ia32_shufps512:
4762   case X86::BI__builtin_ia32_dbpsadbw128:
4763   case X86::BI__builtin_ia32_dbpsadbw256:
4764   case X86::BI__builtin_ia32_dbpsadbw512:
4765   case X86::BI__builtin_ia32_vpshldd128:
4766   case X86::BI__builtin_ia32_vpshldd256:
4767   case X86::BI__builtin_ia32_vpshldd512:
4768   case X86::BI__builtin_ia32_vpshldq128:
4769   case X86::BI__builtin_ia32_vpshldq256:
4770   case X86::BI__builtin_ia32_vpshldq512:
4771   case X86::BI__builtin_ia32_vpshldw128:
4772   case X86::BI__builtin_ia32_vpshldw256:
4773   case X86::BI__builtin_ia32_vpshldw512:
4774   case X86::BI__builtin_ia32_vpshrdd128:
4775   case X86::BI__builtin_ia32_vpshrdd256:
4776   case X86::BI__builtin_ia32_vpshrdd512:
4777   case X86::BI__builtin_ia32_vpshrdq128:
4778   case X86::BI__builtin_ia32_vpshrdq256:
4779   case X86::BI__builtin_ia32_vpshrdq512:
4780   case X86::BI__builtin_ia32_vpshrdw128:
4781   case X86::BI__builtin_ia32_vpshrdw256:
4782   case X86::BI__builtin_ia32_vpshrdw512:
4783     i = 2; l = 0; u = 255;
4784     break;
4785   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4786   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4787   case X86::BI__builtin_ia32_fixupimmps512_mask:
4788   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4789   case X86::BI__builtin_ia32_fixupimmsd_mask:
4790   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4791   case X86::BI__builtin_ia32_fixupimmss_mask:
4792   case X86::BI__builtin_ia32_fixupimmss_maskz:
4793   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4794   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4795   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4796   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4797   case X86::BI__builtin_ia32_fixupimmps128_mask:
4798   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4799   case X86::BI__builtin_ia32_fixupimmps256_mask:
4800   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4801   case X86::BI__builtin_ia32_pternlogd512_mask:
4802   case X86::BI__builtin_ia32_pternlogd512_maskz:
4803   case X86::BI__builtin_ia32_pternlogq512_mask:
4804   case X86::BI__builtin_ia32_pternlogq512_maskz:
4805   case X86::BI__builtin_ia32_pternlogd128_mask:
4806   case X86::BI__builtin_ia32_pternlogd128_maskz:
4807   case X86::BI__builtin_ia32_pternlogd256_mask:
4808   case X86::BI__builtin_ia32_pternlogd256_maskz:
4809   case X86::BI__builtin_ia32_pternlogq128_mask:
4810   case X86::BI__builtin_ia32_pternlogq128_maskz:
4811   case X86::BI__builtin_ia32_pternlogq256_mask:
4812   case X86::BI__builtin_ia32_pternlogq256_maskz:
4813     i = 3; l = 0; u = 255;
4814     break;
4815   case X86::BI__builtin_ia32_gatherpfdpd:
4816   case X86::BI__builtin_ia32_gatherpfdps:
4817   case X86::BI__builtin_ia32_gatherpfqpd:
4818   case X86::BI__builtin_ia32_gatherpfqps:
4819   case X86::BI__builtin_ia32_scatterpfdpd:
4820   case X86::BI__builtin_ia32_scatterpfdps:
4821   case X86::BI__builtin_ia32_scatterpfqpd:
4822   case X86::BI__builtin_ia32_scatterpfqps:
4823     i = 4; l = 2; u = 3;
4824     break;
4825   case X86::BI__builtin_ia32_reducesd_mask:
4826   case X86::BI__builtin_ia32_reducess_mask:
4827   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4828   case X86::BI__builtin_ia32_rndscaless_round_mask:
4829   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4830   case X86::BI__builtin_ia32_reducesh_mask:
4831     i = 4; l = 0; u = 255;
4832     break;
4833   }
4834 
4835   // Note that we don't force a hard error on the range check here, allowing
4836   // template-generated or macro-generated dead code to potentially have out-of-
4837   // range values. These need to code generate, but don't need to necessarily
4838   // make any sense. We use a warning that defaults to an error.
4839   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4840 }
4841 
4842 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4843 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4844 /// Returns true when the format fits the function and the FormatStringInfo has
4845 /// been populated.
4846 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4847                                FormatStringInfo *FSI) {
4848   FSI->HasVAListArg = Format->getFirstArg() == 0;
4849   FSI->FormatIdx = Format->getFormatIdx() - 1;
4850   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4851 
4852   // The way the format attribute works in GCC, the implicit this argument
4853   // of member functions is counted. However, it doesn't appear in our own
4854   // lists, so decrement format_idx in that case.
4855   if (IsCXXMember) {
4856     if(FSI->FormatIdx == 0)
4857       return false;
4858     --FSI->FormatIdx;
4859     if (FSI->FirstDataArg != 0)
4860       --FSI->FirstDataArg;
4861   }
4862   return true;
4863 }
4864 
4865 /// Checks if a the given expression evaluates to null.
4866 ///
4867 /// Returns true if the value evaluates to null.
4868 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4869   // If the expression has non-null type, it doesn't evaluate to null.
4870   if (auto nullability
4871         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4872     if (*nullability == NullabilityKind::NonNull)
4873       return false;
4874   }
4875 
4876   // As a special case, transparent unions initialized with zero are
4877   // considered null for the purposes of the nonnull attribute.
4878   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4879     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4880       if (const CompoundLiteralExpr *CLE =
4881           dyn_cast<CompoundLiteralExpr>(Expr))
4882         if (const InitListExpr *ILE =
4883             dyn_cast<InitListExpr>(CLE->getInitializer()))
4884           Expr = ILE->getInit(0);
4885   }
4886 
4887   bool Result;
4888   return (!Expr->isValueDependent() &&
4889           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4890           !Result);
4891 }
4892 
4893 static void CheckNonNullArgument(Sema &S,
4894                                  const Expr *ArgExpr,
4895                                  SourceLocation CallSiteLoc) {
4896   if (CheckNonNullExpr(S, ArgExpr))
4897     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4898                           S.PDiag(diag::warn_null_arg)
4899                               << ArgExpr->getSourceRange());
4900 }
4901 
4902 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4903   FormatStringInfo FSI;
4904   if ((GetFormatStringType(Format) == FST_NSString) &&
4905       getFormatStringInfo(Format, false, &FSI)) {
4906     Idx = FSI.FormatIdx;
4907     return true;
4908   }
4909   return false;
4910 }
4911 
4912 /// Diagnose use of %s directive in an NSString which is being passed
4913 /// as formatting string to formatting method.
4914 static void
4915 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4916                                         const NamedDecl *FDecl,
4917                                         Expr **Args,
4918                                         unsigned NumArgs) {
4919   unsigned Idx = 0;
4920   bool Format = false;
4921   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4922   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4923     Idx = 2;
4924     Format = true;
4925   }
4926   else
4927     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4928       if (S.GetFormatNSStringIdx(I, Idx)) {
4929         Format = true;
4930         break;
4931       }
4932     }
4933   if (!Format || NumArgs <= Idx)
4934     return;
4935   const Expr *FormatExpr = Args[Idx];
4936   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4937     FormatExpr = CSCE->getSubExpr();
4938   const StringLiteral *FormatString;
4939   if (const ObjCStringLiteral *OSL =
4940       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4941     FormatString = OSL->getString();
4942   else
4943     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4944   if (!FormatString)
4945     return;
4946   if (S.FormatStringHasSArg(FormatString)) {
4947     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4948       << "%s" << 1 << 1;
4949     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4950       << FDecl->getDeclName();
4951   }
4952 }
4953 
4954 /// Determine whether the given type has a non-null nullability annotation.
4955 static bool isNonNullType(ASTContext &ctx, QualType type) {
4956   if (auto nullability = type->getNullability(ctx))
4957     return *nullability == NullabilityKind::NonNull;
4958 
4959   return false;
4960 }
4961 
4962 static void CheckNonNullArguments(Sema &S,
4963                                   const NamedDecl *FDecl,
4964                                   const FunctionProtoType *Proto,
4965                                   ArrayRef<const Expr *> Args,
4966                                   SourceLocation CallSiteLoc) {
4967   assert((FDecl || Proto) && "Need a function declaration or prototype");
4968 
4969   // Already checked by by constant evaluator.
4970   if (S.isConstantEvaluated())
4971     return;
4972   // Check the attributes attached to the method/function itself.
4973   llvm::SmallBitVector NonNullArgs;
4974   if (FDecl) {
4975     // Handle the nonnull attribute on the function/method declaration itself.
4976     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4977       if (!NonNull->args_size()) {
4978         // Easy case: all pointer arguments are nonnull.
4979         for (const auto *Arg : Args)
4980           if (S.isValidPointerAttrType(Arg->getType()))
4981             CheckNonNullArgument(S, Arg, CallSiteLoc);
4982         return;
4983       }
4984 
4985       for (const ParamIdx &Idx : NonNull->args()) {
4986         unsigned IdxAST = Idx.getASTIndex();
4987         if (IdxAST >= Args.size())
4988           continue;
4989         if (NonNullArgs.empty())
4990           NonNullArgs.resize(Args.size());
4991         NonNullArgs.set(IdxAST);
4992       }
4993     }
4994   }
4995 
4996   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4997     // Handle the nonnull attribute on the parameters of the
4998     // function/method.
4999     ArrayRef<ParmVarDecl*> parms;
5000     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5001       parms = FD->parameters();
5002     else
5003       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5004 
5005     unsigned ParamIndex = 0;
5006     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5007          I != E; ++I, ++ParamIndex) {
5008       const ParmVarDecl *PVD = *I;
5009       if (PVD->hasAttr<NonNullAttr>() ||
5010           isNonNullType(S.Context, PVD->getType())) {
5011         if (NonNullArgs.empty())
5012           NonNullArgs.resize(Args.size());
5013 
5014         NonNullArgs.set(ParamIndex);
5015       }
5016     }
5017   } else {
5018     // If we have a non-function, non-method declaration but no
5019     // function prototype, try to dig out the function prototype.
5020     if (!Proto) {
5021       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5022         QualType type = VD->getType().getNonReferenceType();
5023         if (auto pointerType = type->getAs<PointerType>())
5024           type = pointerType->getPointeeType();
5025         else if (auto blockType = type->getAs<BlockPointerType>())
5026           type = blockType->getPointeeType();
5027         // FIXME: data member pointers?
5028 
5029         // Dig out the function prototype, if there is one.
5030         Proto = type->getAs<FunctionProtoType>();
5031       }
5032     }
5033 
5034     // Fill in non-null argument information from the nullability
5035     // information on the parameter types (if we have them).
5036     if (Proto) {
5037       unsigned Index = 0;
5038       for (auto paramType : Proto->getParamTypes()) {
5039         if (isNonNullType(S.Context, paramType)) {
5040           if (NonNullArgs.empty())
5041             NonNullArgs.resize(Args.size());
5042 
5043           NonNullArgs.set(Index);
5044         }
5045 
5046         ++Index;
5047       }
5048     }
5049   }
5050 
5051   // Check for non-null arguments.
5052   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5053        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5054     if (NonNullArgs[ArgIndex])
5055       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5056   }
5057 }
5058 
5059 /// Warn if a pointer or reference argument passed to a function points to an
5060 /// object that is less aligned than the parameter. This can happen when
5061 /// creating a typedef with a lower alignment than the original type and then
5062 /// calling functions defined in terms of the original type.
5063 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5064                              StringRef ParamName, QualType ArgTy,
5065                              QualType ParamTy) {
5066 
5067   // If a function accepts a pointer or reference type
5068   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5069     return;
5070 
5071   // If the parameter is a pointer type, get the pointee type for the
5072   // argument too. If the parameter is a reference type, don't try to get
5073   // the pointee type for the argument.
5074   if (ParamTy->isPointerType())
5075     ArgTy = ArgTy->getPointeeType();
5076 
5077   // Remove reference or pointer
5078   ParamTy = ParamTy->getPointeeType();
5079 
5080   // Find expected alignment, and the actual alignment of the passed object.
5081   // getTypeAlignInChars requires complete types
5082   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5083       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5084       ArgTy->isUndeducedType())
5085     return;
5086 
5087   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5088   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5089 
5090   // If the argument is less aligned than the parameter, there is a
5091   // potential alignment issue.
5092   if (ArgAlign < ParamAlign)
5093     Diag(Loc, diag::warn_param_mismatched_alignment)
5094         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5095         << ParamName << (FDecl != nullptr) << FDecl;
5096 }
5097 
5098 /// Handles the checks for format strings, non-POD arguments to vararg
5099 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5100 /// attributes.
5101 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5102                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5103                      bool IsMemberFunction, SourceLocation Loc,
5104                      SourceRange Range, VariadicCallType CallType) {
5105   // FIXME: We should check as much as we can in the template definition.
5106   if (CurContext->isDependentContext())
5107     return;
5108 
5109   // Printf and scanf checking.
5110   llvm::SmallBitVector CheckedVarArgs;
5111   if (FDecl) {
5112     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5113       // Only create vector if there are format attributes.
5114       CheckedVarArgs.resize(Args.size());
5115 
5116       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5117                            CheckedVarArgs);
5118     }
5119   }
5120 
5121   // Refuse POD arguments that weren't caught by the format string
5122   // checks above.
5123   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5124   if (CallType != VariadicDoesNotApply &&
5125       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5126     unsigned NumParams = Proto ? Proto->getNumParams()
5127                        : FDecl && isa<FunctionDecl>(FDecl)
5128                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5129                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5130                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5131                        : 0;
5132 
5133     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5134       // Args[ArgIdx] can be null in malformed code.
5135       if (const Expr *Arg = Args[ArgIdx]) {
5136         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5137           checkVariadicArgument(Arg, CallType);
5138       }
5139     }
5140   }
5141 
5142   if (FDecl || Proto) {
5143     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5144 
5145     // Type safety checking.
5146     if (FDecl) {
5147       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5148         CheckArgumentWithTypeTag(I, Args, Loc);
5149     }
5150   }
5151 
5152   // Check that passed arguments match the alignment of original arguments.
5153   // Try to get the missing prototype from the declaration.
5154   if (!Proto && FDecl) {
5155     const auto *FT = FDecl->getFunctionType();
5156     if (isa_and_nonnull<FunctionProtoType>(FT))
5157       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5158   }
5159   if (Proto) {
5160     // For variadic functions, we may have more args than parameters.
5161     // For some K&R functions, we may have less args than parameters.
5162     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5163     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5164       // Args[ArgIdx] can be null in malformed code.
5165       if (const Expr *Arg = Args[ArgIdx]) {
5166         if (Arg->containsErrors())
5167           continue;
5168 
5169         QualType ParamTy = Proto->getParamType(ArgIdx);
5170         QualType ArgTy = Arg->getType();
5171         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5172                           ArgTy, ParamTy);
5173       }
5174     }
5175   }
5176 
5177   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5178     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5179     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5180     if (!Arg->isValueDependent()) {
5181       Expr::EvalResult Align;
5182       if (Arg->EvaluateAsInt(Align, Context)) {
5183         const llvm::APSInt &I = Align.Val.getInt();
5184         if (!I.isPowerOf2())
5185           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5186               << Arg->getSourceRange();
5187 
5188         if (I > Sema::MaximumAlignment)
5189           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5190               << Arg->getSourceRange() << Sema::MaximumAlignment;
5191       }
5192     }
5193   }
5194 
5195   if (FD)
5196     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5197 }
5198 
5199 /// CheckConstructorCall - Check a constructor call for correctness and safety
5200 /// properties not enforced by the C type system.
5201 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5202                                 ArrayRef<const Expr *> Args,
5203                                 const FunctionProtoType *Proto,
5204                                 SourceLocation Loc) {
5205   VariadicCallType CallType =
5206       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5207 
5208   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5209   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5210                     Context.getPointerType(Ctor->getThisObjectType()));
5211 
5212   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5213             Loc, SourceRange(), CallType);
5214 }
5215 
5216 /// CheckFunctionCall - Check a direct function call for various correctness
5217 /// and safety properties not strictly enforced by the C type system.
5218 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5219                              const FunctionProtoType *Proto) {
5220   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5221                               isa<CXXMethodDecl>(FDecl);
5222   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5223                           IsMemberOperatorCall;
5224   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5225                                                   TheCall->getCallee());
5226   Expr** Args = TheCall->getArgs();
5227   unsigned NumArgs = TheCall->getNumArgs();
5228 
5229   Expr *ImplicitThis = nullptr;
5230   if (IsMemberOperatorCall) {
5231     // If this is a call to a member operator, hide the first argument
5232     // from checkCall.
5233     // FIXME: Our choice of AST representation here is less than ideal.
5234     ImplicitThis = Args[0];
5235     ++Args;
5236     --NumArgs;
5237   } else if (IsMemberFunction)
5238     ImplicitThis =
5239         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5240 
5241   if (ImplicitThis) {
5242     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5243     // used.
5244     QualType ThisType = ImplicitThis->getType();
5245     if (!ThisType->isPointerType()) {
5246       assert(!ThisType->isReferenceType());
5247       ThisType = Context.getPointerType(ThisType);
5248     }
5249 
5250     QualType ThisTypeFromDecl =
5251         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5252 
5253     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5254                       ThisTypeFromDecl);
5255   }
5256 
5257   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5258             IsMemberFunction, TheCall->getRParenLoc(),
5259             TheCall->getCallee()->getSourceRange(), CallType);
5260 
5261   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5262   // None of the checks below are needed for functions that don't have
5263   // simple names (e.g., C++ conversion functions).
5264   if (!FnInfo)
5265     return false;
5266 
5267   CheckTCBEnforcement(TheCall, FDecl);
5268 
5269   CheckAbsoluteValueFunction(TheCall, FDecl);
5270   CheckMaxUnsignedZero(TheCall, FDecl);
5271 
5272   if (getLangOpts().ObjC)
5273     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5274 
5275   unsigned CMId = FDecl->getMemoryFunctionKind();
5276 
5277   // Handle memory setting and copying functions.
5278   switch (CMId) {
5279   case 0:
5280     return false;
5281   case Builtin::BIstrlcpy: // fallthrough
5282   case Builtin::BIstrlcat:
5283     CheckStrlcpycatArguments(TheCall, FnInfo);
5284     break;
5285   case Builtin::BIstrncat:
5286     CheckStrncatArguments(TheCall, FnInfo);
5287     break;
5288   case Builtin::BIfree:
5289     CheckFreeArguments(TheCall);
5290     break;
5291   default:
5292     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5293   }
5294 
5295   return false;
5296 }
5297 
5298 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5299                                ArrayRef<const Expr *> Args) {
5300   VariadicCallType CallType =
5301       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5302 
5303   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5304             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5305             CallType);
5306 
5307   return false;
5308 }
5309 
5310 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5311                             const FunctionProtoType *Proto) {
5312   QualType Ty;
5313   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5314     Ty = V->getType().getNonReferenceType();
5315   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5316     Ty = F->getType().getNonReferenceType();
5317   else
5318     return false;
5319 
5320   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5321       !Ty->isFunctionProtoType())
5322     return false;
5323 
5324   VariadicCallType CallType;
5325   if (!Proto || !Proto->isVariadic()) {
5326     CallType = VariadicDoesNotApply;
5327   } else if (Ty->isBlockPointerType()) {
5328     CallType = VariadicBlock;
5329   } else { // Ty->isFunctionPointerType()
5330     CallType = VariadicFunction;
5331   }
5332 
5333   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5334             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5335             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5336             TheCall->getCallee()->getSourceRange(), CallType);
5337 
5338   return false;
5339 }
5340 
5341 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5342 /// such as function pointers returned from functions.
5343 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5344   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5345                                                   TheCall->getCallee());
5346   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5347             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5348             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5349             TheCall->getCallee()->getSourceRange(), CallType);
5350 
5351   return false;
5352 }
5353 
5354 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5355   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5356     return false;
5357 
5358   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5359   switch (Op) {
5360   case AtomicExpr::AO__c11_atomic_init:
5361   case AtomicExpr::AO__opencl_atomic_init:
5362     llvm_unreachable("There is no ordering argument for an init");
5363 
5364   case AtomicExpr::AO__c11_atomic_load:
5365   case AtomicExpr::AO__opencl_atomic_load:
5366   case AtomicExpr::AO__hip_atomic_load:
5367   case AtomicExpr::AO__atomic_load_n:
5368   case AtomicExpr::AO__atomic_load:
5369     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5370            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5371 
5372   case AtomicExpr::AO__c11_atomic_store:
5373   case AtomicExpr::AO__opencl_atomic_store:
5374   case AtomicExpr::AO__hip_atomic_store:
5375   case AtomicExpr::AO__atomic_store:
5376   case AtomicExpr::AO__atomic_store_n:
5377     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5378            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5379            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5380 
5381   default:
5382     return true;
5383   }
5384 }
5385 
5386 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5387                                          AtomicExpr::AtomicOp Op) {
5388   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5389   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5390   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5391   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5392                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5393                          Op);
5394 }
5395 
5396 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5397                                  SourceLocation RParenLoc, MultiExprArg Args,
5398                                  AtomicExpr::AtomicOp Op,
5399                                  AtomicArgumentOrder ArgOrder) {
5400   // All the non-OpenCL operations take one of the following forms.
5401   // The OpenCL operations take the __c11 forms with one extra argument for
5402   // synchronization scope.
5403   enum {
5404     // C    __c11_atomic_init(A *, C)
5405     Init,
5406 
5407     // C    __c11_atomic_load(A *, int)
5408     Load,
5409 
5410     // void __atomic_load(A *, CP, int)
5411     LoadCopy,
5412 
5413     // void __atomic_store(A *, CP, int)
5414     Copy,
5415 
5416     // C    __c11_atomic_add(A *, M, int)
5417     Arithmetic,
5418 
5419     // C    __atomic_exchange_n(A *, CP, int)
5420     Xchg,
5421 
5422     // void __atomic_exchange(A *, C *, CP, int)
5423     GNUXchg,
5424 
5425     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5426     C11CmpXchg,
5427 
5428     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5429     GNUCmpXchg
5430   } Form = Init;
5431 
5432   const unsigned NumForm = GNUCmpXchg + 1;
5433   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5434   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5435   // where:
5436   //   C is an appropriate type,
5437   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5438   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5439   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5440   //   the int parameters are for orderings.
5441 
5442   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5443       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5444       "need to update code for modified forms");
5445   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5446                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5447                         AtomicExpr::AO__atomic_load,
5448                 "need to update code for modified C11 atomics");
5449   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5450                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5451   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5452                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5453   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5454                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5455                IsOpenCL;
5456   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5457              Op == AtomicExpr::AO__atomic_store_n ||
5458              Op == AtomicExpr::AO__atomic_exchange_n ||
5459              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5460   bool IsAddSub = false;
5461 
5462   switch (Op) {
5463   case AtomicExpr::AO__c11_atomic_init:
5464   case AtomicExpr::AO__opencl_atomic_init:
5465     Form = Init;
5466     break;
5467 
5468   case AtomicExpr::AO__c11_atomic_load:
5469   case AtomicExpr::AO__opencl_atomic_load:
5470   case AtomicExpr::AO__hip_atomic_load:
5471   case AtomicExpr::AO__atomic_load_n:
5472     Form = Load;
5473     break;
5474 
5475   case AtomicExpr::AO__atomic_load:
5476     Form = LoadCopy;
5477     break;
5478 
5479   case AtomicExpr::AO__c11_atomic_store:
5480   case AtomicExpr::AO__opencl_atomic_store:
5481   case AtomicExpr::AO__hip_atomic_store:
5482   case AtomicExpr::AO__atomic_store:
5483   case AtomicExpr::AO__atomic_store_n:
5484     Form = Copy;
5485     break;
5486   case AtomicExpr::AO__hip_atomic_fetch_add:
5487   case AtomicExpr::AO__hip_atomic_fetch_min:
5488   case AtomicExpr::AO__hip_atomic_fetch_max:
5489   case AtomicExpr::AO__c11_atomic_fetch_add:
5490   case AtomicExpr::AO__c11_atomic_fetch_sub:
5491   case AtomicExpr::AO__opencl_atomic_fetch_add:
5492   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5493   case AtomicExpr::AO__atomic_fetch_add:
5494   case AtomicExpr::AO__atomic_fetch_sub:
5495   case AtomicExpr::AO__atomic_add_fetch:
5496   case AtomicExpr::AO__atomic_sub_fetch:
5497     IsAddSub = true;
5498     Form = Arithmetic;
5499     break;
5500   case AtomicExpr::AO__c11_atomic_fetch_and:
5501   case AtomicExpr::AO__c11_atomic_fetch_or:
5502   case AtomicExpr::AO__c11_atomic_fetch_xor:
5503   case AtomicExpr::AO__hip_atomic_fetch_and:
5504   case AtomicExpr::AO__hip_atomic_fetch_or:
5505   case AtomicExpr::AO__hip_atomic_fetch_xor:
5506   case AtomicExpr::AO__c11_atomic_fetch_nand:
5507   case AtomicExpr::AO__opencl_atomic_fetch_and:
5508   case AtomicExpr::AO__opencl_atomic_fetch_or:
5509   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5510   case AtomicExpr::AO__atomic_fetch_and:
5511   case AtomicExpr::AO__atomic_fetch_or:
5512   case AtomicExpr::AO__atomic_fetch_xor:
5513   case AtomicExpr::AO__atomic_fetch_nand:
5514   case AtomicExpr::AO__atomic_and_fetch:
5515   case AtomicExpr::AO__atomic_or_fetch:
5516   case AtomicExpr::AO__atomic_xor_fetch:
5517   case AtomicExpr::AO__atomic_nand_fetch:
5518     Form = Arithmetic;
5519     break;
5520   case AtomicExpr::AO__c11_atomic_fetch_min:
5521   case AtomicExpr::AO__c11_atomic_fetch_max:
5522   case AtomicExpr::AO__opencl_atomic_fetch_min:
5523   case AtomicExpr::AO__opencl_atomic_fetch_max:
5524   case AtomicExpr::AO__atomic_min_fetch:
5525   case AtomicExpr::AO__atomic_max_fetch:
5526   case AtomicExpr::AO__atomic_fetch_min:
5527   case AtomicExpr::AO__atomic_fetch_max:
5528     Form = Arithmetic;
5529     break;
5530 
5531   case AtomicExpr::AO__c11_atomic_exchange:
5532   case AtomicExpr::AO__hip_atomic_exchange:
5533   case AtomicExpr::AO__opencl_atomic_exchange:
5534   case AtomicExpr::AO__atomic_exchange_n:
5535     Form = Xchg;
5536     break;
5537 
5538   case AtomicExpr::AO__atomic_exchange:
5539     Form = GNUXchg;
5540     break;
5541 
5542   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5543   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5544   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5545   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5546   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5547   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5548     Form = C11CmpXchg;
5549     break;
5550 
5551   case AtomicExpr::AO__atomic_compare_exchange:
5552   case AtomicExpr::AO__atomic_compare_exchange_n:
5553     Form = GNUCmpXchg;
5554     break;
5555   }
5556 
5557   unsigned AdjustedNumArgs = NumArgs[Form];
5558   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5559     ++AdjustedNumArgs;
5560   // Check we have the right number of arguments.
5561   if (Args.size() < AdjustedNumArgs) {
5562     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5563         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5564         << ExprRange;
5565     return ExprError();
5566   } else if (Args.size() > AdjustedNumArgs) {
5567     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5568          diag::err_typecheck_call_too_many_args)
5569         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5570         << ExprRange;
5571     return ExprError();
5572   }
5573 
5574   // Inspect the first argument of the atomic operation.
5575   Expr *Ptr = Args[0];
5576   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5577   if (ConvertedPtr.isInvalid())
5578     return ExprError();
5579 
5580   Ptr = ConvertedPtr.get();
5581   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5582   if (!pointerType) {
5583     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5584         << Ptr->getType() << Ptr->getSourceRange();
5585     return ExprError();
5586   }
5587 
5588   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5589   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5590   QualType ValType = AtomTy; // 'C'
5591   if (IsC11) {
5592     if (!AtomTy->isAtomicType()) {
5593       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5594           << Ptr->getType() << Ptr->getSourceRange();
5595       return ExprError();
5596     }
5597     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5598         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5599       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5600           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5601           << Ptr->getSourceRange();
5602       return ExprError();
5603     }
5604     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5605   } else if (Form != Load && Form != LoadCopy) {
5606     if (ValType.isConstQualified()) {
5607       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5608           << Ptr->getType() << Ptr->getSourceRange();
5609       return ExprError();
5610     }
5611   }
5612 
5613   // For an arithmetic operation, the implied arithmetic must be well-formed.
5614   if (Form == Arithmetic) {
5615     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5616     // trivial type errors.
5617     auto IsAllowedValueType = [&](QualType ValType) {
5618       if (ValType->isIntegerType())
5619         return true;
5620       if (ValType->isPointerType())
5621         return true;
5622       if (!ValType->isFloatingType())
5623         return false;
5624       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5625       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5626           &Context.getTargetInfo().getLongDoubleFormat() ==
5627               &llvm::APFloat::x87DoubleExtended())
5628         return false;
5629       return true;
5630     };
5631     if (IsAddSub && !IsAllowedValueType(ValType)) {
5632       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5633           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5634       return ExprError();
5635     }
5636     if (!IsAddSub && !ValType->isIntegerType()) {
5637       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5638           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5639       return ExprError();
5640     }
5641     if (IsC11 && ValType->isPointerType() &&
5642         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5643                             diag::err_incomplete_type)) {
5644       return ExprError();
5645     }
5646   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5647     // For __atomic_*_n operations, the value type must be a scalar integral or
5648     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5649     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5650         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5651     return ExprError();
5652   }
5653 
5654   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5655       !AtomTy->isScalarType()) {
5656     // For GNU atomics, require a trivially-copyable type. This is not part of
5657     // the GNU atomics specification but we enforce it for consistency with
5658     // other atomics which generally all require a trivially-copyable type. This
5659     // is because atomics just copy bits.
5660     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5661         << Ptr->getType() << Ptr->getSourceRange();
5662     return ExprError();
5663   }
5664 
5665   switch (ValType.getObjCLifetime()) {
5666   case Qualifiers::OCL_None:
5667   case Qualifiers::OCL_ExplicitNone:
5668     // okay
5669     break;
5670 
5671   case Qualifiers::OCL_Weak:
5672   case Qualifiers::OCL_Strong:
5673   case Qualifiers::OCL_Autoreleasing:
5674     // FIXME: Can this happen? By this point, ValType should be known
5675     // to be trivially copyable.
5676     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5677         << ValType << Ptr->getSourceRange();
5678     return ExprError();
5679   }
5680 
5681   // All atomic operations have an overload which takes a pointer to a volatile
5682   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5683   // into the result or the other operands. Similarly atomic_load takes a
5684   // pointer to a const 'A'.
5685   ValType.removeLocalVolatile();
5686   ValType.removeLocalConst();
5687   QualType ResultType = ValType;
5688   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5689       Form == Init)
5690     ResultType = Context.VoidTy;
5691   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5692     ResultType = Context.BoolTy;
5693 
5694   // The type of a parameter passed 'by value'. In the GNU atomics, such
5695   // arguments are actually passed as pointers.
5696   QualType ByValType = ValType; // 'CP'
5697   bool IsPassedByAddress = false;
5698   if (!IsC11 && !IsHIP && !IsN) {
5699     ByValType = Ptr->getType();
5700     IsPassedByAddress = true;
5701   }
5702 
5703   SmallVector<Expr *, 5> APIOrderedArgs;
5704   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5705     APIOrderedArgs.push_back(Args[0]);
5706     switch (Form) {
5707     case Init:
5708     case Load:
5709       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5710       break;
5711     case LoadCopy:
5712     case Copy:
5713     case Arithmetic:
5714     case Xchg:
5715       APIOrderedArgs.push_back(Args[2]); // Val1
5716       APIOrderedArgs.push_back(Args[1]); // Order
5717       break;
5718     case GNUXchg:
5719       APIOrderedArgs.push_back(Args[2]); // Val1
5720       APIOrderedArgs.push_back(Args[3]); // Val2
5721       APIOrderedArgs.push_back(Args[1]); // Order
5722       break;
5723     case C11CmpXchg:
5724       APIOrderedArgs.push_back(Args[2]); // Val1
5725       APIOrderedArgs.push_back(Args[4]); // Val2
5726       APIOrderedArgs.push_back(Args[1]); // Order
5727       APIOrderedArgs.push_back(Args[3]); // OrderFail
5728       break;
5729     case GNUCmpXchg:
5730       APIOrderedArgs.push_back(Args[2]); // Val1
5731       APIOrderedArgs.push_back(Args[4]); // Val2
5732       APIOrderedArgs.push_back(Args[5]); // Weak
5733       APIOrderedArgs.push_back(Args[1]); // Order
5734       APIOrderedArgs.push_back(Args[3]); // OrderFail
5735       break;
5736     }
5737   } else
5738     APIOrderedArgs.append(Args.begin(), Args.end());
5739 
5740   // The first argument's non-CV pointer type is used to deduce the type of
5741   // subsequent arguments, except for:
5742   //  - weak flag (always converted to bool)
5743   //  - memory order (always converted to int)
5744   //  - scope  (always converted to int)
5745   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5746     QualType Ty;
5747     if (i < NumVals[Form] + 1) {
5748       switch (i) {
5749       case 0:
5750         // The first argument is always a pointer. It has a fixed type.
5751         // It is always dereferenced, a nullptr is undefined.
5752         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5753         // Nothing else to do: we already know all we want about this pointer.
5754         continue;
5755       case 1:
5756         // The second argument is the non-atomic operand. For arithmetic, this
5757         // is always passed by value, and for a compare_exchange it is always
5758         // passed by address. For the rest, GNU uses by-address and C11 uses
5759         // by-value.
5760         assert(Form != Load);
5761         if (Form == Arithmetic && ValType->isPointerType())
5762           Ty = Context.getPointerDiffType();
5763         else if (Form == Init || Form == Arithmetic)
5764           Ty = ValType;
5765         else if (Form == Copy || Form == Xchg) {
5766           if (IsPassedByAddress) {
5767             // The value pointer is always dereferenced, a nullptr is undefined.
5768             CheckNonNullArgument(*this, APIOrderedArgs[i],
5769                                  ExprRange.getBegin());
5770           }
5771           Ty = ByValType;
5772         } else {
5773           Expr *ValArg = APIOrderedArgs[i];
5774           // The value pointer is always dereferenced, a nullptr is undefined.
5775           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5776           LangAS AS = LangAS::Default;
5777           // Keep address space of non-atomic pointer type.
5778           if (const PointerType *PtrTy =
5779                   ValArg->getType()->getAs<PointerType>()) {
5780             AS = PtrTy->getPointeeType().getAddressSpace();
5781           }
5782           Ty = Context.getPointerType(
5783               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5784         }
5785         break;
5786       case 2:
5787         // The third argument to compare_exchange / GNU exchange is the desired
5788         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5789         if (IsPassedByAddress)
5790           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5791         Ty = ByValType;
5792         break;
5793       case 3:
5794         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5795         Ty = Context.BoolTy;
5796         break;
5797       }
5798     } else {
5799       // The order(s) and scope are always converted to int.
5800       Ty = Context.IntTy;
5801     }
5802 
5803     InitializedEntity Entity =
5804         InitializedEntity::InitializeParameter(Context, Ty, false);
5805     ExprResult Arg = APIOrderedArgs[i];
5806     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5807     if (Arg.isInvalid())
5808       return true;
5809     APIOrderedArgs[i] = Arg.get();
5810   }
5811 
5812   // Permute the arguments into a 'consistent' order.
5813   SmallVector<Expr*, 5> SubExprs;
5814   SubExprs.push_back(Ptr);
5815   switch (Form) {
5816   case Init:
5817     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5818     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5819     break;
5820   case Load:
5821     SubExprs.push_back(APIOrderedArgs[1]); // Order
5822     break;
5823   case LoadCopy:
5824   case Copy:
5825   case Arithmetic:
5826   case Xchg:
5827     SubExprs.push_back(APIOrderedArgs[2]); // Order
5828     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5829     break;
5830   case GNUXchg:
5831     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5832     SubExprs.push_back(APIOrderedArgs[3]); // Order
5833     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5834     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5835     break;
5836   case C11CmpXchg:
5837     SubExprs.push_back(APIOrderedArgs[3]); // Order
5838     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5839     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5840     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5841     break;
5842   case GNUCmpXchg:
5843     SubExprs.push_back(APIOrderedArgs[4]); // Order
5844     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5845     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5846     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5847     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5848     break;
5849   }
5850 
5851   if (SubExprs.size() >= 2 && Form != Init) {
5852     if (Optional<llvm::APSInt> Result =
5853             SubExprs[1]->getIntegerConstantExpr(Context))
5854       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5855         Diag(SubExprs[1]->getBeginLoc(),
5856              diag::warn_atomic_op_has_invalid_memory_order)
5857             << SubExprs[1]->getSourceRange();
5858   }
5859 
5860   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5861     auto *Scope = Args[Args.size() - 1];
5862     if (Optional<llvm::APSInt> Result =
5863             Scope->getIntegerConstantExpr(Context)) {
5864       if (!ScopeModel->isValid(Result->getZExtValue()))
5865         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5866             << Scope->getSourceRange();
5867     }
5868     SubExprs.push_back(Scope);
5869   }
5870 
5871   AtomicExpr *AE = new (Context)
5872       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5873 
5874   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5875        Op == AtomicExpr::AO__c11_atomic_store ||
5876        Op == AtomicExpr::AO__opencl_atomic_load ||
5877        Op == AtomicExpr::AO__hip_atomic_load ||
5878        Op == AtomicExpr::AO__opencl_atomic_store ||
5879        Op == AtomicExpr::AO__hip_atomic_store) &&
5880       Context.AtomicUsesUnsupportedLibcall(AE))
5881     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5882         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5883              Op == AtomicExpr::AO__opencl_atomic_load ||
5884              Op == AtomicExpr::AO__hip_atomic_load)
5885                 ? 0
5886                 : 1);
5887 
5888   if (ValType->isBitIntType()) {
5889     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5890     return ExprError();
5891   }
5892 
5893   return AE;
5894 }
5895 
5896 /// checkBuiltinArgument - Given a call to a builtin function, perform
5897 /// normal type-checking on the given argument, updating the call in
5898 /// place.  This is useful when a builtin function requires custom
5899 /// type-checking for some of its arguments but not necessarily all of
5900 /// them.
5901 ///
5902 /// Returns true on error.
5903 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5904   FunctionDecl *Fn = E->getDirectCallee();
5905   assert(Fn && "builtin call without direct callee!");
5906 
5907   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5908   InitializedEntity Entity =
5909     InitializedEntity::InitializeParameter(S.Context, Param);
5910 
5911   ExprResult Arg = E->getArg(0);
5912   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5913   if (Arg.isInvalid())
5914     return true;
5915 
5916   E->setArg(ArgIndex, Arg.get());
5917   return false;
5918 }
5919 
5920 /// We have a call to a function like __sync_fetch_and_add, which is an
5921 /// overloaded function based on the pointer type of its first argument.
5922 /// The main BuildCallExpr routines have already promoted the types of
5923 /// arguments because all of these calls are prototyped as void(...).
5924 ///
5925 /// This function goes through and does final semantic checking for these
5926 /// builtins, as well as generating any warnings.
5927 ExprResult
5928 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5929   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5930   Expr *Callee = TheCall->getCallee();
5931   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5932   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5933 
5934   // Ensure that we have at least one argument to do type inference from.
5935   if (TheCall->getNumArgs() < 1) {
5936     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5937         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5938     return ExprError();
5939   }
5940 
5941   // Inspect the first argument of the atomic builtin.  This should always be
5942   // a pointer type, whose element is an integral scalar or pointer type.
5943   // Because it is a pointer type, we don't have to worry about any implicit
5944   // casts here.
5945   // FIXME: We don't allow floating point scalars as input.
5946   Expr *FirstArg = TheCall->getArg(0);
5947   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5948   if (FirstArgResult.isInvalid())
5949     return ExprError();
5950   FirstArg = FirstArgResult.get();
5951   TheCall->setArg(0, FirstArg);
5952 
5953   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5954   if (!pointerType) {
5955     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5956         << FirstArg->getType() << FirstArg->getSourceRange();
5957     return ExprError();
5958   }
5959 
5960   QualType ValType = pointerType->getPointeeType();
5961   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5962       !ValType->isBlockPointerType()) {
5963     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5964         << FirstArg->getType() << FirstArg->getSourceRange();
5965     return ExprError();
5966   }
5967 
5968   if (ValType.isConstQualified()) {
5969     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5970         << FirstArg->getType() << FirstArg->getSourceRange();
5971     return ExprError();
5972   }
5973 
5974   switch (ValType.getObjCLifetime()) {
5975   case Qualifiers::OCL_None:
5976   case Qualifiers::OCL_ExplicitNone:
5977     // okay
5978     break;
5979 
5980   case Qualifiers::OCL_Weak:
5981   case Qualifiers::OCL_Strong:
5982   case Qualifiers::OCL_Autoreleasing:
5983     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5984         << ValType << FirstArg->getSourceRange();
5985     return ExprError();
5986   }
5987 
5988   // Strip any qualifiers off ValType.
5989   ValType = ValType.getUnqualifiedType();
5990 
5991   // The majority of builtins return a value, but a few have special return
5992   // types, so allow them to override appropriately below.
5993   QualType ResultType = ValType;
5994 
5995   // We need to figure out which concrete builtin this maps onto.  For example,
5996   // __sync_fetch_and_add with a 2 byte object turns into
5997   // __sync_fetch_and_add_2.
5998 #define BUILTIN_ROW(x) \
5999   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6000     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6001 
6002   static const unsigned BuiltinIndices[][5] = {
6003     BUILTIN_ROW(__sync_fetch_and_add),
6004     BUILTIN_ROW(__sync_fetch_and_sub),
6005     BUILTIN_ROW(__sync_fetch_and_or),
6006     BUILTIN_ROW(__sync_fetch_and_and),
6007     BUILTIN_ROW(__sync_fetch_and_xor),
6008     BUILTIN_ROW(__sync_fetch_and_nand),
6009 
6010     BUILTIN_ROW(__sync_add_and_fetch),
6011     BUILTIN_ROW(__sync_sub_and_fetch),
6012     BUILTIN_ROW(__sync_and_and_fetch),
6013     BUILTIN_ROW(__sync_or_and_fetch),
6014     BUILTIN_ROW(__sync_xor_and_fetch),
6015     BUILTIN_ROW(__sync_nand_and_fetch),
6016 
6017     BUILTIN_ROW(__sync_val_compare_and_swap),
6018     BUILTIN_ROW(__sync_bool_compare_and_swap),
6019     BUILTIN_ROW(__sync_lock_test_and_set),
6020     BUILTIN_ROW(__sync_lock_release),
6021     BUILTIN_ROW(__sync_swap)
6022   };
6023 #undef BUILTIN_ROW
6024 
6025   // Determine the index of the size.
6026   unsigned SizeIndex;
6027   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6028   case 1: SizeIndex = 0; break;
6029   case 2: SizeIndex = 1; break;
6030   case 4: SizeIndex = 2; break;
6031   case 8: SizeIndex = 3; break;
6032   case 16: SizeIndex = 4; break;
6033   default:
6034     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6035         << FirstArg->getType() << FirstArg->getSourceRange();
6036     return ExprError();
6037   }
6038 
6039   // Each of these builtins has one pointer argument, followed by some number of
6040   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6041   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6042   // as the number of fixed args.
6043   unsigned BuiltinID = FDecl->getBuiltinID();
6044   unsigned BuiltinIndex, NumFixed = 1;
6045   bool WarnAboutSemanticsChange = false;
6046   switch (BuiltinID) {
6047   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6048   case Builtin::BI__sync_fetch_and_add:
6049   case Builtin::BI__sync_fetch_and_add_1:
6050   case Builtin::BI__sync_fetch_and_add_2:
6051   case Builtin::BI__sync_fetch_and_add_4:
6052   case Builtin::BI__sync_fetch_and_add_8:
6053   case Builtin::BI__sync_fetch_and_add_16:
6054     BuiltinIndex = 0;
6055     break;
6056 
6057   case Builtin::BI__sync_fetch_and_sub:
6058   case Builtin::BI__sync_fetch_and_sub_1:
6059   case Builtin::BI__sync_fetch_and_sub_2:
6060   case Builtin::BI__sync_fetch_and_sub_4:
6061   case Builtin::BI__sync_fetch_and_sub_8:
6062   case Builtin::BI__sync_fetch_and_sub_16:
6063     BuiltinIndex = 1;
6064     break;
6065 
6066   case Builtin::BI__sync_fetch_and_or:
6067   case Builtin::BI__sync_fetch_and_or_1:
6068   case Builtin::BI__sync_fetch_and_or_2:
6069   case Builtin::BI__sync_fetch_and_or_4:
6070   case Builtin::BI__sync_fetch_and_or_8:
6071   case Builtin::BI__sync_fetch_and_or_16:
6072     BuiltinIndex = 2;
6073     break;
6074 
6075   case Builtin::BI__sync_fetch_and_and:
6076   case Builtin::BI__sync_fetch_and_and_1:
6077   case Builtin::BI__sync_fetch_and_and_2:
6078   case Builtin::BI__sync_fetch_and_and_4:
6079   case Builtin::BI__sync_fetch_and_and_8:
6080   case Builtin::BI__sync_fetch_and_and_16:
6081     BuiltinIndex = 3;
6082     break;
6083 
6084   case Builtin::BI__sync_fetch_and_xor:
6085   case Builtin::BI__sync_fetch_and_xor_1:
6086   case Builtin::BI__sync_fetch_and_xor_2:
6087   case Builtin::BI__sync_fetch_and_xor_4:
6088   case Builtin::BI__sync_fetch_and_xor_8:
6089   case Builtin::BI__sync_fetch_and_xor_16:
6090     BuiltinIndex = 4;
6091     break;
6092 
6093   case Builtin::BI__sync_fetch_and_nand:
6094   case Builtin::BI__sync_fetch_and_nand_1:
6095   case Builtin::BI__sync_fetch_and_nand_2:
6096   case Builtin::BI__sync_fetch_and_nand_4:
6097   case Builtin::BI__sync_fetch_and_nand_8:
6098   case Builtin::BI__sync_fetch_and_nand_16:
6099     BuiltinIndex = 5;
6100     WarnAboutSemanticsChange = true;
6101     break;
6102 
6103   case Builtin::BI__sync_add_and_fetch:
6104   case Builtin::BI__sync_add_and_fetch_1:
6105   case Builtin::BI__sync_add_and_fetch_2:
6106   case Builtin::BI__sync_add_and_fetch_4:
6107   case Builtin::BI__sync_add_and_fetch_8:
6108   case Builtin::BI__sync_add_and_fetch_16:
6109     BuiltinIndex = 6;
6110     break;
6111 
6112   case Builtin::BI__sync_sub_and_fetch:
6113   case Builtin::BI__sync_sub_and_fetch_1:
6114   case Builtin::BI__sync_sub_and_fetch_2:
6115   case Builtin::BI__sync_sub_and_fetch_4:
6116   case Builtin::BI__sync_sub_and_fetch_8:
6117   case Builtin::BI__sync_sub_and_fetch_16:
6118     BuiltinIndex = 7;
6119     break;
6120 
6121   case Builtin::BI__sync_and_and_fetch:
6122   case Builtin::BI__sync_and_and_fetch_1:
6123   case Builtin::BI__sync_and_and_fetch_2:
6124   case Builtin::BI__sync_and_and_fetch_4:
6125   case Builtin::BI__sync_and_and_fetch_8:
6126   case Builtin::BI__sync_and_and_fetch_16:
6127     BuiltinIndex = 8;
6128     break;
6129 
6130   case Builtin::BI__sync_or_and_fetch:
6131   case Builtin::BI__sync_or_and_fetch_1:
6132   case Builtin::BI__sync_or_and_fetch_2:
6133   case Builtin::BI__sync_or_and_fetch_4:
6134   case Builtin::BI__sync_or_and_fetch_8:
6135   case Builtin::BI__sync_or_and_fetch_16:
6136     BuiltinIndex = 9;
6137     break;
6138 
6139   case Builtin::BI__sync_xor_and_fetch:
6140   case Builtin::BI__sync_xor_and_fetch_1:
6141   case Builtin::BI__sync_xor_and_fetch_2:
6142   case Builtin::BI__sync_xor_and_fetch_4:
6143   case Builtin::BI__sync_xor_and_fetch_8:
6144   case Builtin::BI__sync_xor_and_fetch_16:
6145     BuiltinIndex = 10;
6146     break;
6147 
6148   case Builtin::BI__sync_nand_and_fetch:
6149   case Builtin::BI__sync_nand_and_fetch_1:
6150   case Builtin::BI__sync_nand_and_fetch_2:
6151   case Builtin::BI__sync_nand_and_fetch_4:
6152   case Builtin::BI__sync_nand_and_fetch_8:
6153   case Builtin::BI__sync_nand_and_fetch_16:
6154     BuiltinIndex = 11;
6155     WarnAboutSemanticsChange = true;
6156     break;
6157 
6158   case Builtin::BI__sync_val_compare_and_swap:
6159   case Builtin::BI__sync_val_compare_and_swap_1:
6160   case Builtin::BI__sync_val_compare_and_swap_2:
6161   case Builtin::BI__sync_val_compare_and_swap_4:
6162   case Builtin::BI__sync_val_compare_and_swap_8:
6163   case Builtin::BI__sync_val_compare_and_swap_16:
6164     BuiltinIndex = 12;
6165     NumFixed = 2;
6166     break;
6167 
6168   case Builtin::BI__sync_bool_compare_and_swap:
6169   case Builtin::BI__sync_bool_compare_and_swap_1:
6170   case Builtin::BI__sync_bool_compare_and_swap_2:
6171   case Builtin::BI__sync_bool_compare_and_swap_4:
6172   case Builtin::BI__sync_bool_compare_and_swap_8:
6173   case Builtin::BI__sync_bool_compare_and_swap_16:
6174     BuiltinIndex = 13;
6175     NumFixed = 2;
6176     ResultType = Context.BoolTy;
6177     break;
6178 
6179   case Builtin::BI__sync_lock_test_and_set:
6180   case Builtin::BI__sync_lock_test_and_set_1:
6181   case Builtin::BI__sync_lock_test_and_set_2:
6182   case Builtin::BI__sync_lock_test_and_set_4:
6183   case Builtin::BI__sync_lock_test_and_set_8:
6184   case Builtin::BI__sync_lock_test_and_set_16:
6185     BuiltinIndex = 14;
6186     break;
6187 
6188   case Builtin::BI__sync_lock_release:
6189   case Builtin::BI__sync_lock_release_1:
6190   case Builtin::BI__sync_lock_release_2:
6191   case Builtin::BI__sync_lock_release_4:
6192   case Builtin::BI__sync_lock_release_8:
6193   case Builtin::BI__sync_lock_release_16:
6194     BuiltinIndex = 15;
6195     NumFixed = 0;
6196     ResultType = Context.VoidTy;
6197     break;
6198 
6199   case Builtin::BI__sync_swap:
6200   case Builtin::BI__sync_swap_1:
6201   case Builtin::BI__sync_swap_2:
6202   case Builtin::BI__sync_swap_4:
6203   case Builtin::BI__sync_swap_8:
6204   case Builtin::BI__sync_swap_16:
6205     BuiltinIndex = 16;
6206     break;
6207   }
6208 
6209   // Now that we know how many fixed arguments we expect, first check that we
6210   // have at least that many.
6211   if (TheCall->getNumArgs() < 1+NumFixed) {
6212     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6213         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6214         << Callee->getSourceRange();
6215     return ExprError();
6216   }
6217 
6218   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6219       << Callee->getSourceRange();
6220 
6221   if (WarnAboutSemanticsChange) {
6222     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6223         << Callee->getSourceRange();
6224   }
6225 
6226   // Get the decl for the concrete builtin from this, we can tell what the
6227   // concrete integer type we should convert to is.
6228   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6229   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6230   FunctionDecl *NewBuiltinDecl;
6231   if (NewBuiltinID == BuiltinID)
6232     NewBuiltinDecl = FDecl;
6233   else {
6234     // Perform builtin lookup to avoid redeclaring it.
6235     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6236     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6237     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6238     assert(Res.getFoundDecl());
6239     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6240     if (!NewBuiltinDecl)
6241       return ExprError();
6242   }
6243 
6244   // The first argument --- the pointer --- has a fixed type; we
6245   // deduce the types of the rest of the arguments accordingly.  Walk
6246   // the remaining arguments, converting them to the deduced value type.
6247   for (unsigned i = 0; i != NumFixed; ++i) {
6248     ExprResult Arg = TheCall->getArg(i+1);
6249 
6250     // GCC does an implicit conversion to the pointer or integer ValType.  This
6251     // can fail in some cases (1i -> int**), check for this error case now.
6252     // Initialize the argument.
6253     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6254                                                    ValType, /*consume*/ false);
6255     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6256     if (Arg.isInvalid())
6257       return ExprError();
6258 
6259     // Okay, we have something that *can* be converted to the right type.  Check
6260     // to see if there is a potentially weird extension going on here.  This can
6261     // happen when you do an atomic operation on something like an char* and
6262     // pass in 42.  The 42 gets converted to char.  This is even more strange
6263     // for things like 45.123 -> char, etc.
6264     // FIXME: Do this check.
6265     TheCall->setArg(i+1, Arg.get());
6266   }
6267 
6268   // Create a new DeclRefExpr to refer to the new decl.
6269   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6270       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6271       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6272       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6273 
6274   // Set the callee in the CallExpr.
6275   // FIXME: This loses syntactic information.
6276   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6277   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6278                                               CK_BuiltinFnToFnPtr);
6279   TheCall->setCallee(PromotedCall.get());
6280 
6281   // Change the result type of the call to match the original value type. This
6282   // is arbitrary, but the codegen for these builtins ins design to handle it
6283   // gracefully.
6284   TheCall->setType(ResultType);
6285 
6286   // Prohibit problematic uses of bit-precise integer types with atomic
6287   // builtins. The arguments would have already been converted to the first
6288   // argument's type, so only need to check the first argument.
6289   const auto *BitIntValType = ValType->getAs<BitIntType>();
6290   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6291     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6292     return ExprError();
6293   }
6294 
6295   return TheCallResult;
6296 }
6297 
6298 /// SemaBuiltinNontemporalOverloaded - We have a call to
6299 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6300 /// overloaded function based on the pointer type of its last argument.
6301 ///
6302 /// This function goes through and does final semantic checking for these
6303 /// builtins.
6304 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6305   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6306   DeclRefExpr *DRE =
6307       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6308   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6309   unsigned BuiltinID = FDecl->getBuiltinID();
6310   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6311           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6312          "Unexpected nontemporal load/store builtin!");
6313   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6314   unsigned numArgs = isStore ? 2 : 1;
6315 
6316   // Ensure that we have the proper number of arguments.
6317   if (checkArgCount(*this, TheCall, numArgs))
6318     return ExprError();
6319 
6320   // Inspect the last argument of the nontemporal builtin.  This should always
6321   // be a pointer type, from which we imply the type of the memory access.
6322   // Because it is a pointer type, we don't have to worry about any implicit
6323   // casts here.
6324   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6325   ExprResult PointerArgResult =
6326       DefaultFunctionArrayLvalueConversion(PointerArg);
6327 
6328   if (PointerArgResult.isInvalid())
6329     return ExprError();
6330   PointerArg = PointerArgResult.get();
6331   TheCall->setArg(numArgs - 1, PointerArg);
6332 
6333   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6334   if (!pointerType) {
6335     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6336         << PointerArg->getType() << PointerArg->getSourceRange();
6337     return ExprError();
6338   }
6339 
6340   QualType ValType = pointerType->getPointeeType();
6341 
6342   // Strip any qualifiers off ValType.
6343   ValType = ValType.getUnqualifiedType();
6344   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6345       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6346       !ValType->isVectorType()) {
6347     Diag(DRE->getBeginLoc(),
6348          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6349         << PointerArg->getType() << PointerArg->getSourceRange();
6350     return ExprError();
6351   }
6352 
6353   if (!isStore) {
6354     TheCall->setType(ValType);
6355     return TheCallResult;
6356   }
6357 
6358   ExprResult ValArg = TheCall->getArg(0);
6359   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6360       Context, ValType, /*consume*/ false);
6361   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6362   if (ValArg.isInvalid())
6363     return ExprError();
6364 
6365   TheCall->setArg(0, ValArg.get());
6366   TheCall->setType(Context.VoidTy);
6367   return TheCallResult;
6368 }
6369 
6370 /// CheckObjCString - Checks that the argument to the builtin
6371 /// CFString constructor is correct
6372 /// Note: It might also make sense to do the UTF-16 conversion here (would
6373 /// simplify the backend).
6374 bool Sema::CheckObjCString(Expr *Arg) {
6375   Arg = Arg->IgnoreParenCasts();
6376   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6377 
6378   if (!Literal || !Literal->isAscii()) {
6379     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6380         << Arg->getSourceRange();
6381     return true;
6382   }
6383 
6384   if (Literal->containsNonAsciiOrNull()) {
6385     StringRef String = Literal->getString();
6386     unsigned NumBytes = String.size();
6387     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6388     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6389     llvm::UTF16 *ToPtr = &ToBuf[0];
6390 
6391     llvm::ConversionResult Result =
6392         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6393                                  ToPtr + NumBytes, llvm::strictConversion);
6394     // Check for conversion failure.
6395     if (Result != llvm::conversionOK)
6396       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6397           << Arg->getSourceRange();
6398   }
6399   return false;
6400 }
6401 
6402 /// CheckObjCString - Checks that the format string argument to the os_log()
6403 /// and os_trace() functions is correct, and converts it to const char *.
6404 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6405   Arg = Arg->IgnoreParenCasts();
6406   auto *Literal = dyn_cast<StringLiteral>(Arg);
6407   if (!Literal) {
6408     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6409       Literal = ObjcLiteral->getString();
6410     }
6411   }
6412 
6413   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6414     return ExprError(
6415         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6416         << Arg->getSourceRange());
6417   }
6418 
6419   ExprResult Result(Literal);
6420   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6421   InitializedEntity Entity =
6422       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6423   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6424   return Result;
6425 }
6426 
6427 /// Check that the user is calling the appropriate va_start builtin for the
6428 /// target and calling convention.
6429 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6430   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6431   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6432   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6433                     TT.getArch() == llvm::Triple::aarch64_32);
6434   bool IsWindows = TT.isOSWindows();
6435   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6436   if (IsX64 || IsAArch64) {
6437     CallingConv CC = CC_C;
6438     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6439       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6440     if (IsMSVAStart) {
6441       // Don't allow this in System V ABI functions.
6442       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6443         return S.Diag(Fn->getBeginLoc(),
6444                       diag::err_ms_va_start_used_in_sysv_function);
6445     } else {
6446       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6447       // On x64 Windows, don't allow this in System V ABI functions.
6448       // (Yes, that means there's no corresponding way to support variadic
6449       // System V ABI functions on Windows.)
6450       if ((IsWindows && CC == CC_X86_64SysV) ||
6451           (!IsWindows && CC == CC_Win64))
6452         return S.Diag(Fn->getBeginLoc(),
6453                       diag::err_va_start_used_in_wrong_abi_function)
6454                << !IsWindows;
6455     }
6456     return false;
6457   }
6458 
6459   if (IsMSVAStart)
6460     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6461   return false;
6462 }
6463 
6464 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6465                                              ParmVarDecl **LastParam = nullptr) {
6466   // Determine whether the current function, block, or obj-c method is variadic
6467   // and get its parameter list.
6468   bool IsVariadic = false;
6469   ArrayRef<ParmVarDecl *> Params;
6470   DeclContext *Caller = S.CurContext;
6471   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6472     IsVariadic = Block->isVariadic();
6473     Params = Block->parameters();
6474   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6475     IsVariadic = FD->isVariadic();
6476     Params = FD->parameters();
6477   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6478     IsVariadic = MD->isVariadic();
6479     // FIXME: This isn't correct for methods (results in bogus warning).
6480     Params = MD->parameters();
6481   } else if (isa<CapturedDecl>(Caller)) {
6482     // We don't support va_start in a CapturedDecl.
6483     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6484     return true;
6485   } else {
6486     // This must be some other declcontext that parses exprs.
6487     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6488     return true;
6489   }
6490 
6491   if (!IsVariadic) {
6492     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6493     return true;
6494   }
6495 
6496   if (LastParam)
6497     *LastParam = Params.empty() ? nullptr : Params.back();
6498 
6499   return false;
6500 }
6501 
6502 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6503 /// for validity.  Emit an error and return true on failure; return false
6504 /// on success.
6505 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6506   Expr *Fn = TheCall->getCallee();
6507 
6508   if (checkVAStartABI(*this, BuiltinID, Fn))
6509     return true;
6510 
6511   if (checkArgCount(*this, TheCall, 2))
6512     return true;
6513 
6514   // Type-check the first argument normally.
6515   if (checkBuiltinArgument(*this, TheCall, 0))
6516     return true;
6517 
6518   // Check that the current function is variadic, and get its last parameter.
6519   ParmVarDecl *LastParam;
6520   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6521     return true;
6522 
6523   // Verify that the second argument to the builtin is the last argument of the
6524   // current function or method.
6525   bool SecondArgIsLastNamedArgument = false;
6526   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6527 
6528   // These are valid if SecondArgIsLastNamedArgument is false after the next
6529   // block.
6530   QualType Type;
6531   SourceLocation ParamLoc;
6532   bool IsCRegister = false;
6533 
6534   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6535     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6536       SecondArgIsLastNamedArgument = PV == LastParam;
6537 
6538       Type = PV->getType();
6539       ParamLoc = PV->getLocation();
6540       IsCRegister =
6541           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6542     }
6543   }
6544 
6545   if (!SecondArgIsLastNamedArgument)
6546     Diag(TheCall->getArg(1)->getBeginLoc(),
6547          diag::warn_second_arg_of_va_start_not_last_named_param);
6548   else if (IsCRegister || Type->isReferenceType() ||
6549            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6550              // Promotable integers are UB, but enumerations need a bit of
6551              // extra checking to see what their promotable type actually is.
6552              if (!Type->isPromotableIntegerType())
6553                return false;
6554              if (!Type->isEnumeralType())
6555                return true;
6556              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6557              return !(ED &&
6558                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6559            }()) {
6560     unsigned Reason = 0;
6561     if (Type->isReferenceType())  Reason = 1;
6562     else if (IsCRegister)         Reason = 2;
6563     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6564     Diag(ParamLoc, diag::note_parameter_type) << Type;
6565   }
6566 
6567   TheCall->setType(Context.VoidTy);
6568   return false;
6569 }
6570 
6571 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6572   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6573     const LangOptions &LO = getLangOpts();
6574 
6575     if (LO.CPlusPlus)
6576       return Arg->getType()
6577                  .getCanonicalType()
6578                  .getTypePtr()
6579                  ->getPointeeType()
6580                  .withoutLocalFastQualifiers() == Context.CharTy;
6581 
6582     // In C, allow aliasing through `char *`, this is required for AArch64 at
6583     // least.
6584     return true;
6585   };
6586 
6587   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6588   //                 const char *named_addr);
6589 
6590   Expr *Func = Call->getCallee();
6591 
6592   if (Call->getNumArgs() < 3)
6593     return Diag(Call->getEndLoc(),
6594                 diag::err_typecheck_call_too_few_args_at_least)
6595            << 0 /*function call*/ << 3 << Call->getNumArgs();
6596 
6597   // Type-check the first argument normally.
6598   if (checkBuiltinArgument(*this, Call, 0))
6599     return true;
6600 
6601   // Check that the current function is variadic.
6602   if (checkVAStartIsInVariadicFunction(*this, Func))
6603     return true;
6604 
6605   // __va_start on Windows does not validate the parameter qualifiers
6606 
6607   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6608   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6609 
6610   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6611   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6612 
6613   const QualType &ConstCharPtrTy =
6614       Context.getPointerType(Context.CharTy.withConst());
6615   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6616     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6617         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6618         << 0                                      /* qualifier difference */
6619         << 3                                      /* parameter mismatch */
6620         << 2 << Arg1->getType() << ConstCharPtrTy;
6621 
6622   const QualType SizeTy = Context.getSizeType();
6623   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6624     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6625         << Arg2->getType() << SizeTy << 1 /* different class */
6626         << 0                              /* qualifier difference */
6627         << 3                              /* parameter mismatch */
6628         << 3 << Arg2->getType() << SizeTy;
6629 
6630   return false;
6631 }
6632 
6633 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6634 /// friends.  This is declared to take (...), so we have to check everything.
6635 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6636   if (checkArgCount(*this, TheCall, 2))
6637     return true;
6638 
6639   ExprResult OrigArg0 = TheCall->getArg(0);
6640   ExprResult OrigArg1 = TheCall->getArg(1);
6641 
6642   // Do standard promotions between the two arguments, returning their common
6643   // type.
6644   QualType Res = UsualArithmeticConversions(
6645       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6646   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6647     return true;
6648 
6649   // Make sure any conversions are pushed back into the call; this is
6650   // type safe since unordered compare builtins are declared as "_Bool
6651   // foo(...)".
6652   TheCall->setArg(0, OrigArg0.get());
6653   TheCall->setArg(1, OrigArg1.get());
6654 
6655   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6656     return false;
6657 
6658   // If the common type isn't a real floating type, then the arguments were
6659   // invalid for this operation.
6660   if (Res.isNull() || !Res->isRealFloatingType())
6661     return Diag(OrigArg0.get()->getBeginLoc(),
6662                 diag::err_typecheck_call_invalid_ordered_compare)
6663            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6664            << SourceRange(OrigArg0.get()->getBeginLoc(),
6665                           OrigArg1.get()->getEndLoc());
6666 
6667   return false;
6668 }
6669 
6670 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6671 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6672 /// to check everything. We expect the last argument to be a floating point
6673 /// value.
6674 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6675   if (checkArgCount(*this, TheCall, NumArgs))
6676     return true;
6677 
6678   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6679   // on all preceding parameters just being int.  Try all of those.
6680   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6681     Expr *Arg = TheCall->getArg(i);
6682 
6683     if (Arg->isTypeDependent())
6684       return false;
6685 
6686     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6687 
6688     if (Res.isInvalid())
6689       return true;
6690     TheCall->setArg(i, Res.get());
6691   }
6692 
6693   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6694 
6695   if (OrigArg->isTypeDependent())
6696     return false;
6697 
6698   // Usual Unary Conversions will convert half to float, which we want for
6699   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6700   // type how it is, but do normal L->Rvalue conversions.
6701   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6702     OrigArg = UsualUnaryConversions(OrigArg).get();
6703   else
6704     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6705   TheCall->setArg(NumArgs - 1, OrigArg);
6706 
6707   // This operation requires a non-_Complex floating-point number.
6708   if (!OrigArg->getType()->isRealFloatingType())
6709     return Diag(OrigArg->getBeginLoc(),
6710                 diag::err_typecheck_call_invalid_unary_fp)
6711            << OrigArg->getType() << OrigArg->getSourceRange();
6712 
6713   return false;
6714 }
6715 
6716 /// Perform semantic analysis for a call to __builtin_complex.
6717 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6718   if (checkArgCount(*this, TheCall, 2))
6719     return true;
6720 
6721   bool Dependent = false;
6722   for (unsigned I = 0; I != 2; ++I) {
6723     Expr *Arg = TheCall->getArg(I);
6724     QualType T = Arg->getType();
6725     if (T->isDependentType()) {
6726       Dependent = true;
6727       continue;
6728     }
6729 
6730     // Despite supporting _Complex int, GCC requires a real floating point type
6731     // for the operands of __builtin_complex.
6732     if (!T->isRealFloatingType()) {
6733       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6734              << Arg->getType() << Arg->getSourceRange();
6735     }
6736 
6737     ExprResult Converted = DefaultLvalueConversion(Arg);
6738     if (Converted.isInvalid())
6739       return true;
6740     TheCall->setArg(I, Converted.get());
6741   }
6742 
6743   if (Dependent) {
6744     TheCall->setType(Context.DependentTy);
6745     return false;
6746   }
6747 
6748   Expr *Real = TheCall->getArg(0);
6749   Expr *Imag = TheCall->getArg(1);
6750   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6751     return Diag(Real->getBeginLoc(),
6752                 diag::err_typecheck_call_different_arg_types)
6753            << Real->getType() << Imag->getType()
6754            << Real->getSourceRange() << Imag->getSourceRange();
6755   }
6756 
6757   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6758   // don't allow this builtin to form those types either.
6759   // FIXME: Should we allow these types?
6760   if (Real->getType()->isFloat16Type())
6761     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6762            << "_Float16";
6763   if (Real->getType()->isHalfType())
6764     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6765            << "half";
6766 
6767   TheCall->setType(Context.getComplexType(Real->getType()));
6768   return false;
6769 }
6770 
6771 // Customized Sema Checking for VSX builtins that have the following signature:
6772 // vector [...] builtinName(vector [...], vector [...], const int);
6773 // Which takes the same type of vectors (any legal vector type) for the first
6774 // two arguments and takes compile time constant for the third argument.
6775 // Example builtins are :
6776 // vector double vec_xxpermdi(vector double, vector double, int);
6777 // vector short vec_xxsldwi(vector short, vector short, int);
6778 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6779   unsigned ExpectedNumArgs = 3;
6780   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6781     return true;
6782 
6783   // Check the third argument is a compile time constant
6784   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6785     return Diag(TheCall->getBeginLoc(),
6786                 diag::err_vsx_builtin_nonconstant_argument)
6787            << 3 /* argument index */ << TheCall->getDirectCallee()
6788            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6789                           TheCall->getArg(2)->getEndLoc());
6790 
6791   QualType Arg1Ty = TheCall->getArg(0)->getType();
6792   QualType Arg2Ty = TheCall->getArg(1)->getType();
6793 
6794   // Check the type of argument 1 and argument 2 are vectors.
6795   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6796   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6797       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6798     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6799            << TheCall->getDirectCallee()
6800            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6801                           TheCall->getArg(1)->getEndLoc());
6802   }
6803 
6804   // Check the first two arguments are the same type.
6805   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6806     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6807            << TheCall->getDirectCallee()
6808            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6809                           TheCall->getArg(1)->getEndLoc());
6810   }
6811 
6812   // When default clang type checking is turned off and the customized type
6813   // checking is used, the returning type of the function must be explicitly
6814   // set. Otherwise it is _Bool by default.
6815   TheCall->setType(Arg1Ty);
6816 
6817   return false;
6818 }
6819 
6820 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6821 // This is declared to take (...), so we have to check everything.
6822 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6823   if (TheCall->getNumArgs() < 2)
6824     return ExprError(Diag(TheCall->getEndLoc(),
6825                           diag::err_typecheck_call_too_few_args_at_least)
6826                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6827                      << TheCall->getSourceRange());
6828 
6829   // Determine which of the following types of shufflevector we're checking:
6830   // 1) unary, vector mask: (lhs, mask)
6831   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6832   QualType resType = TheCall->getArg(0)->getType();
6833   unsigned numElements = 0;
6834 
6835   if (!TheCall->getArg(0)->isTypeDependent() &&
6836       !TheCall->getArg(1)->isTypeDependent()) {
6837     QualType LHSType = TheCall->getArg(0)->getType();
6838     QualType RHSType = TheCall->getArg(1)->getType();
6839 
6840     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6841       return ExprError(
6842           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6843           << TheCall->getDirectCallee()
6844           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6845                          TheCall->getArg(1)->getEndLoc()));
6846 
6847     numElements = LHSType->castAs<VectorType>()->getNumElements();
6848     unsigned numResElements = TheCall->getNumArgs() - 2;
6849 
6850     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6851     // with mask.  If so, verify that RHS is an integer vector type with the
6852     // same number of elts as lhs.
6853     if (TheCall->getNumArgs() == 2) {
6854       if (!RHSType->hasIntegerRepresentation() ||
6855           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6856         return ExprError(Diag(TheCall->getBeginLoc(),
6857                               diag::err_vec_builtin_incompatible_vector)
6858                          << TheCall->getDirectCallee()
6859                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6860                                         TheCall->getArg(1)->getEndLoc()));
6861     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6862       return ExprError(Diag(TheCall->getBeginLoc(),
6863                             diag::err_vec_builtin_incompatible_vector)
6864                        << TheCall->getDirectCallee()
6865                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6866                                       TheCall->getArg(1)->getEndLoc()));
6867     } else if (numElements != numResElements) {
6868       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6869       resType = Context.getVectorType(eltType, numResElements,
6870                                       VectorType::GenericVector);
6871     }
6872   }
6873 
6874   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6875     if (TheCall->getArg(i)->isTypeDependent() ||
6876         TheCall->getArg(i)->isValueDependent())
6877       continue;
6878 
6879     Optional<llvm::APSInt> Result;
6880     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6881       return ExprError(Diag(TheCall->getBeginLoc(),
6882                             diag::err_shufflevector_nonconstant_argument)
6883                        << TheCall->getArg(i)->getSourceRange());
6884 
6885     // Allow -1 which will be translated to undef in the IR.
6886     if (Result->isSigned() && Result->isAllOnes())
6887       continue;
6888 
6889     if (Result->getActiveBits() > 64 ||
6890         Result->getZExtValue() >= numElements * 2)
6891       return ExprError(Diag(TheCall->getBeginLoc(),
6892                             diag::err_shufflevector_argument_too_large)
6893                        << TheCall->getArg(i)->getSourceRange());
6894   }
6895 
6896   SmallVector<Expr*, 32> exprs;
6897 
6898   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6899     exprs.push_back(TheCall->getArg(i));
6900     TheCall->setArg(i, nullptr);
6901   }
6902 
6903   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6904                                          TheCall->getCallee()->getBeginLoc(),
6905                                          TheCall->getRParenLoc());
6906 }
6907 
6908 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6909 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6910                                        SourceLocation BuiltinLoc,
6911                                        SourceLocation RParenLoc) {
6912   ExprValueKind VK = VK_PRValue;
6913   ExprObjectKind OK = OK_Ordinary;
6914   QualType DstTy = TInfo->getType();
6915   QualType SrcTy = E->getType();
6916 
6917   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6918     return ExprError(Diag(BuiltinLoc,
6919                           diag::err_convertvector_non_vector)
6920                      << E->getSourceRange());
6921   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6922     return ExprError(Diag(BuiltinLoc,
6923                           diag::err_convertvector_non_vector_type));
6924 
6925   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6926     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6927     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6928     if (SrcElts != DstElts)
6929       return ExprError(Diag(BuiltinLoc,
6930                             diag::err_convertvector_incompatible_vector)
6931                        << E->getSourceRange());
6932   }
6933 
6934   return new (Context)
6935       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6936 }
6937 
6938 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6939 // This is declared to take (const void*, ...) and can take two
6940 // optional constant int args.
6941 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6942   unsigned NumArgs = TheCall->getNumArgs();
6943 
6944   if (NumArgs > 3)
6945     return Diag(TheCall->getEndLoc(),
6946                 diag::err_typecheck_call_too_many_args_at_most)
6947            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6948 
6949   // Argument 0 is checked for us and the remaining arguments must be
6950   // constant integers.
6951   for (unsigned i = 1; i != NumArgs; ++i)
6952     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6953       return true;
6954 
6955   return false;
6956 }
6957 
6958 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6959 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6960   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6961     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6962            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6963   if (checkArgCount(*this, TheCall, 1))
6964     return true;
6965   Expr *Arg = TheCall->getArg(0);
6966   if (Arg->isInstantiationDependent())
6967     return false;
6968 
6969   QualType ArgTy = Arg->getType();
6970   if (!ArgTy->hasFloatingRepresentation())
6971     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6972            << ArgTy;
6973   if (Arg->isLValue()) {
6974     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6975     TheCall->setArg(0, FirstArg.get());
6976   }
6977   TheCall->setType(TheCall->getArg(0)->getType());
6978   return false;
6979 }
6980 
6981 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6982 // __assume does not evaluate its arguments, and should warn if its argument
6983 // has side effects.
6984 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6985   Expr *Arg = TheCall->getArg(0);
6986   if (Arg->isInstantiationDependent()) return false;
6987 
6988   if (Arg->HasSideEffects(Context))
6989     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6990         << Arg->getSourceRange()
6991         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6992 
6993   return false;
6994 }
6995 
6996 /// Handle __builtin_alloca_with_align. This is declared
6997 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6998 /// than 8.
6999 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7000   // The alignment must be a constant integer.
7001   Expr *Arg = TheCall->getArg(1);
7002 
7003   // We can't check the value of a dependent argument.
7004   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7005     if (const auto *UE =
7006             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7007       if (UE->getKind() == UETT_AlignOf ||
7008           UE->getKind() == UETT_PreferredAlignOf)
7009         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7010             << Arg->getSourceRange();
7011 
7012     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7013 
7014     if (!Result.isPowerOf2())
7015       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7016              << Arg->getSourceRange();
7017 
7018     if (Result < Context.getCharWidth())
7019       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7020              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7021 
7022     if (Result > std::numeric_limits<int32_t>::max())
7023       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7024              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7025   }
7026 
7027   return false;
7028 }
7029 
7030 /// Handle __builtin_assume_aligned. This is declared
7031 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7032 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7033   unsigned NumArgs = TheCall->getNumArgs();
7034 
7035   if (NumArgs > 3)
7036     return Diag(TheCall->getEndLoc(),
7037                 diag::err_typecheck_call_too_many_args_at_most)
7038            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7039 
7040   // The alignment must be a constant integer.
7041   Expr *Arg = TheCall->getArg(1);
7042 
7043   // We can't check the value of a dependent argument.
7044   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7045     llvm::APSInt Result;
7046     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7047       return true;
7048 
7049     if (!Result.isPowerOf2())
7050       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7051              << Arg->getSourceRange();
7052 
7053     if (Result > Sema::MaximumAlignment)
7054       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7055           << Arg->getSourceRange() << Sema::MaximumAlignment;
7056   }
7057 
7058   if (NumArgs > 2) {
7059     ExprResult Arg(TheCall->getArg(2));
7060     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7061       Context.getSizeType(), false);
7062     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7063     if (Arg.isInvalid()) return true;
7064     TheCall->setArg(2, Arg.get());
7065   }
7066 
7067   return false;
7068 }
7069 
7070 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7071   unsigned BuiltinID =
7072       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7073   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7074 
7075   unsigned NumArgs = TheCall->getNumArgs();
7076   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7077   if (NumArgs < NumRequiredArgs) {
7078     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7079            << 0 /* function call */ << NumRequiredArgs << NumArgs
7080            << TheCall->getSourceRange();
7081   }
7082   if (NumArgs >= NumRequiredArgs + 0x100) {
7083     return Diag(TheCall->getEndLoc(),
7084                 diag::err_typecheck_call_too_many_args_at_most)
7085            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7086            << TheCall->getSourceRange();
7087   }
7088   unsigned i = 0;
7089 
7090   // For formatting call, check buffer arg.
7091   if (!IsSizeCall) {
7092     ExprResult Arg(TheCall->getArg(i));
7093     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7094         Context, Context.VoidPtrTy, false);
7095     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7096     if (Arg.isInvalid())
7097       return true;
7098     TheCall->setArg(i, Arg.get());
7099     i++;
7100   }
7101 
7102   // Check string literal arg.
7103   unsigned FormatIdx = i;
7104   {
7105     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7106     if (Arg.isInvalid())
7107       return true;
7108     TheCall->setArg(i, Arg.get());
7109     i++;
7110   }
7111 
7112   // Make sure variadic args are scalar.
7113   unsigned FirstDataArg = i;
7114   while (i < NumArgs) {
7115     ExprResult Arg = DefaultVariadicArgumentPromotion(
7116         TheCall->getArg(i), VariadicFunction, nullptr);
7117     if (Arg.isInvalid())
7118       return true;
7119     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7120     if (ArgSize.getQuantity() >= 0x100) {
7121       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7122              << i << (int)ArgSize.getQuantity() << 0xff
7123              << TheCall->getSourceRange();
7124     }
7125     TheCall->setArg(i, Arg.get());
7126     i++;
7127   }
7128 
7129   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7130   // call to avoid duplicate diagnostics.
7131   if (!IsSizeCall) {
7132     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7133     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7134     bool Success = CheckFormatArguments(
7135         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7136         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7137         CheckedVarArgs);
7138     if (!Success)
7139       return true;
7140   }
7141 
7142   if (IsSizeCall) {
7143     TheCall->setType(Context.getSizeType());
7144   } else {
7145     TheCall->setType(Context.VoidPtrTy);
7146   }
7147   return false;
7148 }
7149 
7150 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7151 /// TheCall is a constant expression.
7152 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7153                                   llvm::APSInt &Result) {
7154   Expr *Arg = TheCall->getArg(ArgNum);
7155   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7156   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7157 
7158   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7159 
7160   Optional<llvm::APSInt> R;
7161   if (!(R = Arg->getIntegerConstantExpr(Context)))
7162     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7163            << FDecl->getDeclName() << Arg->getSourceRange();
7164   Result = *R;
7165   return false;
7166 }
7167 
7168 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7169 /// TheCall is a constant expression in the range [Low, High].
7170 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7171                                        int Low, int High, bool RangeIsError) {
7172   if (isConstantEvaluated())
7173     return false;
7174   llvm::APSInt Result;
7175 
7176   // We can't check the value of a dependent argument.
7177   Expr *Arg = TheCall->getArg(ArgNum);
7178   if (Arg->isTypeDependent() || Arg->isValueDependent())
7179     return false;
7180 
7181   // Check constant-ness first.
7182   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7183     return true;
7184 
7185   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7186     if (RangeIsError)
7187       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7188              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7189     else
7190       // Defer the warning until we know if the code will be emitted so that
7191       // dead code can ignore this.
7192       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7193                           PDiag(diag::warn_argument_invalid_range)
7194                               << toString(Result, 10) << Low << High
7195                               << Arg->getSourceRange());
7196   }
7197 
7198   return false;
7199 }
7200 
7201 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7202 /// TheCall is a constant expression is a multiple of Num..
7203 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7204                                           unsigned Num) {
7205   llvm::APSInt Result;
7206 
7207   // We can't check the value of a dependent argument.
7208   Expr *Arg = TheCall->getArg(ArgNum);
7209   if (Arg->isTypeDependent() || Arg->isValueDependent())
7210     return false;
7211 
7212   // Check constant-ness first.
7213   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7214     return true;
7215 
7216   if (Result.getSExtValue() % Num != 0)
7217     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7218            << Num << Arg->getSourceRange();
7219 
7220   return false;
7221 }
7222 
7223 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7224 /// constant expression representing a power of 2.
7225 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7226   llvm::APSInt Result;
7227 
7228   // We can't check the value of a dependent argument.
7229   Expr *Arg = TheCall->getArg(ArgNum);
7230   if (Arg->isTypeDependent() || Arg->isValueDependent())
7231     return false;
7232 
7233   // Check constant-ness first.
7234   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7235     return true;
7236 
7237   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7238   // and only if x is a power of 2.
7239   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7240     return false;
7241 
7242   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7243          << Arg->getSourceRange();
7244 }
7245 
7246 static bool IsShiftedByte(llvm::APSInt Value) {
7247   if (Value.isNegative())
7248     return false;
7249 
7250   // Check if it's a shifted byte, by shifting it down
7251   while (true) {
7252     // If the value fits in the bottom byte, the check passes.
7253     if (Value < 0x100)
7254       return true;
7255 
7256     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7257     // fails.
7258     if ((Value & 0xFF) != 0)
7259       return false;
7260 
7261     // If the bottom 8 bits are all 0, but something above that is nonzero,
7262     // then shifting the value right by 8 bits won't affect whether it's a
7263     // shifted byte or not. So do that, and go round again.
7264     Value >>= 8;
7265   }
7266 }
7267 
7268 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7269 /// a constant expression representing an arbitrary byte value shifted left by
7270 /// a multiple of 8 bits.
7271 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7272                                              unsigned ArgBits) {
7273   llvm::APSInt Result;
7274 
7275   // We can't check the value of a dependent argument.
7276   Expr *Arg = TheCall->getArg(ArgNum);
7277   if (Arg->isTypeDependent() || Arg->isValueDependent())
7278     return false;
7279 
7280   // Check constant-ness first.
7281   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7282     return true;
7283 
7284   // Truncate to the given size.
7285   Result = Result.getLoBits(ArgBits);
7286   Result.setIsUnsigned(true);
7287 
7288   if (IsShiftedByte(Result))
7289     return false;
7290 
7291   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7292          << Arg->getSourceRange();
7293 }
7294 
7295 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7296 /// TheCall is a constant expression representing either a shifted byte value,
7297 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7298 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7299 /// Arm MVE intrinsics.
7300 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7301                                                    int ArgNum,
7302                                                    unsigned ArgBits) {
7303   llvm::APSInt Result;
7304 
7305   // We can't check the value of a dependent argument.
7306   Expr *Arg = TheCall->getArg(ArgNum);
7307   if (Arg->isTypeDependent() || Arg->isValueDependent())
7308     return false;
7309 
7310   // Check constant-ness first.
7311   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7312     return true;
7313 
7314   // Truncate to the given size.
7315   Result = Result.getLoBits(ArgBits);
7316   Result.setIsUnsigned(true);
7317 
7318   // Check to see if it's in either of the required forms.
7319   if (IsShiftedByte(Result) ||
7320       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7321     return false;
7322 
7323   return Diag(TheCall->getBeginLoc(),
7324               diag::err_argument_not_shifted_byte_or_xxff)
7325          << Arg->getSourceRange();
7326 }
7327 
7328 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7329 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7330   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7331     if (checkArgCount(*this, TheCall, 2))
7332       return true;
7333     Expr *Arg0 = TheCall->getArg(0);
7334     Expr *Arg1 = TheCall->getArg(1);
7335 
7336     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7337     if (FirstArg.isInvalid())
7338       return true;
7339     QualType FirstArgType = FirstArg.get()->getType();
7340     if (!FirstArgType->isAnyPointerType())
7341       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7342                << "first" << FirstArgType << Arg0->getSourceRange();
7343     TheCall->setArg(0, FirstArg.get());
7344 
7345     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7346     if (SecArg.isInvalid())
7347       return true;
7348     QualType SecArgType = SecArg.get()->getType();
7349     if (!SecArgType->isIntegerType())
7350       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7351                << "second" << SecArgType << Arg1->getSourceRange();
7352 
7353     // Derive the return type from the pointer argument.
7354     TheCall->setType(FirstArgType);
7355     return false;
7356   }
7357 
7358   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7359     if (checkArgCount(*this, TheCall, 2))
7360       return true;
7361 
7362     Expr *Arg0 = TheCall->getArg(0);
7363     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7364     if (FirstArg.isInvalid())
7365       return true;
7366     QualType FirstArgType = FirstArg.get()->getType();
7367     if (!FirstArgType->isAnyPointerType())
7368       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7369                << "first" << FirstArgType << Arg0->getSourceRange();
7370     TheCall->setArg(0, FirstArg.get());
7371 
7372     // Derive the return type from the pointer argument.
7373     TheCall->setType(FirstArgType);
7374 
7375     // Second arg must be an constant in range [0,15]
7376     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7377   }
7378 
7379   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7380     if (checkArgCount(*this, TheCall, 2))
7381       return true;
7382     Expr *Arg0 = TheCall->getArg(0);
7383     Expr *Arg1 = TheCall->getArg(1);
7384 
7385     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7386     if (FirstArg.isInvalid())
7387       return true;
7388     QualType FirstArgType = FirstArg.get()->getType();
7389     if (!FirstArgType->isAnyPointerType())
7390       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7391                << "first" << FirstArgType << Arg0->getSourceRange();
7392 
7393     QualType SecArgType = Arg1->getType();
7394     if (!SecArgType->isIntegerType())
7395       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7396                << "second" << SecArgType << Arg1->getSourceRange();
7397     TheCall->setType(Context.IntTy);
7398     return false;
7399   }
7400 
7401   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7402       BuiltinID == AArch64::BI__builtin_arm_stg) {
7403     if (checkArgCount(*this, TheCall, 1))
7404       return true;
7405     Expr *Arg0 = TheCall->getArg(0);
7406     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7407     if (FirstArg.isInvalid())
7408       return true;
7409 
7410     QualType FirstArgType = FirstArg.get()->getType();
7411     if (!FirstArgType->isAnyPointerType())
7412       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7413                << "first" << FirstArgType << Arg0->getSourceRange();
7414     TheCall->setArg(0, FirstArg.get());
7415 
7416     // Derive the return type from the pointer argument.
7417     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7418       TheCall->setType(FirstArgType);
7419     return false;
7420   }
7421 
7422   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7423     Expr *ArgA = TheCall->getArg(0);
7424     Expr *ArgB = TheCall->getArg(1);
7425 
7426     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7427     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7428 
7429     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7430       return true;
7431 
7432     QualType ArgTypeA = ArgExprA.get()->getType();
7433     QualType ArgTypeB = ArgExprB.get()->getType();
7434 
7435     auto isNull = [&] (Expr *E) -> bool {
7436       return E->isNullPointerConstant(
7437                         Context, Expr::NPC_ValueDependentIsNotNull); };
7438 
7439     // argument should be either a pointer or null
7440     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7441       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7442         << "first" << ArgTypeA << ArgA->getSourceRange();
7443 
7444     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7445       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7446         << "second" << ArgTypeB << ArgB->getSourceRange();
7447 
7448     // Ensure Pointee types are compatible
7449     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7450         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7451       QualType pointeeA = ArgTypeA->getPointeeType();
7452       QualType pointeeB = ArgTypeB->getPointeeType();
7453       if (!Context.typesAreCompatible(
7454              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7455              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7456         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7457           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7458           << ArgB->getSourceRange();
7459       }
7460     }
7461 
7462     // at least one argument should be pointer type
7463     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7464       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7465         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7466 
7467     if (isNull(ArgA)) // adopt type of the other pointer
7468       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7469 
7470     if (isNull(ArgB))
7471       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7472 
7473     TheCall->setArg(0, ArgExprA.get());
7474     TheCall->setArg(1, ArgExprB.get());
7475     TheCall->setType(Context.LongLongTy);
7476     return false;
7477   }
7478   assert(false && "Unhandled ARM MTE intrinsic");
7479   return true;
7480 }
7481 
7482 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7483 /// TheCall is an ARM/AArch64 special register string literal.
7484 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7485                                     int ArgNum, unsigned ExpectedFieldNum,
7486                                     bool AllowName) {
7487   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7488                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7489                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7490                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7491                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7492                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7493   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7494                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7495                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7496                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7497                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7498                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7499   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7500 
7501   // We can't check the value of a dependent argument.
7502   Expr *Arg = TheCall->getArg(ArgNum);
7503   if (Arg->isTypeDependent() || Arg->isValueDependent())
7504     return false;
7505 
7506   // Check if the argument is a string literal.
7507   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7508     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7509            << Arg->getSourceRange();
7510 
7511   // Check the type of special register given.
7512   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7513   SmallVector<StringRef, 6> Fields;
7514   Reg.split(Fields, ":");
7515 
7516   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7517     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7518            << Arg->getSourceRange();
7519 
7520   // If the string is the name of a register then we cannot check that it is
7521   // valid here but if the string is of one the forms described in ACLE then we
7522   // can check that the supplied fields are integers and within the valid
7523   // ranges.
7524   if (Fields.size() > 1) {
7525     bool FiveFields = Fields.size() == 5;
7526 
7527     bool ValidString = true;
7528     if (IsARMBuiltin) {
7529       ValidString &= Fields[0].startswith_insensitive("cp") ||
7530                      Fields[0].startswith_insensitive("p");
7531       if (ValidString)
7532         Fields[0] = Fields[0].drop_front(
7533             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7534 
7535       ValidString &= Fields[2].startswith_insensitive("c");
7536       if (ValidString)
7537         Fields[2] = Fields[2].drop_front(1);
7538 
7539       if (FiveFields) {
7540         ValidString &= Fields[3].startswith_insensitive("c");
7541         if (ValidString)
7542           Fields[3] = Fields[3].drop_front(1);
7543       }
7544     }
7545 
7546     SmallVector<int, 5> Ranges;
7547     if (FiveFields)
7548       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7549     else
7550       Ranges.append({15, 7, 15});
7551 
7552     for (unsigned i=0; i<Fields.size(); ++i) {
7553       int IntField;
7554       ValidString &= !Fields[i].getAsInteger(10, IntField);
7555       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7556     }
7557 
7558     if (!ValidString)
7559       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7560              << Arg->getSourceRange();
7561   } else if (IsAArch64Builtin && Fields.size() == 1) {
7562     // If the register name is one of those that appear in the condition below
7563     // and the special register builtin being used is one of the write builtins,
7564     // then we require that the argument provided for writing to the register
7565     // is an integer constant expression. This is because it will be lowered to
7566     // an MSR (immediate) instruction, so we need to know the immediate at
7567     // compile time.
7568     if (TheCall->getNumArgs() != 2)
7569       return false;
7570 
7571     std::string RegLower = Reg.lower();
7572     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7573         RegLower != "pan" && RegLower != "uao")
7574       return false;
7575 
7576     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7577   }
7578 
7579   return false;
7580 }
7581 
7582 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7583 /// Emit an error and return true on failure; return false on success.
7584 /// TypeStr is a string containing the type descriptor of the value returned by
7585 /// the builtin and the descriptors of the expected type of the arguments.
7586 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7587                                  const char *TypeStr) {
7588 
7589   assert((TypeStr[0] != '\0') &&
7590          "Invalid types in PPC MMA builtin declaration");
7591 
7592   switch (BuiltinID) {
7593   default:
7594     // This function is called in CheckPPCBuiltinFunctionCall where the
7595     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7596     // we are isolating the pair vector memop builtins that can be used with mma
7597     // off so the default case is every builtin that requires mma and paired
7598     // vector memops.
7599     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7600                          diag::err_ppc_builtin_only_on_arch, "10") ||
7601         SemaFeatureCheck(*this, TheCall, "mma",
7602                          diag::err_ppc_builtin_only_on_arch, "10"))
7603       return true;
7604     break;
7605   case PPC::BI__builtin_vsx_lxvp:
7606   case PPC::BI__builtin_vsx_stxvp:
7607   case PPC::BI__builtin_vsx_assemble_pair:
7608   case PPC::BI__builtin_vsx_disassemble_pair:
7609     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7610                          diag::err_ppc_builtin_only_on_arch, "10"))
7611       return true;
7612     break;
7613   }
7614 
7615   unsigned Mask = 0;
7616   unsigned ArgNum = 0;
7617 
7618   // The first type in TypeStr is the type of the value returned by the
7619   // builtin. So we first read that type and change the type of TheCall.
7620   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7621   TheCall->setType(type);
7622 
7623   while (*TypeStr != '\0') {
7624     Mask = 0;
7625     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7626     if (ArgNum >= TheCall->getNumArgs()) {
7627       ArgNum++;
7628       break;
7629     }
7630 
7631     Expr *Arg = TheCall->getArg(ArgNum);
7632     QualType PassedType = Arg->getType();
7633     QualType StrippedRVType = PassedType.getCanonicalType();
7634 
7635     // Strip Restrict/Volatile qualifiers.
7636     if (StrippedRVType.isRestrictQualified() ||
7637         StrippedRVType.isVolatileQualified())
7638       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7639 
7640     // The only case where the argument type and expected type are allowed to
7641     // mismatch is if the argument type is a non-void pointer (or array) and
7642     // expected type is a void pointer.
7643     if (StrippedRVType != ExpectedType)
7644       if (!(ExpectedType->isVoidPointerType() &&
7645             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7646         return Diag(Arg->getBeginLoc(),
7647                     diag::err_typecheck_convert_incompatible)
7648                << PassedType << ExpectedType << 1 << 0 << 0;
7649 
7650     // If the value of the Mask is not 0, we have a constraint in the size of
7651     // the integer argument so here we ensure the argument is a constant that
7652     // is in the valid range.
7653     if (Mask != 0 &&
7654         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7655       return true;
7656 
7657     ArgNum++;
7658   }
7659 
7660   // In case we exited early from the previous loop, there are other types to
7661   // read from TypeStr. So we need to read them all to ensure we have the right
7662   // number of arguments in TheCall and if it is not the case, to display a
7663   // better error message.
7664   while (*TypeStr != '\0') {
7665     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7666     ArgNum++;
7667   }
7668   if (checkArgCount(*this, TheCall, ArgNum))
7669     return true;
7670 
7671   return false;
7672 }
7673 
7674 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7675 /// This checks that the target supports __builtin_longjmp and
7676 /// that val is a constant 1.
7677 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7678   if (!Context.getTargetInfo().hasSjLjLowering())
7679     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7680            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7681 
7682   Expr *Arg = TheCall->getArg(1);
7683   llvm::APSInt Result;
7684 
7685   // TODO: This is less than ideal. Overload this to take a value.
7686   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7687     return true;
7688 
7689   if (Result != 1)
7690     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7691            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7692 
7693   return false;
7694 }
7695 
7696 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7697 /// This checks that the target supports __builtin_setjmp.
7698 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7699   if (!Context.getTargetInfo().hasSjLjLowering())
7700     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7701            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7702   return false;
7703 }
7704 
7705 namespace {
7706 
7707 class UncoveredArgHandler {
7708   enum { Unknown = -1, AllCovered = -2 };
7709 
7710   signed FirstUncoveredArg = Unknown;
7711   SmallVector<const Expr *, 4> DiagnosticExprs;
7712 
7713 public:
7714   UncoveredArgHandler() = default;
7715 
7716   bool hasUncoveredArg() const {
7717     return (FirstUncoveredArg >= 0);
7718   }
7719 
7720   unsigned getUncoveredArg() const {
7721     assert(hasUncoveredArg() && "no uncovered argument");
7722     return FirstUncoveredArg;
7723   }
7724 
7725   void setAllCovered() {
7726     // A string has been found with all arguments covered, so clear out
7727     // the diagnostics.
7728     DiagnosticExprs.clear();
7729     FirstUncoveredArg = AllCovered;
7730   }
7731 
7732   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7733     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7734 
7735     // Don't update if a previous string covers all arguments.
7736     if (FirstUncoveredArg == AllCovered)
7737       return;
7738 
7739     // UncoveredArgHandler tracks the highest uncovered argument index
7740     // and with it all the strings that match this index.
7741     if (NewFirstUncoveredArg == FirstUncoveredArg)
7742       DiagnosticExprs.push_back(StrExpr);
7743     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7744       DiagnosticExprs.clear();
7745       DiagnosticExprs.push_back(StrExpr);
7746       FirstUncoveredArg = NewFirstUncoveredArg;
7747     }
7748   }
7749 
7750   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7751 };
7752 
7753 enum StringLiteralCheckType {
7754   SLCT_NotALiteral,
7755   SLCT_UncheckedLiteral,
7756   SLCT_CheckedLiteral
7757 };
7758 
7759 } // namespace
7760 
7761 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7762                                      BinaryOperatorKind BinOpKind,
7763                                      bool AddendIsRight) {
7764   unsigned BitWidth = Offset.getBitWidth();
7765   unsigned AddendBitWidth = Addend.getBitWidth();
7766   // There might be negative interim results.
7767   if (Addend.isUnsigned()) {
7768     Addend = Addend.zext(++AddendBitWidth);
7769     Addend.setIsSigned(true);
7770   }
7771   // Adjust the bit width of the APSInts.
7772   if (AddendBitWidth > BitWidth) {
7773     Offset = Offset.sext(AddendBitWidth);
7774     BitWidth = AddendBitWidth;
7775   } else if (BitWidth > AddendBitWidth) {
7776     Addend = Addend.sext(BitWidth);
7777   }
7778 
7779   bool Ov = false;
7780   llvm::APSInt ResOffset = Offset;
7781   if (BinOpKind == BO_Add)
7782     ResOffset = Offset.sadd_ov(Addend, Ov);
7783   else {
7784     assert(AddendIsRight && BinOpKind == BO_Sub &&
7785            "operator must be add or sub with addend on the right");
7786     ResOffset = Offset.ssub_ov(Addend, Ov);
7787   }
7788 
7789   // We add an offset to a pointer here so we should support an offset as big as
7790   // possible.
7791   if (Ov) {
7792     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7793            "index (intermediate) result too big");
7794     Offset = Offset.sext(2 * BitWidth);
7795     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7796     return;
7797   }
7798 
7799   Offset = ResOffset;
7800 }
7801 
7802 namespace {
7803 
7804 // This is a wrapper class around StringLiteral to support offsetted string
7805 // literals as format strings. It takes the offset into account when returning
7806 // the string and its length or the source locations to display notes correctly.
7807 class FormatStringLiteral {
7808   const StringLiteral *FExpr;
7809   int64_t Offset;
7810 
7811  public:
7812   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7813       : FExpr(fexpr), Offset(Offset) {}
7814 
7815   StringRef getString() const {
7816     return FExpr->getString().drop_front(Offset);
7817   }
7818 
7819   unsigned getByteLength() const {
7820     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7821   }
7822 
7823   unsigned getLength() const { return FExpr->getLength() - Offset; }
7824   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7825 
7826   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7827 
7828   QualType getType() const { return FExpr->getType(); }
7829 
7830   bool isAscii() const { return FExpr->isAscii(); }
7831   bool isWide() const { return FExpr->isWide(); }
7832   bool isUTF8() const { return FExpr->isUTF8(); }
7833   bool isUTF16() const { return FExpr->isUTF16(); }
7834   bool isUTF32() const { return FExpr->isUTF32(); }
7835   bool isPascal() const { return FExpr->isPascal(); }
7836 
7837   SourceLocation getLocationOfByte(
7838       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7839       const TargetInfo &Target, unsigned *StartToken = nullptr,
7840       unsigned *StartTokenByteOffset = nullptr) const {
7841     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7842                                     StartToken, StartTokenByteOffset);
7843   }
7844 
7845   SourceLocation getBeginLoc() const LLVM_READONLY {
7846     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7847   }
7848 
7849   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7850 };
7851 
7852 }  // namespace
7853 
7854 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7855                               const Expr *OrigFormatExpr,
7856                               ArrayRef<const Expr *> Args,
7857                               bool HasVAListArg, unsigned format_idx,
7858                               unsigned firstDataArg,
7859                               Sema::FormatStringType Type,
7860                               bool inFunctionCall,
7861                               Sema::VariadicCallType CallType,
7862                               llvm::SmallBitVector &CheckedVarArgs,
7863                               UncoveredArgHandler &UncoveredArg,
7864                               bool IgnoreStringsWithoutSpecifiers);
7865 
7866 // Determine if an expression is a string literal or constant string.
7867 // If this function returns false on the arguments to a function expecting a
7868 // format string, we will usually need to emit a warning.
7869 // True string literals are then checked by CheckFormatString.
7870 static StringLiteralCheckType
7871 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7872                       bool HasVAListArg, unsigned format_idx,
7873                       unsigned firstDataArg, Sema::FormatStringType Type,
7874                       Sema::VariadicCallType CallType, bool InFunctionCall,
7875                       llvm::SmallBitVector &CheckedVarArgs,
7876                       UncoveredArgHandler &UncoveredArg,
7877                       llvm::APSInt Offset,
7878                       bool IgnoreStringsWithoutSpecifiers = false) {
7879   if (S.isConstantEvaluated())
7880     return SLCT_NotALiteral;
7881  tryAgain:
7882   assert(Offset.isSigned() && "invalid offset");
7883 
7884   if (E->isTypeDependent() || E->isValueDependent())
7885     return SLCT_NotALiteral;
7886 
7887   E = E->IgnoreParenCasts();
7888 
7889   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7890     // Technically -Wformat-nonliteral does not warn about this case.
7891     // The behavior of printf and friends in this case is implementation
7892     // dependent.  Ideally if the format string cannot be null then
7893     // it should have a 'nonnull' attribute in the function prototype.
7894     return SLCT_UncheckedLiteral;
7895 
7896   switch (E->getStmtClass()) {
7897   case Stmt::BinaryConditionalOperatorClass:
7898   case Stmt::ConditionalOperatorClass: {
7899     // The expression is a literal if both sub-expressions were, and it was
7900     // completely checked only if both sub-expressions were checked.
7901     const AbstractConditionalOperator *C =
7902         cast<AbstractConditionalOperator>(E);
7903 
7904     // Determine whether it is necessary to check both sub-expressions, for
7905     // example, because the condition expression is a constant that can be
7906     // evaluated at compile time.
7907     bool CheckLeft = true, CheckRight = true;
7908 
7909     bool Cond;
7910     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7911                                                  S.isConstantEvaluated())) {
7912       if (Cond)
7913         CheckRight = false;
7914       else
7915         CheckLeft = false;
7916     }
7917 
7918     // We need to maintain the offsets for the right and the left hand side
7919     // separately to check if every possible indexed expression is a valid
7920     // string literal. They might have different offsets for different string
7921     // literals in the end.
7922     StringLiteralCheckType Left;
7923     if (!CheckLeft)
7924       Left = SLCT_UncheckedLiteral;
7925     else {
7926       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7927                                    HasVAListArg, format_idx, firstDataArg,
7928                                    Type, CallType, InFunctionCall,
7929                                    CheckedVarArgs, UncoveredArg, Offset,
7930                                    IgnoreStringsWithoutSpecifiers);
7931       if (Left == SLCT_NotALiteral || !CheckRight) {
7932         return Left;
7933       }
7934     }
7935 
7936     StringLiteralCheckType Right = checkFormatStringExpr(
7937         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7938         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7939         IgnoreStringsWithoutSpecifiers);
7940 
7941     return (CheckLeft && Left < Right) ? Left : Right;
7942   }
7943 
7944   case Stmt::ImplicitCastExprClass:
7945     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7946     goto tryAgain;
7947 
7948   case Stmt::OpaqueValueExprClass:
7949     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7950       E = src;
7951       goto tryAgain;
7952     }
7953     return SLCT_NotALiteral;
7954 
7955   case Stmt::PredefinedExprClass:
7956     // While __func__, etc., are technically not string literals, they
7957     // cannot contain format specifiers and thus are not a security
7958     // liability.
7959     return SLCT_UncheckedLiteral;
7960 
7961   case Stmt::DeclRefExprClass: {
7962     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7963 
7964     // As an exception, do not flag errors for variables binding to
7965     // const string literals.
7966     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7967       bool isConstant = false;
7968       QualType T = DR->getType();
7969 
7970       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7971         isConstant = AT->getElementType().isConstant(S.Context);
7972       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7973         isConstant = T.isConstant(S.Context) &&
7974                      PT->getPointeeType().isConstant(S.Context);
7975       } else if (T->isObjCObjectPointerType()) {
7976         // In ObjC, there is usually no "const ObjectPointer" type,
7977         // so don't check if the pointee type is constant.
7978         isConstant = T.isConstant(S.Context);
7979       }
7980 
7981       if (isConstant) {
7982         if (const Expr *Init = VD->getAnyInitializer()) {
7983           // Look through initializers like const char c[] = { "foo" }
7984           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7985             if (InitList->isStringLiteralInit())
7986               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7987           }
7988           return checkFormatStringExpr(S, Init, Args,
7989                                        HasVAListArg, format_idx,
7990                                        firstDataArg, Type, CallType,
7991                                        /*InFunctionCall*/ false, CheckedVarArgs,
7992                                        UncoveredArg, Offset);
7993         }
7994       }
7995 
7996       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7997       // special check to see if the format string is a function parameter
7998       // of the function calling the printf function.  If the function
7999       // has an attribute indicating it is a printf-like function, then we
8000       // should suppress warnings concerning non-literals being used in a call
8001       // to a vprintf function.  For example:
8002       //
8003       // void
8004       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8005       //      va_list ap;
8006       //      va_start(ap, fmt);
8007       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8008       //      ...
8009       // }
8010       if (HasVAListArg) {
8011         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8012           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8013             int PVIndex = PV->getFunctionScopeIndex() + 1;
8014             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8015               // adjust for implicit parameter
8016               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8017                 if (MD->isInstance())
8018                   ++PVIndex;
8019               // We also check if the formats are compatible.
8020               // We can't pass a 'scanf' string to a 'printf' function.
8021               if (PVIndex == PVFormat->getFormatIdx() &&
8022                   Type == S.GetFormatStringType(PVFormat))
8023                 return SLCT_UncheckedLiteral;
8024             }
8025           }
8026         }
8027       }
8028     }
8029 
8030     return SLCT_NotALiteral;
8031   }
8032 
8033   case Stmt::CallExprClass:
8034   case Stmt::CXXMemberCallExprClass: {
8035     const CallExpr *CE = cast<CallExpr>(E);
8036     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8037       bool IsFirst = true;
8038       StringLiteralCheckType CommonResult;
8039       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8040         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8041         StringLiteralCheckType Result = checkFormatStringExpr(
8042             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8043             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8044             IgnoreStringsWithoutSpecifiers);
8045         if (IsFirst) {
8046           CommonResult = Result;
8047           IsFirst = false;
8048         }
8049       }
8050       if (!IsFirst)
8051         return CommonResult;
8052 
8053       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8054         unsigned BuiltinID = FD->getBuiltinID();
8055         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8056             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8057           const Expr *Arg = CE->getArg(0);
8058           return checkFormatStringExpr(S, Arg, Args,
8059                                        HasVAListArg, format_idx,
8060                                        firstDataArg, Type, CallType,
8061                                        InFunctionCall, CheckedVarArgs,
8062                                        UncoveredArg, Offset,
8063                                        IgnoreStringsWithoutSpecifiers);
8064         }
8065       }
8066     }
8067 
8068     return SLCT_NotALiteral;
8069   }
8070   case Stmt::ObjCMessageExprClass: {
8071     const auto *ME = cast<ObjCMessageExpr>(E);
8072     if (const auto *MD = ME->getMethodDecl()) {
8073       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8074         // As a special case heuristic, if we're using the method -[NSBundle
8075         // localizedStringForKey:value:table:], ignore any key strings that lack
8076         // format specifiers. The idea is that if the key doesn't have any
8077         // format specifiers then its probably just a key to map to the
8078         // localized strings. If it does have format specifiers though, then its
8079         // likely that the text of the key is the format string in the
8080         // programmer's language, and should be checked.
8081         const ObjCInterfaceDecl *IFace;
8082         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8083             IFace->getIdentifier()->isStr("NSBundle") &&
8084             MD->getSelector().isKeywordSelector(
8085                 {"localizedStringForKey", "value", "table"})) {
8086           IgnoreStringsWithoutSpecifiers = true;
8087         }
8088 
8089         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8090         return checkFormatStringExpr(
8091             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8092             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8093             IgnoreStringsWithoutSpecifiers);
8094       }
8095     }
8096 
8097     return SLCT_NotALiteral;
8098   }
8099   case Stmt::ObjCStringLiteralClass:
8100   case Stmt::StringLiteralClass: {
8101     const StringLiteral *StrE = nullptr;
8102 
8103     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8104       StrE = ObjCFExpr->getString();
8105     else
8106       StrE = cast<StringLiteral>(E);
8107 
8108     if (StrE) {
8109       if (Offset.isNegative() || Offset > StrE->getLength()) {
8110         // TODO: It would be better to have an explicit warning for out of
8111         // bounds literals.
8112         return SLCT_NotALiteral;
8113       }
8114       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8115       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8116                         firstDataArg, Type, InFunctionCall, CallType,
8117                         CheckedVarArgs, UncoveredArg,
8118                         IgnoreStringsWithoutSpecifiers);
8119       return SLCT_CheckedLiteral;
8120     }
8121 
8122     return SLCT_NotALiteral;
8123   }
8124   case Stmt::BinaryOperatorClass: {
8125     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8126 
8127     // A string literal + an int offset is still a string literal.
8128     if (BinOp->isAdditiveOp()) {
8129       Expr::EvalResult LResult, RResult;
8130 
8131       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8132           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8133       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8134           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8135 
8136       if (LIsInt != RIsInt) {
8137         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8138 
8139         if (LIsInt) {
8140           if (BinOpKind == BO_Add) {
8141             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8142             E = BinOp->getRHS();
8143             goto tryAgain;
8144           }
8145         } else {
8146           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8147           E = BinOp->getLHS();
8148           goto tryAgain;
8149         }
8150       }
8151     }
8152 
8153     return SLCT_NotALiteral;
8154   }
8155   case Stmt::UnaryOperatorClass: {
8156     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8157     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8158     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8159       Expr::EvalResult IndexResult;
8160       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8161                                        Expr::SE_NoSideEffects,
8162                                        S.isConstantEvaluated())) {
8163         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8164                    /*RHS is int*/ true);
8165         E = ASE->getBase();
8166         goto tryAgain;
8167       }
8168     }
8169 
8170     return SLCT_NotALiteral;
8171   }
8172 
8173   default:
8174     return SLCT_NotALiteral;
8175   }
8176 }
8177 
8178 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8179   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8180       .Case("scanf", FST_Scanf)
8181       .Cases("printf", "printf0", FST_Printf)
8182       .Cases("NSString", "CFString", FST_NSString)
8183       .Case("strftime", FST_Strftime)
8184       .Case("strfmon", FST_Strfmon)
8185       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8186       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8187       .Case("os_trace", FST_OSLog)
8188       .Case("os_log", FST_OSLog)
8189       .Default(FST_Unknown);
8190 }
8191 
8192 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8193 /// functions) for correct use of format strings.
8194 /// Returns true if a format string has been fully checked.
8195 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8196                                 ArrayRef<const Expr *> Args,
8197                                 bool IsCXXMember,
8198                                 VariadicCallType CallType,
8199                                 SourceLocation Loc, SourceRange Range,
8200                                 llvm::SmallBitVector &CheckedVarArgs) {
8201   FormatStringInfo FSI;
8202   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8203     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8204                                 FSI.FirstDataArg, GetFormatStringType(Format),
8205                                 CallType, Loc, Range, CheckedVarArgs);
8206   return false;
8207 }
8208 
8209 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8210                                 bool HasVAListArg, unsigned format_idx,
8211                                 unsigned firstDataArg, FormatStringType Type,
8212                                 VariadicCallType CallType,
8213                                 SourceLocation Loc, SourceRange Range,
8214                                 llvm::SmallBitVector &CheckedVarArgs) {
8215   // CHECK: printf/scanf-like function is called with no format string.
8216   if (format_idx >= Args.size()) {
8217     Diag(Loc, diag::warn_missing_format_string) << Range;
8218     return false;
8219   }
8220 
8221   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8222 
8223   // CHECK: format string is not a string literal.
8224   //
8225   // Dynamically generated format strings are difficult to
8226   // automatically vet at compile time.  Requiring that format strings
8227   // are string literals: (1) permits the checking of format strings by
8228   // the compiler and thereby (2) can practically remove the source of
8229   // many format string exploits.
8230 
8231   // Format string can be either ObjC string (e.g. @"%d") or
8232   // C string (e.g. "%d")
8233   // ObjC string uses the same format specifiers as C string, so we can use
8234   // the same format string checking logic for both ObjC and C strings.
8235   UncoveredArgHandler UncoveredArg;
8236   StringLiteralCheckType CT =
8237       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8238                             format_idx, firstDataArg, Type, CallType,
8239                             /*IsFunctionCall*/ true, CheckedVarArgs,
8240                             UncoveredArg,
8241                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8242 
8243   // Generate a diagnostic where an uncovered argument is detected.
8244   if (UncoveredArg.hasUncoveredArg()) {
8245     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8246     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8247     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8248   }
8249 
8250   if (CT != SLCT_NotALiteral)
8251     // Literal format string found, check done!
8252     return CT == SLCT_CheckedLiteral;
8253 
8254   // Strftime is particular as it always uses a single 'time' argument,
8255   // so it is safe to pass a non-literal string.
8256   if (Type == FST_Strftime)
8257     return false;
8258 
8259   // Do not emit diag when the string param is a macro expansion and the
8260   // format is either NSString or CFString. This is a hack to prevent
8261   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8262   // which are usually used in place of NS and CF string literals.
8263   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8264   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8265     return false;
8266 
8267   // If there are no arguments specified, warn with -Wformat-security, otherwise
8268   // warn only with -Wformat-nonliteral.
8269   if (Args.size() == firstDataArg) {
8270     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8271       << OrigFormatExpr->getSourceRange();
8272     switch (Type) {
8273     default:
8274       break;
8275     case FST_Kprintf:
8276     case FST_FreeBSDKPrintf:
8277     case FST_Printf:
8278       Diag(FormatLoc, diag::note_format_security_fixit)
8279         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8280       break;
8281     case FST_NSString:
8282       Diag(FormatLoc, diag::note_format_security_fixit)
8283         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8284       break;
8285     }
8286   } else {
8287     Diag(FormatLoc, diag::warn_format_nonliteral)
8288       << OrigFormatExpr->getSourceRange();
8289   }
8290   return false;
8291 }
8292 
8293 namespace {
8294 
8295 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8296 protected:
8297   Sema &S;
8298   const FormatStringLiteral *FExpr;
8299   const Expr *OrigFormatExpr;
8300   const Sema::FormatStringType FSType;
8301   const unsigned FirstDataArg;
8302   const unsigned NumDataArgs;
8303   const char *Beg; // Start of format string.
8304   const bool HasVAListArg;
8305   ArrayRef<const Expr *> Args;
8306   unsigned FormatIdx;
8307   llvm::SmallBitVector CoveredArgs;
8308   bool usesPositionalArgs = false;
8309   bool atFirstArg = true;
8310   bool inFunctionCall;
8311   Sema::VariadicCallType CallType;
8312   llvm::SmallBitVector &CheckedVarArgs;
8313   UncoveredArgHandler &UncoveredArg;
8314 
8315 public:
8316   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8317                      const Expr *origFormatExpr,
8318                      const Sema::FormatStringType type, unsigned firstDataArg,
8319                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8320                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8321                      bool inFunctionCall, Sema::VariadicCallType callType,
8322                      llvm::SmallBitVector &CheckedVarArgs,
8323                      UncoveredArgHandler &UncoveredArg)
8324       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8325         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8326         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8327         inFunctionCall(inFunctionCall), CallType(callType),
8328         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8329     CoveredArgs.resize(numDataArgs);
8330     CoveredArgs.reset();
8331   }
8332 
8333   void DoneProcessing();
8334 
8335   void HandleIncompleteSpecifier(const char *startSpecifier,
8336                                  unsigned specifierLen) override;
8337 
8338   void HandleInvalidLengthModifier(
8339                            const analyze_format_string::FormatSpecifier &FS,
8340                            const analyze_format_string::ConversionSpecifier &CS,
8341                            const char *startSpecifier, unsigned specifierLen,
8342                            unsigned DiagID);
8343 
8344   void HandleNonStandardLengthModifier(
8345                     const analyze_format_string::FormatSpecifier &FS,
8346                     const char *startSpecifier, unsigned specifierLen);
8347 
8348   void HandleNonStandardConversionSpecifier(
8349                     const analyze_format_string::ConversionSpecifier &CS,
8350                     const char *startSpecifier, unsigned specifierLen);
8351 
8352   void HandlePosition(const char *startPos, unsigned posLen) override;
8353 
8354   void HandleInvalidPosition(const char *startSpecifier,
8355                              unsigned specifierLen,
8356                              analyze_format_string::PositionContext p) override;
8357 
8358   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8359 
8360   void HandleNullChar(const char *nullCharacter) override;
8361 
8362   template <typename Range>
8363   static void
8364   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8365                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8366                        bool IsStringLocation, Range StringRange,
8367                        ArrayRef<FixItHint> Fixit = None);
8368 
8369 protected:
8370   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8371                                         const char *startSpec,
8372                                         unsigned specifierLen,
8373                                         const char *csStart, unsigned csLen);
8374 
8375   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8376                                          const char *startSpec,
8377                                          unsigned specifierLen);
8378 
8379   SourceRange getFormatStringRange();
8380   CharSourceRange getSpecifierRange(const char *startSpecifier,
8381                                     unsigned specifierLen);
8382   SourceLocation getLocationOfByte(const char *x);
8383 
8384   const Expr *getDataArg(unsigned i) const;
8385 
8386   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8387                     const analyze_format_string::ConversionSpecifier &CS,
8388                     const char *startSpecifier, unsigned specifierLen,
8389                     unsigned argIndex);
8390 
8391   template <typename Range>
8392   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8393                             bool IsStringLocation, Range StringRange,
8394                             ArrayRef<FixItHint> Fixit = None);
8395 };
8396 
8397 } // namespace
8398 
8399 SourceRange CheckFormatHandler::getFormatStringRange() {
8400   return OrigFormatExpr->getSourceRange();
8401 }
8402 
8403 CharSourceRange CheckFormatHandler::
8404 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8405   SourceLocation Start = getLocationOfByte(startSpecifier);
8406   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8407 
8408   // Advance the end SourceLocation by one due to half-open ranges.
8409   End = End.getLocWithOffset(1);
8410 
8411   return CharSourceRange::getCharRange(Start, End);
8412 }
8413 
8414 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8415   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8416                                   S.getLangOpts(), S.Context.getTargetInfo());
8417 }
8418 
8419 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8420                                                    unsigned specifierLen){
8421   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8422                        getLocationOfByte(startSpecifier),
8423                        /*IsStringLocation*/true,
8424                        getSpecifierRange(startSpecifier, specifierLen));
8425 }
8426 
8427 void CheckFormatHandler::HandleInvalidLengthModifier(
8428     const analyze_format_string::FormatSpecifier &FS,
8429     const analyze_format_string::ConversionSpecifier &CS,
8430     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8431   using namespace analyze_format_string;
8432 
8433   const LengthModifier &LM = FS.getLengthModifier();
8434   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8435 
8436   // See if we know how to fix this length modifier.
8437   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8438   if (FixedLM) {
8439     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8440                          getLocationOfByte(LM.getStart()),
8441                          /*IsStringLocation*/true,
8442                          getSpecifierRange(startSpecifier, specifierLen));
8443 
8444     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8445       << FixedLM->toString()
8446       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8447 
8448   } else {
8449     FixItHint Hint;
8450     if (DiagID == diag::warn_format_nonsensical_length)
8451       Hint = FixItHint::CreateRemoval(LMRange);
8452 
8453     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8454                          getLocationOfByte(LM.getStart()),
8455                          /*IsStringLocation*/true,
8456                          getSpecifierRange(startSpecifier, specifierLen),
8457                          Hint);
8458   }
8459 }
8460 
8461 void CheckFormatHandler::HandleNonStandardLengthModifier(
8462     const analyze_format_string::FormatSpecifier &FS,
8463     const char *startSpecifier, unsigned specifierLen) {
8464   using namespace analyze_format_string;
8465 
8466   const LengthModifier &LM = FS.getLengthModifier();
8467   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8468 
8469   // See if we know how to fix this length modifier.
8470   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8471   if (FixedLM) {
8472     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8473                            << LM.toString() << 0,
8474                          getLocationOfByte(LM.getStart()),
8475                          /*IsStringLocation*/true,
8476                          getSpecifierRange(startSpecifier, specifierLen));
8477 
8478     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8479       << FixedLM->toString()
8480       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8481 
8482   } else {
8483     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8484                            << LM.toString() << 0,
8485                          getLocationOfByte(LM.getStart()),
8486                          /*IsStringLocation*/true,
8487                          getSpecifierRange(startSpecifier, specifierLen));
8488   }
8489 }
8490 
8491 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8492     const analyze_format_string::ConversionSpecifier &CS,
8493     const char *startSpecifier, unsigned specifierLen) {
8494   using namespace analyze_format_string;
8495 
8496   // See if we know how to fix this conversion specifier.
8497   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8498   if (FixedCS) {
8499     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8500                           << CS.toString() << /*conversion specifier*/1,
8501                          getLocationOfByte(CS.getStart()),
8502                          /*IsStringLocation*/true,
8503                          getSpecifierRange(startSpecifier, specifierLen));
8504 
8505     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8506     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8507       << FixedCS->toString()
8508       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8509   } else {
8510     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8511                           << CS.toString() << /*conversion specifier*/1,
8512                          getLocationOfByte(CS.getStart()),
8513                          /*IsStringLocation*/true,
8514                          getSpecifierRange(startSpecifier, specifierLen));
8515   }
8516 }
8517 
8518 void CheckFormatHandler::HandlePosition(const char *startPos,
8519                                         unsigned posLen) {
8520   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8521                                getLocationOfByte(startPos),
8522                                /*IsStringLocation*/true,
8523                                getSpecifierRange(startPos, posLen));
8524 }
8525 
8526 void
8527 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8528                                      analyze_format_string::PositionContext p) {
8529   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8530                          << (unsigned) p,
8531                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8532                        getSpecifierRange(startPos, posLen));
8533 }
8534 
8535 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8536                                             unsigned posLen) {
8537   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8538                                getLocationOfByte(startPos),
8539                                /*IsStringLocation*/true,
8540                                getSpecifierRange(startPos, posLen));
8541 }
8542 
8543 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8544   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8545     // The presence of a null character is likely an error.
8546     EmitFormatDiagnostic(
8547       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8548       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8549       getFormatStringRange());
8550   }
8551 }
8552 
8553 // Note that this may return NULL if there was an error parsing or building
8554 // one of the argument expressions.
8555 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8556   return Args[FirstDataArg + i];
8557 }
8558 
8559 void CheckFormatHandler::DoneProcessing() {
8560   // Does the number of data arguments exceed the number of
8561   // format conversions in the format string?
8562   if (!HasVAListArg) {
8563       // Find any arguments that weren't covered.
8564     CoveredArgs.flip();
8565     signed notCoveredArg = CoveredArgs.find_first();
8566     if (notCoveredArg >= 0) {
8567       assert((unsigned)notCoveredArg < NumDataArgs);
8568       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8569     } else {
8570       UncoveredArg.setAllCovered();
8571     }
8572   }
8573 }
8574 
8575 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8576                                    const Expr *ArgExpr) {
8577   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8578          "Invalid state");
8579 
8580   if (!ArgExpr)
8581     return;
8582 
8583   SourceLocation Loc = ArgExpr->getBeginLoc();
8584 
8585   if (S.getSourceManager().isInSystemMacro(Loc))
8586     return;
8587 
8588   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8589   for (auto E : DiagnosticExprs)
8590     PDiag << E->getSourceRange();
8591 
8592   CheckFormatHandler::EmitFormatDiagnostic(
8593                                   S, IsFunctionCall, DiagnosticExprs[0],
8594                                   PDiag, Loc, /*IsStringLocation*/false,
8595                                   DiagnosticExprs[0]->getSourceRange());
8596 }
8597 
8598 bool
8599 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8600                                                      SourceLocation Loc,
8601                                                      const char *startSpec,
8602                                                      unsigned specifierLen,
8603                                                      const char *csStart,
8604                                                      unsigned csLen) {
8605   bool keepGoing = true;
8606   if (argIndex < NumDataArgs) {
8607     // Consider the argument coverered, even though the specifier doesn't
8608     // make sense.
8609     CoveredArgs.set(argIndex);
8610   }
8611   else {
8612     // If argIndex exceeds the number of data arguments we
8613     // don't issue a warning because that is just a cascade of warnings (and
8614     // they may have intended '%%' anyway). We don't want to continue processing
8615     // the format string after this point, however, as we will like just get
8616     // gibberish when trying to match arguments.
8617     keepGoing = false;
8618   }
8619 
8620   StringRef Specifier(csStart, csLen);
8621 
8622   // If the specifier in non-printable, it could be the first byte of a UTF-8
8623   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8624   // hex value.
8625   std::string CodePointStr;
8626   if (!llvm::sys::locale::isPrint(*csStart)) {
8627     llvm::UTF32 CodePoint;
8628     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8629     const llvm::UTF8 *E =
8630         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8631     llvm::ConversionResult Result =
8632         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8633 
8634     if (Result != llvm::conversionOK) {
8635       unsigned char FirstChar = *csStart;
8636       CodePoint = (llvm::UTF32)FirstChar;
8637     }
8638 
8639     llvm::raw_string_ostream OS(CodePointStr);
8640     if (CodePoint < 256)
8641       OS << "\\x" << llvm::format("%02x", CodePoint);
8642     else if (CodePoint <= 0xFFFF)
8643       OS << "\\u" << llvm::format("%04x", CodePoint);
8644     else
8645       OS << "\\U" << llvm::format("%08x", CodePoint);
8646     OS.flush();
8647     Specifier = CodePointStr;
8648   }
8649 
8650   EmitFormatDiagnostic(
8651       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8652       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8653 
8654   return keepGoing;
8655 }
8656 
8657 void
8658 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8659                                                       const char *startSpec,
8660                                                       unsigned specifierLen) {
8661   EmitFormatDiagnostic(
8662     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8663     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8664 }
8665 
8666 bool
8667 CheckFormatHandler::CheckNumArgs(
8668   const analyze_format_string::FormatSpecifier &FS,
8669   const analyze_format_string::ConversionSpecifier &CS,
8670   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8671 
8672   if (argIndex >= NumDataArgs) {
8673     PartialDiagnostic PDiag = FS.usesPositionalArg()
8674       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8675            << (argIndex+1) << NumDataArgs)
8676       : S.PDiag(diag::warn_printf_insufficient_data_args);
8677     EmitFormatDiagnostic(
8678       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8679       getSpecifierRange(startSpecifier, specifierLen));
8680 
8681     // Since more arguments than conversion tokens are given, by extension
8682     // all arguments are covered, so mark this as so.
8683     UncoveredArg.setAllCovered();
8684     return false;
8685   }
8686   return true;
8687 }
8688 
8689 template<typename Range>
8690 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8691                                               SourceLocation Loc,
8692                                               bool IsStringLocation,
8693                                               Range StringRange,
8694                                               ArrayRef<FixItHint> FixIt) {
8695   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8696                        Loc, IsStringLocation, StringRange, FixIt);
8697 }
8698 
8699 /// If the format string is not within the function call, emit a note
8700 /// so that the function call and string are in diagnostic messages.
8701 ///
8702 /// \param InFunctionCall if true, the format string is within the function
8703 /// call and only one diagnostic message will be produced.  Otherwise, an
8704 /// extra note will be emitted pointing to location of the format string.
8705 ///
8706 /// \param ArgumentExpr the expression that is passed as the format string
8707 /// argument in the function call.  Used for getting locations when two
8708 /// diagnostics are emitted.
8709 ///
8710 /// \param PDiag the callee should already have provided any strings for the
8711 /// diagnostic message.  This function only adds locations and fixits
8712 /// to diagnostics.
8713 ///
8714 /// \param Loc primary location for diagnostic.  If two diagnostics are
8715 /// required, one will be at Loc and a new SourceLocation will be created for
8716 /// the other one.
8717 ///
8718 /// \param IsStringLocation if true, Loc points to the format string should be
8719 /// used for the note.  Otherwise, Loc points to the argument list and will
8720 /// be used with PDiag.
8721 ///
8722 /// \param StringRange some or all of the string to highlight.  This is
8723 /// templated so it can accept either a CharSourceRange or a SourceRange.
8724 ///
8725 /// \param FixIt optional fix it hint for the format string.
8726 template <typename Range>
8727 void CheckFormatHandler::EmitFormatDiagnostic(
8728     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8729     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8730     Range StringRange, ArrayRef<FixItHint> FixIt) {
8731   if (InFunctionCall) {
8732     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8733     D << StringRange;
8734     D << FixIt;
8735   } else {
8736     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8737       << ArgumentExpr->getSourceRange();
8738 
8739     const Sema::SemaDiagnosticBuilder &Note =
8740       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8741              diag::note_format_string_defined);
8742 
8743     Note << StringRange;
8744     Note << FixIt;
8745   }
8746 }
8747 
8748 //===--- CHECK: Printf format string checking ------------------------------===//
8749 
8750 namespace {
8751 
8752 class CheckPrintfHandler : public CheckFormatHandler {
8753 public:
8754   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8755                      const Expr *origFormatExpr,
8756                      const Sema::FormatStringType type, unsigned firstDataArg,
8757                      unsigned numDataArgs, bool isObjC, const char *beg,
8758                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8759                      unsigned formatIdx, bool inFunctionCall,
8760                      Sema::VariadicCallType CallType,
8761                      llvm::SmallBitVector &CheckedVarArgs,
8762                      UncoveredArgHandler &UncoveredArg)
8763       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8764                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8765                            inFunctionCall, CallType, CheckedVarArgs,
8766                            UncoveredArg) {}
8767 
8768   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8769 
8770   /// Returns true if '%@' specifiers are allowed in the format string.
8771   bool allowsObjCArg() const {
8772     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8773            FSType == Sema::FST_OSTrace;
8774   }
8775 
8776   bool HandleInvalidPrintfConversionSpecifier(
8777                                       const analyze_printf::PrintfSpecifier &FS,
8778                                       const char *startSpecifier,
8779                                       unsigned specifierLen) override;
8780 
8781   void handleInvalidMaskType(StringRef MaskType) override;
8782 
8783   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8784                              const char *startSpecifier,
8785                              unsigned specifierLen) override;
8786   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8787                        const char *StartSpecifier,
8788                        unsigned SpecifierLen,
8789                        const Expr *E);
8790 
8791   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8792                     const char *startSpecifier, unsigned specifierLen);
8793   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8794                            const analyze_printf::OptionalAmount &Amt,
8795                            unsigned type,
8796                            const char *startSpecifier, unsigned specifierLen);
8797   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8798                   const analyze_printf::OptionalFlag &flag,
8799                   const char *startSpecifier, unsigned specifierLen);
8800   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8801                          const analyze_printf::OptionalFlag &ignoredFlag,
8802                          const analyze_printf::OptionalFlag &flag,
8803                          const char *startSpecifier, unsigned specifierLen);
8804   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8805                            const Expr *E);
8806 
8807   void HandleEmptyObjCModifierFlag(const char *startFlag,
8808                                    unsigned flagLen) override;
8809 
8810   void HandleInvalidObjCModifierFlag(const char *startFlag,
8811                                             unsigned flagLen) override;
8812 
8813   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8814                                            const char *flagsEnd,
8815                                            const char *conversionPosition)
8816                                              override;
8817 };
8818 
8819 } // namespace
8820 
8821 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8822                                       const analyze_printf::PrintfSpecifier &FS,
8823                                       const char *startSpecifier,
8824                                       unsigned specifierLen) {
8825   const analyze_printf::PrintfConversionSpecifier &CS =
8826     FS.getConversionSpecifier();
8827 
8828   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8829                                           getLocationOfByte(CS.getStart()),
8830                                           startSpecifier, specifierLen,
8831                                           CS.getStart(), CS.getLength());
8832 }
8833 
8834 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8835   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8836 }
8837 
8838 bool CheckPrintfHandler::HandleAmount(
8839                                const analyze_format_string::OptionalAmount &Amt,
8840                                unsigned k, const char *startSpecifier,
8841                                unsigned specifierLen) {
8842   if (Amt.hasDataArgument()) {
8843     if (!HasVAListArg) {
8844       unsigned argIndex = Amt.getArgIndex();
8845       if (argIndex >= NumDataArgs) {
8846         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8847                                << k,
8848                              getLocationOfByte(Amt.getStart()),
8849                              /*IsStringLocation*/true,
8850                              getSpecifierRange(startSpecifier, specifierLen));
8851         // Don't do any more checking.  We will just emit
8852         // spurious errors.
8853         return false;
8854       }
8855 
8856       // Type check the data argument.  It should be an 'int'.
8857       // Although not in conformance with C99, we also allow the argument to be
8858       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8859       // doesn't emit a warning for that case.
8860       CoveredArgs.set(argIndex);
8861       const Expr *Arg = getDataArg(argIndex);
8862       if (!Arg)
8863         return false;
8864 
8865       QualType T = Arg->getType();
8866 
8867       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8868       assert(AT.isValid());
8869 
8870       if (!AT.matchesType(S.Context, T)) {
8871         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8872                                << k << AT.getRepresentativeTypeName(S.Context)
8873                                << T << Arg->getSourceRange(),
8874                              getLocationOfByte(Amt.getStart()),
8875                              /*IsStringLocation*/true,
8876                              getSpecifierRange(startSpecifier, specifierLen));
8877         // Don't do any more checking.  We will just emit
8878         // spurious errors.
8879         return false;
8880       }
8881     }
8882   }
8883   return true;
8884 }
8885 
8886 void CheckPrintfHandler::HandleInvalidAmount(
8887                                       const analyze_printf::PrintfSpecifier &FS,
8888                                       const analyze_printf::OptionalAmount &Amt,
8889                                       unsigned type,
8890                                       const char *startSpecifier,
8891                                       unsigned specifierLen) {
8892   const analyze_printf::PrintfConversionSpecifier &CS =
8893     FS.getConversionSpecifier();
8894 
8895   FixItHint fixit =
8896     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8897       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8898                                  Amt.getConstantLength()))
8899       : FixItHint();
8900 
8901   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8902                          << type << CS.toString(),
8903                        getLocationOfByte(Amt.getStart()),
8904                        /*IsStringLocation*/true,
8905                        getSpecifierRange(startSpecifier, specifierLen),
8906                        fixit);
8907 }
8908 
8909 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8910                                     const analyze_printf::OptionalFlag &flag,
8911                                     const char *startSpecifier,
8912                                     unsigned specifierLen) {
8913   // Warn about pointless flag with a fixit removal.
8914   const analyze_printf::PrintfConversionSpecifier &CS =
8915     FS.getConversionSpecifier();
8916   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8917                          << flag.toString() << CS.toString(),
8918                        getLocationOfByte(flag.getPosition()),
8919                        /*IsStringLocation*/true,
8920                        getSpecifierRange(startSpecifier, specifierLen),
8921                        FixItHint::CreateRemoval(
8922                          getSpecifierRange(flag.getPosition(), 1)));
8923 }
8924 
8925 void CheckPrintfHandler::HandleIgnoredFlag(
8926                                 const analyze_printf::PrintfSpecifier &FS,
8927                                 const analyze_printf::OptionalFlag &ignoredFlag,
8928                                 const analyze_printf::OptionalFlag &flag,
8929                                 const char *startSpecifier,
8930                                 unsigned specifierLen) {
8931   // Warn about ignored flag with a fixit removal.
8932   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8933                          << ignoredFlag.toString() << flag.toString(),
8934                        getLocationOfByte(ignoredFlag.getPosition()),
8935                        /*IsStringLocation*/true,
8936                        getSpecifierRange(startSpecifier, specifierLen),
8937                        FixItHint::CreateRemoval(
8938                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8939 }
8940 
8941 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8942                                                      unsigned flagLen) {
8943   // Warn about an empty flag.
8944   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8945                        getLocationOfByte(startFlag),
8946                        /*IsStringLocation*/true,
8947                        getSpecifierRange(startFlag, flagLen));
8948 }
8949 
8950 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8951                                                        unsigned flagLen) {
8952   // Warn about an invalid flag.
8953   auto Range = getSpecifierRange(startFlag, flagLen);
8954   StringRef flag(startFlag, flagLen);
8955   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8956                       getLocationOfByte(startFlag),
8957                       /*IsStringLocation*/true,
8958                       Range, FixItHint::CreateRemoval(Range));
8959 }
8960 
8961 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8962     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8963     // Warn about using '[...]' without a '@' conversion.
8964     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8965     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8966     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8967                          getLocationOfByte(conversionPosition),
8968                          /*IsStringLocation*/true,
8969                          Range, FixItHint::CreateRemoval(Range));
8970 }
8971 
8972 // Determines if the specified is a C++ class or struct containing
8973 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8974 // "c_str()").
8975 template<typename MemberKind>
8976 static llvm::SmallPtrSet<MemberKind*, 1>
8977 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8978   const RecordType *RT = Ty->getAs<RecordType>();
8979   llvm::SmallPtrSet<MemberKind*, 1> Results;
8980 
8981   if (!RT)
8982     return Results;
8983   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8984   if (!RD || !RD->getDefinition())
8985     return Results;
8986 
8987   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8988                  Sema::LookupMemberName);
8989   R.suppressDiagnostics();
8990 
8991   // We just need to include all members of the right kind turned up by the
8992   // filter, at this point.
8993   if (S.LookupQualifiedName(R, RT->getDecl()))
8994     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8995       NamedDecl *decl = (*I)->getUnderlyingDecl();
8996       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8997         Results.insert(FK);
8998     }
8999   return Results;
9000 }
9001 
9002 /// Check if we could call '.c_str()' on an object.
9003 ///
9004 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9005 /// allow the call, or if it would be ambiguous).
9006 bool Sema::hasCStrMethod(const Expr *E) {
9007   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9008 
9009   MethodSet Results =
9010       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9011   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9012        MI != ME; ++MI)
9013     if ((*MI)->getMinRequiredArguments() == 0)
9014       return true;
9015   return false;
9016 }
9017 
9018 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9019 // better diagnostic if so. AT is assumed to be valid.
9020 // Returns true when a c_str() conversion method is found.
9021 bool CheckPrintfHandler::checkForCStrMembers(
9022     const analyze_printf::ArgType &AT, const Expr *E) {
9023   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9024 
9025   MethodSet Results =
9026       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9027 
9028   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9029        MI != ME; ++MI) {
9030     const CXXMethodDecl *Method = *MI;
9031     if (Method->getMinRequiredArguments() == 0 &&
9032         AT.matchesType(S.Context, Method->getReturnType())) {
9033       // FIXME: Suggest parens if the expression needs them.
9034       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9035       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9036           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9037       return true;
9038     }
9039   }
9040 
9041   return false;
9042 }
9043 
9044 bool
9045 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
9046                                             &FS,
9047                                           const char *startSpecifier,
9048                                           unsigned specifierLen) {
9049   using namespace analyze_format_string;
9050   using namespace analyze_printf;
9051 
9052   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9053 
9054   if (FS.consumesDataArgument()) {
9055     if (atFirstArg) {
9056         atFirstArg = false;
9057         usesPositionalArgs = FS.usesPositionalArg();
9058     }
9059     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9060       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9061                                         startSpecifier, specifierLen);
9062       return false;
9063     }
9064   }
9065 
9066   // First check if the field width, precision, and conversion specifier
9067   // have matching data arguments.
9068   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9069                     startSpecifier, specifierLen)) {
9070     return false;
9071   }
9072 
9073   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9074                     startSpecifier, specifierLen)) {
9075     return false;
9076   }
9077 
9078   if (!CS.consumesDataArgument()) {
9079     // FIXME: Technically specifying a precision or field width here
9080     // makes no sense.  Worth issuing a warning at some point.
9081     return true;
9082   }
9083 
9084   // Consume the argument.
9085   unsigned argIndex = FS.getArgIndex();
9086   if (argIndex < NumDataArgs) {
9087     // The check to see if the argIndex is valid will come later.
9088     // We set the bit here because we may exit early from this
9089     // function if we encounter some other error.
9090     CoveredArgs.set(argIndex);
9091   }
9092 
9093   // FreeBSD kernel extensions.
9094   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9095       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9096     // We need at least two arguments.
9097     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9098       return false;
9099 
9100     // Claim the second argument.
9101     CoveredArgs.set(argIndex + 1);
9102 
9103     // Type check the first argument (int for %b, pointer for %D)
9104     const Expr *Ex = getDataArg(argIndex);
9105     const analyze_printf::ArgType &AT =
9106       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9107         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9108     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9109       EmitFormatDiagnostic(
9110           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9111               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9112               << false << Ex->getSourceRange(),
9113           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9114           getSpecifierRange(startSpecifier, specifierLen));
9115 
9116     // Type check the second argument (char * for both %b and %D)
9117     Ex = getDataArg(argIndex + 1);
9118     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9119     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9120       EmitFormatDiagnostic(
9121           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9122               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9123               << false << Ex->getSourceRange(),
9124           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9125           getSpecifierRange(startSpecifier, specifierLen));
9126 
9127      return true;
9128   }
9129 
9130   // Check for using an Objective-C specific conversion specifier
9131   // in a non-ObjC literal.
9132   if (!allowsObjCArg() && CS.isObjCArg()) {
9133     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9134                                                   specifierLen);
9135   }
9136 
9137   // %P can only be used with os_log.
9138   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9139     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9140                                                   specifierLen);
9141   }
9142 
9143   // %n is not allowed with os_log.
9144   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9145     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9146                          getLocationOfByte(CS.getStart()),
9147                          /*IsStringLocation*/ false,
9148                          getSpecifierRange(startSpecifier, specifierLen));
9149 
9150     return true;
9151   }
9152 
9153   // Only scalars are allowed for os_trace.
9154   if (FSType == Sema::FST_OSTrace &&
9155       (CS.getKind() == ConversionSpecifier::PArg ||
9156        CS.getKind() == ConversionSpecifier::sArg ||
9157        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9158     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9159                                                   specifierLen);
9160   }
9161 
9162   // Check for use of public/private annotation outside of os_log().
9163   if (FSType != Sema::FST_OSLog) {
9164     if (FS.isPublic().isSet()) {
9165       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9166                                << "public",
9167                            getLocationOfByte(FS.isPublic().getPosition()),
9168                            /*IsStringLocation*/ false,
9169                            getSpecifierRange(startSpecifier, specifierLen));
9170     }
9171     if (FS.isPrivate().isSet()) {
9172       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9173                                << "private",
9174                            getLocationOfByte(FS.isPrivate().getPosition()),
9175                            /*IsStringLocation*/ false,
9176                            getSpecifierRange(startSpecifier, specifierLen));
9177     }
9178   }
9179 
9180   // Check for invalid use of field width
9181   if (!FS.hasValidFieldWidth()) {
9182     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9183         startSpecifier, specifierLen);
9184   }
9185 
9186   // Check for invalid use of precision
9187   if (!FS.hasValidPrecision()) {
9188     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9189         startSpecifier, specifierLen);
9190   }
9191 
9192   // Precision is mandatory for %P specifier.
9193   if (CS.getKind() == ConversionSpecifier::PArg &&
9194       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9195     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9196                          getLocationOfByte(startSpecifier),
9197                          /*IsStringLocation*/ false,
9198                          getSpecifierRange(startSpecifier, specifierLen));
9199   }
9200 
9201   // Check each flag does not conflict with any other component.
9202   if (!FS.hasValidThousandsGroupingPrefix())
9203     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9204   if (!FS.hasValidLeadingZeros())
9205     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9206   if (!FS.hasValidPlusPrefix())
9207     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9208   if (!FS.hasValidSpacePrefix())
9209     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9210   if (!FS.hasValidAlternativeForm())
9211     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9212   if (!FS.hasValidLeftJustified())
9213     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9214 
9215   // Check that flags are not ignored by another flag
9216   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9217     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9218         startSpecifier, specifierLen);
9219   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9220     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9221             startSpecifier, specifierLen);
9222 
9223   // Check the length modifier is valid with the given conversion specifier.
9224   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9225                                  S.getLangOpts()))
9226     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9227                                 diag::warn_format_nonsensical_length);
9228   else if (!FS.hasStandardLengthModifier())
9229     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9230   else if (!FS.hasStandardLengthConversionCombination())
9231     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9232                                 diag::warn_format_non_standard_conversion_spec);
9233 
9234   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9235     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9236 
9237   // The remaining checks depend on the data arguments.
9238   if (HasVAListArg)
9239     return true;
9240 
9241   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9242     return false;
9243 
9244   const Expr *Arg = getDataArg(argIndex);
9245   if (!Arg)
9246     return true;
9247 
9248   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9249 }
9250 
9251 static bool requiresParensToAddCast(const Expr *E) {
9252   // FIXME: We should have a general way to reason about operator
9253   // precedence and whether parens are actually needed here.
9254   // Take care of a few common cases where they aren't.
9255   const Expr *Inside = E->IgnoreImpCasts();
9256   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9257     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9258 
9259   switch (Inside->getStmtClass()) {
9260   case Stmt::ArraySubscriptExprClass:
9261   case Stmt::CallExprClass:
9262   case Stmt::CharacterLiteralClass:
9263   case Stmt::CXXBoolLiteralExprClass:
9264   case Stmt::DeclRefExprClass:
9265   case Stmt::FloatingLiteralClass:
9266   case Stmt::IntegerLiteralClass:
9267   case Stmt::MemberExprClass:
9268   case Stmt::ObjCArrayLiteralClass:
9269   case Stmt::ObjCBoolLiteralExprClass:
9270   case Stmt::ObjCBoxedExprClass:
9271   case Stmt::ObjCDictionaryLiteralClass:
9272   case Stmt::ObjCEncodeExprClass:
9273   case Stmt::ObjCIvarRefExprClass:
9274   case Stmt::ObjCMessageExprClass:
9275   case Stmt::ObjCPropertyRefExprClass:
9276   case Stmt::ObjCStringLiteralClass:
9277   case Stmt::ObjCSubscriptRefExprClass:
9278   case Stmt::ParenExprClass:
9279   case Stmt::StringLiteralClass:
9280   case Stmt::UnaryOperatorClass:
9281     return false;
9282   default:
9283     return true;
9284   }
9285 }
9286 
9287 static std::pair<QualType, StringRef>
9288 shouldNotPrintDirectly(const ASTContext &Context,
9289                        QualType IntendedTy,
9290                        const Expr *E) {
9291   // Use a 'while' to peel off layers of typedefs.
9292   QualType TyTy = IntendedTy;
9293   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9294     StringRef Name = UserTy->getDecl()->getName();
9295     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9296       .Case("CFIndex", Context.getNSIntegerType())
9297       .Case("NSInteger", Context.getNSIntegerType())
9298       .Case("NSUInteger", Context.getNSUIntegerType())
9299       .Case("SInt32", Context.IntTy)
9300       .Case("UInt32", Context.UnsignedIntTy)
9301       .Default(QualType());
9302 
9303     if (!CastTy.isNull())
9304       return std::make_pair(CastTy, Name);
9305 
9306     TyTy = UserTy->desugar();
9307   }
9308 
9309   // Strip parens if necessary.
9310   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9311     return shouldNotPrintDirectly(Context,
9312                                   PE->getSubExpr()->getType(),
9313                                   PE->getSubExpr());
9314 
9315   // If this is a conditional expression, then its result type is constructed
9316   // via usual arithmetic conversions and thus there might be no necessary
9317   // typedef sugar there.  Recurse to operands to check for NSInteger &
9318   // Co. usage condition.
9319   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9320     QualType TrueTy, FalseTy;
9321     StringRef TrueName, FalseName;
9322 
9323     std::tie(TrueTy, TrueName) =
9324       shouldNotPrintDirectly(Context,
9325                              CO->getTrueExpr()->getType(),
9326                              CO->getTrueExpr());
9327     std::tie(FalseTy, FalseName) =
9328       shouldNotPrintDirectly(Context,
9329                              CO->getFalseExpr()->getType(),
9330                              CO->getFalseExpr());
9331 
9332     if (TrueTy == FalseTy)
9333       return std::make_pair(TrueTy, TrueName);
9334     else if (TrueTy.isNull())
9335       return std::make_pair(FalseTy, FalseName);
9336     else if (FalseTy.isNull())
9337       return std::make_pair(TrueTy, TrueName);
9338   }
9339 
9340   return std::make_pair(QualType(), StringRef());
9341 }
9342 
9343 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9344 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9345 /// type do not count.
9346 static bool
9347 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9348   QualType From = ICE->getSubExpr()->getType();
9349   QualType To = ICE->getType();
9350   // It's an integer promotion if the destination type is the promoted
9351   // source type.
9352   if (ICE->getCastKind() == CK_IntegralCast &&
9353       From->isPromotableIntegerType() &&
9354       S.Context.getPromotedIntegerType(From) == To)
9355     return true;
9356   // Look through vector types, since we do default argument promotion for
9357   // those in OpenCL.
9358   if (const auto *VecTy = From->getAs<ExtVectorType>())
9359     From = VecTy->getElementType();
9360   if (const auto *VecTy = To->getAs<ExtVectorType>())
9361     To = VecTy->getElementType();
9362   // It's a floating promotion if the source type is a lower rank.
9363   return ICE->getCastKind() == CK_FloatingCast &&
9364          S.Context.getFloatingTypeOrder(From, To) < 0;
9365 }
9366 
9367 bool
9368 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9369                                     const char *StartSpecifier,
9370                                     unsigned SpecifierLen,
9371                                     const Expr *E) {
9372   using namespace analyze_format_string;
9373   using namespace analyze_printf;
9374 
9375   // Now type check the data expression that matches the
9376   // format specifier.
9377   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9378   if (!AT.isValid())
9379     return true;
9380 
9381   QualType ExprTy = E->getType();
9382   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9383     ExprTy = TET->getUnderlyingExpr()->getType();
9384   }
9385 
9386   // Diagnose attempts to print a boolean value as a character. Unlike other
9387   // -Wformat diagnostics, this is fine from a type perspective, but it still
9388   // doesn't make sense.
9389   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9390       E->isKnownToHaveBooleanValue()) {
9391     const CharSourceRange &CSR =
9392         getSpecifierRange(StartSpecifier, SpecifierLen);
9393     SmallString<4> FSString;
9394     llvm::raw_svector_ostream os(FSString);
9395     FS.toString(os);
9396     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9397                              << FSString,
9398                          E->getExprLoc(), false, CSR);
9399     return true;
9400   }
9401 
9402   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9403   if (Match == analyze_printf::ArgType::Match)
9404     return true;
9405 
9406   // Look through argument promotions for our error message's reported type.
9407   // This includes the integral and floating promotions, but excludes array
9408   // and function pointer decay (seeing that an argument intended to be a
9409   // string has type 'char [6]' is probably more confusing than 'char *') and
9410   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9411   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9412     if (isArithmeticArgumentPromotion(S, ICE)) {
9413       E = ICE->getSubExpr();
9414       ExprTy = E->getType();
9415 
9416       // Check if we didn't match because of an implicit cast from a 'char'
9417       // or 'short' to an 'int'.  This is done because printf is a varargs
9418       // function.
9419       if (ICE->getType() == S.Context.IntTy ||
9420           ICE->getType() == S.Context.UnsignedIntTy) {
9421         // All further checking is done on the subexpression
9422         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9423             AT.matchesType(S.Context, ExprTy);
9424         if (ImplicitMatch == analyze_printf::ArgType::Match)
9425           return true;
9426         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9427             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9428           Match = ImplicitMatch;
9429       }
9430     }
9431   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9432     // Special case for 'a', which has type 'int' in C.
9433     // Note, however, that we do /not/ want to treat multibyte constants like
9434     // 'MooV' as characters! This form is deprecated but still exists. In
9435     // addition, don't treat expressions as of type 'char' if one byte length
9436     // modifier is provided.
9437     if (ExprTy == S.Context.IntTy &&
9438         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9439       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9440         ExprTy = S.Context.CharTy;
9441   }
9442 
9443   // Look through enums to their underlying type.
9444   bool IsEnum = false;
9445   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9446     ExprTy = EnumTy->getDecl()->getIntegerType();
9447     IsEnum = true;
9448   }
9449 
9450   // %C in an Objective-C context prints a unichar, not a wchar_t.
9451   // If the argument is an integer of some kind, believe the %C and suggest
9452   // a cast instead of changing the conversion specifier.
9453   QualType IntendedTy = ExprTy;
9454   if (isObjCContext() &&
9455       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9456     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9457         !ExprTy->isCharType()) {
9458       // 'unichar' is defined as a typedef of unsigned short, but we should
9459       // prefer using the typedef if it is visible.
9460       IntendedTy = S.Context.UnsignedShortTy;
9461 
9462       // While we are here, check if the value is an IntegerLiteral that happens
9463       // to be within the valid range.
9464       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9465         const llvm::APInt &V = IL->getValue();
9466         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9467           return true;
9468       }
9469 
9470       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9471                           Sema::LookupOrdinaryName);
9472       if (S.LookupName(Result, S.getCurScope())) {
9473         NamedDecl *ND = Result.getFoundDecl();
9474         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9475           if (TD->getUnderlyingType() == IntendedTy)
9476             IntendedTy = S.Context.getTypedefType(TD);
9477       }
9478     }
9479   }
9480 
9481   // Special-case some of Darwin's platform-independence types by suggesting
9482   // casts to primitive types that are known to be large enough.
9483   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9484   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9485     QualType CastTy;
9486     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9487     if (!CastTy.isNull()) {
9488       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9489       // (long in ASTContext). Only complain to pedants.
9490       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9491           (AT.isSizeT() || AT.isPtrdiffT()) &&
9492           AT.matchesType(S.Context, CastTy))
9493         Match = ArgType::NoMatchPedantic;
9494       IntendedTy = CastTy;
9495       ShouldNotPrintDirectly = true;
9496     }
9497   }
9498 
9499   // We may be able to offer a FixItHint if it is a supported type.
9500   PrintfSpecifier fixedFS = FS;
9501   bool Success =
9502       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9503 
9504   if (Success) {
9505     // Get the fix string from the fixed format specifier
9506     SmallString<16> buf;
9507     llvm::raw_svector_ostream os(buf);
9508     fixedFS.toString(os);
9509 
9510     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9511 
9512     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9513       unsigned Diag;
9514       switch (Match) {
9515       case ArgType::Match: llvm_unreachable("expected non-matching");
9516       case ArgType::NoMatchPedantic:
9517         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9518         break;
9519       case ArgType::NoMatchTypeConfusion:
9520         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9521         break;
9522       case ArgType::NoMatch:
9523         Diag = diag::warn_format_conversion_argument_type_mismatch;
9524         break;
9525       }
9526 
9527       // In this case, the specifier is wrong and should be changed to match
9528       // the argument.
9529       EmitFormatDiagnostic(S.PDiag(Diag)
9530                                << AT.getRepresentativeTypeName(S.Context)
9531                                << IntendedTy << IsEnum << E->getSourceRange(),
9532                            E->getBeginLoc(),
9533                            /*IsStringLocation*/ false, SpecRange,
9534                            FixItHint::CreateReplacement(SpecRange, os.str()));
9535     } else {
9536       // The canonical type for formatting this value is different from the
9537       // actual type of the expression. (This occurs, for example, with Darwin's
9538       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9539       // should be printed as 'long' for 64-bit compatibility.)
9540       // Rather than emitting a normal format/argument mismatch, we want to
9541       // add a cast to the recommended type (and correct the format string
9542       // if necessary).
9543       SmallString<16> CastBuf;
9544       llvm::raw_svector_ostream CastFix(CastBuf);
9545       CastFix << "(";
9546       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9547       CastFix << ")";
9548 
9549       SmallVector<FixItHint,4> Hints;
9550       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9551         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9552 
9553       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9554         // If there's already a cast present, just replace it.
9555         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9556         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9557 
9558       } else if (!requiresParensToAddCast(E)) {
9559         // If the expression has high enough precedence,
9560         // just write the C-style cast.
9561         Hints.push_back(
9562             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9563       } else {
9564         // Otherwise, add parens around the expression as well as the cast.
9565         CastFix << "(";
9566         Hints.push_back(
9567             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9568 
9569         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9570         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9571       }
9572 
9573       if (ShouldNotPrintDirectly) {
9574         // The expression has a type that should not be printed directly.
9575         // We extract the name from the typedef because we don't want to show
9576         // the underlying type in the diagnostic.
9577         StringRef Name;
9578         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9579           Name = TypedefTy->getDecl()->getName();
9580         else
9581           Name = CastTyName;
9582         unsigned Diag = Match == ArgType::NoMatchPedantic
9583                             ? diag::warn_format_argument_needs_cast_pedantic
9584                             : diag::warn_format_argument_needs_cast;
9585         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9586                                            << E->getSourceRange(),
9587                              E->getBeginLoc(), /*IsStringLocation=*/false,
9588                              SpecRange, Hints);
9589       } else {
9590         // In this case, the expression could be printed using a different
9591         // specifier, but we've decided that the specifier is probably correct
9592         // and we should cast instead. Just use the normal warning message.
9593         EmitFormatDiagnostic(
9594             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9595                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9596                 << E->getSourceRange(),
9597             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9598       }
9599     }
9600   } else {
9601     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9602                                                    SpecifierLen);
9603     // Since the warning for passing non-POD types to variadic functions
9604     // was deferred until now, we emit a warning for non-POD
9605     // arguments here.
9606     switch (S.isValidVarArgType(ExprTy)) {
9607     case Sema::VAK_Valid:
9608     case Sema::VAK_ValidInCXX11: {
9609       unsigned Diag;
9610       switch (Match) {
9611       case ArgType::Match: llvm_unreachable("expected non-matching");
9612       case ArgType::NoMatchPedantic:
9613         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9614         break;
9615       case ArgType::NoMatchTypeConfusion:
9616         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9617         break;
9618       case ArgType::NoMatch:
9619         Diag = diag::warn_format_conversion_argument_type_mismatch;
9620         break;
9621       }
9622 
9623       EmitFormatDiagnostic(
9624           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9625                         << IsEnum << CSR << E->getSourceRange(),
9626           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9627       break;
9628     }
9629     case Sema::VAK_Undefined:
9630     case Sema::VAK_MSVCUndefined:
9631       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9632                                << S.getLangOpts().CPlusPlus11 << ExprTy
9633                                << CallType
9634                                << AT.getRepresentativeTypeName(S.Context) << CSR
9635                                << E->getSourceRange(),
9636                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9637       checkForCStrMembers(AT, E);
9638       break;
9639 
9640     case Sema::VAK_Invalid:
9641       if (ExprTy->isObjCObjectType())
9642         EmitFormatDiagnostic(
9643             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9644                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9645                 << AT.getRepresentativeTypeName(S.Context) << CSR
9646                 << E->getSourceRange(),
9647             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9648       else
9649         // FIXME: If this is an initializer list, suggest removing the braces
9650         // or inserting a cast to the target type.
9651         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9652             << isa<InitListExpr>(E) << ExprTy << CallType
9653             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9654       break;
9655     }
9656 
9657     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9658            "format string specifier index out of range");
9659     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9660   }
9661 
9662   return true;
9663 }
9664 
9665 //===--- CHECK: Scanf format string checking ------------------------------===//
9666 
9667 namespace {
9668 
9669 class CheckScanfHandler : public CheckFormatHandler {
9670 public:
9671   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9672                     const Expr *origFormatExpr, Sema::FormatStringType type,
9673                     unsigned firstDataArg, unsigned numDataArgs,
9674                     const char *beg, bool hasVAListArg,
9675                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9676                     bool inFunctionCall, Sema::VariadicCallType CallType,
9677                     llvm::SmallBitVector &CheckedVarArgs,
9678                     UncoveredArgHandler &UncoveredArg)
9679       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9680                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9681                            inFunctionCall, CallType, CheckedVarArgs,
9682                            UncoveredArg) {}
9683 
9684   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9685                             const char *startSpecifier,
9686                             unsigned specifierLen) override;
9687 
9688   bool HandleInvalidScanfConversionSpecifier(
9689           const analyze_scanf::ScanfSpecifier &FS,
9690           const char *startSpecifier,
9691           unsigned specifierLen) override;
9692 
9693   void HandleIncompleteScanList(const char *start, const char *end) override;
9694 };
9695 
9696 } // namespace
9697 
9698 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9699                                                  const char *end) {
9700   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9701                        getLocationOfByte(end), /*IsStringLocation*/true,
9702                        getSpecifierRange(start, end - start));
9703 }
9704 
9705 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9706                                         const analyze_scanf::ScanfSpecifier &FS,
9707                                         const char *startSpecifier,
9708                                         unsigned specifierLen) {
9709   const analyze_scanf::ScanfConversionSpecifier &CS =
9710     FS.getConversionSpecifier();
9711 
9712   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9713                                           getLocationOfByte(CS.getStart()),
9714                                           startSpecifier, specifierLen,
9715                                           CS.getStart(), CS.getLength());
9716 }
9717 
9718 bool CheckScanfHandler::HandleScanfSpecifier(
9719                                        const analyze_scanf::ScanfSpecifier &FS,
9720                                        const char *startSpecifier,
9721                                        unsigned specifierLen) {
9722   using namespace analyze_scanf;
9723   using namespace analyze_format_string;
9724 
9725   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9726 
9727   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9728   // be used to decide if we are using positional arguments consistently.
9729   if (FS.consumesDataArgument()) {
9730     if (atFirstArg) {
9731       atFirstArg = false;
9732       usesPositionalArgs = FS.usesPositionalArg();
9733     }
9734     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9735       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9736                                         startSpecifier, specifierLen);
9737       return false;
9738     }
9739   }
9740 
9741   // Check if the field with is non-zero.
9742   const OptionalAmount &Amt = FS.getFieldWidth();
9743   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9744     if (Amt.getConstantAmount() == 0) {
9745       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9746                                                    Amt.getConstantLength());
9747       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9748                            getLocationOfByte(Amt.getStart()),
9749                            /*IsStringLocation*/true, R,
9750                            FixItHint::CreateRemoval(R));
9751     }
9752   }
9753 
9754   if (!FS.consumesDataArgument()) {
9755     // FIXME: Technically specifying a precision or field width here
9756     // makes no sense.  Worth issuing a warning at some point.
9757     return true;
9758   }
9759 
9760   // Consume the argument.
9761   unsigned argIndex = FS.getArgIndex();
9762   if (argIndex < NumDataArgs) {
9763       // The check to see if the argIndex is valid will come later.
9764       // We set the bit here because we may exit early from this
9765       // function if we encounter some other error.
9766     CoveredArgs.set(argIndex);
9767   }
9768 
9769   // Check the length modifier is valid with the given conversion specifier.
9770   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9771                                  S.getLangOpts()))
9772     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9773                                 diag::warn_format_nonsensical_length);
9774   else if (!FS.hasStandardLengthModifier())
9775     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9776   else if (!FS.hasStandardLengthConversionCombination())
9777     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9778                                 diag::warn_format_non_standard_conversion_spec);
9779 
9780   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9781     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9782 
9783   // The remaining checks depend on the data arguments.
9784   if (HasVAListArg)
9785     return true;
9786 
9787   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9788     return false;
9789 
9790   // Check that the argument type matches the format specifier.
9791   const Expr *Ex = getDataArg(argIndex);
9792   if (!Ex)
9793     return true;
9794 
9795   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9796 
9797   if (!AT.isValid()) {
9798     return true;
9799   }
9800 
9801   analyze_format_string::ArgType::MatchKind Match =
9802       AT.matchesType(S.Context, Ex->getType());
9803   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9804   if (Match == analyze_format_string::ArgType::Match)
9805     return true;
9806 
9807   ScanfSpecifier fixedFS = FS;
9808   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9809                                  S.getLangOpts(), S.Context);
9810 
9811   unsigned Diag =
9812       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9813                : diag::warn_format_conversion_argument_type_mismatch;
9814 
9815   if (Success) {
9816     // Get the fix string from the fixed format specifier.
9817     SmallString<128> buf;
9818     llvm::raw_svector_ostream os(buf);
9819     fixedFS.toString(os);
9820 
9821     EmitFormatDiagnostic(
9822         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9823                       << Ex->getType() << false << Ex->getSourceRange(),
9824         Ex->getBeginLoc(),
9825         /*IsStringLocation*/ false,
9826         getSpecifierRange(startSpecifier, specifierLen),
9827         FixItHint::CreateReplacement(
9828             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9829   } else {
9830     EmitFormatDiagnostic(S.PDiag(Diag)
9831                              << AT.getRepresentativeTypeName(S.Context)
9832                              << Ex->getType() << false << Ex->getSourceRange(),
9833                          Ex->getBeginLoc(),
9834                          /*IsStringLocation*/ false,
9835                          getSpecifierRange(startSpecifier, specifierLen));
9836   }
9837 
9838   return true;
9839 }
9840 
9841 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9842                               const Expr *OrigFormatExpr,
9843                               ArrayRef<const Expr *> Args,
9844                               bool HasVAListArg, unsigned format_idx,
9845                               unsigned firstDataArg,
9846                               Sema::FormatStringType Type,
9847                               bool inFunctionCall,
9848                               Sema::VariadicCallType CallType,
9849                               llvm::SmallBitVector &CheckedVarArgs,
9850                               UncoveredArgHandler &UncoveredArg,
9851                               bool IgnoreStringsWithoutSpecifiers) {
9852   // CHECK: is the format string a wide literal?
9853   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9854     CheckFormatHandler::EmitFormatDiagnostic(
9855         S, inFunctionCall, Args[format_idx],
9856         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9857         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9858     return;
9859   }
9860 
9861   // Str - The format string.  NOTE: this is NOT null-terminated!
9862   StringRef StrRef = FExpr->getString();
9863   const char *Str = StrRef.data();
9864   // Account for cases where the string literal is truncated in a declaration.
9865   const ConstantArrayType *T =
9866     S.Context.getAsConstantArrayType(FExpr->getType());
9867   assert(T && "String literal not of constant array type!");
9868   size_t TypeSize = T->getSize().getZExtValue();
9869   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9870   const unsigned numDataArgs = Args.size() - firstDataArg;
9871 
9872   if (IgnoreStringsWithoutSpecifiers &&
9873       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9874           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9875     return;
9876 
9877   // Emit a warning if the string literal is truncated and does not contain an
9878   // embedded null character.
9879   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9880     CheckFormatHandler::EmitFormatDiagnostic(
9881         S, inFunctionCall, Args[format_idx],
9882         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9883         FExpr->getBeginLoc(),
9884         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9885     return;
9886   }
9887 
9888   // CHECK: empty format string?
9889   if (StrLen == 0 && numDataArgs > 0) {
9890     CheckFormatHandler::EmitFormatDiagnostic(
9891         S, inFunctionCall, Args[format_idx],
9892         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9893         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9894     return;
9895   }
9896 
9897   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9898       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9899       Type == Sema::FST_OSTrace) {
9900     CheckPrintfHandler H(
9901         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9902         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9903         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9904         CheckedVarArgs, UncoveredArg);
9905 
9906     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9907                                                   S.getLangOpts(),
9908                                                   S.Context.getTargetInfo(),
9909                                             Type == Sema::FST_FreeBSDKPrintf))
9910       H.DoneProcessing();
9911   } else if (Type == Sema::FST_Scanf) {
9912     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9913                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9914                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9915 
9916     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9917                                                  S.getLangOpts(),
9918                                                  S.Context.getTargetInfo()))
9919       H.DoneProcessing();
9920   } // TODO: handle other formats
9921 }
9922 
9923 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9924   // Str - The format string.  NOTE: this is NOT null-terminated!
9925   StringRef StrRef = FExpr->getString();
9926   const char *Str = StrRef.data();
9927   // Account for cases where the string literal is truncated in a declaration.
9928   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9929   assert(T && "String literal not of constant array type!");
9930   size_t TypeSize = T->getSize().getZExtValue();
9931   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9932   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9933                                                          getLangOpts(),
9934                                                          Context.getTargetInfo());
9935 }
9936 
9937 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9938 
9939 // Returns the related absolute value function that is larger, of 0 if one
9940 // does not exist.
9941 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9942   switch (AbsFunction) {
9943   default:
9944     return 0;
9945 
9946   case Builtin::BI__builtin_abs:
9947     return Builtin::BI__builtin_labs;
9948   case Builtin::BI__builtin_labs:
9949     return Builtin::BI__builtin_llabs;
9950   case Builtin::BI__builtin_llabs:
9951     return 0;
9952 
9953   case Builtin::BI__builtin_fabsf:
9954     return Builtin::BI__builtin_fabs;
9955   case Builtin::BI__builtin_fabs:
9956     return Builtin::BI__builtin_fabsl;
9957   case Builtin::BI__builtin_fabsl:
9958     return 0;
9959 
9960   case Builtin::BI__builtin_cabsf:
9961     return Builtin::BI__builtin_cabs;
9962   case Builtin::BI__builtin_cabs:
9963     return Builtin::BI__builtin_cabsl;
9964   case Builtin::BI__builtin_cabsl:
9965     return 0;
9966 
9967   case Builtin::BIabs:
9968     return Builtin::BIlabs;
9969   case Builtin::BIlabs:
9970     return Builtin::BIllabs;
9971   case Builtin::BIllabs:
9972     return 0;
9973 
9974   case Builtin::BIfabsf:
9975     return Builtin::BIfabs;
9976   case Builtin::BIfabs:
9977     return Builtin::BIfabsl;
9978   case Builtin::BIfabsl:
9979     return 0;
9980 
9981   case Builtin::BIcabsf:
9982    return Builtin::BIcabs;
9983   case Builtin::BIcabs:
9984     return Builtin::BIcabsl;
9985   case Builtin::BIcabsl:
9986     return 0;
9987   }
9988 }
9989 
9990 // Returns the argument type of the absolute value function.
9991 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9992                                              unsigned AbsType) {
9993   if (AbsType == 0)
9994     return QualType();
9995 
9996   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9997   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9998   if (Error != ASTContext::GE_None)
9999     return QualType();
10000 
10001   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10002   if (!FT)
10003     return QualType();
10004 
10005   if (FT->getNumParams() != 1)
10006     return QualType();
10007 
10008   return FT->getParamType(0);
10009 }
10010 
10011 // Returns the best absolute value function, or zero, based on type and
10012 // current absolute value function.
10013 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10014                                    unsigned AbsFunctionKind) {
10015   unsigned BestKind = 0;
10016   uint64_t ArgSize = Context.getTypeSize(ArgType);
10017   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10018        Kind = getLargerAbsoluteValueFunction(Kind)) {
10019     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10020     if (Context.getTypeSize(ParamType) >= ArgSize) {
10021       if (BestKind == 0)
10022         BestKind = Kind;
10023       else if (Context.hasSameType(ParamType, ArgType)) {
10024         BestKind = Kind;
10025         break;
10026       }
10027     }
10028   }
10029   return BestKind;
10030 }
10031 
10032 enum AbsoluteValueKind {
10033   AVK_Integer,
10034   AVK_Floating,
10035   AVK_Complex
10036 };
10037 
10038 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10039   if (T->isIntegralOrEnumerationType())
10040     return AVK_Integer;
10041   if (T->isRealFloatingType())
10042     return AVK_Floating;
10043   if (T->isAnyComplexType())
10044     return AVK_Complex;
10045 
10046   llvm_unreachable("Type not integer, floating, or complex");
10047 }
10048 
10049 // Changes the absolute value function to a different type.  Preserves whether
10050 // the function is a builtin.
10051 static unsigned changeAbsFunction(unsigned AbsKind,
10052                                   AbsoluteValueKind ValueKind) {
10053   switch (ValueKind) {
10054   case AVK_Integer:
10055     switch (AbsKind) {
10056     default:
10057       return 0;
10058     case Builtin::BI__builtin_fabsf:
10059     case Builtin::BI__builtin_fabs:
10060     case Builtin::BI__builtin_fabsl:
10061     case Builtin::BI__builtin_cabsf:
10062     case Builtin::BI__builtin_cabs:
10063     case Builtin::BI__builtin_cabsl:
10064       return Builtin::BI__builtin_abs;
10065     case Builtin::BIfabsf:
10066     case Builtin::BIfabs:
10067     case Builtin::BIfabsl:
10068     case Builtin::BIcabsf:
10069     case Builtin::BIcabs:
10070     case Builtin::BIcabsl:
10071       return Builtin::BIabs;
10072     }
10073   case AVK_Floating:
10074     switch (AbsKind) {
10075     default:
10076       return 0;
10077     case Builtin::BI__builtin_abs:
10078     case Builtin::BI__builtin_labs:
10079     case Builtin::BI__builtin_llabs:
10080     case Builtin::BI__builtin_cabsf:
10081     case Builtin::BI__builtin_cabs:
10082     case Builtin::BI__builtin_cabsl:
10083       return Builtin::BI__builtin_fabsf;
10084     case Builtin::BIabs:
10085     case Builtin::BIlabs:
10086     case Builtin::BIllabs:
10087     case Builtin::BIcabsf:
10088     case Builtin::BIcabs:
10089     case Builtin::BIcabsl:
10090       return Builtin::BIfabsf;
10091     }
10092   case AVK_Complex:
10093     switch (AbsKind) {
10094     default:
10095       return 0;
10096     case Builtin::BI__builtin_abs:
10097     case Builtin::BI__builtin_labs:
10098     case Builtin::BI__builtin_llabs:
10099     case Builtin::BI__builtin_fabsf:
10100     case Builtin::BI__builtin_fabs:
10101     case Builtin::BI__builtin_fabsl:
10102       return Builtin::BI__builtin_cabsf;
10103     case Builtin::BIabs:
10104     case Builtin::BIlabs:
10105     case Builtin::BIllabs:
10106     case Builtin::BIfabsf:
10107     case Builtin::BIfabs:
10108     case Builtin::BIfabsl:
10109       return Builtin::BIcabsf;
10110     }
10111   }
10112   llvm_unreachable("Unable to convert function");
10113 }
10114 
10115 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10116   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10117   if (!FnInfo)
10118     return 0;
10119 
10120   switch (FDecl->getBuiltinID()) {
10121   default:
10122     return 0;
10123   case Builtin::BI__builtin_abs:
10124   case Builtin::BI__builtin_fabs:
10125   case Builtin::BI__builtin_fabsf:
10126   case Builtin::BI__builtin_fabsl:
10127   case Builtin::BI__builtin_labs:
10128   case Builtin::BI__builtin_llabs:
10129   case Builtin::BI__builtin_cabs:
10130   case Builtin::BI__builtin_cabsf:
10131   case Builtin::BI__builtin_cabsl:
10132   case Builtin::BIabs:
10133   case Builtin::BIlabs:
10134   case Builtin::BIllabs:
10135   case Builtin::BIfabs:
10136   case Builtin::BIfabsf:
10137   case Builtin::BIfabsl:
10138   case Builtin::BIcabs:
10139   case Builtin::BIcabsf:
10140   case Builtin::BIcabsl:
10141     return FDecl->getBuiltinID();
10142   }
10143   llvm_unreachable("Unknown Builtin type");
10144 }
10145 
10146 // If the replacement is valid, emit a note with replacement function.
10147 // Additionally, suggest including the proper header if not already included.
10148 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10149                             unsigned AbsKind, QualType ArgType) {
10150   bool EmitHeaderHint = true;
10151   const char *HeaderName = nullptr;
10152   const char *FunctionName = nullptr;
10153   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10154     FunctionName = "std::abs";
10155     if (ArgType->isIntegralOrEnumerationType()) {
10156       HeaderName = "cstdlib";
10157     } else if (ArgType->isRealFloatingType()) {
10158       HeaderName = "cmath";
10159     } else {
10160       llvm_unreachable("Invalid Type");
10161     }
10162 
10163     // Lookup all std::abs
10164     if (NamespaceDecl *Std = S.getStdNamespace()) {
10165       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10166       R.suppressDiagnostics();
10167       S.LookupQualifiedName(R, Std);
10168 
10169       for (const auto *I : R) {
10170         const FunctionDecl *FDecl = nullptr;
10171         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10172           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10173         } else {
10174           FDecl = dyn_cast<FunctionDecl>(I);
10175         }
10176         if (!FDecl)
10177           continue;
10178 
10179         // Found std::abs(), check that they are the right ones.
10180         if (FDecl->getNumParams() != 1)
10181           continue;
10182 
10183         // Check that the parameter type can handle the argument.
10184         QualType ParamType = FDecl->getParamDecl(0)->getType();
10185         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10186             S.Context.getTypeSize(ArgType) <=
10187                 S.Context.getTypeSize(ParamType)) {
10188           // Found a function, don't need the header hint.
10189           EmitHeaderHint = false;
10190           break;
10191         }
10192       }
10193     }
10194   } else {
10195     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10196     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10197 
10198     if (HeaderName) {
10199       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10200       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10201       R.suppressDiagnostics();
10202       S.LookupName(R, S.getCurScope());
10203 
10204       if (R.isSingleResult()) {
10205         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10206         if (FD && FD->getBuiltinID() == AbsKind) {
10207           EmitHeaderHint = false;
10208         } else {
10209           return;
10210         }
10211       } else if (!R.empty()) {
10212         return;
10213       }
10214     }
10215   }
10216 
10217   S.Diag(Loc, diag::note_replace_abs_function)
10218       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10219 
10220   if (!HeaderName)
10221     return;
10222 
10223   if (!EmitHeaderHint)
10224     return;
10225 
10226   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10227                                                     << FunctionName;
10228 }
10229 
10230 template <std::size_t StrLen>
10231 static bool IsStdFunction(const FunctionDecl *FDecl,
10232                           const char (&Str)[StrLen]) {
10233   if (!FDecl)
10234     return false;
10235   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10236     return false;
10237   if (!FDecl->isInStdNamespace())
10238     return false;
10239 
10240   return true;
10241 }
10242 
10243 // Warn when using the wrong abs() function.
10244 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10245                                       const FunctionDecl *FDecl) {
10246   if (Call->getNumArgs() != 1)
10247     return;
10248 
10249   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10250   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10251   if (AbsKind == 0 && !IsStdAbs)
10252     return;
10253 
10254   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10255   QualType ParamType = Call->getArg(0)->getType();
10256 
10257   // Unsigned types cannot be negative.  Suggest removing the absolute value
10258   // function call.
10259   if (ArgType->isUnsignedIntegerType()) {
10260     const char *FunctionName =
10261         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10262     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10263     Diag(Call->getExprLoc(), diag::note_remove_abs)
10264         << FunctionName
10265         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10266     return;
10267   }
10268 
10269   // Taking the absolute value of a pointer is very suspicious, they probably
10270   // wanted to index into an array, dereference a pointer, call a function, etc.
10271   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10272     unsigned DiagType = 0;
10273     if (ArgType->isFunctionType())
10274       DiagType = 1;
10275     else if (ArgType->isArrayType())
10276       DiagType = 2;
10277 
10278     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10279     return;
10280   }
10281 
10282   // std::abs has overloads which prevent most of the absolute value problems
10283   // from occurring.
10284   if (IsStdAbs)
10285     return;
10286 
10287   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10288   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10289 
10290   // The argument and parameter are the same kind.  Check if they are the right
10291   // size.
10292   if (ArgValueKind == ParamValueKind) {
10293     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10294       return;
10295 
10296     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10297     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10298         << FDecl << ArgType << ParamType;
10299 
10300     if (NewAbsKind == 0)
10301       return;
10302 
10303     emitReplacement(*this, Call->getExprLoc(),
10304                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10305     return;
10306   }
10307 
10308   // ArgValueKind != ParamValueKind
10309   // The wrong type of absolute value function was used.  Attempt to find the
10310   // proper one.
10311   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10312   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10313   if (NewAbsKind == 0)
10314     return;
10315 
10316   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10317       << FDecl << ParamValueKind << ArgValueKind;
10318 
10319   emitReplacement(*this, Call->getExprLoc(),
10320                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10321 }
10322 
10323 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10324 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10325                                 const FunctionDecl *FDecl) {
10326   if (!Call || !FDecl) return;
10327 
10328   // Ignore template specializations and macros.
10329   if (inTemplateInstantiation()) return;
10330   if (Call->getExprLoc().isMacroID()) return;
10331 
10332   // Only care about the one template argument, two function parameter std::max
10333   if (Call->getNumArgs() != 2) return;
10334   if (!IsStdFunction(FDecl, "max")) return;
10335   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10336   if (!ArgList) return;
10337   if (ArgList->size() != 1) return;
10338 
10339   // Check that template type argument is unsigned integer.
10340   const auto& TA = ArgList->get(0);
10341   if (TA.getKind() != TemplateArgument::Type) return;
10342   QualType ArgType = TA.getAsType();
10343   if (!ArgType->isUnsignedIntegerType()) return;
10344 
10345   // See if either argument is a literal zero.
10346   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10347     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10348     if (!MTE) return false;
10349     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10350     if (!Num) return false;
10351     if (Num->getValue() != 0) return false;
10352     return true;
10353   };
10354 
10355   const Expr *FirstArg = Call->getArg(0);
10356   const Expr *SecondArg = Call->getArg(1);
10357   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10358   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10359 
10360   // Only warn when exactly one argument is zero.
10361   if (IsFirstArgZero == IsSecondArgZero) return;
10362 
10363   SourceRange FirstRange = FirstArg->getSourceRange();
10364   SourceRange SecondRange = SecondArg->getSourceRange();
10365 
10366   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10367 
10368   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10369       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10370 
10371   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10372   SourceRange RemovalRange;
10373   if (IsFirstArgZero) {
10374     RemovalRange = SourceRange(FirstRange.getBegin(),
10375                                SecondRange.getBegin().getLocWithOffset(-1));
10376   } else {
10377     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10378                                SecondRange.getEnd());
10379   }
10380 
10381   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10382         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10383         << FixItHint::CreateRemoval(RemovalRange);
10384 }
10385 
10386 //===--- CHECK: Standard memory functions ---------------------------------===//
10387 
10388 /// Takes the expression passed to the size_t parameter of functions
10389 /// such as memcmp, strncat, etc and warns if it's a comparison.
10390 ///
10391 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10392 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10393                                            IdentifierInfo *FnName,
10394                                            SourceLocation FnLoc,
10395                                            SourceLocation RParenLoc) {
10396   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10397   if (!Size)
10398     return false;
10399 
10400   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10401   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10402     return false;
10403 
10404   SourceRange SizeRange = Size->getSourceRange();
10405   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10406       << SizeRange << FnName;
10407   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10408       << FnName
10409       << FixItHint::CreateInsertion(
10410              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10411       << FixItHint::CreateRemoval(RParenLoc);
10412   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10413       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10414       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10415                                     ")");
10416 
10417   return true;
10418 }
10419 
10420 /// Determine whether the given type is or contains a dynamic class type
10421 /// (e.g., whether it has a vtable).
10422 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10423                                                      bool &IsContained) {
10424   // Look through array types while ignoring qualifiers.
10425   const Type *Ty = T->getBaseElementTypeUnsafe();
10426   IsContained = false;
10427 
10428   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10429   RD = RD ? RD->getDefinition() : nullptr;
10430   if (!RD || RD->isInvalidDecl())
10431     return nullptr;
10432 
10433   if (RD->isDynamicClass())
10434     return RD;
10435 
10436   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10437   // It's impossible for a class to transitively contain itself by value, so
10438   // infinite recursion is impossible.
10439   for (auto *FD : RD->fields()) {
10440     bool SubContained;
10441     if (const CXXRecordDecl *ContainedRD =
10442             getContainedDynamicClass(FD->getType(), SubContained)) {
10443       IsContained = true;
10444       return ContainedRD;
10445     }
10446   }
10447 
10448   return nullptr;
10449 }
10450 
10451 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10452   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10453     if (Unary->getKind() == UETT_SizeOf)
10454       return Unary;
10455   return nullptr;
10456 }
10457 
10458 /// If E is a sizeof expression, returns its argument expression,
10459 /// otherwise returns NULL.
10460 static const Expr *getSizeOfExprArg(const Expr *E) {
10461   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10462     if (!SizeOf->isArgumentType())
10463       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10464   return nullptr;
10465 }
10466 
10467 /// If E is a sizeof expression, returns its argument type.
10468 static QualType getSizeOfArgType(const Expr *E) {
10469   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10470     return SizeOf->getTypeOfArgument();
10471   return QualType();
10472 }
10473 
10474 namespace {
10475 
10476 struct SearchNonTrivialToInitializeField
10477     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10478   using Super =
10479       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10480 
10481   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10482 
10483   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10484                      SourceLocation SL) {
10485     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10486       asDerived().visitArray(PDIK, AT, SL);
10487       return;
10488     }
10489 
10490     Super::visitWithKind(PDIK, FT, SL);
10491   }
10492 
10493   void visitARCStrong(QualType FT, SourceLocation SL) {
10494     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10495   }
10496   void visitARCWeak(QualType FT, SourceLocation SL) {
10497     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10498   }
10499   void visitStruct(QualType FT, SourceLocation SL) {
10500     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10501       visit(FD->getType(), FD->getLocation());
10502   }
10503   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10504                   const ArrayType *AT, SourceLocation SL) {
10505     visit(getContext().getBaseElementType(AT), SL);
10506   }
10507   void visitTrivial(QualType FT, SourceLocation SL) {}
10508 
10509   static void diag(QualType RT, const Expr *E, Sema &S) {
10510     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10511   }
10512 
10513   ASTContext &getContext() { return S.getASTContext(); }
10514 
10515   const Expr *E;
10516   Sema &S;
10517 };
10518 
10519 struct SearchNonTrivialToCopyField
10520     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10521   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10522 
10523   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10524 
10525   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10526                      SourceLocation SL) {
10527     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10528       asDerived().visitArray(PCK, AT, SL);
10529       return;
10530     }
10531 
10532     Super::visitWithKind(PCK, FT, SL);
10533   }
10534 
10535   void visitARCStrong(QualType FT, SourceLocation SL) {
10536     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10537   }
10538   void visitARCWeak(QualType FT, SourceLocation SL) {
10539     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10540   }
10541   void visitStruct(QualType FT, SourceLocation SL) {
10542     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10543       visit(FD->getType(), FD->getLocation());
10544   }
10545   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10546                   SourceLocation SL) {
10547     visit(getContext().getBaseElementType(AT), SL);
10548   }
10549   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10550                 SourceLocation SL) {}
10551   void visitTrivial(QualType FT, SourceLocation SL) {}
10552   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10553 
10554   static void diag(QualType RT, const Expr *E, Sema &S) {
10555     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10556   }
10557 
10558   ASTContext &getContext() { return S.getASTContext(); }
10559 
10560   const Expr *E;
10561   Sema &S;
10562 };
10563 
10564 }
10565 
10566 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10567 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10568   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10569 
10570   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10571     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10572       return false;
10573 
10574     return doesExprLikelyComputeSize(BO->getLHS()) ||
10575            doesExprLikelyComputeSize(BO->getRHS());
10576   }
10577 
10578   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10579 }
10580 
10581 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10582 ///
10583 /// \code
10584 ///   #define MACRO 0
10585 ///   foo(MACRO);
10586 ///   foo(0);
10587 /// \endcode
10588 ///
10589 /// This should return true for the first call to foo, but not for the second
10590 /// (regardless of whether foo is a macro or function).
10591 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10592                                         SourceLocation CallLoc,
10593                                         SourceLocation ArgLoc) {
10594   if (!CallLoc.isMacroID())
10595     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10596 
10597   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10598          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10599 }
10600 
10601 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10602 /// last two arguments transposed.
10603 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10604   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10605     return;
10606 
10607   const Expr *SizeArg =
10608     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10609 
10610   auto isLiteralZero = [](const Expr *E) {
10611     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10612   };
10613 
10614   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10615   SourceLocation CallLoc = Call->getRParenLoc();
10616   SourceManager &SM = S.getSourceManager();
10617   if (isLiteralZero(SizeArg) &&
10618       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10619 
10620     SourceLocation DiagLoc = SizeArg->getExprLoc();
10621 
10622     // Some platforms #define bzero to __builtin_memset. See if this is the
10623     // case, and if so, emit a better diagnostic.
10624     if (BId == Builtin::BIbzero ||
10625         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10626                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10627       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10628       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10629     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10630       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10631       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10632     }
10633     return;
10634   }
10635 
10636   // If the second argument to a memset is a sizeof expression and the third
10637   // isn't, this is also likely an error. This should catch
10638   // 'memset(buf, sizeof(buf), 0xff)'.
10639   if (BId == Builtin::BImemset &&
10640       doesExprLikelyComputeSize(Call->getArg(1)) &&
10641       !doesExprLikelyComputeSize(Call->getArg(2))) {
10642     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10643     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10644     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10645     return;
10646   }
10647 }
10648 
10649 /// Check for dangerous or invalid arguments to memset().
10650 ///
10651 /// This issues warnings on known problematic, dangerous or unspecified
10652 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10653 /// function calls.
10654 ///
10655 /// \param Call The call expression to diagnose.
10656 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10657                                    unsigned BId,
10658                                    IdentifierInfo *FnName) {
10659   assert(BId != 0);
10660 
10661   // It is possible to have a non-standard definition of memset.  Validate
10662   // we have enough arguments, and if not, abort further checking.
10663   unsigned ExpectedNumArgs =
10664       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10665   if (Call->getNumArgs() < ExpectedNumArgs)
10666     return;
10667 
10668   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10669                       BId == Builtin::BIstrndup ? 1 : 2);
10670   unsigned LenArg =
10671       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10672   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10673 
10674   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10675                                      Call->getBeginLoc(), Call->getRParenLoc()))
10676     return;
10677 
10678   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10679   CheckMemaccessSize(*this, BId, Call);
10680 
10681   // We have special checking when the length is a sizeof expression.
10682   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10683   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10684   llvm::FoldingSetNodeID SizeOfArgID;
10685 
10686   // Although widely used, 'bzero' is not a standard function. Be more strict
10687   // with the argument types before allowing diagnostics and only allow the
10688   // form bzero(ptr, sizeof(...)).
10689   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10690   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10691     return;
10692 
10693   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10694     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10695     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10696 
10697     QualType DestTy = Dest->getType();
10698     QualType PointeeTy;
10699     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10700       PointeeTy = DestPtrTy->getPointeeType();
10701 
10702       // Never warn about void type pointers. This can be used to suppress
10703       // false positives.
10704       if (PointeeTy->isVoidType())
10705         continue;
10706 
10707       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10708       // actually comparing the expressions for equality. Because computing the
10709       // expression IDs can be expensive, we only do this if the diagnostic is
10710       // enabled.
10711       if (SizeOfArg &&
10712           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10713                            SizeOfArg->getExprLoc())) {
10714         // We only compute IDs for expressions if the warning is enabled, and
10715         // cache the sizeof arg's ID.
10716         if (SizeOfArgID == llvm::FoldingSetNodeID())
10717           SizeOfArg->Profile(SizeOfArgID, Context, true);
10718         llvm::FoldingSetNodeID DestID;
10719         Dest->Profile(DestID, Context, true);
10720         if (DestID == SizeOfArgID) {
10721           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10722           //       over sizeof(src) as well.
10723           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10724           StringRef ReadableName = FnName->getName();
10725 
10726           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10727             if (UnaryOp->getOpcode() == UO_AddrOf)
10728               ActionIdx = 1; // If its an address-of operator, just remove it.
10729           if (!PointeeTy->isIncompleteType() &&
10730               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10731             ActionIdx = 2; // If the pointee's size is sizeof(char),
10732                            // suggest an explicit length.
10733 
10734           // If the function is defined as a builtin macro, do not show macro
10735           // expansion.
10736           SourceLocation SL = SizeOfArg->getExprLoc();
10737           SourceRange DSR = Dest->getSourceRange();
10738           SourceRange SSR = SizeOfArg->getSourceRange();
10739           SourceManager &SM = getSourceManager();
10740 
10741           if (SM.isMacroArgExpansion(SL)) {
10742             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10743             SL = SM.getSpellingLoc(SL);
10744             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10745                              SM.getSpellingLoc(DSR.getEnd()));
10746             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10747                              SM.getSpellingLoc(SSR.getEnd()));
10748           }
10749 
10750           DiagRuntimeBehavior(SL, SizeOfArg,
10751                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10752                                 << ReadableName
10753                                 << PointeeTy
10754                                 << DestTy
10755                                 << DSR
10756                                 << SSR);
10757           DiagRuntimeBehavior(SL, SizeOfArg,
10758                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10759                                 << ActionIdx
10760                                 << SSR);
10761 
10762           break;
10763         }
10764       }
10765 
10766       // Also check for cases where the sizeof argument is the exact same
10767       // type as the memory argument, and where it points to a user-defined
10768       // record type.
10769       if (SizeOfArgTy != QualType()) {
10770         if (PointeeTy->isRecordType() &&
10771             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10772           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10773                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10774                                 << FnName << SizeOfArgTy << ArgIdx
10775                                 << PointeeTy << Dest->getSourceRange()
10776                                 << LenExpr->getSourceRange());
10777           break;
10778         }
10779       }
10780     } else if (DestTy->isArrayType()) {
10781       PointeeTy = DestTy;
10782     }
10783 
10784     if (PointeeTy == QualType())
10785       continue;
10786 
10787     // Always complain about dynamic classes.
10788     bool IsContained;
10789     if (const CXXRecordDecl *ContainedRD =
10790             getContainedDynamicClass(PointeeTy, IsContained)) {
10791 
10792       unsigned OperationType = 0;
10793       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10794       // "overwritten" if we're warning about the destination for any call
10795       // but memcmp; otherwise a verb appropriate to the call.
10796       if (ArgIdx != 0 || IsCmp) {
10797         if (BId == Builtin::BImemcpy)
10798           OperationType = 1;
10799         else if(BId == Builtin::BImemmove)
10800           OperationType = 2;
10801         else if (IsCmp)
10802           OperationType = 3;
10803       }
10804 
10805       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10806                           PDiag(diag::warn_dyn_class_memaccess)
10807                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10808                               << IsContained << ContainedRD << OperationType
10809                               << Call->getCallee()->getSourceRange());
10810     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10811              BId != Builtin::BImemset)
10812       DiagRuntimeBehavior(
10813         Dest->getExprLoc(), Dest,
10814         PDiag(diag::warn_arc_object_memaccess)
10815           << ArgIdx << FnName << PointeeTy
10816           << Call->getCallee()->getSourceRange());
10817     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10818       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10819           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10820         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10821                             PDiag(diag::warn_cstruct_memaccess)
10822                                 << ArgIdx << FnName << PointeeTy << 0);
10823         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10824       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10825                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10826         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10827                             PDiag(diag::warn_cstruct_memaccess)
10828                                 << ArgIdx << FnName << PointeeTy << 1);
10829         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10830       } else {
10831         continue;
10832       }
10833     } else
10834       continue;
10835 
10836     DiagRuntimeBehavior(
10837       Dest->getExprLoc(), Dest,
10838       PDiag(diag::note_bad_memaccess_silence)
10839         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10840     break;
10841   }
10842 }
10843 
10844 // A little helper routine: ignore addition and subtraction of integer literals.
10845 // This intentionally does not ignore all integer constant expressions because
10846 // we don't want to remove sizeof().
10847 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10848   Ex = Ex->IgnoreParenCasts();
10849 
10850   while (true) {
10851     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10852     if (!BO || !BO->isAdditiveOp())
10853       break;
10854 
10855     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10856     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10857 
10858     if (isa<IntegerLiteral>(RHS))
10859       Ex = LHS;
10860     else if (isa<IntegerLiteral>(LHS))
10861       Ex = RHS;
10862     else
10863       break;
10864   }
10865 
10866   return Ex;
10867 }
10868 
10869 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10870                                                       ASTContext &Context) {
10871   // Only handle constant-sized or VLAs, but not flexible members.
10872   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10873     // Only issue the FIXIT for arrays of size > 1.
10874     if (CAT->getSize().getSExtValue() <= 1)
10875       return false;
10876   } else if (!Ty->isVariableArrayType()) {
10877     return false;
10878   }
10879   return true;
10880 }
10881 
10882 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10883 // be the size of the source, instead of the destination.
10884 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10885                                     IdentifierInfo *FnName) {
10886 
10887   // Don't crash if the user has the wrong number of arguments
10888   unsigned NumArgs = Call->getNumArgs();
10889   if ((NumArgs != 3) && (NumArgs != 4))
10890     return;
10891 
10892   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10893   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10894   const Expr *CompareWithSrc = nullptr;
10895 
10896   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10897                                      Call->getBeginLoc(), Call->getRParenLoc()))
10898     return;
10899 
10900   // Look for 'strlcpy(dst, x, sizeof(x))'
10901   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10902     CompareWithSrc = Ex;
10903   else {
10904     // Look for 'strlcpy(dst, x, strlen(x))'
10905     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10906       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10907           SizeCall->getNumArgs() == 1)
10908         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10909     }
10910   }
10911 
10912   if (!CompareWithSrc)
10913     return;
10914 
10915   // Determine if the argument to sizeof/strlen is equal to the source
10916   // argument.  In principle there's all kinds of things you could do
10917   // here, for instance creating an == expression and evaluating it with
10918   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10919   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10920   if (!SrcArgDRE)
10921     return;
10922 
10923   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10924   if (!CompareWithSrcDRE ||
10925       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10926     return;
10927 
10928   const Expr *OriginalSizeArg = Call->getArg(2);
10929   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10930       << OriginalSizeArg->getSourceRange() << FnName;
10931 
10932   // Output a FIXIT hint if the destination is an array (rather than a
10933   // pointer to an array).  This could be enhanced to handle some
10934   // pointers if we know the actual size, like if DstArg is 'array+2'
10935   // we could say 'sizeof(array)-2'.
10936   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10937   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10938     return;
10939 
10940   SmallString<128> sizeString;
10941   llvm::raw_svector_ostream OS(sizeString);
10942   OS << "sizeof(";
10943   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10944   OS << ")";
10945 
10946   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10947       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10948                                       OS.str());
10949 }
10950 
10951 /// Check if two expressions refer to the same declaration.
10952 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10953   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10954     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10955       return D1->getDecl() == D2->getDecl();
10956   return false;
10957 }
10958 
10959 static const Expr *getStrlenExprArg(const Expr *E) {
10960   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10961     const FunctionDecl *FD = CE->getDirectCallee();
10962     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10963       return nullptr;
10964     return CE->getArg(0)->IgnoreParenCasts();
10965   }
10966   return nullptr;
10967 }
10968 
10969 // Warn on anti-patterns as the 'size' argument to strncat.
10970 // The correct size argument should look like following:
10971 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10972 void Sema::CheckStrncatArguments(const CallExpr *CE,
10973                                  IdentifierInfo *FnName) {
10974   // Don't crash if the user has the wrong number of arguments.
10975   if (CE->getNumArgs() < 3)
10976     return;
10977   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10978   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10979   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10980 
10981   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10982                                      CE->getRParenLoc()))
10983     return;
10984 
10985   // Identify common expressions, which are wrongly used as the size argument
10986   // to strncat and may lead to buffer overflows.
10987   unsigned PatternType = 0;
10988   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10989     // - sizeof(dst)
10990     if (referToTheSameDecl(SizeOfArg, DstArg))
10991       PatternType = 1;
10992     // - sizeof(src)
10993     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10994       PatternType = 2;
10995   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10996     if (BE->getOpcode() == BO_Sub) {
10997       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10998       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10999       // - sizeof(dst) - strlen(dst)
11000       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11001           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11002         PatternType = 1;
11003       // - sizeof(src) - (anything)
11004       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11005         PatternType = 2;
11006     }
11007   }
11008 
11009   if (PatternType == 0)
11010     return;
11011 
11012   // Generate the diagnostic.
11013   SourceLocation SL = LenArg->getBeginLoc();
11014   SourceRange SR = LenArg->getSourceRange();
11015   SourceManager &SM = getSourceManager();
11016 
11017   // If the function is defined as a builtin macro, do not show macro expansion.
11018   if (SM.isMacroArgExpansion(SL)) {
11019     SL = SM.getSpellingLoc(SL);
11020     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11021                      SM.getSpellingLoc(SR.getEnd()));
11022   }
11023 
11024   // Check if the destination is an array (rather than a pointer to an array).
11025   QualType DstTy = DstArg->getType();
11026   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11027                                                                     Context);
11028   if (!isKnownSizeArray) {
11029     if (PatternType == 1)
11030       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11031     else
11032       Diag(SL, diag::warn_strncat_src_size) << SR;
11033     return;
11034   }
11035 
11036   if (PatternType == 1)
11037     Diag(SL, diag::warn_strncat_large_size) << SR;
11038   else
11039     Diag(SL, diag::warn_strncat_src_size) << SR;
11040 
11041   SmallString<128> sizeString;
11042   llvm::raw_svector_ostream OS(sizeString);
11043   OS << "sizeof(";
11044   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11045   OS << ") - ";
11046   OS << "strlen(";
11047   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11048   OS << ") - 1";
11049 
11050   Diag(SL, diag::note_strncat_wrong_size)
11051     << FixItHint::CreateReplacement(SR, OS.str());
11052 }
11053 
11054 namespace {
11055 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11056                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11057   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11058     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11059         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11060     return;
11061   }
11062 }
11063 
11064 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11065                                  const UnaryOperator *UnaryExpr) {
11066   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11067     const Decl *D = Lvalue->getDecl();
11068     if (isa<DeclaratorDecl>(D))
11069       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11070         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11071   }
11072 
11073   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11074     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11075                                       Lvalue->getMemberDecl());
11076 }
11077 
11078 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11079                             const UnaryOperator *UnaryExpr) {
11080   const auto *Lambda = dyn_cast<LambdaExpr>(
11081       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11082   if (!Lambda)
11083     return;
11084 
11085   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11086       << CalleeName << 2 /*object: lambda expression*/;
11087 }
11088 
11089 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11090                                   const DeclRefExpr *Lvalue) {
11091   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11092   if (Var == nullptr)
11093     return;
11094 
11095   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11096       << CalleeName << 0 /*object: */ << Var;
11097 }
11098 
11099 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11100                             const CastExpr *Cast) {
11101   SmallString<128> SizeString;
11102   llvm::raw_svector_ostream OS(SizeString);
11103 
11104   clang::CastKind Kind = Cast->getCastKind();
11105   if (Kind == clang::CK_BitCast &&
11106       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11107     return;
11108   if (Kind == clang::CK_IntegralToPointer &&
11109       !isa<IntegerLiteral>(
11110           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11111     return;
11112 
11113   switch (Cast->getCastKind()) {
11114   case clang::CK_BitCast:
11115   case clang::CK_IntegralToPointer:
11116   case clang::CK_FunctionToPointerDecay:
11117     OS << '\'';
11118     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11119     OS << '\'';
11120     break;
11121   default:
11122     return;
11123   }
11124 
11125   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11126       << CalleeName << 0 /*object: */ << OS.str();
11127 }
11128 } // namespace
11129 
11130 /// Alerts the user that they are attempting to free a non-malloc'd object.
11131 void Sema::CheckFreeArguments(const CallExpr *E) {
11132   const std::string CalleeName =
11133       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11134 
11135   { // Prefer something that doesn't involve a cast to make things simpler.
11136     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11137     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11138       switch (UnaryExpr->getOpcode()) {
11139       case UnaryOperator::Opcode::UO_AddrOf:
11140         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11141       case UnaryOperator::Opcode::UO_Plus:
11142         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11143       default:
11144         break;
11145       }
11146 
11147     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11148       if (Lvalue->getType()->isArrayType())
11149         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11150 
11151     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11152       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11153           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11154       return;
11155     }
11156 
11157     if (isa<BlockExpr>(Arg)) {
11158       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11159           << CalleeName << 1 /*object: block*/;
11160       return;
11161     }
11162   }
11163   // Maybe the cast was important, check after the other cases.
11164   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11165     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11166 }
11167 
11168 void
11169 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11170                          SourceLocation ReturnLoc,
11171                          bool isObjCMethod,
11172                          const AttrVec *Attrs,
11173                          const FunctionDecl *FD) {
11174   // Check if the return value is null but should not be.
11175   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11176        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11177       CheckNonNullExpr(*this, RetValExp))
11178     Diag(ReturnLoc, diag::warn_null_ret)
11179       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11180 
11181   // C++11 [basic.stc.dynamic.allocation]p4:
11182   //   If an allocation function declared with a non-throwing
11183   //   exception-specification fails to allocate storage, it shall return
11184   //   a null pointer. Any other allocation function that fails to allocate
11185   //   storage shall indicate failure only by throwing an exception [...]
11186   if (FD) {
11187     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11188     if (Op == OO_New || Op == OO_Array_New) {
11189       const FunctionProtoType *Proto
11190         = FD->getType()->castAs<FunctionProtoType>();
11191       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11192           CheckNonNullExpr(*this, RetValExp))
11193         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11194           << FD << getLangOpts().CPlusPlus11;
11195     }
11196   }
11197 
11198   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11199   // here prevent the user from using a PPC MMA type as trailing return type.
11200   if (Context.getTargetInfo().getTriple().isPPC64())
11201     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11202 }
11203 
11204 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11205 
11206 /// Check for comparisons of floating point operands using != and ==.
11207 /// Issue a warning if these are no self-comparisons, as they are not likely
11208 /// to do what the programmer intended.
11209 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11210   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11211   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11212 
11213   // Special case: check for x == x (which is OK).
11214   // Do not emit warnings for such cases.
11215   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11216     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11217       if (DRL->getDecl() == DRR->getDecl())
11218         return;
11219 
11220   // Special case: check for comparisons against literals that can be exactly
11221   //  represented by APFloat.  In such cases, do not emit a warning.  This
11222   //  is a heuristic: often comparison against such literals are used to
11223   //  detect if a value in a variable has not changed.  This clearly can
11224   //  lead to false negatives.
11225   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11226     if (FLL->isExact())
11227       return;
11228   } else
11229     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11230       if (FLR->isExact())
11231         return;
11232 
11233   // Check for comparisons with builtin types.
11234   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11235     if (CL->getBuiltinCallee())
11236       return;
11237 
11238   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11239     if (CR->getBuiltinCallee())
11240       return;
11241 
11242   // Emit the diagnostic.
11243   Diag(Loc, diag::warn_floatingpoint_eq)
11244     << LHS->getSourceRange() << RHS->getSourceRange();
11245 }
11246 
11247 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11248 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11249 
11250 namespace {
11251 
11252 /// Structure recording the 'active' range of an integer-valued
11253 /// expression.
11254 struct IntRange {
11255   /// The number of bits active in the int. Note that this includes exactly one
11256   /// sign bit if !NonNegative.
11257   unsigned Width;
11258 
11259   /// True if the int is known not to have negative values. If so, all leading
11260   /// bits before Width are known zero, otherwise they are known to be the
11261   /// same as the MSB within Width.
11262   bool NonNegative;
11263 
11264   IntRange(unsigned Width, bool NonNegative)
11265       : Width(Width), NonNegative(NonNegative) {}
11266 
11267   /// Number of bits excluding the sign bit.
11268   unsigned valueBits() const {
11269     return NonNegative ? Width : Width - 1;
11270   }
11271 
11272   /// Returns the range of the bool type.
11273   static IntRange forBoolType() {
11274     return IntRange(1, true);
11275   }
11276 
11277   /// Returns the range of an opaque value of the given integral type.
11278   static IntRange forValueOfType(ASTContext &C, QualType T) {
11279     return forValueOfCanonicalType(C,
11280                           T->getCanonicalTypeInternal().getTypePtr());
11281   }
11282 
11283   /// Returns the range of an opaque value of a canonical integral type.
11284   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11285     assert(T->isCanonicalUnqualified());
11286 
11287     if (const VectorType *VT = dyn_cast<VectorType>(T))
11288       T = VT->getElementType().getTypePtr();
11289     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11290       T = CT->getElementType().getTypePtr();
11291     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11292       T = AT->getValueType().getTypePtr();
11293 
11294     if (!C.getLangOpts().CPlusPlus) {
11295       // For enum types in C code, use the underlying datatype.
11296       if (const EnumType *ET = dyn_cast<EnumType>(T))
11297         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11298     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11299       // For enum types in C++, use the known bit width of the enumerators.
11300       EnumDecl *Enum = ET->getDecl();
11301       // In C++11, enums can have a fixed underlying type. Use this type to
11302       // compute the range.
11303       if (Enum->isFixed()) {
11304         return IntRange(C.getIntWidth(QualType(T, 0)),
11305                         !ET->isSignedIntegerOrEnumerationType());
11306       }
11307 
11308       unsigned NumPositive = Enum->getNumPositiveBits();
11309       unsigned NumNegative = Enum->getNumNegativeBits();
11310 
11311       if (NumNegative == 0)
11312         return IntRange(NumPositive, true/*NonNegative*/);
11313       else
11314         return IntRange(std::max(NumPositive + 1, NumNegative),
11315                         false/*NonNegative*/);
11316     }
11317 
11318     if (const auto *EIT = dyn_cast<BitIntType>(T))
11319       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11320 
11321     const BuiltinType *BT = cast<BuiltinType>(T);
11322     assert(BT->isInteger());
11323 
11324     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11325   }
11326 
11327   /// Returns the "target" range of a canonical integral type, i.e.
11328   /// the range of values expressible in the type.
11329   ///
11330   /// This matches forValueOfCanonicalType except that enums have the
11331   /// full range of their type, not the range of their enumerators.
11332   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11333     assert(T->isCanonicalUnqualified());
11334 
11335     if (const VectorType *VT = dyn_cast<VectorType>(T))
11336       T = VT->getElementType().getTypePtr();
11337     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11338       T = CT->getElementType().getTypePtr();
11339     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11340       T = AT->getValueType().getTypePtr();
11341     if (const EnumType *ET = dyn_cast<EnumType>(T))
11342       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11343 
11344     if (const auto *EIT = dyn_cast<BitIntType>(T))
11345       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11346 
11347     const BuiltinType *BT = cast<BuiltinType>(T);
11348     assert(BT->isInteger());
11349 
11350     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11351   }
11352 
11353   /// Returns the supremum of two ranges: i.e. their conservative merge.
11354   static IntRange join(IntRange L, IntRange R) {
11355     bool Unsigned = L.NonNegative && R.NonNegative;
11356     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11357                     L.NonNegative && R.NonNegative);
11358   }
11359 
11360   /// Return the range of a bitwise-AND of the two ranges.
11361   static IntRange bit_and(IntRange L, IntRange R) {
11362     unsigned Bits = std::max(L.Width, R.Width);
11363     bool NonNegative = false;
11364     if (L.NonNegative) {
11365       Bits = std::min(Bits, L.Width);
11366       NonNegative = true;
11367     }
11368     if (R.NonNegative) {
11369       Bits = std::min(Bits, R.Width);
11370       NonNegative = true;
11371     }
11372     return IntRange(Bits, NonNegative);
11373   }
11374 
11375   /// Return the range of a sum of the two ranges.
11376   static IntRange sum(IntRange L, IntRange R) {
11377     bool Unsigned = L.NonNegative && R.NonNegative;
11378     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11379                     Unsigned);
11380   }
11381 
11382   /// Return the range of a difference of the two ranges.
11383   static IntRange difference(IntRange L, IntRange R) {
11384     // We need a 1-bit-wider range if:
11385     //   1) LHS can be negative: least value can be reduced.
11386     //   2) RHS can be negative: greatest value can be increased.
11387     bool CanWiden = !L.NonNegative || !R.NonNegative;
11388     bool Unsigned = L.NonNegative && R.Width == 0;
11389     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11390                         !Unsigned,
11391                     Unsigned);
11392   }
11393 
11394   /// Return the range of a product of the two ranges.
11395   static IntRange product(IntRange L, IntRange R) {
11396     // If both LHS and RHS can be negative, we can form
11397     //   -2^L * -2^R = 2^(L + R)
11398     // which requires L + R + 1 value bits to represent.
11399     bool CanWiden = !L.NonNegative && !R.NonNegative;
11400     bool Unsigned = L.NonNegative && R.NonNegative;
11401     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11402                     Unsigned);
11403   }
11404 
11405   /// Return the range of a remainder operation between the two ranges.
11406   static IntRange rem(IntRange L, IntRange R) {
11407     // The result of a remainder can't be larger than the result of
11408     // either side. The sign of the result is the sign of the LHS.
11409     bool Unsigned = L.NonNegative;
11410     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11411                     Unsigned);
11412   }
11413 };
11414 
11415 } // namespace
11416 
11417 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11418                               unsigned MaxWidth) {
11419   if (value.isSigned() && value.isNegative())
11420     return IntRange(value.getMinSignedBits(), false);
11421 
11422   if (value.getBitWidth() > MaxWidth)
11423     value = value.trunc(MaxWidth);
11424 
11425   // isNonNegative() just checks the sign bit without considering
11426   // signedness.
11427   return IntRange(value.getActiveBits(), true);
11428 }
11429 
11430 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11431                               unsigned MaxWidth) {
11432   if (result.isInt())
11433     return GetValueRange(C, result.getInt(), MaxWidth);
11434 
11435   if (result.isVector()) {
11436     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11437     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11438       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11439       R = IntRange::join(R, El);
11440     }
11441     return R;
11442   }
11443 
11444   if (result.isComplexInt()) {
11445     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11446     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11447     return IntRange::join(R, I);
11448   }
11449 
11450   // This can happen with lossless casts to intptr_t of "based" lvalues.
11451   // Assume it might use arbitrary bits.
11452   // FIXME: The only reason we need to pass the type in here is to get
11453   // the sign right on this one case.  It would be nice if APValue
11454   // preserved this.
11455   assert(result.isLValue() || result.isAddrLabelDiff());
11456   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11457 }
11458 
11459 static QualType GetExprType(const Expr *E) {
11460   QualType Ty = E->getType();
11461   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11462     Ty = AtomicRHS->getValueType();
11463   return Ty;
11464 }
11465 
11466 /// Pseudo-evaluate the given integer expression, estimating the
11467 /// range of values it might take.
11468 ///
11469 /// \param MaxWidth The width to which the value will be truncated.
11470 /// \param Approximate If \c true, return a likely range for the result: in
11471 ///        particular, assume that arithmetic on narrower types doesn't leave
11472 ///        those types. If \c false, return a range including all possible
11473 ///        result values.
11474 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11475                              bool InConstantContext, bool Approximate) {
11476   E = E->IgnoreParens();
11477 
11478   // Try a full evaluation first.
11479   Expr::EvalResult result;
11480   if (E->EvaluateAsRValue(result, C, InConstantContext))
11481     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11482 
11483   // I think we only want to look through implicit casts here; if the
11484   // user has an explicit widening cast, we should treat the value as
11485   // being of the new, wider type.
11486   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11487     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11488       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11489                           Approximate);
11490 
11491     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11492 
11493     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11494                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11495 
11496     // Assume that non-integer casts can span the full range of the type.
11497     if (!isIntegerCast)
11498       return OutputTypeRange;
11499 
11500     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11501                                      std::min(MaxWidth, OutputTypeRange.Width),
11502                                      InConstantContext, Approximate);
11503 
11504     // Bail out if the subexpr's range is as wide as the cast type.
11505     if (SubRange.Width >= OutputTypeRange.Width)
11506       return OutputTypeRange;
11507 
11508     // Otherwise, we take the smaller width, and we're non-negative if
11509     // either the output type or the subexpr is.
11510     return IntRange(SubRange.Width,
11511                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11512   }
11513 
11514   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11515     // If we can fold the condition, just take that operand.
11516     bool CondResult;
11517     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11518       return GetExprRange(C,
11519                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11520                           MaxWidth, InConstantContext, Approximate);
11521 
11522     // Otherwise, conservatively merge.
11523     // GetExprRange requires an integer expression, but a throw expression
11524     // results in a void type.
11525     Expr *E = CO->getTrueExpr();
11526     IntRange L = E->getType()->isVoidType()
11527                      ? IntRange{0, true}
11528                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11529     E = CO->getFalseExpr();
11530     IntRange R = E->getType()->isVoidType()
11531                      ? IntRange{0, true}
11532                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11533     return IntRange::join(L, R);
11534   }
11535 
11536   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11537     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11538 
11539     switch (BO->getOpcode()) {
11540     case BO_Cmp:
11541       llvm_unreachable("builtin <=> should have class type");
11542 
11543     // Boolean-valued operations are single-bit and positive.
11544     case BO_LAnd:
11545     case BO_LOr:
11546     case BO_LT:
11547     case BO_GT:
11548     case BO_LE:
11549     case BO_GE:
11550     case BO_EQ:
11551     case BO_NE:
11552       return IntRange::forBoolType();
11553 
11554     // The type of the assignments is the type of the LHS, so the RHS
11555     // is not necessarily the same type.
11556     case BO_MulAssign:
11557     case BO_DivAssign:
11558     case BO_RemAssign:
11559     case BO_AddAssign:
11560     case BO_SubAssign:
11561     case BO_XorAssign:
11562     case BO_OrAssign:
11563       // TODO: bitfields?
11564       return IntRange::forValueOfType(C, GetExprType(E));
11565 
11566     // Simple assignments just pass through the RHS, which will have
11567     // been coerced to the LHS type.
11568     case BO_Assign:
11569       // TODO: bitfields?
11570       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11571                           Approximate);
11572 
11573     // Operations with opaque sources are black-listed.
11574     case BO_PtrMemD:
11575     case BO_PtrMemI:
11576       return IntRange::forValueOfType(C, GetExprType(E));
11577 
11578     // Bitwise-and uses the *infinum* of the two source ranges.
11579     case BO_And:
11580     case BO_AndAssign:
11581       Combine = IntRange::bit_and;
11582       break;
11583 
11584     // Left shift gets black-listed based on a judgement call.
11585     case BO_Shl:
11586       // ...except that we want to treat '1 << (blah)' as logically
11587       // positive.  It's an important idiom.
11588       if (IntegerLiteral *I
11589             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11590         if (I->getValue() == 1) {
11591           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11592           return IntRange(R.Width, /*NonNegative*/ true);
11593         }
11594       }
11595       LLVM_FALLTHROUGH;
11596 
11597     case BO_ShlAssign:
11598       return IntRange::forValueOfType(C, GetExprType(E));
11599 
11600     // Right shift by a constant can narrow its left argument.
11601     case BO_Shr:
11602     case BO_ShrAssign: {
11603       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11604                                 Approximate);
11605 
11606       // If the shift amount is a positive constant, drop the width by
11607       // that much.
11608       if (Optional<llvm::APSInt> shift =
11609               BO->getRHS()->getIntegerConstantExpr(C)) {
11610         if (shift->isNonNegative()) {
11611           unsigned zext = shift->getZExtValue();
11612           if (zext >= L.Width)
11613             L.Width = (L.NonNegative ? 0 : 1);
11614           else
11615             L.Width -= zext;
11616         }
11617       }
11618 
11619       return L;
11620     }
11621 
11622     // Comma acts as its right operand.
11623     case BO_Comma:
11624       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11625                           Approximate);
11626 
11627     case BO_Add:
11628       if (!Approximate)
11629         Combine = IntRange::sum;
11630       break;
11631 
11632     case BO_Sub:
11633       if (BO->getLHS()->getType()->isPointerType())
11634         return IntRange::forValueOfType(C, GetExprType(E));
11635       if (!Approximate)
11636         Combine = IntRange::difference;
11637       break;
11638 
11639     case BO_Mul:
11640       if (!Approximate)
11641         Combine = IntRange::product;
11642       break;
11643 
11644     // The width of a division result is mostly determined by the size
11645     // of the LHS.
11646     case BO_Div: {
11647       // Don't 'pre-truncate' the operands.
11648       unsigned opWidth = C.getIntWidth(GetExprType(E));
11649       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11650                                 Approximate);
11651 
11652       // If the divisor is constant, use that.
11653       if (Optional<llvm::APSInt> divisor =
11654               BO->getRHS()->getIntegerConstantExpr(C)) {
11655         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11656         if (log2 >= L.Width)
11657           L.Width = (L.NonNegative ? 0 : 1);
11658         else
11659           L.Width = std::min(L.Width - log2, MaxWidth);
11660         return L;
11661       }
11662 
11663       // Otherwise, just use the LHS's width.
11664       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11665       // could be -1.
11666       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11667                                 Approximate);
11668       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11669     }
11670 
11671     case BO_Rem:
11672       Combine = IntRange::rem;
11673       break;
11674 
11675     // The default behavior is okay for these.
11676     case BO_Xor:
11677     case BO_Or:
11678       break;
11679     }
11680 
11681     // Combine the two ranges, but limit the result to the type in which we
11682     // performed the computation.
11683     QualType T = GetExprType(E);
11684     unsigned opWidth = C.getIntWidth(T);
11685     IntRange L =
11686         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11687     IntRange R =
11688         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11689     IntRange C = Combine(L, R);
11690     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11691     C.Width = std::min(C.Width, MaxWidth);
11692     return C;
11693   }
11694 
11695   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11696     switch (UO->getOpcode()) {
11697     // Boolean-valued operations are white-listed.
11698     case UO_LNot:
11699       return IntRange::forBoolType();
11700 
11701     // Operations with opaque sources are black-listed.
11702     case UO_Deref:
11703     case UO_AddrOf: // should be impossible
11704       return IntRange::forValueOfType(C, GetExprType(E));
11705 
11706     default:
11707       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11708                           Approximate);
11709     }
11710   }
11711 
11712   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11713     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11714                         Approximate);
11715 
11716   if (const auto *BitField = E->getSourceBitField())
11717     return IntRange(BitField->getBitWidthValue(C),
11718                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11719 
11720   return IntRange::forValueOfType(C, GetExprType(E));
11721 }
11722 
11723 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11724                              bool InConstantContext, bool Approximate) {
11725   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11726                       Approximate);
11727 }
11728 
11729 /// Checks whether the given value, which currently has the given
11730 /// source semantics, has the same value when coerced through the
11731 /// target semantics.
11732 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11733                                  const llvm::fltSemantics &Src,
11734                                  const llvm::fltSemantics &Tgt) {
11735   llvm::APFloat truncated = value;
11736 
11737   bool ignored;
11738   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11739   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11740 
11741   return truncated.bitwiseIsEqual(value);
11742 }
11743 
11744 /// Checks whether the given value, which currently has the given
11745 /// source semantics, has the same value when coerced through the
11746 /// target semantics.
11747 ///
11748 /// The value might be a vector of floats (or a complex number).
11749 static bool IsSameFloatAfterCast(const APValue &value,
11750                                  const llvm::fltSemantics &Src,
11751                                  const llvm::fltSemantics &Tgt) {
11752   if (value.isFloat())
11753     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11754 
11755   if (value.isVector()) {
11756     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11757       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11758         return false;
11759     return true;
11760   }
11761 
11762   assert(value.isComplexFloat());
11763   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11764           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11765 }
11766 
11767 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11768                                        bool IsListInit = false);
11769 
11770 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11771   // Suppress cases where we are comparing against an enum constant.
11772   if (const DeclRefExpr *DR =
11773       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11774     if (isa<EnumConstantDecl>(DR->getDecl()))
11775       return true;
11776 
11777   // Suppress cases where the value is expanded from a macro, unless that macro
11778   // is how a language represents a boolean literal. This is the case in both C
11779   // and Objective-C.
11780   SourceLocation BeginLoc = E->getBeginLoc();
11781   if (BeginLoc.isMacroID()) {
11782     StringRef MacroName = Lexer::getImmediateMacroName(
11783         BeginLoc, S.getSourceManager(), S.getLangOpts());
11784     return MacroName != "YES" && MacroName != "NO" &&
11785            MacroName != "true" && MacroName != "false";
11786   }
11787 
11788   return false;
11789 }
11790 
11791 static bool isKnownToHaveUnsignedValue(Expr *E) {
11792   return E->getType()->isIntegerType() &&
11793          (!E->getType()->isSignedIntegerType() ||
11794           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11795 }
11796 
11797 namespace {
11798 /// The promoted range of values of a type. In general this has the
11799 /// following structure:
11800 ///
11801 ///     |-----------| . . . |-----------|
11802 ///     ^           ^       ^           ^
11803 ///    Min       HoleMin  HoleMax      Max
11804 ///
11805 /// ... where there is only a hole if a signed type is promoted to unsigned
11806 /// (in which case Min and Max are the smallest and largest representable
11807 /// values).
11808 struct PromotedRange {
11809   // Min, or HoleMax if there is a hole.
11810   llvm::APSInt PromotedMin;
11811   // Max, or HoleMin if there is a hole.
11812   llvm::APSInt PromotedMax;
11813 
11814   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11815     if (R.Width == 0)
11816       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11817     else if (R.Width >= BitWidth && !Unsigned) {
11818       // Promotion made the type *narrower*. This happens when promoting
11819       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11820       // Treat all values of 'signed int' as being in range for now.
11821       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11822       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11823     } else {
11824       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11825                         .extOrTrunc(BitWidth);
11826       PromotedMin.setIsUnsigned(Unsigned);
11827 
11828       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11829                         .extOrTrunc(BitWidth);
11830       PromotedMax.setIsUnsigned(Unsigned);
11831     }
11832   }
11833 
11834   // Determine whether this range is contiguous (has no hole).
11835   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11836 
11837   // Where a constant value is within the range.
11838   enum ComparisonResult {
11839     LT = 0x1,
11840     LE = 0x2,
11841     GT = 0x4,
11842     GE = 0x8,
11843     EQ = 0x10,
11844     NE = 0x20,
11845     InRangeFlag = 0x40,
11846 
11847     Less = LE | LT | NE,
11848     Min = LE | InRangeFlag,
11849     InRange = InRangeFlag,
11850     Max = GE | InRangeFlag,
11851     Greater = GE | GT | NE,
11852 
11853     OnlyValue = LE | GE | EQ | InRangeFlag,
11854     InHole = NE
11855   };
11856 
11857   ComparisonResult compare(const llvm::APSInt &Value) const {
11858     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11859            Value.isUnsigned() == PromotedMin.isUnsigned());
11860     if (!isContiguous()) {
11861       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11862       if (Value.isMinValue()) return Min;
11863       if (Value.isMaxValue()) return Max;
11864       if (Value >= PromotedMin) return InRange;
11865       if (Value <= PromotedMax) return InRange;
11866       return InHole;
11867     }
11868 
11869     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11870     case -1: return Less;
11871     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11872     case 1:
11873       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11874       case -1: return InRange;
11875       case 0: return Max;
11876       case 1: return Greater;
11877       }
11878     }
11879 
11880     llvm_unreachable("impossible compare result");
11881   }
11882 
11883   static llvm::Optional<StringRef>
11884   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11885     if (Op == BO_Cmp) {
11886       ComparisonResult LTFlag = LT, GTFlag = GT;
11887       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11888 
11889       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11890       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11891       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11892       return llvm::None;
11893     }
11894 
11895     ComparisonResult TrueFlag, FalseFlag;
11896     if (Op == BO_EQ) {
11897       TrueFlag = EQ;
11898       FalseFlag = NE;
11899     } else if (Op == BO_NE) {
11900       TrueFlag = NE;
11901       FalseFlag = EQ;
11902     } else {
11903       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11904         TrueFlag = LT;
11905         FalseFlag = GE;
11906       } else {
11907         TrueFlag = GT;
11908         FalseFlag = LE;
11909       }
11910       if (Op == BO_GE || Op == BO_LE)
11911         std::swap(TrueFlag, FalseFlag);
11912     }
11913     if (R & TrueFlag)
11914       return StringRef("true");
11915     if (R & FalseFlag)
11916       return StringRef("false");
11917     return llvm::None;
11918   }
11919 };
11920 }
11921 
11922 static bool HasEnumType(Expr *E) {
11923   // Strip off implicit integral promotions.
11924   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11925     if (ICE->getCastKind() != CK_IntegralCast &&
11926         ICE->getCastKind() != CK_NoOp)
11927       break;
11928     E = ICE->getSubExpr();
11929   }
11930 
11931   return E->getType()->isEnumeralType();
11932 }
11933 
11934 static int classifyConstantValue(Expr *Constant) {
11935   // The values of this enumeration are used in the diagnostics
11936   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11937   enum ConstantValueKind {
11938     Miscellaneous = 0,
11939     LiteralTrue,
11940     LiteralFalse
11941   };
11942   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11943     return BL->getValue() ? ConstantValueKind::LiteralTrue
11944                           : ConstantValueKind::LiteralFalse;
11945   return ConstantValueKind::Miscellaneous;
11946 }
11947 
11948 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11949                                         Expr *Constant, Expr *Other,
11950                                         const llvm::APSInt &Value,
11951                                         bool RhsConstant) {
11952   if (S.inTemplateInstantiation())
11953     return false;
11954 
11955   Expr *OriginalOther = Other;
11956 
11957   Constant = Constant->IgnoreParenImpCasts();
11958   Other = Other->IgnoreParenImpCasts();
11959 
11960   // Suppress warnings on tautological comparisons between values of the same
11961   // enumeration type. There are only two ways we could warn on this:
11962   //  - If the constant is outside the range of representable values of
11963   //    the enumeration. In such a case, we should warn about the cast
11964   //    to enumeration type, not about the comparison.
11965   //  - If the constant is the maximum / minimum in-range value. For an
11966   //    enumeratin type, such comparisons can be meaningful and useful.
11967   if (Constant->getType()->isEnumeralType() &&
11968       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11969     return false;
11970 
11971   IntRange OtherValueRange = GetExprRange(
11972       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11973 
11974   QualType OtherT = Other->getType();
11975   if (const auto *AT = OtherT->getAs<AtomicType>())
11976     OtherT = AT->getValueType();
11977   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11978 
11979   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11980   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11981   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11982                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11983                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11984 
11985   // Whether we're treating Other as being a bool because of the form of
11986   // expression despite it having another type (typically 'int' in C).
11987   bool OtherIsBooleanDespiteType =
11988       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11989   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11990     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11991 
11992   // Check if all values in the range of possible values of this expression
11993   // lead to the same comparison outcome.
11994   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11995                                         Value.isUnsigned());
11996   auto Cmp = OtherPromotedValueRange.compare(Value);
11997   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11998   if (!Result)
11999     return false;
12000 
12001   // Also consider the range determined by the type alone. This allows us to
12002   // classify the warning under the proper diagnostic group.
12003   bool TautologicalTypeCompare = false;
12004   {
12005     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12006                                          Value.isUnsigned());
12007     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12008     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12009                                                        RhsConstant)) {
12010       TautologicalTypeCompare = true;
12011       Cmp = TypeCmp;
12012       Result = TypeResult;
12013     }
12014   }
12015 
12016   // Don't warn if the non-constant operand actually always evaluates to the
12017   // same value.
12018   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12019     return false;
12020 
12021   // Suppress the diagnostic for an in-range comparison if the constant comes
12022   // from a macro or enumerator. We don't want to diagnose
12023   //
12024   //   some_long_value <= INT_MAX
12025   //
12026   // when sizeof(int) == sizeof(long).
12027   bool InRange = Cmp & PromotedRange::InRangeFlag;
12028   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12029     return false;
12030 
12031   // A comparison of an unsigned bit-field against 0 is really a type problem,
12032   // even though at the type level the bit-field might promote to 'signed int'.
12033   if (Other->refersToBitField() && InRange && Value == 0 &&
12034       Other->getType()->isUnsignedIntegerOrEnumerationType())
12035     TautologicalTypeCompare = true;
12036 
12037   // If this is a comparison to an enum constant, include that
12038   // constant in the diagnostic.
12039   const EnumConstantDecl *ED = nullptr;
12040   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12041     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12042 
12043   // Should be enough for uint128 (39 decimal digits)
12044   SmallString<64> PrettySourceValue;
12045   llvm::raw_svector_ostream OS(PrettySourceValue);
12046   if (ED) {
12047     OS << '\'' << *ED << "' (" << Value << ")";
12048   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12049                Constant->IgnoreParenImpCasts())) {
12050     OS << (BL->getValue() ? "YES" : "NO");
12051   } else {
12052     OS << Value;
12053   }
12054 
12055   if (!TautologicalTypeCompare) {
12056     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12057         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12058         << E->getOpcodeStr() << OS.str() << *Result
12059         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12060     return true;
12061   }
12062 
12063   if (IsObjCSignedCharBool) {
12064     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12065                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12066                               << OS.str() << *Result);
12067     return true;
12068   }
12069 
12070   // FIXME: We use a somewhat different formatting for the in-range cases and
12071   // cases involving boolean values for historical reasons. We should pick a
12072   // consistent way of presenting these diagnostics.
12073   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12074 
12075     S.DiagRuntimeBehavior(
12076         E->getOperatorLoc(), E,
12077         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12078                          : diag::warn_tautological_bool_compare)
12079             << OS.str() << classifyConstantValue(Constant) << OtherT
12080             << OtherIsBooleanDespiteType << *Result
12081             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12082   } else {
12083     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12084     unsigned Diag =
12085         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12086             ? (HasEnumType(OriginalOther)
12087                    ? diag::warn_unsigned_enum_always_true_comparison
12088                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12089                               : diag::warn_unsigned_always_true_comparison)
12090             : diag::warn_tautological_constant_compare;
12091 
12092     S.Diag(E->getOperatorLoc(), Diag)
12093         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12094         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12095   }
12096 
12097   return true;
12098 }
12099 
12100 /// Analyze the operands of the given comparison.  Implements the
12101 /// fallback case from AnalyzeComparison.
12102 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12103   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12104   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12105 }
12106 
12107 /// Implements -Wsign-compare.
12108 ///
12109 /// \param E the binary operator to check for warnings
12110 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12111   // The type the comparison is being performed in.
12112   QualType T = E->getLHS()->getType();
12113 
12114   // Only analyze comparison operators where both sides have been converted to
12115   // the same type.
12116   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12117     return AnalyzeImpConvsInComparison(S, E);
12118 
12119   // Don't analyze value-dependent comparisons directly.
12120   if (E->isValueDependent())
12121     return AnalyzeImpConvsInComparison(S, E);
12122 
12123   Expr *LHS = E->getLHS();
12124   Expr *RHS = E->getRHS();
12125 
12126   if (T->isIntegralType(S.Context)) {
12127     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12128     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12129 
12130     // We don't care about expressions whose result is a constant.
12131     if (RHSValue && LHSValue)
12132       return AnalyzeImpConvsInComparison(S, E);
12133 
12134     // We only care about expressions where just one side is literal
12135     if ((bool)RHSValue ^ (bool)LHSValue) {
12136       // Is the constant on the RHS or LHS?
12137       const bool RhsConstant = (bool)RHSValue;
12138       Expr *Const = RhsConstant ? RHS : LHS;
12139       Expr *Other = RhsConstant ? LHS : RHS;
12140       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12141 
12142       // Check whether an integer constant comparison results in a value
12143       // of 'true' or 'false'.
12144       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12145         return AnalyzeImpConvsInComparison(S, E);
12146     }
12147   }
12148 
12149   if (!T->hasUnsignedIntegerRepresentation()) {
12150     // We don't do anything special if this isn't an unsigned integral
12151     // comparison:  we're only interested in integral comparisons, and
12152     // signed comparisons only happen in cases we don't care to warn about.
12153     return AnalyzeImpConvsInComparison(S, E);
12154   }
12155 
12156   LHS = LHS->IgnoreParenImpCasts();
12157   RHS = RHS->IgnoreParenImpCasts();
12158 
12159   if (!S.getLangOpts().CPlusPlus) {
12160     // Avoid warning about comparison of integers with different signs when
12161     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12162     // the type of `E`.
12163     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12164       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12165     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12166       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12167   }
12168 
12169   // Check to see if one of the (unmodified) operands is of different
12170   // signedness.
12171   Expr *signedOperand, *unsignedOperand;
12172   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12173     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12174            "unsigned comparison between two signed integer expressions?");
12175     signedOperand = LHS;
12176     unsignedOperand = RHS;
12177   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12178     signedOperand = RHS;
12179     unsignedOperand = LHS;
12180   } else {
12181     return AnalyzeImpConvsInComparison(S, E);
12182   }
12183 
12184   // Otherwise, calculate the effective range of the signed operand.
12185   IntRange signedRange = GetExprRange(
12186       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12187 
12188   // Go ahead and analyze implicit conversions in the operands.  Note
12189   // that we skip the implicit conversions on both sides.
12190   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12191   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12192 
12193   // If the signed range is non-negative, -Wsign-compare won't fire.
12194   if (signedRange.NonNegative)
12195     return;
12196 
12197   // For (in)equality comparisons, if the unsigned operand is a
12198   // constant which cannot collide with a overflowed signed operand,
12199   // then reinterpreting the signed operand as unsigned will not
12200   // change the result of the comparison.
12201   if (E->isEqualityOp()) {
12202     unsigned comparisonWidth = S.Context.getIntWidth(T);
12203     IntRange unsignedRange =
12204         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12205                      /*Approximate*/ true);
12206 
12207     // We should never be unable to prove that the unsigned operand is
12208     // non-negative.
12209     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12210 
12211     if (unsignedRange.Width < comparisonWidth)
12212       return;
12213   }
12214 
12215   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12216                         S.PDiag(diag::warn_mixed_sign_comparison)
12217                             << LHS->getType() << RHS->getType()
12218                             << LHS->getSourceRange() << RHS->getSourceRange());
12219 }
12220 
12221 /// Analyzes an attempt to assign the given value to a bitfield.
12222 ///
12223 /// Returns true if there was something fishy about the attempt.
12224 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12225                                       SourceLocation InitLoc) {
12226   assert(Bitfield->isBitField());
12227   if (Bitfield->isInvalidDecl())
12228     return false;
12229 
12230   // White-list bool bitfields.
12231   QualType BitfieldType = Bitfield->getType();
12232   if (BitfieldType->isBooleanType())
12233      return false;
12234 
12235   if (BitfieldType->isEnumeralType()) {
12236     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12237     // If the underlying enum type was not explicitly specified as an unsigned
12238     // type and the enum contain only positive values, MSVC++ will cause an
12239     // inconsistency by storing this as a signed type.
12240     if (S.getLangOpts().CPlusPlus11 &&
12241         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12242         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12243         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12244       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12245           << BitfieldEnumDecl;
12246     }
12247   }
12248 
12249   if (Bitfield->getType()->isBooleanType())
12250     return false;
12251 
12252   // Ignore value- or type-dependent expressions.
12253   if (Bitfield->getBitWidth()->isValueDependent() ||
12254       Bitfield->getBitWidth()->isTypeDependent() ||
12255       Init->isValueDependent() ||
12256       Init->isTypeDependent())
12257     return false;
12258 
12259   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12260   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12261 
12262   Expr::EvalResult Result;
12263   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12264                                    Expr::SE_AllowSideEffects)) {
12265     // The RHS is not constant.  If the RHS has an enum type, make sure the
12266     // bitfield is wide enough to hold all the values of the enum without
12267     // truncation.
12268     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12269       EnumDecl *ED = EnumTy->getDecl();
12270       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12271 
12272       // Enum types are implicitly signed on Windows, so check if there are any
12273       // negative enumerators to see if the enum was intended to be signed or
12274       // not.
12275       bool SignedEnum = ED->getNumNegativeBits() > 0;
12276 
12277       // Check for surprising sign changes when assigning enum values to a
12278       // bitfield of different signedness.  If the bitfield is signed and we
12279       // have exactly the right number of bits to store this unsigned enum,
12280       // suggest changing the enum to an unsigned type. This typically happens
12281       // on Windows where unfixed enums always use an underlying type of 'int'.
12282       unsigned DiagID = 0;
12283       if (SignedEnum && !SignedBitfield) {
12284         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12285       } else if (SignedBitfield && !SignedEnum &&
12286                  ED->getNumPositiveBits() == FieldWidth) {
12287         DiagID = diag::warn_signed_bitfield_enum_conversion;
12288       }
12289 
12290       if (DiagID) {
12291         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12292         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12293         SourceRange TypeRange =
12294             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12295         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12296             << SignedEnum << TypeRange;
12297       }
12298 
12299       // Compute the required bitwidth. If the enum has negative values, we need
12300       // one more bit than the normal number of positive bits to represent the
12301       // sign bit.
12302       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12303                                                   ED->getNumNegativeBits())
12304                                        : ED->getNumPositiveBits();
12305 
12306       // Check the bitwidth.
12307       if (BitsNeeded > FieldWidth) {
12308         Expr *WidthExpr = Bitfield->getBitWidth();
12309         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12310             << Bitfield << ED;
12311         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12312             << BitsNeeded << ED << WidthExpr->getSourceRange();
12313       }
12314     }
12315 
12316     return false;
12317   }
12318 
12319   llvm::APSInt Value = Result.Val.getInt();
12320 
12321   unsigned OriginalWidth = Value.getBitWidth();
12322 
12323   if (!Value.isSigned() || Value.isNegative())
12324     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12325       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12326         OriginalWidth = Value.getMinSignedBits();
12327 
12328   if (OriginalWidth <= FieldWidth)
12329     return false;
12330 
12331   // Compute the value which the bitfield will contain.
12332   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12333   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12334 
12335   // Check whether the stored value is equal to the original value.
12336   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12337   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12338     return false;
12339 
12340   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12341   // therefore don't strictly fit into a signed bitfield of width 1.
12342   if (FieldWidth == 1 && Value == 1)
12343     return false;
12344 
12345   std::string PrettyValue = toString(Value, 10);
12346   std::string PrettyTrunc = toString(TruncatedValue, 10);
12347 
12348   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12349     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12350     << Init->getSourceRange();
12351 
12352   return true;
12353 }
12354 
12355 /// Analyze the given simple or compound assignment for warning-worthy
12356 /// operations.
12357 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12358   // Just recurse on the LHS.
12359   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12360 
12361   // We want to recurse on the RHS as normal unless we're assigning to
12362   // a bitfield.
12363   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12364     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12365                                   E->getOperatorLoc())) {
12366       // Recurse, ignoring any implicit conversions on the RHS.
12367       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12368                                         E->getOperatorLoc());
12369     }
12370   }
12371 
12372   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12373 
12374   // Diagnose implicitly sequentially-consistent atomic assignment.
12375   if (E->getLHS()->getType()->isAtomicType())
12376     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12377 }
12378 
12379 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12380 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12381                             SourceLocation CContext, unsigned diag,
12382                             bool pruneControlFlow = false) {
12383   if (pruneControlFlow) {
12384     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12385                           S.PDiag(diag)
12386                               << SourceType << T << E->getSourceRange()
12387                               << SourceRange(CContext));
12388     return;
12389   }
12390   S.Diag(E->getExprLoc(), diag)
12391     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12392 }
12393 
12394 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12395 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12396                             SourceLocation CContext,
12397                             unsigned diag, bool pruneControlFlow = false) {
12398   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12399 }
12400 
12401 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12402   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12403       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12404 }
12405 
12406 static void adornObjCBoolConversionDiagWithTernaryFixit(
12407     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12408   Expr *Ignored = SourceExpr->IgnoreImplicit();
12409   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12410     Ignored = OVE->getSourceExpr();
12411   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12412                      isa<BinaryOperator>(Ignored) ||
12413                      isa<CXXOperatorCallExpr>(Ignored);
12414   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12415   if (NeedsParens)
12416     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12417             << FixItHint::CreateInsertion(EndLoc, ")");
12418   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12419 }
12420 
12421 /// Diagnose an implicit cast from a floating point value to an integer value.
12422 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12423                                     SourceLocation CContext) {
12424   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12425   const bool PruneWarnings = S.inTemplateInstantiation();
12426 
12427   Expr *InnerE = E->IgnoreParenImpCasts();
12428   // We also want to warn on, e.g., "int i = -1.234"
12429   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12430     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12431       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12432 
12433   const bool IsLiteral =
12434       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12435 
12436   llvm::APFloat Value(0.0);
12437   bool IsConstant =
12438     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12439   if (!IsConstant) {
12440     if (isObjCSignedCharBool(S, T)) {
12441       return adornObjCBoolConversionDiagWithTernaryFixit(
12442           S, E,
12443           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12444               << E->getType());
12445     }
12446 
12447     return DiagnoseImpCast(S, E, T, CContext,
12448                            diag::warn_impcast_float_integer, PruneWarnings);
12449   }
12450 
12451   bool isExact = false;
12452 
12453   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12454                             T->hasUnsignedIntegerRepresentation());
12455   llvm::APFloat::opStatus Result = Value.convertToInteger(
12456       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12457 
12458   // FIXME: Force the precision of the source value down so we don't print
12459   // digits which are usually useless (we don't really care here if we
12460   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12461   // would automatically print the shortest representation, but it's a bit
12462   // tricky to implement.
12463   SmallString<16> PrettySourceValue;
12464   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12465   precision = (precision * 59 + 195) / 196;
12466   Value.toString(PrettySourceValue, precision);
12467 
12468   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12469     return adornObjCBoolConversionDiagWithTernaryFixit(
12470         S, E,
12471         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12472             << PrettySourceValue);
12473   }
12474 
12475   if (Result == llvm::APFloat::opOK && isExact) {
12476     if (IsLiteral) return;
12477     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12478                            PruneWarnings);
12479   }
12480 
12481   // Conversion of a floating-point value to a non-bool integer where the
12482   // integral part cannot be represented by the integer type is undefined.
12483   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12484     return DiagnoseImpCast(
12485         S, E, T, CContext,
12486         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12487                   : diag::warn_impcast_float_to_integer_out_of_range,
12488         PruneWarnings);
12489 
12490   unsigned DiagID = 0;
12491   if (IsLiteral) {
12492     // Warn on floating point literal to integer.
12493     DiagID = diag::warn_impcast_literal_float_to_integer;
12494   } else if (IntegerValue == 0) {
12495     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12496       return DiagnoseImpCast(S, E, T, CContext,
12497                              diag::warn_impcast_float_integer, PruneWarnings);
12498     }
12499     // Warn on non-zero to zero conversion.
12500     DiagID = diag::warn_impcast_float_to_integer_zero;
12501   } else {
12502     if (IntegerValue.isUnsigned()) {
12503       if (!IntegerValue.isMaxValue()) {
12504         return DiagnoseImpCast(S, E, T, CContext,
12505                                diag::warn_impcast_float_integer, PruneWarnings);
12506       }
12507     } else {  // IntegerValue.isSigned()
12508       if (!IntegerValue.isMaxSignedValue() &&
12509           !IntegerValue.isMinSignedValue()) {
12510         return DiagnoseImpCast(S, E, T, CContext,
12511                                diag::warn_impcast_float_integer, PruneWarnings);
12512       }
12513     }
12514     // Warn on evaluatable floating point expression to integer conversion.
12515     DiagID = diag::warn_impcast_float_to_integer;
12516   }
12517 
12518   SmallString<16> PrettyTargetValue;
12519   if (IsBool)
12520     PrettyTargetValue = Value.isZero() ? "false" : "true";
12521   else
12522     IntegerValue.toString(PrettyTargetValue);
12523 
12524   if (PruneWarnings) {
12525     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12526                           S.PDiag(DiagID)
12527                               << E->getType() << T.getUnqualifiedType()
12528                               << PrettySourceValue << PrettyTargetValue
12529                               << E->getSourceRange() << SourceRange(CContext));
12530   } else {
12531     S.Diag(E->getExprLoc(), DiagID)
12532         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12533         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12534   }
12535 }
12536 
12537 /// Analyze the given compound assignment for the possible losing of
12538 /// floating-point precision.
12539 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12540   assert(isa<CompoundAssignOperator>(E) &&
12541          "Must be compound assignment operation");
12542   // Recurse on the LHS and RHS in here
12543   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12544   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12545 
12546   if (E->getLHS()->getType()->isAtomicType())
12547     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12548 
12549   // Now check the outermost expression
12550   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12551   const auto *RBT = cast<CompoundAssignOperator>(E)
12552                         ->getComputationResultType()
12553                         ->getAs<BuiltinType>();
12554 
12555   // The below checks assume source is floating point.
12556   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12557 
12558   // If source is floating point but target is an integer.
12559   if (ResultBT->isInteger())
12560     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12561                            E->getExprLoc(), diag::warn_impcast_float_integer);
12562 
12563   if (!ResultBT->isFloatingPoint())
12564     return;
12565 
12566   // If both source and target are floating points, warn about losing precision.
12567   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12568       QualType(ResultBT, 0), QualType(RBT, 0));
12569   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12570     // warn about dropping FP rank.
12571     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12572                     diag::warn_impcast_float_result_precision);
12573 }
12574 
12575 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12576                                       IntRange Range) {
12577   if (!Range.Width) return "0";
12578 
12579   llvm::APSInt ValueInRange = Value;
12580   ValueInRange.setIsSigned(!Range.NonNegative);
12581   ValueInRange = ValueInRange.trunc(Range.Width);
12582   return toString(ValueInRange, 10);
12583 }
12584 
12585 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12586   if (!isa<ImplicitCastExpr>(Ex))
12587     return false;
12588 
12589   Expr *InnerE = Ex->IgnoreParenImpCasts();
12590   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12591   const Type *Source =
12592     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12593   if (Target->isDependentType())
12594     return false;
12595 
12596   const BuiltinType *FloatCandidateBT =
12597     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12598   const Type *BoolCandidateType = ToBool ? Target : Source;
12599 
12600   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12601           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12602 }
12603 
12604 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12605                                              SourceLocation CC) {
12606   unsigned NumArgs = TheCall->getNumArgs();
12607   for (unsigned i = 0; i < NumArgs; ++i) {
12608     Expr *CurrA = TheCall->getArg(i);
12609     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12610       continue;
12611 
12612     bool IsSwapped = ((i > 0) &&
12613         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12614     IsSwapped |= ((i < (NumArgs - 1)) &&
12615         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12616     if (IsSwapped) {
12617       // Warn on this floating-point to bool conversion.
12618       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12619                       CurrA->getType(), CC,
12620                       diag::warn_impcast_floating_point_to_bool);
12621     }
12622   }
12623 }
12624 
12625 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12626                                    SourceLocation CC) {
12627   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12628                         E->getExprLoc()))
12629     return;
12630 
12631   // Don't warn on functions which have return type nullptr_t.
12632   if (isa<CallExpr>(E))
12633     return;
12634 
12635   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12636   const Expr::NullPointerConstantKind NullKind =
12637       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12638   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12639     return;
12640 
12641   // Return if target type is a safe conversion.
12642   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12643       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12644     return;
12645 
12646   SourceLocation Loc = E->getSourceRange().getBegin();
12647 
12648   // Venture through the macro stacks to get to the source of macro arguments.
12649   // The new location is a better location than the complete location that was
12650   // passed in.
12651   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12652   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12653 
12654   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12655   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12656     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12657         Loc, S.SourceMgr, S.getLangOpts());
12658     if (MacroName == "NULL")
12659       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12660   }
12661 
12662   // Only warn if the null and context location are in the same macro expansion.
12663   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12664     return;
12665 
12666   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12667       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12668       << FixItHint::CreateReplacement(Loc,
12669                                       S.getFixItZeroLiteralForType(T, Loc));
12670 }
12671 
12672 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12673                                   ObjCArrayLiteral *ArrayLiteral);
12674 
12675 static void
12676 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12677                            ObjCDictionaryLiteral *DictionaryLiteral);
12678 
12679 /// Check a single element within a collection literal against the
12680 /// target element type.
12681 static void checkObjCCollectionLiteralElement(Sema &S,
12682                                               QualType TargetElementType,
12683                                               Expr *Element,
12684                                               unsigned ElementKind) {
12685   // Skip a bitcast to 'id' or qualified 'id'.
12686   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12687     if (ICE->getCastKind() == CK_BitCast &&
12688         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12689       Element = ICE->getSubExpr();
12690   }
12691 
12692   QualType ElementType = Element->getType();
12693   ExprResult ElementResult(Element);
12694   if (ElementType->getAs<ObjCObjectPointerType>() &&
12695       S.CheckSingleAssignmentConstraints(TargetElementType,
12696                                          ElementResult,
12697                                          false, false)
12698         != Sema::Compatible) {
12699     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12700         << ElementType << ElementKind << TargetElementType
12701         << Element->getSourceRange();
12702   }
12703 
12704   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12705     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12706   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12707     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12708 }
12709 
12710 /// Check an Objective-C array literal being converted to the given
12711 /// target type.
12712 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12713                                   ObjCArrayLiteral *ArrayLiteral) {
12714   if (!S.NSArrayDecl)
12715     return;
12716 
12717   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12718   if (!TargetObjCPtr)
12719     return;
12720 
12721   if (TargetObjCPtr->isUnspecialized() ||
12722       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12723         != S.NSArrayDecl->getCanonicalDecl())
12724     return;
12725 
12726   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12727   if (TypeArgs.size() != 1)
12728     return;
12729 
12730   QualType TargetElementType = TypeArgs[0];
12731   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12732     checkObjCCollectionLiteralElement(S, TargetElementType,
12733                                       ArrayLiteral->getElement(I),
12734                                       0);
12735   }
12736 }
12737 
12738 /// Check an Objective-C dictionary literal being converted to the given
12739 /// target type.
12740 static void
12741 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12742                            ObjCDictionaryLiteral *DictionaryLiteral) {
12743   if (!S.NSDictionaryDecl)
12744     return;
12745 
12746   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12747   if (!TargetObjCPtr)
12748     return;
12749 
12750   if (TargetObjCPtr->isUnspecialized() ||
12751       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12752         != S.NSDictionaryDecl->getCanonicalDecl())
12753     return;
12754 
12755   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12756   if (TypeArgs.size() != 2)
12757     return;
12758 
12759   QualType TargetKeyType = TypeArgs[0];
12760   QualType TargetObjectType = TypeArgs[1];
12761   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12762     auto Element = DictionaryLiteral->getKeyValueElement(I);
12763     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12764     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12765   }
12766 }
12767 
12768 // Helper function to filter out cases for constant width constant conversion.
12769 // Don't warn on char array initialization or for non-decimal values.
12770 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12771                                           SourceLocation CC) {
12772   // If initializing from a constant, and the constant starts with '0',
12773   // then it is a binary, octal, or hexadecimal.  Allow these constants
12774   // to fill all the bits, even if there is a sign change.
12775   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12776     const char FirstLiteralCharacter =
12777         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12778     if (FirstLiteralCharacter == '0')
12779       return false;
12780   }
12781 
12782   // If the CC location points to a '{', and the type is char, then assume
12783   // assume it is an array initialization.
12784   if (CC.isValid() && T->isCharType()) {
12785     const char FirstContextCharacter =
12786         S.getSourceManager().getCharacterData(CC)[0];
12787     if (FirstContextCharacter == '{')
12788       return false;
12789   }
12790 
12791   return true;
12792 }
12793 
12794 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12795   const auto *IL = dyn_cast<IntegerLiteral>(E);
12796   if (!IL) {
12797     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12798       if (UO->getOpcode() == UO_Minus)
12799         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12800     }
12801   }
12802 
12803   return IL;
12804 }
12805 
12806 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12807   E = E->IgnoreParenImpCasts();
12808   SourceLocation ExprLoc = E->getExprLoc();
12809 
12810   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12811     BinaryOperator::Opcode Opc = BO->getOpcode();
12812     Expr::EvalResult Result;
12813     // Do not diagnose unsigned shifts.
12814     if (Opc == BO_Shl) {
12815       const auto *LHS = getIntegerLiteral(BO->getLHS());
12816       const auto *RHS = getIntegerLiteral(BO->getRHS());
12817       if (LHS && LHS->getValue() == 0)
12818         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12819       else if (!E->isValueDependent() && LHS && RHS &&
12820                RHS->getValue().isNonNegative() &&
12821                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12822         S.Diag(ExprLoc, diag::warn_left_shift_always)
12823             << (Result.Val.getInt() != 0);
12824       else if (E->getType()->isSignedIntegerType())
12825         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12826     }
12827   }
12828 
12829   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12830     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12831     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12832     if (!LHS || !RHS)
12833       return;
12834     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12835         (RHS->getValue() == 0 || RHS->getValue() == 1))
12836       // Do not diagnose common idioms.
12837       return;
12838     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12839       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12840   }
12841 }
12842 
12843 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12844                                     SourceLocation CC,
12845                                     bool *ICContext = nullptr,
12846                                     bool IsListInit = false) {
12847   if (E->isTypeDependent() || E->isValueDependent()) return;
12848 
12849   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12850   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12851   if (Source == Target) return;
12852   if (Target->isDependentType()) return;
12853 
12854   // If the conversion context location is invalid don't complain. We also
12855   // don't want to emit a warning if the issue occurs from the expansion of
12856   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12857   // delay this check as long as possible. Once we detect we are in that
12858   // scenario, we just return.
12859   if (CC.isInvalid())
12860     return;
12861 
12862   if (Source->isAtomicType())
12863     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12864 
12865   // Diagnose implicit casts to bool.
12866   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12867     if (isa<StringLiteral>(E))
12868       // Warn on string literal to bool.  Checks for string literals in logical
12869       // and expressions, for instance, assert(0 && "error here"), are
12870       // prevented by a check in AnalyzeImplicitConversions().
12871       return DiagnoseImpCast(S, E, T, CC,
12872                              diag::warn_impcast_string_literal_to_bool);
12873     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12874         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12875       // This covers the literal expressions that evaluate to Objective-C
12876       // objects.
12877       return DiagnoseImpCast(S, E, T, CC,
12878                              diag::warn_impcast_objective_c_literal_to_bool);
12879     }
12880     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12881       // Warn on pointer to bool conversion that is always true.
12882       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12883                                      SourceRange(CC));
12884     }
12885   }
12886 
12887   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12888   // is a typedef for signed char (macOS), then that constant value has to be 1
12889   // or 0.
12890   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12891     Expr::EvalResult Result;
12892     if (E->EvaluateAsInt(Result, S.getASTContext(),
12893                          Expr::SE_AllowSideEffects)) {
12894       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12895         adornObjCBoolConversionDiagWithTernaryFixit(
12896             S, E,
12897             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12898                 << toString(Result.Val.getInt(), 10));
12899       }
12900       return;
12901     }
12902   }
12903 
12904   // Check implicit casts from Objective-C collection literals to specialized
12905   // collection types, e.g., NSArray<NSString *> *.
12906   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12907     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12908   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12909     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12910 
12911   // Strip vector types.
12912   if (isa<VectorType>(Source)) {
12913     if (Target->isVLSTBuiltinType() &&
12914         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12915                                          QualType(Source, 0)) ||
12916          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12917                                             QualType(Source, 0))))
12918       return;
12919 
12920     if (!isa<VectorType>(Target)) {
12921       if (S.SourceMgr.isInSystemMacro(CC))
12922         return;
12923       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12924     }
12925 
12926     // If the vector cast is cast between two vectors of the same size, it is
12927     // a bitcast, not a conversion.
12928     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12929       return;
12930 
12931     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12932     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12933   }
12934   if (auto VecTy = dyn_cast<VectorType>(Target))
12935     Target = VecTy->getElementType().getTypePtr();
12936 
12937   // Strip complex types.
12938   if (isa<ComplexType>(Source)) {
12939     if (!isa<ComplexType>(Target)) {
12940       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12941         return;
12942 
12943       return DiagnoseImpCast(S, E, T, CC,
12944                              S.getLangOpts().CPlusPlus
12945                                  ? diag::err_impcast_complex_scalar
12946                                  : diag::warn_impcast_complex_scalar);
12947     }
12948 
12949     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12950     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12951   }
12952 
12953   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12954   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12955 
12956   // If the source is floating point...
12957   if (SourceBT && SourceBT->isFloatingPoint()) {
12958     // ...and the target is floating point...
12959     if (TargetBT && TargetBT->isFloatingPoint()) {
12960       // ...then warn if we're dropping FP rank.
12961 
12962       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12963           QualType(SourceBT, 0), QualType(TargetBT, 0));
12964       if (Order > 0) {
12965         // Don't warn about float constants that are precisely
12966         // representable in the target type.
12967         Expr::EvalResult result;
12968         if (E->EvaluateAsRValue(result, S.Context)) {
12969           // Value might be a float, a float vector, or a float complex.
12970           if (IsSameFloatAfterCast(result.Val,
12971                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12972                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12973             return;
12974         }
12975 
12976         if (S.SourceMgr.isInSystemMacro(CC))
12977           return;
12978 
12979         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12980       }
12981       // ... or possibly if we're increasing rank, too
12982       else if (Order < 0) {
12983         if (S.SourceMgr.isInSystemMacro(CC))
12984           return;
12985 
12986         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12987       }
12988       return;
12989     }
12990 
12991     // If the target is integral, always warn.
12992     if (TargetBT && TargetBT->isInteger()) {
12993       if (S.SourceMgr.isInSystemMacro(CC))
12994         return;
12995 
12996       DiagnoseFloatingImpCast(S, E, T, CC);
12997     }
12998 
12999     // Detect the case where a call result is converted from floating-point to
13000     // to bool, and the final argument to the call is converted from bool, to
13001     // discover this typo:
13002     //
13003     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13004     //
13005     // FIXME: This is an incredibly special case; is there some more general
13006     // way to detect this class of misplaced-parentheses bug?
13007     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13008       // Check last argument of function call to see if it is an
13009       // implicit cast from a type matching the type the result
13010       // is being cast to.
13011       CallExpr *CEx = cast<CallExpr>(E);
13012       if (unsigned NumArgs = CEx->getNumArgs()) {
13013         Expr *LastA = CEx->getArg(NumArgs - 1);
13014         Expr *InnerE = LastA->IgnoreParenImpCasts();
13015         if (isa<ImplicitCastExpr>(LastA) &&
13016             InnerE->getType()->isBooleanType()) {
13017           // Warn on this floating-point to bool conversion
13018           DiagnoseImpCast(S, E, T, CC,
13019                           diag::warn_impcast_floating_point_to_bool);
13020         }
13021       }
13022     }
13023     return;
13024   }
13025 
13026   // Valid casts involving fixed point types should be accounted for here.
13027   if (Source->isFixedPointType()) {
13028     if (Target->isUnsaturatedFixedPointType()) {
13029       Expr::EvalResult Result;
13030       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13031                                   S.isConstantEvaluated())) {
13032         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13033         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13034         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13035         if (Value > MaxVal || Value < MinVal) {
13036           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13037                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13038                                     << Value.toString() << T
13039                                     << E->getSourceRange()
13040                                     << clang::SourceRange(CC));
13041           return;
13042         }
13043       }
13044     } else if (Target->isIntegerType()) {
13045       Expr::EvalResult Result;
13046       if (!S.isConstantEvaluated() &&
13047           E->EvaluateAsFixedPoint(Result, S.Context,
13048                                   Expr::SE_AllowSideEffects)) {
13049         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13050 
13051         bool Overflowed;
13052         llvm::APSInt IntResult = FXResult.convertToInt(
13053             S.Context.getIntWidth(T),
13054             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13055 
13056         if (Overflowed) {
13057           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13058                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13059                                     << FXResult.toString() << T
13060                                     << E->getSourceRange()
13061                                     << clang::SourceRange(CC));
13062           return;
13063         }
13064       }
13065     }
13066   } else if (Target->isUnsaturatedFixedPointType()) {
13067     if (Source->isIntegerType()) {
13068       Expr::EvalResult Result;
13069       if (!S.isConstantEvaluated() &&
13070           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13071         llvm::APSInt Value = Result.Val.getInt();
13072 
13073         bool Overflowed;
13074         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13075             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13076 
13077         if (Overflowed) {
13078           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13079                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13080                                     << toString(Value, /*Radix=*/10) << T
13081                                     << E->getSourceRange()
13082                                     << clang::SourceRange(CC));
13083           return;
13084         }
13085       }
13086     }
13087   }
13088 
13089   // If we are casting an integer type to a floating point type without
13090   // initialization-list syntax, we might lose accuracy if the floating
13091   // point type has a narrower significand than the integer type.
13092   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13093       TargetBT->isFloatingType() && !IsListInit) {
13094     // Determine the number of precision bits in the source integer type.
13095     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13096                                         /*Approximate*/ true);
13097     unsigned int SourcePrecision = SourceRange.Width;
13098 
13099     // Determine the number of precision bits in the
13100     // target floating point type.
13101     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13102         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13103 
13104     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13105         SourcePrecision > TargetPrecision) {
13106 
13107       if (Optional<llvm::APSInt> SourceInt =
13108               E->getIntegerConstantExpr(S.Context)) {
13109         // If the source integer is a constant, convert it to the target
13110         // floating point type. Issue a warning if the value changes
13111         // during the whole conversion.
13112         llvm::APFloat TargetFloatValue(
13113             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13114         llvm::APFloat::opStatus ConversionStatus =
13115             TargetFloatValue.convertFromAPInt(
13116                 *SourceInt, SourceBT->isSignedInteger(),
13117                 llvm::APFloat::rmNearestTiesToEven);
13118 
13119         if (ConversionStatus != llvm::APFloat::opOK) {
13120           SmallString<32> PrettySourceValue;
13121           SourceInt->toString(PrettySourceValue, 10);
13122           SmallString<32> PrettyTargetValue;
13123           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13124 
13125           S.DiagRuntimeBehavior(
13126               E->getExprLoc(), E,
13127               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13128                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13129                   << E->getSourceRange() << clang::SourceRange(CC));
13130         }
13131       } else {
13132         // Otherwise, the implicit conversion may lose precision.
13133         DiagnoseImpCast(S, E, T, CC,
13134                         diag::warn_impcast_integer_float_precision);
13135       }
13136     }
13137   }
13138 
13139   DiagnoseNullConversion(S, E, T, CC);
13140 
13141   S.DiscardMisalignedMemberAddress(Target, E);
13142 
13143   if (Target->isBooleanType())
13144     DiagnoseIntInBoolContext(S, E);
13145 
13146   if (!Source->isIntegerType() || !Target->isIntegerType())
13147     return;
13148 
13149   // TODO: remove this early return once the false positives for constant->bool
13150   // in templates, macros, etc, are reduced or removed.
13151   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13152     return;
13153 
13154   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13155       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13156     return adornObjCBoolConversionDiagWithTernaryFixit(
13157         S, E,
13158         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13159             << E->getType());
13160   }
13161 
13162   IntRange SourceTypeRange =
13163       IntRange::forTargetOfCanonicalType(S.Context, Source);
13164   IntRange LikelySourceRange =
13165       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13166   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13167 
13168   if (LikelySourceRange.Width > TargetRange.Width) {
13169     // If the source is a constant, use a default-on diagnostic.
13170     // TODO: this should happen for bitfield stores, too.
13171     Expr::EvalResult Result;
13172     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13173                          S.isConstantEvaluated())) {
13174       llvm::APSInt Value(32);
13175       Value = Result.Val.getInt();
13176 
13177       if (S.SourceMgr.isInSystemMacro(CC))
13178         return;
13179 
13180       std::string PrettySourceValue = toString(Value, 10);
13181       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13182 
13183       S.DiagRuntimeBehavior(
13184           E->getExprLoc(), E,
13185           S.PDiag(diag::warn_impcast_integer_precision_constant)
13186               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13187               << E->getSourceRange() << SourceRange(CC));
13188       return;
13189     }
13190 
13191     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13192     if (S.SourceMgr.isInSystemMacro(CC))
13193       return;
13194 
13195     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13196       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13197                              /* pruneControlFlow */ true);
13198     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13199   }
13200 
13201   if (TargetRange.Width > SourceTypeRange.Width) {
13202     if (auto *UO = dyn_cast<UnaryOperator>(E))
13203       if (UO->getOpcode() == UO_Minus)
13204         if (Source->isUnsignedIntegerType()) {
13205           if (Target->isUnsignedIntegerType())
13206             return DiagnoseImpCast(S, E, T, CC,
13207                                    diag::warn_impcast_high_order_zero_bits);
13208           if (Target->isSignedIntegerType())
13209             return DiagnoseImpCast(S, E, T, CC,
13210                                    diag::warn_impcast_nonnegative_result);
13211         }
13212   }
13213 
13214   if (TargetRange.Width == LikelySourceRange.Width &&
13215       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13216       Source->isSignedIntegerType()) {
13217     // Warn when doing a signed to signed conversion, warn if the positive
13218     // source value is exactly the width of the target type, which will
13219     // cause a negative value to be stored.
13220 
13221     Expr::EvalResult Result;
13222     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13223         !S.SourceMgr.isInSystemMacro(CC)) {
13224       llvm::APSInt Value = Result.Val.getInt();
13225       if (isSameWidthConstantConversion(S, E, T, CC)) {
13226         std::string PrettySourceValue = toString(Value, 10);
13227         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13228 
13229         S.DiagRuntimeBehavior(
13230             E->getExprLoc(), E,
13231             S.PDiag(diag::warn_impcast_integer_precision_constant)
13232                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13233                 << E->getSourceRange() << SourceRange(CC));
13234         return;
13235       }
13236     }
13237 
13238     // Fall through for non-constants to give a sign conversion warning.
13239   }
13240 
13241   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13242       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13243        LikelySourceRange.Width == TargetRange.Width)) {
13244     if (S.SourceMgr.isInSystemMacro(CC))
13245       return;
13246 
13247     unsigned DiagID = diag::warn_impcast_integer_sign;
13248 
13249     // Traditionally, gcc has warned about this under -Wsign-compare.
13250     // We also want to warn about it in -Wconversion.
13251     // So if -Wconversion is off, use a completely identical diagnostic
13252     // in the sign-compare group.
13253     // The conditional-checking code will
13254     if (ICContext) {
13255       DiagID = diag::warn_impcast_integer_sign_conditional;
13256       *ICContext = true;
13257     }
13258 
13259     return DiagnoseImpCast(S, E, T, CC, DiagID);
13260   }
13261 
13262   // Diagnose conversions between different enumeration types.
13263   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13264   // type, to give us better diagnostics.
13265   QualType SourceType = E->getType();
13266   if (!S.getLangOpts().CPlusPlus) {
13267     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13268       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13269         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13270         SourceType = S.Context.getTypeDeclType(Enum);
13271         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13272       }
13273   }
13274 
13275   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13276     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13277       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13278           TargetEnum->getDecl()->hasNameForLinkage() &&
13279           SourceEnum != TargetEnum) {
13280         if (S.SourceMgr.isInSystemMacro(CC))
13281           return;
13282 
13283         return DiagnoseImpCast(S, E, SourceType, T, CC,
13284                                diag::warn_impcast_different_enum_types);
13285       }
13286 }
13287 
13288 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13289                                      SourceLocation CC, QualType T);
13290 
13291 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13292                                     SourceLocation CC, bool &ICContext) {
13293   E = E->IgnoreParenImpCasts();
13294 
13295   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13296     return CheckConditionalOperator(S, CO, CC, T);
13297 
13298   AnalyzeImplicitConversions(S, E, CC);
13299   if (E->getType() != T)
13300     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13301 }
13302 
13303 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13304                                      SourceLocation CC, QualType T) {
13305   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13306 
13307   Expr *TrueExpr = E->getTrueExpr();
13308   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13309     TrueExpr = BCO->getCommon();
13310 
13311   bool Suspicious = false;
13312   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13313   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13314 
13315   if (T->isBooleanType())
13316     DiagnoseIntInBoolContext(S, E);
13317 
13318   // If -Wconversion would have warned about either of the candidates
13319   // for a signedness conversion to the context type...
13320   if (!Suspicious) return;
13321 
13322   // ...but it's currently ignored...
13323   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13324     return;
13325 
13326   // ...then check whether it would have warned about either of the
13327   // candidates for a signedness conversion to the condition type.
13328   if (E->getType() == T) return;
13329 
13330   Suspicious = false;
13331   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13332                           E->getType(), CC, &Suspicious);
13333   if (!Suspicious)
13334     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13335                             E->getType(), CC, &Suspicious);
13336 }
13337 
13338 /// Check conversion of given expression to boolean.
13339 /// Input argument E is a logical expression.
13340 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13341   if (S.getLangOpts().Bool)
13342     return;
13343   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13344     return;
13345   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13346 }
13347 
13348 namespace {
13349 struct AnalyzeImplicitConversionsWorkItem {
13350   Expr *E;
13351   SourceLocation CC;
13352   bool IsListInit;
13353 };
13354 }
13355 
13356 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13357 /// that should be visited are added to WorkList.
13358 static void AnalyzeImplicitConversions(
13359     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13360     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13361   Expr *OrigE = Item.E;
13362   SourceLocation CC = Item.CC;
13363 
13364   QualType T = OrigE->getType();
13365   Expr *E = OrigE->IgnoreParenImpCasts();
13366 
13367   // Propagate whether we are in a C++ list initialization expression.
13368   // If so, we do not issue warnings for implicit int-float conversion
13369   // precision loss, because C++11 narrowing already handles it.
13370   bool IsListInit = Item.IsListInit ||
13371                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13372 
13373   if (E->isTypeDependent() || E->isValueDependent())
13374     return;
13375 
13376   Expr *SourceExpr = E;
13377   // Examine, but don't traverse into the source expression of an
13378   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13379   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13380   // evaluate it in the context of checking the specific conversion to T though.
13381   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13382     if (auto *Src = OVE->getSourceExpr())
13383       SourceExpr = Src;
13384 
13385   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13386     if (UO->getOpcode() == UO_Not &&
13387         UO->getSubExpr()->isKnownToHaveBooleanValue())
13388       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13389           << OrigE->getSourceRange() << T->isBooleanType()
13390           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13391 
13392   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13393     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13394         BO->getLHS()->isKnownToHaveBooleanValue() &&
13395         BO->getRHS()->isKnownToHaveBooleanValue() &&
13396         BO->getLHS()->HasSideEffects(S.Context) &&
13397         BO->getRHS()->HasSideEffects(S.Context)) {
13398       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13399           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13400           << FixItHint::CreateReplacement(
13401                  BO->getOperatorLoc(),
13402                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13403       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13404     }
13405 
13406   // For conditional operators, we analyze the arguments as if they
13407   // were being fed directly into the output.
13408   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13409     CheckConditionalOperator(S, CO, CC, T);
13410     return;
13411   }
13412 
13413   // Check implicit argument conversions for function calls.
13414   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13415     CheckImplicitArgumentConversions(S, Call, CC);
13416 
13417   // Go ahead and check any implicit conversions we might have skipped.
13418   // The non-canonical typecheck is just an optimization;
13419   // CheckImplicitConversion will filter out dead implicit conversions.
13420   if (SourceExpr->getType() != T)
13421     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13422 
13423   // Now continue drilling into this expression.
13424 
13425   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13426     // The bound subexpressions in a PseudoObjectExpr are not reachable
13427     // as transitive children.
13428     // FIXME: Use a more uniform representation for this.
13429     for (auto *SE : POE->semantics())
13430       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13431         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13432   }
13433 
13434   // Skip past explicit casts.
13435   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13436     E = CE->getSubExpr()->IgnoreParenImpCasts();
13437     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13438       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13439     WorkList.push_back({E, CC, IsListInit});
13440     return;
13441   }
13442 
13443   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13444     // Do a somewhat different check with comparison operators.
13445     if (BO->isComparisonOp())
13446       return AnalyzeComparison(S, BO);
13447 
13448     // And with simple assignments.
13449     if (BO->getOpcode() == BO_Assign)
13450       return AnalyzeAssignment(S, BO);
13451     // And with compound assignments.
13452     if (BO->isAssignmentOp())
13453       return AnalyzeCompoundAssignment(S, BO);
13454   }
13455 
13456   // These break the otherwise-useful invariant below.  Fortunately,
13457   // we don't really need to recurse into them, because any internal
13458   // expressions should have been analyzed already when they were
13459   // built into statements.
13460   if (isa<StmtExpr>(E)) return;
13461 
13462   // Don't descend into unevaluated contexts.
13463   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13464 
13465   // Now just recurse over the expression's children.
13466   CC = E->getExprLoc();
13467   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13468   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13469   for (Stmt *SubStmt : E->children()) {
13470     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13471     if (!ChildExpr)
13472       continue;
13473 
13474     if (IsLogicalAndOperator &&
13475         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13476       // Ignore checking string literals that are in logical and operators.
13477       // This is a common pattern for asserts.
13478       continue;
13479     WorkList.push_back({ChildExpr, CC, IsListInit});
13480   }
13481 
13482   if (BO && BO->isLogicalOp()) {
13483     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13484     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13485       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13486 
13487     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13488     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13489       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13490   }
13491 
13492   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13493     if (U->getOpcode() == UO_LNot) {
13494       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13495     } else if (U->getOpcode() != UO_AddrOf) {
13496       if (U->getSubExpr()->getType()->isAtomicType())
13497         S.Diag(U->getSubExpr()->getBeginLoc(),
13498                diag::warn_atomic_implicit_seq_cst);
13499     }
13500   }
13501 }
13502 
13503 /// AnalyzeImplicitConversions - Find and report any interesting
13504 /// implicit conversions in the given expression.  There are a couple
13505 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13506 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13507                                        bool IsListInit/*= false*/) {
13508   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13509   WorkList.push_back({OrigE, CC, IsListInit});
13510   while (!WorkList.empty())
13511     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13512 }
13513 
13514 /// Diagnose integer type and any valid implicit conversion to it.
13515 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13516   // Taking into account implicit conversions,
13517   // allow any integer.
13518   if (!E->getType()->isIntegerType()) {
13519     S.Diag(E->getBeginLoc(),
13520            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13521     return true;
13522   }
13523   // Potentially emit standard warnings for implicit conversions if enabled
13524   // using -Wconversion.
13525   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13526   return false;
13527 }
13528 
13529 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13530 // Returns true when emitting a warning about taking the address of a reference.
13531 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13532                               const PartialDiagnostic &PD) {
13533   E = E->IgnoreParenImpCasts();
13534 
13535   const FunctionDecl *FD = nullptr;
13536 
13537   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13538     if (!DRE->getDecl()->getType()->isReferenceType())
13539       return false;
13540   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13541     if (!M->getMemberDecl()->getType()->isReferenceType())
13542       return false;
13543   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13544     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13545       return false;
13546     FD = Call->getDirectCallee();
13547   } else {
13548     return false;
13549   }
13550 
13551   SemaRef.Diag(E->getExprLoc(), PD);
13552 
13553   // If possible, point to location of function.
13554   if (FD) {
13555     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13556   }
13557 
13558   return true;
13559 }
13560 
13561 // Returns true if the SourceLocation is expanded from any macro body.
13562 // Returns false if the SourceLocation is invalid, is from not in a macro
13563 // expansion, or is from expanded from a top-level macro argument.
13564 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13565   if (Loc.isInvalid())
13566     return false;
13567 
13568   while (Loc.isMacroID()) {
13569     if (SM.isMacroBodyExpansion(Loc))
13570       return true;
13571     Loc = SM.getImmediateMacroCallerLoc(Loc);
13572   }
13573 
13574   return false;
13575 }
13576 
13577 /// Diagnose pointers that are always non-null.
13578 /// \param E the expression containing the pointer
13579 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13580 /// compared to a null pointer
13581 /// \param IsEqual True when the comparison is equal to a null pointer
13582 /// \param Range Extra SourceRange to highlight in the diagnostic
13583 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13584                                         Expr::NullPointerConstantKind NullKind,
13585                                         bool IsEqual, SourceRange Range) {
13586   if (!E)
13587     return;
13588 
13589   // Don't warn inside macros.
13590   if (E->getExprLoc().isMacroID()) {
13591     const SourceManager &SM = getSourceManager();
13592     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13593         IsInAnyMacroBody(SM, Range.getBegin()))
13594       return;
13595   }
13596   E = E->IgnoreImpCasts();
13597 
13598   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13599 
13600   if (isa<CXXThisExpr>(E)) {
13601     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13602                                 : diag::warn_this_bool_conversion;
13603     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13604     return;
13605   }
13606 
13607   bool IsAddressOf = false;
13608 
13609   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13610     if (UO->getOpcode() != UO_AddrOf)
13611       return;
13612     IsAddressOf = true;
13613     E = UO->getSubExpr();
13614   }
13615 
13616   if (IsAddressOf) {
13617     unsigned DiagID = IsCompare
13618                           ? diag::warn_address_of_reference_null_compare
13619                           : diag::warn_address_of_reference_bool_conversion;
13620     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13621                                          << IsEqual;
13622     if (CheckForReference(*this, E, PD)) {
13623       return;
13624     }
13625   }
13626 
13627   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13628     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13629     std::string Str;
13630     llvm::raw_string_ostream S(Str);
13631     E->printPretty(S, nullptr, getPrintingPolicy());
13632     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13633                                 : diag::warn_cast_nonnull_to_bool;
13634     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13635       << E->getSourceRange() << Range << IsEqual;
13636     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13637   };
13638 
13639   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13640   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13641     if (auto *Callee = Call->getDirectCallee()) {
13642       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13643         ComplainAboutNonnullParamOrCall(A);
13644         return;
13645       }
13646     }
13647   }
13648 
13649   // Expect to find a single Decl.  Skip anything more complicated.
13650   ValueDecl *D = nullptr;
13651   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13652     D = R->getDecl();
13653   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13654     D = M->getMemberDecl();
13655   }
13656 
13657   // Weak Decls can be null.
13658   if (!D || D->isWeak())
13659     return;
13660 
13661   // Check for parameter decl with nonnull attribute
13662   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13663     if (getCurFunction() &&
13664         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13665       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13666         ComplainAboutNonnullParamOrCall(A);
13667         return;
13668       }
13669 
13670       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13671         // Skip function template not specialized yet.
13672         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13673           return;
13674         auto ParamIter = llvm::find(FD->parameters(), PV);
13675         assert(ParamIter != FD->param_end());
13676         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13677 
13678         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13679           if (!NonNull->args_size()) {
13680               ComplainAboutNonnullParamOrCall(NonNull);
13681               return;
13682           }
13683 
13684           for (const ParamIdx &ArgNo : NonNull->args()) {
13685             if (ArgNo.getASTIndex() == ParamNo) {
13686               ComplainAboutNonnullParamOrCall(NonNull);
13687               return;
13688             }
13689           }
13690         }
13691       }
13692     }
13693   }
13694 
13695   QualType T = D->getType();
13696   const bool IsArray = T->isArrayType();
13697   const bool IsFunction = T->isFunctionType();
13698 
13699   // Address of function is used to silence the function warning.
13700   if (IsAddressOf && IsFunction) {
13701     return;
13702   }
13703 
13704   // Found nothing.
13705   if (!IsAddressOf && !IsFunction && !IsArray)
13706     return;
13707 
13708   // Pretty print the expression for the diagnostic.
13709   std::string Str;
13710   llvm::raw_string_ostream S(Str);
13711   E->printPretty(S, nullptr, getPrintingPolicy());
13712 
13713   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13714                               : diag::warn_impcast_pointer_to_bool;
13715   enum {
13716     AddressOf,
13717     FunctionPointer,
13718     ArrayPointer
13719   } DiagType;
13720   if (IsAddressOf)
13721     DiagType = AddressOf;
13722   else if (IsFunction)
13723     DiagType = FunctionPointer;
13724   else if (IsArray)
13725     DiagType = ArrayPointer;
13726   else
13727     llvm_unreachable("Could not determine diagnostic.");
13728   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13729                                 << Range << IsEqual;
13730 
13731   if (!IsFunction)
13732     return;
13733 
13734   // Suggest '&' to silence the function warning.
13735   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13736       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13737 
13738   // Check to see if '()' fixit should be emitted.
13739   QualType ReturnType;
13740   UnresolvedSet<4> NonTemplateOverloads;
13741   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13742   if (ReturnType.isNull())
13743     return;
13744 
13745   if (IsCompare) {
13746     // There are two cases here.  If there is null constant, the only suggest
13747     // for a pointer return type.  If the null is 0, then suggest if the return
13748     // type is a pointer or an integer type.
13749     if (!ReturnType->isPointerType()) {
13750       if (NullKind == Expr::NPCK_ZeroExpression ||
13751           NullKind == Expr::NPCK_ZeroLiteral) {
13752         if (!ReturnType->isIntegerType())
13753           return;
13754       } else {
13755         return;
13756       }
13757     }
13758   } else { // !IsCompare
13759     // For function to bool, only suggest if the function pointer has bool
13760     // return type.
13761     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13762       return;
13763   }
13764   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13765       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13766 }
13767 
13768 /// Diagnoses "dangerous" implicit conversions within the given
13769 /// expression (which is a full expression).  Implements -Wconversion
13770 /// and -Wsign-compare.
13771 ///
13772 /// \param CC the "context" location of the implicit conversion, i.e.
13773 ///   the most location of the syntactic entity requiring the implicit
13774 ///   conversion
13775 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13776   // Don't diagnose in unevaluated contexts.
13777   if (isUnevaluatedContext())
13778     return;
13779 
13780   // Don't diagnose for value- or type-dependent expressions.
13781   if (E->isTypeDependent() || E->isValueDependent())
13782     return;
13783 
13784   // Check for array bounds violations in cases where the check isn't triggered
13785   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13786   // ArraySubscriptExpr is on the RHS of a variable initialization.
13787   CheckArrayAccess(E);
13788 
13789   // This is not the right CC for (e.g.) a variable initialization.
13790   AnalyzeImplicitConversions(*this, E, CC);
13791 }
13792 
13793 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13794 /// Input argument E is a logical expression.
13795 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13796   ::CheckBoolLikeConversion(*this, E, CC);
13797 }
13798 
13799 /// Diagnose when expression is an integer constant expression and its evaluation
13800 /// results in integer overflow
13801 void Sema::CheckForIntOverflow (Expr *E) {
13802   // Use a work list to deal with nested struct initializers.
13803   SmallVector<Expr *, 2> Exprs(1, E);
13804 
13805   do {
13806     Expr *OriginalE = Exprs.pop_back_val();
13807     Expr *E = OriginalE->IgnoreParenCasts();
13808 
13809     if (isa<BinaryOperator>(E)) {
13810       E->EvaluateForOverflow(Context);
13811       continue;
13812     }
13813 
13814     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13815       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13816     else if (isa<ObjCBoxedExpr>(OriginalE))
13817       E->EvaluateForOverflow(Context);
13818     else if (auto Call = dyn_cast<CallExpr>(E))
13819       Exprs.append(Call->arg_begin(), Call->arg_end());
13820     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13821       Exprs.append(Message->arg_begin(), Message->arg_end());
13822   } while (!Exprs.empty());
13823 }
13824 
13825 namespace {
13826 
13827 /// Visitor for expressions which looks for unsequenced operations on the
13828 /// same object.
13829 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13830   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13831 
13832   /// A tree of sequenced regions within an expression. Two regions are
13833   /// unsequenced if one is an ancestor or a descendent of the other. When we
13834   /// finish processing an expression with sequencing, such as a comma
13835   /// expression, we fold its tree nodes into its parent, since they are
13836   /// unsequenced with respect to nodes we will visit later.
13837   class SequenceTree {
13838     struct Value {
13839       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13840       unsigned Parent : 31;
13841       unsigned Merged : 1;
13842     };
13843     SmallVector<Value, 8> Values;
13844 
13845   public:
13846     /// A region within an expression which may be sequenced with respect
13847     /// to some other region.
13848     class Seq {
13849       friend class SequenceTree;
13850 
13851       unsigned Index;
13852 
13853       explicit Seq(unsigned N) : Index(N) {}
13854 
13855     public:
13856       Seq() : Index(0) {}
13857     };
13858 
13859     SequenceTree() { Values.push_back(Value(0)); }
13860     Seq root() const { return Seq(0); }
13861 
13862     /// Create a new sequence of operations, which is an unsequenced
13863     /// subset of \p Parent. This sequence of operations is sequenced with
13864     /// respect to other children of \p Parent.
13865     Seq allocate(Seq Parent) {
13866       Values.push_back(Value(Parent.Index));
13867       return Seq(Values.size() - 1);
13868     }
13869 
13870     /// Merge a sequence of operations into its parent.
13871     void merge(Seq S) {
13872       Values[S.Index].Merged = true;
13873     }
13874 
13875     /// Determine whether two operations are unsequenced. This operation
13876     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13877     /// should have been merged into its parent as appropriate.
13878     bool isUnsequenced(Seq Cur, Seq Old) {
13879       unsigned C = representative(Cur.Index);
13880       unsigned Target = representative(Old.Index);
13881       while (C >= Target) {
13882         if (C == Target)
13883           return true;
13884         C = Values[C].Parent;
13885       }
13886       return false;
13887     }
13888 
13889   private:
13890     /// Pick a representative for a sequence.
13891     unsigned representative(unsigned K) {
13892       if (Values[K].Merged)
13893         // Perform path compression as we go.
13894         return Values[K].Parent = representative(Values[K].Parent);
13895       return K;
13896     }
13897   };
13898 
13899   /// An object for which we can track unsequenced uses.
13900   using Object = const NamedDecl *;
13901 
13902   /// Different flavors of object usage which we track. We only track the
13903   /// least-sequenced usage of each kind.
13904   enum UsageKind {
13905     /// A read of an object. Multiple unsequenced reads are OK.
13906     UK_Use,
13907 
13908     /// A modification of an object which is sequenced before the value
13909     /// computation of the expression, such as ++n in C++.
13910     UK_ModAsValue,
13911 
13912     /// A modification of an object which is not sequenced before the value
13913     /// computation of the expression, such as n++.
13914     UK_ModAsSideEffect,
13915 
13916     UK_Count = UK_ModAsSideEffect + 1
13917   };
13918 
13919   /// Bundle together a sequencing region and the expression corresponding
13920   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13921   struct Usage {
13922     const Expr *UsageExpr;
13923     SequenceTree::Seq Seq;
13924 
13925     Usage() : UsageExpr(nullptr), Seq() {}
13926   };
13927 
13928   struct UsageInfo {
13929     Usage Uses[UK_Count];
13930 
13931     /// Have we issued a diagnostic for this object already?
13932     bool Diagnosed;
13933 
13934     UsageInfo() : Uses(), Diagnosed(false) {}
13935   };
13936   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13937 
13938   Sema &SemaRef;
13939 
13940   /// Sequenced regions within the expression.
13941   SequenceTree Tree;
13942 
13943   /// Declaration modifications and references which we have seen.
13944   UsageInfoMap UsageMap;
13945 
13946   /// The region we are currently within.
13947   SequenceTree::Seq Region;
13948 
13949   /// Filled in with declarations which were modified as a side-effect
13950   /// (that is, post-increment operations).
13951   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13952 
13953   /// Expressions to check later. We defer checking these to reduce
13954   /// stack usage.
13955   SmallVectorImpl<const Expr *> &WorkList;
13956 
13957   /// RAII object wrapping the visitation of a sequenced subexpression of an
13958   /// expression. At the end of this process, the side-effects of the evaluation
13959   /// become sequenced with respect to the value computation of the result, so
13960   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13961   /// UK_ModAsValue.
13962   struct SequencedSubexpression {
13963     SequencedSubexpression(SequenceChecker &Self)
13964       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13965       Self.ModAsSideEffect = &ModAsSideEffect;
13966     }
13967 
13968     ~SequencedSubexpression() {
13969       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13970         // Add a new usage with usage kind UK_ModAsValue, and then restore
13971         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13972         // the previous one was empty).
13973         UsageInfo &UI = Self.UsageMap[M.first];
13974         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13975         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13976         SideEffectUsage = M.second;
13977       }
13978       Self.ModAsSideEffect = OldModAsSideEffect;
13979     }
13980 
13981     SequenceChecker &Self;
13982     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13983     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13984   };
13985 
13986   /// RAII object wrapping the visitation of a subexpression which we might
13987   /// choose to evaluate as a constant. If any subexpression is evaluated and
13988   /// found to be non-constant, this allows us to suppress the evaluation of
13989   /// the outer expression.
13990   class EvaluationTracker {
13991   public:
13992     EvaluationTracker(SequenceChecker &Self)
13993         : Self(Self), Prev(Self.EvalTracker) {
13994       Self.EvalTracker = this;
13995     }
13996 
13997     ~EvaluationTracker() {
13998       Self.EvalTracker = Prev;
13999       if (Prev)
14000         Prev->EvalOK &= EvalOK;
14001     }
14002 
14003     bool evaluate(const Expr *E, bool &Result) {
14004       if (!EvalOK || E->isValueDependent())
14005         return false;
14006       EvalOK = E->EvaluateAsBooleanCondition(
14007           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14008       return EvalOK;
14009     }
14010 
14011   private:
14012     SequenceChecker &Self;
14013     EvaluationTracker *Prev;
14014     bool EvalOK = true;
14015   } *EvalTracker = nullptr;
14016 
14017   /// Find the object which is produced by the specified expression,
14018   /// if any.
14019   Object getObject(const Expr *E, bool Mod) const {
14020     E = E->IgnoreParenCasts();
14021     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14022       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14023         return getObject(UO->getSubExpr(), Mod);
14024     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14025       if (BO->getOpcode() == BO_Comma)
14026         return getObject(BO->getRHS(), Mod);
14027       if (Mod && BO->isAssignmentOp())
14028         return getObject(BO->getLHS(), Mod);
14029     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14030       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14031       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14032         return ME->getMemberDecl();
14033     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14034       // FIXME: If this is a reference, map through to its value.
14035       return DRE->getDecl();
14036     return nullptr;
14037   }
14038 
14039   /// Note that an object \p O was modified or used by an expression
14040   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14041   /// the object \p O as obtained via the \p UsageMap.
14042   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14043     // Get the old usage for the given object and usage kind.
14044     Usage &U = UI.Uses[UK];
14045     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14046       // If we have a modification as side effect and are in a sequenced
14047       // subexpression, save the old Usage so that we can restore it later
14048       // in SequencedSubexpression::~SequencedSubexpression.
14049       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14050         ModAsSideEffect->push_back(std::make_pair(O, U));
14051       // Then record the new usage with the current sequencing region.
14052       U.UsageExpr = UsageExpr;
14053       U.Seq = Region;
14054     }
14055   }
14056 
14057   /// Check whether a modification or use of an object \p O in an expression
14058   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14059   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14060   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14061   /// usage and false we are checking for a mod-use unsequenced usage.
14062   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14063                   UsageKind OtherKind, bool IsModMod) {
14064     if (UI.Diagnosed)
14065       return;
14066 
14067     const Usage &U = UI.Uses[OtherKind];
14068     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14069       return;
14070 
14071     const Expr *Mod = U.UsageExpr;
14072     const Expr *ModOrUse = UsageExpr;
14073     if (OtherKind == UK_Use)
14074       std::swap(Mod, ModOrUse);
14075 
14076     SemaRef.DiagRuntimeBehavior(
14077         Mod->getExprLoc(), {Mod, ModOrUse},
14078         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14079                                : diag::warn_unsequenced_mod_use)
14080             << O << SourceRange(ModOrUse->getExprLoc()));
14081     UI.Diagnosed = true;
14082   }
14083 
14084   // A note on note{Pre, Post}{Use, Mod}:
14085   //
14086   // (It helps to follow the algorithm with an expression such as
14087   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14088   //  operations before C++17 and both are well-defined in C++17).
14089   //
14090   // When visiting a node which uses/modify an object we first call notePreUse
14091   // or notePreMod before visiting its sub-expression(s). At this point the
14092   // children of the current node have not yet been visited and so the eventual
14093   // uses/modifications resulting from the children of the current node have not
14094   // been recorded yet.
14095   //
14096   // We then visit the children of the current node. After that notePostUse or
14097   // notePostMod is called. These will 1) detect an unsequenced modification
14098   // as side effect (as in "k++ + k") and 2) add a new usage with the
14099   // appropriate usage kind.
14100   //
14101   // We also have to be careful that some operation sequences modification as
14102   // side effect as well (for example: || or ,). To account for this we wrap
14103   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14104   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14105   // which record usages which are modifications as side effect, and then
14106   // downgrade them (or more accurately restore the previous usage which was a
14107   // modification as side effect) when exiting the scope of the sequenced
14108   // subexpression.
14109 
14110   void notePreUse(Object O, const Expr *UseExpr) {
14111     UsageInfo &UI = UsageMap[O];
14112     // Uses conflict with other modifications.
14113     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14114   }
14115 
14116   void notePostUse(Object O, const Expr *UseExpr) {
14117     UsageInfo &UI = UsageMap[O];
14118     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14119                /*IsModMod=*/false);
14120     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14121   }
14122 
14123   void notePreMod(Object O, const Expr *ModExpr) {
14124     UsageInfo &UI = UsageMap[O];
14125     // Modifications conflict with other modifications and with uses.
14126     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14127     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14128   }
14129 
14130   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14131     UsageInfo &UI = UsageMap[O];
14132     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14133                /*IsModMod=*/true);
14134     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14135   }
14136 
14137 public:
14138   SequenceChecker(Sema &S, const Expr *E,
14139                   SmallVectorImpl<const Expr *> &WorkList)
14140       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14141     Visit(E);
14142     // Silence a -Wunused-private-field since WorkList is now unused.
14143     // TODO: Evaluate if it can be used, and if not remove it.
14144     (void)this->WorkList;
14145   }
14146 
14147   void VisitStmt(const Stmt *S) {
14148     // Skip all statements which aren't expressions for now.
14149   }
14150 
14151   void VisitExpr(const Expr *E) {
14152     // By default, just recurse to evaluated subexpressions.
14153     Base::VisitStmt(E);
14154   }
14155 
14156   void VisitCastExpr(const CastExpr *E) {
14157     Object O = Object();
14158     if (E->getCastKind() == CK_LValueToRValue)
14159       O = getObject(E->getSubExpr(), false);
14160 
14161     if (O)
14162       notePreUse(O, E);
14163     VisitExpr(E);
14164     if (O)
14165       notePostUse(O, E);
14166   }
14167 
14168   void VisitSequencedExpressions(const Expr *SequencedBefore,
14169                                  const Expr *SequencedAfter) {
14170     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14171     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14172     SequenceTree::Seq OldRegion = Region;
14173 
14174     {
14175       SequencedSubexpression SeqBefore(*this);
14176       Region = BeforeRegion;
14177       Visit(SequencedBefore);
14178     }
14179 
14180     Region = AfterRegion;
14181     Visit(SequencedAfter);
14182 
14183     Region = OldRegion;
14184 
14185     Tree.merge(BeforeRegion);
14186     Tree.merge(AfterRegion);
14187   }
14188 
14189   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14190     // C++17 [expr.sub]p1:
14191     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14192     //   expression E1 is sequenced before the expression E2.
14193     if (SemaRef.getLangOpts().CPlusPlus17)
14194       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14195     else {
14196       Visit(ASE->getLHS());
14197       Visit(ASE->getRHS());
14198     }
14199   }
14200 
14201   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14202   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14203   void VisitBinPtrMem(const BinaryOperator *BO) {
14204     // C++17 [expr.mptr.oper]p4:
14205     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14206     //  the expression E1 is sequenced before the expression E2.
14207     if (SemaRef.getLangOpts().CPlusPlus17)
14208       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14209     else {
14210       Visit(BO->getLHS());
14211       Visit(BO->getRHS());
14212     }
14213   }
14214 
14215   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14216   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14217   void VisitBinShlShr(const BinaryOperator *BO) {
14218     // C++17 [expr.shift]p4:
14219     //  The expression E1 is sequenced before the expression E2.
14220     if (SemaRef.getLangOpts().CPlusPlus17)
14221       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14222     else {
14223       Visit(BO->getLHS());
14224       Visit(BO->getRHS());
14225     }
14226   }
14227 
14228   void VisitBinComma(const BinaryOperator *BO) {
14229     // C++11 [expr.comma]p1:
14230     //   Every value computation and side effect associated with the left
14231     //   expression is sequenced before every value computation and side
14232     //   effect associated with the right expression.
14233     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14234   }
14235 
14236   void VisitBinAssign(const BinaryOperator *BO) {
14237     SequenceTree::Seq RHSRegion;
14238     SequenceTree::Seq LHSRegion;
14239     if (SemaRef.getLangOpts().CPlusPlus17) {
14240       RHSRegion = Tree.allocate(Region);
14241       LHSRegion = Tree.allocate(Region);
14242     } else {
14243       RHSRegion = Region;
14244       LHSRegion = Region;
14245     }
14246     SequenceTree::Seq OldRegion = Region;
14247 
14248     // C++11 [expr.ass]p1:
14249     //  [...] the assignment is sequenced after the value computation
14250     //  of the right and left operands, [...]
14251     //
14252     // so check it before inspecting the operands and update the
14253     // map afterwards.
14254     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14255     if (O)
14256       notePreMod(O, BO);
14257 
14258     if (SemaRef.getLangOpts().CPlusPlus17) {
14259       // C++17 [expr.ass]p1:
14260       //  [...] The right operand is sequenced before the left operand. [...]
14261       {
14262         SequencedSubexpression SeqBefore(*this);
14263         Region = RHSRegion;
14264         Visit(BO->getRHS());
14265       }
14266 
14267       Region = LHSRegion;
14268       Visit(BO->getLHS());
14269 
14270       if (O && isa<CompoundAssignOperator>(BO))
14271         notePostUse(O, BO);
14272 
14273     } else {
14274       // C++11 does not specify any sequencing between the LHS and RHS.
14275       Region = LHSRegion;
14276       Visit(BO->getLHS());
14277 
14278       if (O && isa<CompoundAssignOperator>(BO))
14279         notePostUse(O, BO);
14280 
14281       Region = RHSRegion;
14282       Visit(BO->getRHS());
14283     }
14284 
14285     // C++11 [expr.ass]p1:
14286     //  the assignment is sequenced [...] before the value computation of the
14287     //  assignment expression.
14288     // C11 6.5.16/3 has no such rule.
14289     Region = OldRegion;
14290     if (O)
14291       notePostMod(O, BO,
14292                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14293                                                   : UK_ModAsSideEffect);
14294     if (SemaRef.getLangOpts().CPlusPlus17) {
14295       Tree.merge(RHSRegion);
14296       Tree.merge(LHSRegion);
14297     }
14298   }
14299 
14300   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14301     VisitBinAssign(CAO);
14302   }
14303 
14304   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14305   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14306   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14307     Object O = getObject(UO->getSubExpr(), true);
14308     if (!O)
14309       return VisitExpr(UO);
14310 
14311     notePreMod(O, UO);
14312     Visit(UO->getSubExpr());
14313     // C++11 [expr.pre.incr]p1:
14314     //   the expression ++x is equivalent to x+=1
14315     notePostMod(O, UO,
14316                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14317                                                 : UK_ModAsSideEffect);
14318   }
14319 
14320   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14321   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14322   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14323     Object O = getObject(UO->getSubExpr(), true);
14324     if (!O)
14325       return VisitExpr(UO);
14326 
14327     notePreMod(O, UO);
14328     Visit(UO->getSubExpr());
14329     notePostMod(O, UO, UK_ModAsSideEffect);
14330   }
14331 
14332   void VisitBinLOr(const BinaryOperator *BO) {
14333     // C++11 [expr.log.or]p2:
14334     //  If the second expression is evaluated, every value computation and
14335     //  side effect associated with the first expression is sequenced before
14336     //  every value computation and side effect associated with the
14337     //  second expression.
14338     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14339     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14340     SequenceTree::Seq OldRegion = Region;
14341 
14342     EvaluationTracker Eval(*this);
14343     {
14344       SequencedSubexpression Sequenced(*this);
14345       Region = LHSRegion;
14346       Visit(BO->getLHS());
14347     }
14348 
14349     // C++11 [expr.log.or]p1:
14350     //  [...] the second operand is not evaluated if the first operand
14351     //  evaluates to true.
14352     bool EvalResult = false;
14353     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14354     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14355     if (ShouldVisitRHS) {
14356       Region = RHSRegion;
14357       Visit(BO->getRHS());
14358     }
14359 
14360     Region = OldRegion;
14361     Tree.merge(LHSRegion);
14362     Tree.merge(RHSRegion);
14363   }
14364 
14365   void VisitBinLAnd(const BinaryOperator *BO) {
14366     // C++11 [expr.log.and]p2:
14367     //  If the second expression is evaluated, every value computation and
14368     //  side effect associated with the first expression is sequenced before
14369     //  every value computation and side effect associated with the
14370     //  second expression.
14371     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14372     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14373     SequenceTree::Seq OldRegion = Region;
14374 
14375     EvaluationTracker Eval(*this);
14376     {
14377       SequencedSubexpression Sequenced(*this);
14378       Region = LHSRegion;
14379       Visit(BO->getLHS());
14380     }
14381 
14382     // C++11 [expr.log.and]p1:
14383     //  [...] the second operand is not evaluated if the first operand is false.
14384     bool EvalResult = false;
14385     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14386     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14387     if (ShouldVisitRHS) {
14388       Region = RHSRegion;
14389       Visit(BO->getRHS());
14390     }
14391 
14392     Region = OldRegion;
14393     Tree.merge(LHSRegion);
14394     Tree.merge(RHSRegion);
14395   }
14396 
14397   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14398     // C++11 [expr.cond]p1:
14399     //  [...] Every value computation and side effect associated with the first
14400     //  expression is sequenced before every value computation and side effect
14401     //  associated with the second or third expression.
14402     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14403 
14404     // No sequencing is specified between the true and false expression.
14405     // However since exactly one of both is going to be evaluated we can
14406     // consider them to be sequenced. This is needed to avoid warning on
14407     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14408     // both the true and false expressions because we can't evaluate x.
14409     // This will still allow us to detect an expression like (pre C++17)
14410     // "(x ? y += 1 : y += 2) = y".
14411     //
14412     // We don't wrap the visitation of the true and false expression with
14413     // SequencedSubexpression because we don't want to downgrade modifications
14414     // as side effect in the true and false expressions after the visition
14415     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14416     // not warn between the two "y++", but we should warn between the "y++"
14417     // and the "y".
14418     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14419     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14420     SequenceTree::Seq OldRegion = Region;
14421 
14422     EvaluationTracker Eval(*this);
14423     {
14424       SequencedSubexpression Sequenced(*this);
14425       Region = ConditionRegion;
14426       Visit(CO->getCond());
14427     }
14428 
14429     // C++11 [expr.cond]p1:
14430     // [...] The first expression is contextually converted to bool (Clause 4).
14431     // It is evaluated and if it is true, the result of the conditional
14432     // expression is the value of the second expression, otherwise that of the
14433     // third expression. Only one of the second and third expressions is
14434     // evaluated. [...]
14435     bool EvalResult = false;
14436     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14437     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14438     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14439     if (ShouldVisitTrueExpr) {
14440       Region = TrueRegion;
14441       Visit(CO->getTrueExpr());
14442     }
14443     if (ShouldVisitFalseExpr) {
14444       Region = FalseRegion;
14445       Visit(CO->getFalseExpr());
14446     }
14447 
14448     Region = OldRegion;
14449     Tree.merge(ConditionRegion);
14450     Tree.merge(TrueRegion);
14451     Tree.merge(FalseRegion);
14452   }
14453 
14454   void VisitCallExpr(const CallExpr *CE) {
14455     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14456 
14457     if (CE->isUnevaluatedBuiltinCall(Context))
14458       return;
14459 
14460     // C++11 [intro.execution]p15:
14461     //   When calling a function [...], every value computation and side effect
14462     //   associated with any argument expression, or with the postfix expression
14463     //   designating the called function, is sequenced before execution of every
14464     //   expression or statement in the body of the function [and thus before
14465     //   the value computation of its result].
14466     SequencedSubexpression Sequenced(*this);
14467     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14468       // C++17 [expr.call]p5
14469       //   The postfix-expression is sequenced before each expression in the
14470       //   expression-list and any default argument. [...]
14471       SequenceTree::Seq CalleeRegion;
14472       SequenceTree::Seq OtherRegion;
14473       if (SemaRef.getLangOpts().CPlusPlus17) {
14474         CalleeRegion = Tree.allocate(Region);
14475         OtherRegion = Tree.allocate(Region);
14476       } else {
14477         CalleeRegion = Region;
14478         OtherRegion = Region;
14479       }
14480       SequenceTree::Seq OldRegion = Region;
14481 
14482       // Visit the callee expression first.
14483       Region = CalleeRegion;
14484       if (SemaRef.getLangOpts().CPlusPlus17) {
14485         SequencedSubexpression Sequenced(*this);
14486         Visit(CE->getCallee());
14487       } else {
14488         Visit(CE->getCallee());
14489       }
14490 
14491       // Then visit the argument expressions.
14492       Region = OtherRegion;
14493       for (const Expr *Argument : CE->arguments())
14494         Visit(Argument);
14495 
14496       Region = OldRegion;
14497       if (SemaRef.getLangOpts().CPlusPlus17) {
14498         Tree.merge(CalleeRegion);
14499         Tree.merge(OtherRegion);
14500       }
14501     });
14502   }
14503 
14504   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14505     // C++17 [over.match.oper]p2:
14506     //   [...] the operator notation is first transformed to the equivalent
14507     //   function-call notation as summarized in Table 12 (where @ denotes one
14508     //   of the operators covered in the specified subclause). However, the
14509     //   operands are sequenced in the order prescribed for the built-in
14510     //   operator (Clause 8).
14511     //
14512     // From the above only overloaded binary operators and overloaded call
14513     // operators have sequencing rules in C++17 that we need to handle
14514     // separately.
14515     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14516         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14517       return VisitCallExpr(CXXOCE);
14518 
14519     enum {
14520       NoSequencing,
14521       LHSBeforeRHS,
14522       RHSBeforeLHS,
14523       LHSBeforeRest
14524     } SequencingKind;
14525     switch (CXXOCE->getOperator()) {
14526     case OO_Equal:
14527     case OO_PlusEqual:
14528     case OO_MinusEqual:
14529     case OO_StarEqual:
14530     case OO_SlashEqual:
14531     case OO_PercentEqual:
14532     case OO_CaretEqual:
14533     case OO_AmpEqual:
14534     case OO_PipeEqual:
14535     case OO_LessLessEqual:
14536     case OO_GreaterGreaterEqual:
14537       SequencingKind = RHSBeforeLHS;
14538       break;
14539 
14540     case OO_LessLess:
14541     case OO_GreaterGreater:
14542     case OO_AmpAmp:
14543     case OO_PipePipe:
14544     case OO_Comma:
14545     case OO_ArrowStar:
14546     case OO_Subscript:
14547       SequencingKind = LHSBeforeRHS;
14548       break;
14549 
14550     case OO_Call:
14551       SequencingKind = LHSBeforeRest;
14552       break;
14553 
14554     default:
14555       SequencingKind = NoSequencing;
14556       break;
14557     }
14558 
14559     if (SequencingKind == NoSequencing)
14560       return VisitCallExpr(CXXOCE);
14561 
14562     // This is a call, so all subexpressions are sequenced before the result.
14563     SequencedSubexpression Sequenced(*this);
14564 
14565     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14566       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14567              "Should only get there with C++17 and above!");
14568       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14569              "Should only get there with an overloaded binary operator"
14570              " or an overloaded call operator!");
14571 
14572       if (SequencingKind == LHSBeforeRest) {
14573         assert(CXXOCE->getOperator() == OO_Call &&
14574                "We should only have an overloaded call operator here!");
14575 
14576         // This is very similar to VisitCallExpr, except that we only have the
14577         // C++17 case. The postfix-expression is the first argument of the
14578         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14579         // are in the following arguments.
14580         //
14581         // Note that we intentionally do not visit the callee expression since
14582         // it is just a decayed reference to a function.
14583         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14584         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14585         SequenceTree::Seq OldRegion = Region;
14586 
14587         assert(CXXOCE->getNumArgs() >= 1 &&
14588                "An overloaded call operator must have at least one argument"
14589                " for the postfix-expression!");
14590         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14591         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14592                                           CXXOCE->getNumArgs() - 1);
14593 
14594         // Visit the postfix-expression first.
14595         {
14596           Region = PostfixExprRegion;
14597           SequencedSubexpression Sequenced(*this);
14598           Visit(PostfixExpr);
14599         }
14600 
14601         // Then visit the argument expressions.
14602         Region = ArgsRegion;
14603         for (const Expr *Arg : Args)
14604           Visit(Arg);
14605 
14606         Region = OldRegion;
14607         Tree.merge(PostfixExprRegion);
14608         Tree.merge(ArgsRegion);
14609       } else {
14610         assert(CXXOCE->getNumArgs() == 2 &&
14611                "Should only have two arguments here!");
14612         assert((SequencingKind == LHSBeforeRHS ||
14613                 SequencingKind == RHSBeforeLHS) &&
14614                "Unexpected sequencing kind!");
14615 
14616         // We do not visit the callee expression since it is just a decayed
14617         // reference to a function.
14618         const Expr *E1 = CXXOCE->getArg(0);
14619         const Expr *E2 = CXXOCE->getArg(1);
14620         if (SequencingKind == RHSBeforeLHS)
14621           std::swap(E1, E2);
14622 
14623         return VisitSequencedExpressions(E1, E2);
14624       }
14625     });
14626   }
14627 
14628   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14629     // This is a call, so all subexpressions are sequenced before the result.
14630     SequencedSubexpression Sequenced(*this);
14631 
14632     if (!CCE->isListInitialization())
14633       return VisitExpr(CCE);
14634 
14635     // In C++11, list initializations are sequenced.
14636     SmallVector<SequenceTree::Seq, 32> Elts;
14637     SequenceTree::Seq Parent = Region;
14638     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14639                                               E = CCE->arg_end();
14640          I != E; ++I) {
14641       Region = Tree.allocate(Parent);
14642       Elts.push_back(Region);
14643       Visit(*I);
14644     }
14645 
14646     // Forget that the initializers are sequenced.
14647     Region = Parent;
14648     for (unsigned I = 0; I < Elts.size(); ++I)
14649       Tree.merge(Elts[I]);
14650   }
14651 
14652   void VisitInitListExpr(const InitListExpr *ILE) {
14653     if (!SemaRef.getLangOpts().CPlusPlus11)
14654       return VisitExpr(ILE);
14655 
14656     // In C++11, list initializations are sequenced.
14657     SmallVector<SequenceTree::Seq, 32> Elts;
14658     SequenceTree::Seq Parent = Region;
14659     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14660       const Expr *E = ILE->getInit(I);
14661       if (!E)
14662         continue;
14663       Region = Tree.allocate(Parent);
14664       Elts.push_back(Region);
14665       Visit(E);
14666     }
14667 
14668     // Forget that the initializers are sequenced.
14669     Region = Parent;
14670     for (unsigned I = 0; I < Elts.size(); ++I)
14671       Tree.merge(Elts[I]);
14672   }
14673 };
14674 
14675 } // namespace
14676 
14677 void Sema::CheckUnsequencedOperations(const Expr *E) {
14678   SmallVector<const Expr *, 8> WorkList;
14679   WorkList.push_back(E);
14680   while (!WorkList.empty()) {
14681     const Expr *Item = WorkList.pop_back_val();
14682     SequenceChecker(*this, Item, WorkList);
14683   }
14684 }
14685 
14686 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14687                               bool IsConstexpr) {
14688   llvm::SaveAndRestore<bool> ConstantContext(
14689       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14690   CheckImplicitConversions(E, CheckLoc);
14691   if (!E->isInstantiationDependent())
14692     CheckUnsequencedOperations(E);
14693   if (!IsConstexpr && !E->isValueDependent())
14694     CheckForIntOverflow(E);
14695   DiagnoseMisalignedMembers();
14696 }
14697 
14698 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14699                                        FieldDecl *BitField,
14700                                        Expr *Init) {
14701   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14702 }
14703 
14704 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14705                                          SourceLocation Loc) {
14706   if (!PType->isVariablyModifiedType())
14707     return;
14708   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14709     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14710     return;
14711   }
14712   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14713     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14714     return;
14715   }
14716   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14717     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14718     return;
14719   }
14720 
14721   const ArrayType *AT = S.Context.getAsArrayType(PType);
14722   if (!AT)
14723     return;
14724 
14725   if (AT->getSizeModifier() != ArrayType::Star) {
14726     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14727     return;
14728   }
14729 
14730   S.Diag(Loc, diag::err_array_star_in_function_definition);
14731 }
14732 
14733 /// CheckParmsForFunctionDef - Check that the parameters of the given
14734 /// function are appropriate for the definition of a function. This
14735 /// takes care of any checks that cannot be performed on the
14736 /// declaration itself, e.g., that the types of each of the function
14737 /// parameters are complete.
14738 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14739                                     bool CheckParameterNames) {
14740   bool HasInvalidParm = false;
14741   for (ParmVarDecl *Param : Parameters) {
14742     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14743     // function declarator that is part of a function definition of
14744     // that function shall not have incomplete type.
14745     //
14746     // This is also C++ [dcl.fct]p6.
14747     if (!Param->isInvalidDecl() &&
14748         RequireCompleteType(Param->getLocation(), Param->getType(),
14749                             diag::err_typecheck_decl_incomplete_type)) {
14750       Param->setInvalidDecl();
14751       HasInvalidParm = true;
14752     }
14753 
14754     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14755     // declaration of each parameter shall include an identifier.
14756     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14757         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14758       // Diagnose this as an extension in C17 and earlier.
14759       if (!getLangOpts().C2x)
14760         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14761     }
14762 
14763     // C99 6.7.5.3p12:
14764     //   If the function declarator is not part of a definition of that
14765     //   function, parameters may have incomplete type and may use the [*]
14766     //   notation in their sequences of declarator specifiers to specify
14767     //   variable length array types.
14768     QualType PType = Param->getOriginalType();
14769     // FIXME: This diagnostic should point the '[*]' if source-location
14770     // information is added for it.
14771     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14772 
14773     // If the parameter is a c++ class type and it has to be destructed in the
14774     // callee function, declare the destructor so that it can be called by the
14775     // callee function. Do not perform any direct access check on the dtor here.
14776     if (!Param->isInvalidDecl()) {
14777       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14778         if (!ClassDecl->isInvalidDecl() &&
14779             !ClassDecl->hasIrrelevantDestructor() &&
14780             !ClassDecl->isDependentContext() &&
14781             ClassDecl->isParamDestroyedInCallee()) {
14782           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14783           MarkFunctionReferenced(Param->getLocation(), Destructor);
14784           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14785         }
14786       }
14787     }
14788 
14789     // Parameters with the pass_object_size attribute only need to be marked
14790     // constant at function definitions. Because we lack information about
14791     // whether we're on a declaration or definition when we're instantiating the
14792     // attribute, we need to check for constness here.
14793     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14794       if (!Param->getType().isConstQualified())
14795         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14796             << Attr->getSpelling() << 1;
14797 
14798     // Check for parameter names shadowing fields from the class.
14799     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14800       // The owning context for the parameter should be the function, but we
14801       // want to see if this function's declaration context is a record.
14802       DeclContext *DC = Param->getDeclContext();
14803       if (DC && DC->isFunctionOrMethod()) {
14804         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14805           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14806                                      RD, /*DeclIsField*/ false);
14807       }
14808     }
14809   }
14810 
14811   return HasInvalidParm;
14812 }
14813 
14814 Optional<std::pair<CharUnits, CharUnits>>
14815 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14816 
14817 /// Compute the alignment and offset of the base class object given the
14818 /// derived-to-base cast expression and the alignment and offset of the derived
14819 /// class object.
14820 static std::pair<CharUnits, CharUnits>
14821 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14822                                    CharUnits BaseAlignment, CharUnits Offset,
14823                                    ASTContext &Ctx) {
14824   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14825        ++PathI) {
14826     const CXXBaseSpecifier *Base = *PathI;
14827     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14828     if (Base->isVirtual()) {
14829       // The complete object may have a lower alignment than the non-virtual
14830       // alignment of the base, in which case the base may be misaligned. Choose
14831       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14832       // conservative lower bound of the complete object alignment.
14833       CharUnits NonVirtualAlignment =
14834           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14835       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14836       Offset = CharUnits::Zero();
14837     } else {
14838       const ASTRecordLayout &RL =
14839           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14840       Offset += RL.getBaseClassOffset(BaseDecl);
14841     }
14842     DerivedType = Base->getType();
14843   }
14844 
14845   return std::make_pair(BaseAlignment, Offset);
14846 }
14847 
14848 /// Compute the alignment and offset of a binary additive operator.
14849 static Optional<std::pair<CharUnits, CharUnits>>
14850 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14851                                      bool IsSub, ASTContext &Ctx) {
14852   QualType PointeeType = PtrE->getType()->getPointeeType();
14853 
14854   if (!PointeeType->isConstantSizeType())
14855     return llvm::None;
14856 
14857   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14858 
14859   if (!P)
14860     return llvm::None;
14861 
14862   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14863   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14864     CharUnits Offset = EltSize * IdxRes->getExtValue();
14865     if (IsSub)
14866       Offset = -Offset;
14867     return std::make_pair(P->first, P->second + Offset);
14868   }
14869 
14870   // If the integer expression isn't a constant expression, compute the lower
14871   // bound of the alignment using the alignment and offset of the pointer
14872   // expression and the element size.
14873   return std::make_pair(
14874       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14875       CharUnits::Zero());
14876 }
14877 
14878 /// This helper function takes an lvalue expression and returns the alignment of
14879 /// a VarDecl and a constant offset from the VarDecl.
14880 Optional<std::pair<CharUnits, CharUnits>>
14881 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14882   E = E->IgnoreParens();
14883   switch (E->getStmtClass()) {
14884   default:
14885     break;
14886   case Stmt::CStyleCastExprClass:
14887   case Stmt::CXXStaticCastExprClass:
14888   case Stmt::ImplicitCastExprClass: {
14889     auto *CE = cast<CastExpr>(E);
14890     const Expr *From = CE->getSubExpr();
14891     switch (CE->getCastKind()) {
14892     default:
14893       break;
14894     case CK_NoOp:
14895       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14896     case CK_UncheckedDerivedToBase:
14897     case CK_DerivedToBase: {
14898       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14899       if (!P)
14900         break;
14901       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14902                                                 P->second, Ctx);
14903     }
14904     }
14905     break;
14906   }
14907   case Stmt::ArraySubscriptExprClass: {
14908     auto *ASE = cast<ArraySubscriptExpr>(E);
14909     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14910                                                 false, Ctx);
14911   }
14912   case Stmt::DeclRefExprClass: {
14913     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14914       // FIXME: If VD is captured by copy or is an escaping __block variable,
14915       // use the alignment of VD's type.
14916       if (!VD->getType()->isReferenceType())
14917         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14918       if (VD->hasInit())
14919         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14920     }
14921     break;
14922   }
14923   case Stmt::MemberExprClass: {
14924     auto *ME = cast<MemberExpr>(E);
14925     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14926     if (!FD || FD->getType()->isReferenceType() ||
14927         FD->getParent()->isInvalidDecl())
14928       break;
14929     Optional<std::pair<CharUnits, CharUnits>> P;
14930     if (ME->isArrow())
14931       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14932     else
14933       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14934     if (!P)
14935       break;
14936     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14937     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14938     return std::make_pair(P->first,
14939                           P->second + CharUnits::fromQuantity(Offset));
14940   }
14941   case Stmt::UnaryOperatorClass: {
14942     auto *UO = cast<UnaryOperator>(E);
14943     switch (UO->getOpcode()) {
14944     default:
14945       break;
14946     case UO_Deref:
14947       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14948     }
14949     break;
14950   }
14951   case Stmt::BinaryOperatorClass: {
14952     auto *BO = cast<BinaryOperator>(E);
14953     auto Opcode = BO->getOpcode();
14954     switch (Opcode) {
14955     default:
14956       break;
14957     case BO_Comma:
14958       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14959     }
14960     break;
14961   }
14962   }
14963   return llvm::None;
14964 }
14965 
14966 /// This helper function takes a pointer expression and returns the alignment of
14967 /// a VarDecl and a constant offset from the VarDecl.
14968 Optional<std::pair<CharUnits, CharUnits>>
14969 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14970   E = E->IgnoreParens();
14971   switch (E->getStmtClass()) {
14972   default:
14973     break;
14974   case Stmt::CStyleCastExprClass:
14975   case Stmt::CXXStaticCastExprClass:
14976   case Stmt::ImplicitCastExprClass: {
14977     auto *CE = cast<CastExpr>(E);
14978     const Expr *From = CE->getSubExpr();
14979     switch (CE->getCastKind()) {
14980     default:
14981       break;
14982     case CK_NoOp:
14983       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14984     case CK_ArrayToPointerDecay:
14985       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14986     case CK_UncheckedDerivedToBase:
14987     case CK_DerivedToBase: {
14988       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14989       if (!P)
14990         break;
14991       return getDerivedToBaseAlignmentAndOffset(
14992           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14993     }
14994     }
14995     break;
14996   }
14997   case Stmt::CXXThisExprClass: {
14998     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14999     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15000     return std::make_pair(Alignment, CharUnits::Zero());
15001   }
15002   case Stmt::UnaryOperatorClass: {
15003     auto *UO = cast<UnaryOperator>(E);
15004     if (UO->getOpcode() == UO_AddrOf)
15005       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15006     break;
15007   }
15008   case Stmt::BinaryOperatorClass: {
15009     auto *BO = cast<BinaryOperator>(E);
15010     auto Opcode = BO->getOpcode();
15011     switch (Opcode) {
15012     default:
15013       break;
15014     case BO_Add:
15015     case BO_Sub: {
15016       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15017       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15018         std::swap(LHS, RHS);
15019       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15020                                                   Ctx);
15021     }
15022     case BO_Comma:
15023       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15024     }
15025     break;
15026   }
15027   }
15028   return llvm::None;
15029 }
15030 
15031 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15032   // See if we can compute the alignment of a VarDecl and an offset from it.
15033   Optional<std::pair<CharUnits, CharUnits>> P =
15034       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15035 
15036   if (P)
15037     return P->first.alignmentAtOffset(P->second);
15038 
15039   // If that failed, return the type's alignment.
15040   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15041 }
15042 
15043 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15044 /// pointer cast increases the alignment requirements.
15045 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15046   // This is actually a lot of work to potentially be doing on every
15047   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15048   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15049     return;
15050 
15051   // Ignore dependent types.
15052   if (T->isDependentType() || Op->getType()->isDependentType())
15053     return;
15054 
15055   // Require that the destination be a pointer type.
15056   const PointerType *DestPtr = T->getAs<PointerType>();
15057   if (!DestPtr) return;
15058 
15059   // If the destination has alignment 1, we're done.
15060   QualType DestPointee = DestPtr->getPointeeType();
15061   if (DestPointee->isIncompleteType()) return;
15062   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15063   if (DestAlign.isOne()) return;
15064 
15065   // Require that the source be a pointer type.
15066   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15067   if (!SrcPtr) return;
15068   QualType SrcPointee = SrcPtr->getPointeeType();
15069 
15070   // Explicitly allow casts from cv void*.  We already implicitly
15071   // allowed casts to cv void*, since they have alignment 1.
15072   // Also allow casts involving incomplete types, which implicitly
15073   // includes 'void'.
15074   if (SrcPointee->isIncompleteType()) return;
15075 
15076   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15077 
15078   if (SrcAlign >= DestAlign) return;
15079 
15080   Diag(TRange.getBegin(), diag::warn_cast_align)
15081     << Op->getType() << T
15082     << static_cast<unsigned>(SrcAlign.getQuantity())
15083     << static_cast<unsigned>(DestAlign.getQuantity())
15084     << TRange << Op->getSourceRange();
15085 }
15086 
15087 /// Check whether this array fits the idiom of a size-one tail padded
15088 /// array member of a struct.
15089 ///
15090 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15091 /// commonly used to emulate flexible arrays in C89 code.
15092 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15093                                     const NamedDecl *ND) {
15094   if (Size != 1 || !ND) return false;
15095 
15096   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15097   if (!FD) return false;
15098 
15099   // Don't consider sizes resulting from macro expansions or template argument
15100   // substitution to form C89 tail-padded arrays.
15101 
15102   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15103   while (TInfo) {
15104     TypeLoc TL = TInfo->getTypeLoc();
15105     // Look through typedefs.
15106     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15107       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15108       TInfo = TDL->getTypeSourceInfo();
15109       continue;
15110     }
15111     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15112       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15113       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15114         return false;
15115     }
15116     break;
15117   }
15118 
15119   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15120   if (!RD) return false;
15121   if (RD->isUnion()) return false;
15122   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15123     if (!CRD->isStandardLayout()) return false;
15124   }
15125 
15126   // See if this is the last field decl in the record.
15127   const Decl *D = FD;
15128   while ((D = D->getNextDeclInContext()))
15129     if (isa<FieldDecl>(D))
15130       return false;
15131   return true;
15132 }
15133 
15134 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15135                             const ArraySubscriptExpr *ASE,
15136                             bool AllowOnePastEnd, bool IndexNegated) {
15137   // Already diagnosed by the constant evaluator.
15138   if (isConstantEvaluated())
15139     return;
15140 
15141   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15142   if (IndexExpr->isValueDependent())
15143     return;
15144 
15145   const Type *EffectiveType =
15146       BaseExpr->getType()->getPointeeOrArrayElementType();
15147   BaseExpr = BaseExpr->IgnoreParenCasts();
15148   const ConstantArrayType *ArrayTy =
15149       Context.getAsConstantArrayType(BaseExpr->getType());
15150 
15151   const Type *BaseType =
15152       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15153   bool IsUnboundedArray = (BaseType == nullptr);
15154   if (EffectiveType->isDependentType() ||
15155       (!IsUnboundedArray && BaseType->isDependentType()))
15156     return;
15157 
15158   Expr::EvalResult Result;
15159   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15160     return;
15161 
15162   llvm::APSInt index = Result.Val.getInt();
15163   if (IndexNegated) {
15164     index.setIsUnsigned(false);
15165     index = -index;
15166   }
15167 
15168   const NamedDecl *ND = nullptr;
15169   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15170     ND = DRE->getDecl();
15171   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15172     ND = ME->getMemberDecl();
15173 
15174   if (IsUnboundedArray) {
15175     if (index.isUnsigned() || !index.isNegative()) {
15176       const auto &ASTC = getASTContext();
15177       unsigned AddrBits =
15178           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15179               EffectiveType->getCanonicalTypeInternal()));
15180       if (index.getBitWidth() < AddrBits)
15181         index = index.zext(AddrBits);
15182       Optional<CharUnits> ElemCharUnits =
15183           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15184       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15185       // pointer) bounds-checking isn't meaningful.
15186       if (!ElemCharUnits)
15187         return;
15188       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15189       // If index has more active bits than address space, we already know
15190       // we have a bounds violation to warn about.  Otherwise, compute
15191       // address of (index + 1)th element, and warn about bounds violation
15192       // only if that address exceeds address space.
15193       if (index.getActiveBits() <= AddrBits) {
15194         bool Overflow;
15195         llvm::APInt Product(index);
15196         Product += 1;
15197         Product = Product.umul_ov(ElemBytes, Overflow);
15198         if (!Overflow && Product.getActiveBits() <= AddrBits)
15199           return;
15200       }
15201 
15202       // Need to compute max possible elements in address space, since that
15203       // is included in diag message.
15204       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15205       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15206       MaxElems += 1;
15207       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15208       MaxElems = MaxElems.udiv(ElemBytes);
15209 
15210       unsigned DiagID =
15211           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15212               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15213 
15214       // Diag message shows element size in bits and in "bytes" (platform-
15215       // dependent CharUnits)
15216       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15217                           PDiag(DiagID)
15218                               << toString(index, 10, true) << AddrBits
15219                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15220                               << toString(ElemBytes, 10, false)
15221                               << toString(MaxElems, 10, false)
15222                               << (unsigned)MaxElems.getLimitedValue(~0U)
15223                               << IndexExpr->getSourceRange());
15224 
15225       if (!ND) {
15226         // Try harder to find a NamedDecl to point at in the note.
15227         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15228           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15229         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15230           ND = DRE->getDecl();
15231         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15232           ND = ME->getMemberDecl();
15233       }
15234 
15235       if (ND)
15236         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15237                             PDiag(diag::note_array_declared_here) << ND);
15238     }
15239     return;
15240   }
15241 
15242   if (index.isUnsigned() || !index.isNegative()) {
15243     // It is possible that the type of the base expression after
15244     // IgnoreParenCasts is incomplete, even though the type of the base
15245     // expression before IgnoreParenCasts is complete (see PR39746 for an
15246     // example). In this case we have no information about whether the array
15247     // access exceeds the array bounds. However we can still diagnose an array
15248     // access which precedes the array bounds.
15249     if (BaseType->isIncompleteType())
15250       return;
15251 
15252     llvm::APInt size = ArrayTy->getSize();
15253     if (!size.isStrictlyPositive())
15254       return;
15255 
15256     if (BaseType != EffectiveType) {
15257       // Make sure we're comparing apples to apples when comparing index to size
15258       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15259       uint64_t array_typesize = Context.getTypeSize(BaseType);
15260       // Handle ptrarith_typesize being zero, such as when casting to void*
15261       if (!ptrarith_typesize) ptrarith_typesize = 1;
15262       if (ptrarith_typesize != array_typesize) {
15263         // There's a cast to a different size type involved
15264         uint64_t ratio = array_typesize / ptrarith_typesize;
15265         // TODO: Be smarter about handling cases where array_typesize is not a
15266         // multiple of ptrarith_typesize
15267         if (ptrarith_typesize * ratio == array_typesize)
15268           size *= llvm::APInt(size.getBitWidth(), ratio);
15269       }
15270     }
15271 
15272     if (size.getBitWidth() > index.getBitWidth())
15273       index = index.zext(size.getBitWidth());
15274     else if (size.getBitWidth() < index.getBitWidth())
15275       size = size.zext(index.getBitWidth());
15276 
15277     // For array subscripting the index must be less than size, but for pointer
15278     // arithmetic also allow the index (offset) to be equal to size since
15279     // computing the next address after the end of the array is legal and
15280     // commonly done e.g. in C++ iterators and range-based for loops.
15281     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15282       return;
15283 
15284     // Also don't warn for arrays of size 1 which are members of some
15285     // structure. These are often used to approximate flexible arrays in C89
15286     // code.
15287     if (IsTailPaddedMemberArray(*this, size, ND))
15288       return;
15289 
15290     // Suppress the warning if the subscript expression (as identified by the
15291     // ']' location) and the index expression are both from macro expansions
15292     // within a system header.
15293     if (ASE) {
15294       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15295           ASE->getRBracketLoc());
15296       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15297         SourceLocation IndexLoc =
15298             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15299         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15300           return;
15301       }
15302     }
15303 
15304     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15305                           : diag::warn_ptr_arith_exceeds_bounds;
15306 
15307     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15308                         PDiag(DiagID) << toString(index, 10, true)
15309                                       << toString(size, 10, true)
15310                                       << (unsigned)size.getLimitedValue(~0U)
15311                                       << IndexExpr->getSourceRange());
15312   } else {
15313     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15314     if (!ASE) {
15315       DiagID = diag::warn_ptr_arith_precedes_bounds;
15316       if (index.isNegative()) index = -index;
15317     }
15318 
15319     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15320                         PDiag(DiagID) << toString(index, 10, true)
15321                                       << IndexExpr->getSourceRange());
15322   }
15323 
15324   if (!ND) {
15325     // Try harder to find a NamedDecl to point at in the note.
15326     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15327       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15328     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15329       ND = DRE->getDecl();
15330     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15331       ND = ME->getMemberDecl();
15332   }
15333 
15334   if (ND)
15335     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15336                         PDiag(diag::note_array_declared_here) << ND);
15337 }
15338 
15339 void Sema::CheckArrayAccess(const Expr *expr) {
15340   int AllowOnePastEnd = 0;
15341   while (expr) {
15342     expr = expr->IgnoreParenImpCasts();
15343     switch (expr->getStmtClass()) {
15344       case Stmt::ArraySubscriptExprClass: {
15345         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15346         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15347                          AllowOnePastEnd > 0);
15348         expr = ASE->getBase();
15349         break;
15350       }
15351       case Stmt::MemberExprClass: {
15352         expr = cast<MemberExpr>(expr)->getBase();
15353         break;
15354       }
15355       case Stmt::OMPArraySectionExprClass: {
15356         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15357         if (ASE->getLowerBound())
15358           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15359                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15360         return;
15361       }
15362       case Stmt::UnaryOperatorClass: {
15363         // Only unwrap the * and & unary operators
15364         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15365         expr = UO->getSubExpr();
15366         switch (UO->getOpcode()) {
15367           case UO_AddrOf:
15368             AllowOnePastEnd++;
15369             break;
15370           case UO_Deref:
15371             AllowOnePastEnd--;
15372             break;
15373           default:
15374             return;
15375         }
15376         break;
15377       }
15378       case Stmt::ConditionalOperatorClass: {
15379         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15380         if (const Expr *lhs = cond->getLHS())
15381           CheckArrayAccess(lhs);
15382         if (const Expr *rhs = cond->getRHS())
15383           CheckArrayAccess(rhs);
15384         return;
15385       }
15386       case Stmt::CXXOperatorCallExprClass: {
15387         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15388         for (const auto *Arg : OCE->arguments())
15389           CheckArrayAccess(Arg);
15390         return;
15391       }
15392       default:
15393         return;
15394     }
15395   }
15396 }
15397 
15398 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15399 
15400 namespace {
15401 
15402 struct RetainCycleOwner {
15403   VarDecl *Variable = nullptr;
15404   SourceRange Range;
15405   SourceLocation Loc;
15406   bool Indirect = false;
15407 
15408   RetainCycleOwner() = default;
15409 
15410   void setLocsFrom(Expr *e) {
15411     Loc = e->getExprLoc();
15412     Range = e->getSourceRange();
15413   }
15414 };
15415 
15416 } // namespace
15417 
15418 /// Consider whether capturing the given variable can possibly lead to
15419 /// a retain cycle.
15420 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15421   // In ARC, it's captured strongly iff the variable has __strong
15422   // lifetime.  In MRR, it's captured strongly if the variable is
15423   // __block and has an appropriate type.
15424   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15425     return false;
15426 
15427   owner.Variable = var;
15428   if (ref)
15429     owner.setLocsFrom(ref);
15430   return true;
15431 }
15432 
15433 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15434   while (true) {
15435     e = e->IgnoreParens();
15436     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15437       switch (cast->getCastKind()) {
15438       case CK_BitCast:
15439       case CK_LValueBitCast:
15440       case CK_LValueToRValue:
15441       case CK_ARCReclaimReturnedObject:
15442         e = cast->getSubExpr();
15443         continue;
15444 
15445       default:
15446         return false;
15447       }
15448     }
15449 
15450     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15451       ObjCIvarDecl *ivar = ref->getDecl();
15452       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15453         return false;
15454 
15455       // Try to find a retain cycle in the base.
15456       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15457         return false;
15458 
15459       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15460       owner.Indirect = true;
15461       return true;
15462     }
15463 
15464     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15465       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15466       if (!var) return false;
15467       return considerVariable(var, ref, owner);
15468     }
15469 
15470     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15471       if (member->isArrow()) return false;
15472 
15473       // Don't count this as an indirect ownership.
15474       e = member->getBase();
15475       continue;
15476     }
15477 
15478     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15479       // Only pay attention to pseudo-objects on property references.
15480       ObjCPropertyRefExpr *pre
15481         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15482                                               ->IgnoreParens());
15483       if (!pre) return false;
15484       if (pre->isImplicitProperty()) return false;
15485       ObjCPropertyDecl *property = pre->getExplicitProperty();
15486       if (!property->isRetaining() &&
15487           !(property->getPropertyIvarDecl() &&
15488             property->getPropertyIvarDecl()->getType()
15489               .getObjCLifetime() == Qualifiers::OCL_Strong))
15490           return false;
15491 
15492       owner.Indirect = true;
15493       if (pre->isSuperReceiver()) {
15494         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15495         if (!owner.Variable)
15496           return false;
15497         owner.Loc = pre->getLocation();
15498         owner.Range = pre->getSourceRange();
15499         return true;
15500       }
15501       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15502                               ->getSourceExpr());
15503       continue;
15504     }
15505 
15506     // Array ivars?
15507 
15508     return false;
15509   }
15510 }
15511 
15512 namespace {
15513 
15514   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15515     ASTContext &Context;
15516     VarDecl *Variable;
15517     Expr *Capturer = nullptr;
15518     bool VarWillBeReased = false;
15519 
15520     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15521         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15522           Context(Context), Variable(variable) {}
15523 
15524     void VisitDeclRefExpr(DeclRefExpr *ref) {
15525       if (ref->getDecl() == Variable && !Capturer)
15526         Capturer = ref;
15527     }
15528 
15529     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15530       if (Capturer) return;
15531       Visit(ref->getBase());
15532       if (Capturer && ref->isFreeIvar())
15533         Capturer = ref;
15534     }
15535 
15536     void VisitBlockExpr(BlockExpr *block) {
15537       // Look inside nested blocks
15538       if (block->getBlockDecl()->capturesVariable(Variable))
15539         Visit(block->getBlockDecl()->getBody());
15540     }
15541 
15542     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15543       if (Capturer) return;
15544       if (OVE->getSourceExpr())
15545         Visit(OVE->getSourceExpr());
15546     }
15547 
15548     void VisitBinaryOperator(BinaryOperator *BinOp) {
15549       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15550         return;
15551       Expr *LHS = BinOp->getLHS();
15552       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15553         if (DRE->getDecl() != Variable)
15554           return;
15555         if (Expr *RHS = BinOp->getRHS()) {
15556           RHS = RHS->IgnoreParenCasts();
15557           Optional<llvm::APSInt> Value;
15558           VarWillBeReased =
15559               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15560                *Value == 0);
15561         }
15562       }
15563     }
15564   };
15565 
15566 } // namespace
15567 
15568 /// Check whether the given argument is a block which captures a
15569 /// variable.
15570 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15571   assert(owner.Variable && owner.Loc.isValid());
15572 
15573   e = e->IgnoreParenCasts();
15574 
15575   // Look through [^{...} copy] and Block_copy(^{...}).
15576   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15577     Selector Cmd = ME->getSelector();
15578     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15579       e = ME->getInstanceReceiver();
15580       if (!e)
15581         return nullptr;
15582       e = e->IgnoreParenCasts();
15583     }
15584   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15585     if (CE->getNumArgs() == 1) {
15586       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15587       if (Fn) {
15588         const IdentifierInfo *FnI = Fn->getIdentifier();
15589         if (FnI && FnI->isStr("_Block_copy")) {
15590           e = CE->getArg(0)->IgnoreParenCasts();
15591         }
15592       }
15593     }
15594   }
15595 
15596   BlockExpr *block = dyn_cast<BlockExpr>(e);
15597   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15598     return nullptr;
15599 
15600   FindCaptureVisitor visitor(S.Context, owner.Variable);
15601   visitor.Visit(block->getBlockDecl()->getBody());
15602   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15603 }
15604 
15605 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15606                                 RetainCycleOwner &owner) {
15607   assert(capturer);
15608   assert(owner.Variable && owner.Loc.isValid());
15609 
15610   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15611     << owner.Variable << capturer->getSourceRange();
15612   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15613     << owner.Indirect << owner.Range;
15614 }
15615 
15616 /// Check for a keyword selector that starts with the word 'add' or
15617 /// 'set'.
15618 static bool isSetterLikeSelector(Selector sel) {
15619   if (sel.isUnarySelector()) return false;
15620 
15621   StringRef str = sel.getNameForSlot(0);
15622   while (!str.empty() && str.front() == '_') str = str.substr(1);
15623   if (str.startswith("set"))
15624     str = str.substr(3);
15625   else if (str.startswith("add")) {
15626     // Specially allow 'addOperationWithBlock:'.
15627     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15628       return false;
15629     str = str.substr(3);
15630   }
15631   else
15632     return false;
15633 
15634   if (str.empty()) return true;
15635   return !isLowercase(str.front());
15636 }
15637 
15638 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15639                                                     ObjCMessageExpr *Message) {
15640   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15641                                                 Message->getReceiverInterface(),
15642                                                 NSAPI::ClassId_NSMutableArray);
15643   if (!IsMutableArray) {
15644     return None;
15645   }
15646 
15647   Selector Sel = Message->getSelector();
15648 
15649   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15650     S.NSAPIObj->getNSArrayMethodKind(Sel);
15651   if (!MKOpt) {
15652     return None;
15653   }
15654 
15655   NSAPI::NSArrayMethodKind MK = *MKOpt;
15656 
15657   switch (MK) {
15658     case NSAPI::NSMutableArr_addObject:
15659     case NSAPI::NSMutableArr_insertObjectAtIndex:
15660     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15661       return 0;
15662     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15663       return 1;
15664 
15665     default:
15666       return None;
15667   }
15668 
15669   return None;
15670 }
15671 
15672 static
15673 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15674                                                   ObjCMessageExpr *Message) {
15675   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15676                                             Message->getReceiverInterface(),
15677                                             NSAPI::ClassId_NSMutableDictionary);
15678   if (!IsMutableDictionary) {
15679     return None;
15680   }
15681 
15682   Selector Sel = Message->getSelector();
15683 
15684   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15685     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15686   if (!MKOpt) {
15687     return None;
15688   }
15689 
15690   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15691 
15692   switch (MK) {
15693     case NSAPI::NSMutableDict_setObjectForKey:
15694     case NSAPI::NSMutableDict_setValueForKey:
15695     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15696       return 0;
15697 
15698     default:
15699       return None;
15700   }
15701 
15702   return None;
15703 }
15704 
15705 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15706   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15707                                                 Message->getReceiverInterface(),
15708                                                 NSAPI::ClassId_NSMutableSet);
15709 
15710   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15711                                             Message->getReceiverInterface(),
15712                                             NSAPI::ClassId_NSMutableOrderedSet);
15713   if (!IsMutableSet && !IsMutableOrderedSet) {
15714     return None;
15715   }
15716 
15717   Selector Sel = Message->getSelector();
15718 
15719   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15720   if (!MKOpt) {
15721     return None;
15722   }
15723 
15724   NSAPI::NSSetMethodKind MK = *MKOpt;
15725 
15726   switch (MK) {
15727     case NSAPI::NSMutableSet_addObject:
15728     case NSAPI::NSOrderedSet_setObjectAtIndex:
15729     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15730     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15731       return 0;
15732     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15733       return 1;
15734   }
15735 
15736   return None;
15737 }
15738 
15739 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15740   if (!Message->isInstanceMessage()) {
15741     return;
15742   }
15743 
15744   Optional<int> ArgOpt;
15745 
15746   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15747       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15748       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15749     return;
15750   }
15751 
15752   int ArgIndex = *ArgOpt;
15753 
15754   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15755   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15756     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15757   }
15758 
15759   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15760     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15761       if (ArgRE->isObjCSelfExpr()) {
15762         Diag(Message->getSourceRange().getBegin(),
15763              diag::warn_objc_circular_container)
15764           << ArgRE->getDecl() << StringRef("'super'");
15765       }
15766     }
15767   } else {
15768     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15769 
15770     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15771       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15772     }
15773 
15774     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15775       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15776         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15777           ValueDecl *Decl = ReceiverRE->getDecl();
15778           Diag(Message->getSourceRange().getBegin(),
15779                diag::warn_objc_circular_container)
15780             << Decl << Decl;
15781           if (!ArgRE->isObjCSelfExpr()) {
15782             Diag(Decl->getLocation(),
15783                  diag::note_objc_circular_container_declared_here)
15784               << Decl;
15785           }
15786         }
15787       }
15788     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15789       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15790         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15791           ObjCIvarDecl *Decl = IvarRE->getDecl();
15792           Diag(Message->getSourceRange().getBegin(),
15793                diag::warn_objc_circular_container)
15794             << Decl << Decl;
15795           Diag(Decl->getLocation(),
15796                diag::note_objc_circular_container_declared_here)
15797             << Decl;
15798         }
15799       }
15800     }
15801   }
15802 }
15803 
15804 /// Check a message send to see if it's likely to cause a retain cycle.
15805 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15806   // Only check instance methods whose selector looks like a setter.
15807   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15808     return;
15809 
15810   // Try to find a variable that the receiver is strongly owned by.
15811   RetainCycleOwner owner;
15812   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15813     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15814       return;
15815   } else {
15816     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15817     owner.Variable = getCurMethodDecl()->getSelfDecl();
15818     owner.Loc = msg->getSuperLoc();
15819     owner.Range = msg->getSuperLoc();
15820   }
15821 
15822   // Check whether the receiver is captured by any of the arguments.
15823   const ObjCMethodDecl *MD = msg->getMethodDecl();
15824   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15825     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15826       // noescape blocks should not be retained by the method.
15827       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15828         continue;
15829       return diagnoseRetainCycle(*this, capturer, owner);
15830     }
15831   }
15832 }
15833 
15834 /// Check a property assign to see if it's likely to cause a retain cycle.
15835 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15836   RetainCycleOwner owner;
15837   if (!findRetainCycleOwner(*this, receiver, owner))
15838     return;
15839 
15840   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15841     diagnoseRetainCycle(*this, capturer, owner);
15842 }
15843 
15844 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15845   RetainCycleOwner Owner;
15846   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15847     return;
15848 
15849   // Because we don't have an expression for the variable, we have to set the
15850   // location explicitly here.
15851   Owner.Loc = Var->getLocation();
15852   Owner.Range = Var->getSourceRange();
15853 
15854   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15855     diagnoseRetainCycle(*this, Capturer, Owner);
15856 }
15857 
15858 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15859                                      Expr *RHS, bool isProperty) {
15860   // Check if RHS is an Objective-C object literal, which also can get
15861   // immediately zapped in a weak reference.  Note that we explicitly
15862   // allow ObjCStringLiterals, since those are designed to never really die.
15863   RHS = RHS->IgnoreParenImpCasts();
15864 
15865   // This enum needs to match with the 'select' in
15866   // warn_objc_arc_literal_assign (off-by-1).
15867   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15868   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15869     return false;
15870 
15871   S.Diag(Loc, diag::warn_arc_literal_assign)
15872     << (unsigned) Kind
15873     << (isProperty ? 0 : 1)
15874     << RHS->getSourceRange();
15875 
15876   return true;
15877 }
15878 
15879 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15880                                     Qualifiers::ObjCLifetime LT,
15881                                     Expr *RHS, bool isProperty) {
15882   // Strip off any implicit cast added to get to the one ARC-specific.
15883   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15884     if (cast->getCastKind() == CK_ARCConsumeObject) {
15885       S.Diag(Loc, diag::warn_arc_retained_assign)
15886         << (LT == Qualifiers::OCL_ExplicitNone)
15887         << (isProperty ? 0 : 1)
15888         << RHS->getSourceRange();
15889       return true;
15890     }
15891     RHS = cast->getSubExpr();
15892   }
15893 
15894   if (LT == Qualifiers::OCL_Weak &&
15895       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15896     return true;
15897 
15898   return false;
15899 }
15900 
15901 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15902                               QualType LHS, Expr *RHS) {
15903   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15904 
15905   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15906     return false;
15907 
15908   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15909     return true;
15910 
15911   return false;
15912 }
15913 
15914 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15915                               Expr *LHS, Expr *RHS) {
15916   QualType LHSType;
15917   // PropertyRef on LHS type need be directly obtained from
15918   // its declaration as it has a PseudoType.
15919   ObjCPropertyRefExpr *PRE
15920     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15921   if (PRE && !PRE->isImplicitProperty()) {
15922     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15923     if (PD)
15924       LHSType = PD->getType();
15925   }
15926 
15927   if (LHSType.isNull())
15928     LHSType = LHS->getType();
15929 
15930   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15931 
15932   if (LT == Qualifiers::OCL_Weak) {
15933     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15934       getCurFunction()->markSafeWeakUse(LHS);
15935   }
15936 
15937   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15938     return;
15939 
15940   // FIXME. Check for other life times.
15941   if (LT != Qualifiers::OCL_None)
15942     return;
15943 
15944   if (PRE) {
15945     if (PRE->isImplicitProperty())
15946       return;
15947     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15948     if (!PD)
15949       return;
15950 
15951     unsigned Attributes = PD->getPropertyAttributes();
15952     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15953       // when 'assign' attribute was not explicitly specified
15954       // by user, ignore it and rely on property type itself
15955       // for lifetime info.
15956       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15957       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15958           LHSType->isObjCRetainableType())
15959         return;
15960 
15961       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15962         if (cast->getCastKind() == CK_ARCConsumeObject) {
15963           Diag(Loc, diag::warn_arc_retained_property_assign)
15964           << RHS->getSourceRange();
15965           return;
15966         }
15967         RHS = cast->getSubExpr();
15968       }
15969     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15970       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15971         return;
15972     }
15973   }
15974 }
15975 
15976 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15977 
15978 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15979                                         SourceLocation StmtLoc,
15980                                         const NullStmt *Body) {
15981   // Do not warn if the body is a macro that expands to nothing, e.g:
15982   //
15983   // #define CALL(x)
15984   // if (condition)
15985   //   CALL(0);
15986   if (Body->hasLeadingEmptyMacro())
15987     return false;
15988 
15989   // Get line numbers of statement and body.
15990   bool StmtLineInvalid;
15991   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15992                                                       &StmtLineInvalid);
15993   if (StmtLineInvalid)
15994     return false;
15995 
15996   bool BodyLineInvalid;
15997   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15998                                                       &BodyLineInvalid);
15999   if (BodyLineInvalid)
16000     return false;
16001 
16002   // Warn if null statement and body are on the same line.
16003   if (StmtLine != BodyLine)
16004     return false;
16005 
16006   return true;
16007 }
16008 
16009 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16010                                  const Stmt *Body,
16011                                  unsigned DiagID) {
16012   // Since this is a syntactic check, don't emit diagnostic for template
16013   // instantiations, this just adds noise.
16014   if (CurrentInstantiationScope)
16015     return;
16016 
16017   // The body should be a null statement.
16018   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16019   if (!NBody)
16020     return;
16021 
16022   // Do the usual checks.
16023   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16024     return;
16025 
16026   Diag(NBody->getSemiLoc(), DiagID);
16027   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16028 }
16029 
16030 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16031                                  const Stmt *PossibleBody) {
16032   assert(!CurrentInstantiationScope); // Ensured by caller
16033 
16034   SourceLocation StmtLoc;
16035   const Stmt *Body;
16036   unsigned DiagID;
16037   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16038     StmtLoc = FS->getRParenLoc();
16039     Body = FS->getBody();
16040     DiagID = diag::warn_empty_for_body;
16041   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16042     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16043     Body = WS->getBody();
16044     DiagID = diag::warn_empty_while_body;
16045   } else
16046     return; // Neither `for' nor `while'.
16047 
16048   // The body should be a null statement.
16049   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16050   if (!NBody)
16051     return;
16052 
16053   // Skip expensive checks if diagnostic is disabled.
16054   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16055     return;
16056 
16057   // Do the usual checks.
16058   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16059     return;
16060 
16061   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16062   // noise level low, emit diagnostics only if for/while is followed by a
16063   // CompoundStmt, e.g.:
16064   //    for (int i = 0; i < n; i++);
16065   //    {
16066   //      a(i);
16067   //    }
16068   // or if for/while is followed by a statement with more indentation
16069   // than for/while itself:
16070   //    for (int i = 0; i < n; i++);
16071   //      a(i);
16072   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16073   if (!ProbableTypo) {
16074     bool BodyColInvalid;
16075     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16076         PossibleBody->getBeginLoc(), &BodyColInvalid);
16077     if (BodyColInvalid)
16078       return;
16079 
16080     bool StmtColInvalid;
16081     unsigned StmtCol =
16082         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16083     if (StmtColInvalid)
16084       return;
16085 
16086     if (BodyCol > StmtCol)
16087       ProbableTypo = true;
16088   }
16089 
16090   if (ProbableTypo) {
16091     Diag(NBody->getSemiLoc(), DiagID);
16092     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16093   }
16094 }
16095 
16096 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16097 
16098 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16099 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16100                              SourceLocation OpLoc) {
16101   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16102     return;
16103 
16104   if (inTemplateInstantiation())
16105     return;
16106 
16107   // Strip parens and casts away.
16108   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16109   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16110 
16111   // Check for a call expression
16112   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16113   if (!CE || CE->getNumArgs() != 1)
16114     return;
16115 
16116   // Check for a call to std::move
16117   if (!CE->isCallToStdMove())
16118     return;
16119 
16120   // Get argument from std::move
16121   RHSExpr = CE->getArg(0);
16122 
16123   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16124   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16125 
16126   // Two DeclRefExpr's, check that the decls are the same.
16127   if (LHSDeclRef && RHSDeclRef) {
16128     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16129       return;
16130     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16131         RHSDeclRef->getDecl()->getCanonicalDecl())
16132       return;
16133 
16134     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16135                                         << LHSExpr->getSourceRange()
16136                                         << RHSExpr->getSourceRange();
16137     return;
16138   }
16139 
16140   // Member variables require a different approach to check for self moves.
16141   // MemberExpr's are the same if every nested MemberExpr refers to the same
16142   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16143   // the base Expr's are CXXThisExpr's.
16144   const Expr *LHSBase = LHSExpr;
16145   const Expr *RHSBase = RHSExpr;
16146   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16147   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16148   if (!LHSME || !RHSME)
16149     return;
16150 
16151   while (LHSME && RHSME) {
16152     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16153         RHSME->getMemberDecl()->getCanonicalDecl())
16154       return;
16155 
16156     LHSBase = LHSME->getBase();
16157     RHSBase = RHSME->getBase();
16158     LHSME = dyn_cast<MemberExpr>(LHSBase);
16159     RHSME = dyn_cast<MemberExpr>(RHSBase);
16160   }
16161 
16162   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16163   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16164   if (LHSDeclRef && RHSDeclRef) {
16165     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16166       return;
16167     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16168         RHSDeclRef->getDecl()->getCanonicalDecl())
16169       return;
16170 
16171     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16172                                         << LHSExpr->getSourceRange()
16173                                         << RHSExpr->getSourceRange();
16174     return;
16175   }
16176 
16177   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16178     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16179                                         << LHSExpr->getSourceRange()
16180                                         << RHSExpr->getSourceRange();
16181 }
16182 
16183 //===--- Layout compatibility ----------------------------------------------//
16184 
16185 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16186 
16187 /// Check if two enumeration types are layout-compatible.
16188 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16189   // C++11 [dcl.enum] p8:
16190   // Two enumeration types are layout-compatible if they have the same
16191   // underlying type.
16192   return ED1->isComplete() && ED2->isComplete() &&
16193          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16194 }
16195 
16196 /// Check if two fields are layout-compatible.
16197 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16198                                FieldDecl *Field2) {
16199   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16200     return false;
16201 
16202   if (Field1->isBitField() != Field2->isBitField())
16203     return false;
16204 
16205   if (Field1->isBitField()) {
16206     // Make sure that the bit-fields are the same length.
16207     unsigned Bits1 = Field1->getBitWidthValue(C);
16208     unsigned Bits2 = Field2->getBitWidthValue(C);
16209 
16210     if (Bits1 != Bits2)
16211       return false;
16212   }
16213 
16214   return true;
16215 }
16216 
16217 /// Check if two standard-layout structs are layout-compatible.
16218 /// (C++11 [class.mem] p17)
16219 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16220                                      RecordDecl *RD2) {
16221   // If both records are C++ classes, check that base classes match.
16222   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16223     // If one of records is a CXXRecordDecl we are in C++ mode,
16224     // thus the other one is a CXXRecordDecl, too.
16225     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16226     // Check number of base classes.
16227     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16228       return false;
16229 
16230     // Check the base classes.
16231     for (CXXRecordDecl::base_class_const_iterator
16232                Base1 = D1CXX->bases_begin(),
16233            BaseEnd1 = D1CXX->bases_end(),
16234               Base2 = D2CXX->bases_begin();
16235          Base1 != BaseEnd1;
16236          ++Base1, ++Base2) {
16237       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16238         return false;
16239     }
16240   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16241     // If only RD2 is a C++ class, it should have zero base classes.
16242     if (D2CXX->getNumBases() > 0)
16243       return false;
16244   }
16245 
16246   // Check the fields.
16247   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16248                              Field2End = RD2->field_end(),
16249                              Field1 = RD1->field_begin(),
16250                              Field1End = RD1->field_end();
16251   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16252     if (!isLayoutCompatible(C, *Field1, *Field2))
16253       return false;
16254   }
16255   if (Field1 != Field1End || Field2 != Field2End)
16256     return false;
16257 
16258   return true;
16259 }
16260 
16261 /// Check if two standard-layout unions are layout-compatible.
16262 /// (C++11 [class.mem] p18)
16263 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16264                                     RecordDecl *RD2) {
16265   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16266   for (auto *Field2 : RD2->fields())
16267     UnmatchedFields.insert(Field2);
16268 
16269   for (auto *Field1 : RD1->fields()) {
16270     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16271         I = UnmatchedFields.begin(),
16272         E = UnmatchedFields.end();
16273 
16274     for ( ; I != E; ++I) {
16275       if (isLayoutCompatible(C, Field1, *I)) {
16276         bool Result = UnmatchedFields.erase(*I);
16277         (void) Result;
16278         assert(Result);
16279         break;
16280       }
16281     }
16282     if (I == E)
16283       return false;
16284   }
16285 
16286   return UnmatchedFields.empty();
16287 }
16288 
16289 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16290                                RecordDecl *RD2) {
16291   if (RD1->isUnion() != RD2->isUnion())
16292     return false;
16293 
16294   if (RD1->isUnion())
16295     return isLayoutCompatibleUnion(C, RD1, RD2);
16296   else
16297     return isLayoutCompatibleStruct(C, RD1, RD2);
16298 }
16299 
16300 /// Check if two types are layout-compatible in C++11 sense.
16301 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16302   if (T1.isNull() || T2.isNull())
16303     return false;
16304 
16305   // C++11 [basic.types] p11:
16306   // If two types T1 and T2 are the same type, then T1 and T2 are
16307   // layout-compatible types.
16308   if (C.hasSameType(T1, T2))
16309     return true;
16310 
16311   T1 = T1.getCanonicalType().getUnqualifiedType();
16312   T2 = T2.getCanonicalType().getUnqualifiedType();
16313 
16314   const Type::TypeClass TC1 = T1->getTypeClass();
16315   const Type::TypeClass TC2 = T2->getTypeClass();
16316 
16317   if (TC1 != TC2)
16318     return false;
16319 
16320   if (TC1 == Type::Enum) {
16321     return isLayoutCompatible(C,
16322                               cast<EnumType>(T1)->getDecl(),
16323                               cast<EnumType>(T2)->getDecl());
16324   } else if (TC1 == Type::Record) {
16325     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16326       return false;
16327 
16328     return isLayoutCompatible(C,
16329                               cast<RecordType>(T1)->getDecl(),
16330                               cast<RecordType>(T2)->getDecl());
16331   }
16332 
16333   return false;
16334 }
16335 
16336 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16337 
16338 /// Given a type tag expression find the type tag itself.
16339 ///
16340 /// \param TypeExpr Type tag expression, as it appears in user's code.
16341 ///
16342 /// \param VD Declaration of an identifier that appears in a type tag.
16343 ///
16344 /// \param MagicValue Type tag magic value.
16345 ///
16346 /// \param isConstantEvaluated whether the evalaution should be performed in
16347 
16348 /// constant context.
16349 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16350                             const ValueDecl **VD, uint64_t *MagicValue,
16351                             bool isConstantEvaluated) {
16352   while(true) {
16353     if (!TypeExpr)
16354       return false;
16355 
16356     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16357 
16358     switch (TypeExpr->getStmtClass()) {
16359     case Stmt::UnaryOperatorClass: {
16360       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16361       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16362         TypeExpr = UO->getSubExpr();
16363         continue;
16364       }
16365       return false;
16366     }
16367 
16368     case Stmt::DeclRefExprClass: {
16369       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16370       *VD = DRE->getDecl();
16371       return true;
16372     }
16373 
16374     case Stmt::IntegerLiteralClass: {
16375       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16376       llvm::APInt MagicValueAPInt = IL->getValue();
16377       if (MagicValueAPInt.getActiveBits() <= 64) {
16378         *MagicValue = MagicValueAPInt.getZExtValue();
16379         return true;
16380       } else
16381         return false;
16382     }
16383 
16384     case Stmt::BinaryConditionalOperatorClass:
16385     case Stmt::ConditionalOperatorClass: {
16386       const AbstractConditionalOperator *ACO =
16387           cast<AbstractConditionalOperator>(TypeExpr);
16388       bool Result;
16389       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16390                                                      isConstantEvaluated)) {
16391         if (Result)
16392           TypeExpr = ACO->getTrueExpr();
16393         else
16394           TypeExpr = ACO->getFalseExpr();
16395         continue;
16396       }
16397       return false;
16398     }
16399 
16400     case Stmt::BinaryOperatorClass: {
16401       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16402       if (BO->getOpcode() == BO_Comma) {
16403         TypeExpr = BO->getRHS();
16404         continue;
16405       }
16406       return false;
16407     }
16408 
16409     default:
16410       return false;
16411     }
16412   }
16413 }
16414 
16415 /// Retrieve the C type corresponding to type tag TypeExpr.
16416 ///
16417 /// \param TypeExpr Expression that specifies a type tag.
16418 ///
16419 /// \param MagicValues Registered magic values.
16420 ///
16421 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16422 ///        kind.
16423 ///
16424 /// \param TypeInfo Information about the corresponding C type.
16425 ///
16426 /// \param isConstantEvaluated whether the evalaution should be performed in
16427 /// constant context.
16428 ///
16429 /// \returns true if the corresponding C type was found.
16430 static bool GetMatchingCType(
16431     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16432     const ASTContext &Ctx,
16433     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16434         *MagicValues,
16435     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16436     bool isConstantEvaluated) {
16437   FoundWrongKind = false;
16438 
16439   // Variable declaration that has type_tag_for_datatype attribute.
16440   const ValueDecl *VD = nullptr;
16441 
16442   uint64_t MagicValue;
16443 
16444   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16445     return false;
16446 
16447   if (VD) {
16448     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16449       if (I->getArgumentKind() != ArgumentKind) {
16450         FoundWrongKind = true;
16451         return false;
16452       }
16453       TypeInfo.Type = I->getMatchingCType();
16454       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16455       TypeInfo.MustBeNull = I->getMustBeNull();
16456       return true;
16457     }
16458     return false;
16459   }
16460 
16461   if (!MagicValues)
16462     return false;
16463 
16464   llvm::DenseMap<Sema::TypeTagMagicValue,
16465                  Sema::TypeTagData>::const_iterator I =
16466       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16467   if (I == MagicValues->end())
16468     return false;
16469 
16470   TypeInfo = I->second;
16471   return true;
16472 }
16473 
16474 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16475                                       uint64_t MagicValue, QualType Type,
16476                                       bool LayoutCompatible,
16477                                       bool MustBeNull) {
16478   if (!TypeTagForDatatypeMagicValues)
16479     TypeTagForDatatypeMagicValues.reset(
16480         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16481 
16482   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16483   (*TypeTagForDatatypeMagicValues)[Magic] =
16484       TypeTagData(Type, LayoutCompatible, MustBeNull);
16485 }
16486 
16487 static bool IsSameCharType(QualType T1, QualType T2) {
16488   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16489   if (!BT1)
16490     return false;
16491 
16492   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16493   if (!BT2)
16494     return false;
16495 
16496   BuiltinType::Kind T1Kind = BT1->getKind();
16497   BuiltinType::Kind T2Kind = BT2->getKind();
16498 
16499   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16500          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16501          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16502          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16503 }
16504 
16505 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16506                                     const ArrayRef<const Expr *> ExprArgs,
16507                                     SourceLocation CallSiteLoc) {
16508   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16509   bool IsPointerAttr = Attr->getIsPointer();
16510 
16511   // Retrieve the argument representing the 'type_tag'.
16512   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16513   if (TypeTagIdxAST >= ExprArgs.size()) {
16514     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16515         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16516     return;
16517   }
16518   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16519   bool FoundWrongKind;
16520   TypeTagData TypeInfo;
16521   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16522                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16523                         TypeInfo, isConstantEvaluated())) {
16524     if (FoundWrongKind)
16525       Diag(TypeTagExpr->getExprLoc(),
16526            diag::warn_type_tag_for_datatype_wrong_kind)
16527         << TypeTagExpr->getSourceRange();
16528     return;
16529   }
16530 
16531   // Retrieve the argument representing the 'arg_idx'.
16532   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16533   if (ArgumentIdxAST >= ExprArgs.size()) {
16534     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16535         << 1 << Attr->getArgumentIdx().getSourceIndex();
16536     return;
16537   }
16538   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16539   if (IsPointerAttr) {
16540     // Skip implicit cast of pointer to `void *' (as a function argument).
16541     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16542       if (ICE->getType()->isVoidPointerType() &&
16543           ICE->getCastKind() == CK_BitCast)
16544         ArgumentExpr = ICE->getSubExpr();
16545   }
16546   QualType ArgumentType = ArgumentExpr->getType();
16547 
16548   // Passing a `void*' pointer shouldn't trigger a warning.
16549   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16550     return;
16551 
16552   if (TypeInfo.MustBeNull) {
16553     // Type tag with matching void type requires a null pointer.
16554     if (!ArgumentExpr->isNullPointerConstant(Context,
16555                                              Expr::NPC_ValueDependentIsNotNull)) {
16556       Diag(ArgumentExpr->getExprLoc(),
16557            diag::warn_type_safety_null_pointer_required)
16558           << ArgumentKind->getName()
16559           << ArgumentExpr->getSourceRange()
16560           << TypeTagExpr->getSourceRange();
16561     }
16562     return;
16563   }
16564 
16565   QualType RequiredType = TypeInfo.Type;
16566   if (IsPointerAttr)
16567     RequiredType = Context.getPointerType(RequiredType);
16568 
16569   bool mismatch = false;
16570   if (!TypeInfo.LayoutCompatible) {
16571     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16572 
16573     // C++11 [basic.fundamental] p1:
16574     // Plain char, signed char, and unsigned char are three distinct types.
16575     //
16576     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16577     // char' depending on the current char signedness mode.
16578     if (mismatch)
16579       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16580                                            RequiredType->getPointeeType())) ||
16581           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16582         mismatch = false;
16583   } else
16584     if (IsPointerAttr)
16585       mismatch = !isLayoutCompatible(Context,
16586                                      ArgumentType->getPointeeType(),
16587                                      RequiredType->getPointeeType());
16588     else
16589       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16590 
16591   if (mismatch)
16592     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16593         << ArgumentType << ArgumentKind
16594         << TypeInfo.LayoutCompatible << RequiredType
16595         << ArgumentExpr->getSourceRange()
16596         << TypeTagExpr->getSourceRange();
16597 }
16598 
16599 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16600                                          CharUnits Alignment) {
16601   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16602 }
16603 
16604 void Sema::DiagnoseMisalignedMembers() {
16605   for (MisalignedMember &m : MisalignedMembers) {
16606     const NamedDecl *ND = m.RD;
16607     if (ND->getName().empty()) {
16608       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16609         ND = TD;
16610     }
16611     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16612         << m.MD << ND << m.E->getSourceRange();
16613   }
16614   MisalignedMembers.clear();
16615 }
16616 
16617 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16618   E = E->IgnoreParens();
16619   if (!T->isPointerType() && !T->isIntegerType())
16620     return;
16621   if (isa<UnaryOperator>(E) &&
16622       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16623     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16624     if (isa<MemberExpr>(Op)) {
16625       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16626       if (MA != MisalignedMembers.end() &&
16627           (T->isIntegerType() ||
16628            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16629                                    Context.getTypeAlignInChars(
16630                                        T->getPointeeType()) <= MA->Alignment))))
16631         MisalignedMembers.erase(MA);
16632     }
16633   }
16634 }
16635 
16636 void Sema::RefersToMemberWithReducedAlignment(
16637     Expr *E,
16638     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16639         Action) {
16640   const auto *ME = dyn_cast<MemberExpr>(E);
16641   if (!ME)
16642     return;
16643 
16644   // No need to check expressions with an __unaligned-qualified type.
16645   if (E->getType().getQualifiers().hasUnaligned())
16646     return;
16647 
16648   // For a chain of MemberExpr like "a.b.c.d" this list
16649   // will keep FieldDecl's like [d, c, b].
16650   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16651   const MemberExpr *TopME = nullptr;
16652   bool AnyIsPacked = false;
16653   do {
16654     QualType BaseType = ME->getBase()->getType();
16655     if (BaseType->isDependentType())
16656       return;
16657     if (ME->isArrow())
16658       BaseType = BaseType->getPointeeType();
16659     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16660     if (RD->isInvalidDecl())
16661       return;
16662 
16663     ValueDecl *MD = ME->getMemberDecl();
16664     auto *FD = dyn_cast<FieldDecl>(MD);
16665     // We do not care about non-data members.
16666     if (!FD || FD->isInvalidDecl())
16667       return;
16668 
16669     AnyIsPacked =
16670         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16671     ReverseMemberChain.push_back(FD);
16672 
16673     TopME = ME;
16674     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16675   } while (ME);
16676   assert(TopME && "We did not compute a topmost MemberExpr!");
16677 
16678   // Not the scope of this diagnostic.
16679   if (!AnyIsPacked)
16680     return;
16681 
16682   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16683   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16684   // TODO: The innermost base of the member expression may be too complicated.
16685   // For now, just disregard these cases. This is left for future
16686   // improvement.
16687   if (!DRE && !isa<CXXThisExpr>(TopBase))
16688       return;
16689 
16690   // Alignment expected by the whole expression.
16691   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16692 
16693   // No need to do anything else with this case.
16694   if (ExpectedAlignment.isOne())
16695     return;
16696 
16697   // Synthesize offset of the whole access.
16698   CharUnits Offset;
16699   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16700     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16701 
16702   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16703   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16704       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16705 
16706   // The base expression of the innermost MemberExpr may give
16707   // stronger guarantees than the class containing the member.
16708   if (DRE && !TopME->isArrow()) {
16709     const ValueDecl *VD = DRE->getDecl();
16710     if (!VD->getType()->isReferenceType())
16711       CompleteObjectAlignment =
16712           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16713   }
16714 
16715   // Check if the synthesized offset fulfills the alignment.
16716   if (Offset % ExpectedAlignment != 0 ||
16717       // It may fulfill the offset it but the effective alignment may still be
16718       // lower than the expected expression alignment.
16719       CompleteObjectAlignment < ExpectedAlignment) {
16720     // If this happens, we want to determine a sensible culprit of this.
16721     // Intuitively, watching the chain of member expressions from right to
16722     // left, we start with the required alignment (as required by the field
16723     // type) but some packed attribute in that chain has reduced the alignment.
16724     // It may happen that another packed structure increases it again. But if
16725     // we are here such increase has not been enough. So pointing the first
16726     // FieldDecl that either is packed or else its RecordDecl is,
16727     // seems reasonable.
16728     FieldDecl *FD = nullptr;
16729     CharUnits Alignment;
16730     for (FieldDecl *FDI : ReverseMemberChain) {
16731       if (FDI->hasAttr<PackedAttr>() ||
16732           FDI->getParent()->hasAttr<PackedAttr>()) {
16733         FD = FDI;
16734         Alignment = std::min(
16735             Context.getTypeAlignInChars(FD->getType()),
16736             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16737         break;
16738       }
16739     }
16740     assert(FD && "We did not find a packed FieldDecl!");
16741     Action(E, FD->getParent(), FD, Alignment);
16742   }
16743 }
16744 
16745 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16746   using namespace std::placeholders;
16747 
16748   RefersToMemberWithReducedAlignment(
16749       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16750                      _2, _3, _4));
16751 }
16752 
16753 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16754 // not a valid type, emit an error message and return true. Otherwise return
16755 // false.
16756 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16757                                         QualType Ty) {
16758   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16759     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16760         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16761     return true;
16762   }
16763   return false;
16764 }
16765 
16766 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16767   if (checkArgCount(*this, TheCall, 1))
16768     return true;
16769 
16770   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16771   if (A.isInvalid())
16772     return true;
16773 
16774   TheCall->setArg(0, A.get());
16775   QualType TyA = A.get()->getType();
16776 
16777   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16778     return true;
16779 
16780   TheCall->setType(TyA);
16781   return false;
16782 }
16783 
16784 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16785   if (checkArgCount(*this, TheCall, 2))
16786     return true;
16787 
16788   ExprResult A = TheCall->getArg(0);
16789   ExprResult B = TheCall->getArg(1);
16790   // Do standard promotions between the two arguments, returning their common
16791   // type.
16792   QualType Res =
16793       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16794   if (A.isInvalid() || B.isInvalid())
16795     return true;
16796 
16797   QualType TyA = A.get()->getType();
16798   QualType TyB = B.get()->getType();
16799 
16800   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16801     return Diag(A.get()->getBeginLoc(),
16802                 diag::err_typecheck_call_different_arg_types)
16803            << TyA << TyB;
16804 
16805   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16806     return true;
16807 
16808   TheCall->setArg(0, A.get());
16809   TheCall->setArg(1, B.get());
16810   TheCall->setType(Res);
16811   return false;
16812 }
16813 
16814 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) {
16815   if (checkArgCount(*this, TheCall, 1))
16816     return true;
16817 
16818   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16819   if (A.isInvalid())
16820     return true;
16821 
16822   TheCall->setArg(0, A.get());
16823   const VectorType *TyA = A.get()->getType()->getAs<VectorType>();
16824   if (!TyA) {
16825     SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16826     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16827            << 1 << /* vector ty*/ 4 << A.get()->getType();
16828   }
16829 
16830   TheCall->setType(TyA->getElementType());
16831   return false;
16832 }
16833 
16834 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16835                                             ExprResult CallResult) {
16836   if (checkArgCount(*this, TheCall, 1))
16837     return ExprError();
16838 
16839   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16840   if (MatrixArg.isInvalid())
16841     return MatrixArg;
16842   Expr *Matrix = MatrixArg.get();
16843 
16844   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16845   if (!MType) {
16846     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16847         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16848     return ExprError();
16849   }
16850 
16851   // Create returned matrix type by swapping rows and columns of the argument
16852   // matrix type.
16853   QualType ResultType = Context.getConstantMatrixType(
16854       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16855 
16856   // Change the return type to the type of the returned matrix.
16857   TheCall->setType(ResultType);
16858 
16859   // Update call argument to use the possibly converted matrix argument.
16860   TheCall->setArg(0, Matrix);
16861   return CallResult;
16862 }
16863 
16864 // Get and verify the matrix dimensions.
16865 static llvm::Optional<unsigned>
16866 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16867   SourceLocation ErrorPos;
16868   Optional<llvm::APSInt> Value =
16869       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16870   if (!Value) {
16871     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16872         << Name;
16873     return {};
16874   }
16875   uint64_t Dim = Value->getZExtValue();
16876   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16877     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16878         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16879     return {};
16880   }
16881   return Dim;
16882 }
16883 
16884 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16885                                                   ExprResult CallResult) {
16886   if (!getLangOpts().MatrixTypes) {
16887     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16888     return ExprError();
16889   }
16890 
16891   if (checkArgCount(*this, TheCall, 4))
16892     return ExprError();
16893 
16894   unsigned PtrArgIdx = 0;
16895   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16896   Expr *RowsExpr = TheCall->getArg(1);
16897   Expr *ColumnsExpr = TheCall->getArg(2);
16898   Expr *StrideExpr = TheCall->getArg(3);
16899 
16900   bool ArgError = false;
16901 
16902   // Check pointer argument.
16903   {
16904     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16905     if (PtrConv.isInvalid())
16906       return PtrConv;
16907     PtrExpr = PtrConv.get();
16908     TheCall->setArg(0, PtrExpr);
16909     if (PtrExpr->isTypeDependent()) {
16910       TheCall->setType(Context.DependentTy);
16911       return TheCall;
16912     }
16913   }
16914 
16915   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16916   QualType ElementTy;
16917   if (!PtrTy) {
16918     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16919         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16920     ArgError = true;
16921   } else {
16922     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16923 
16924     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16925       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16926           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
16927           << PtrExpr->getType();
16928       ArgError = true;
16929     }
16930   }
16931 
16932   // Apply default Lvalue conversions and convert the expression to size_t.
16933   auto ApplyArgumentConversions = [this](Expr *E) {
16934     ExprResult Conv = DefaultLvalueConversion(E);
16935     if (Conv.isInvalid())
16936       return Conv;
16937 
16938     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16939   };
16940 
16941   // Apply conversion to row and column expressions.
16942   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16943   if (!RowsConv.isInvalid()) {
16944     RowsExpr = RowsConv.get();
16945     TheCall->setArg(1, RowsExpr);
16946   } else
16947     RowsExpr = nullptr;
16948 
16949   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16950   if (!ColumnsConv.isInvalid()) {
16951     ColumnsExpr = ColumnsConv.get();
16952     TheCall->setArg(2, ColumnsExpr);
16953   } else
16954     ColumnsExpr = nullptr;
16955 
16956   // If any any part of the result matrix type is still pending, just use
16957   // Context.DependentTy, until all parts are resolved.
16958   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16959       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16960     TheCall->setType(Context.DependentTy);
16961     return CallResult;
16962   }
16963 
16964   // Check row and column dimensions.
16965   llvm::Optional<unsigned> MaybeRows;
16966   if (RowsExpr)
16967     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16968 
16969   llvm::Optional<unsigned> MaybeColumns;
16970   if (ColumnsExpr)
16971     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16972 
16973   // Check stride argument.
16974   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16975   if (StrideConv.isInvalid())
16976     return ExprError();
16977   StrideExpr = StrideConv.get();
16978   TheCall->setArg(3, StrideExpr);
16979 
16980   if (MaybeRows) {
16981     if (Optional<llvm::APSInt> Value =
16982             StrideExpr->getIntegerConstantExpr(Context)) {
16983       uint64_t Stride = Value->getZExtValue();
16984       if (Stride < *MaybeRows) {
16985         Diag(StrideExpr->getBeginLoc(),
16986              diag::err_builtin_matrix_stride_too_small);
16987         ArgError = true;
16988       }
16989     }
16990   }
16991 
16992   if (ArgError || !MaybeRows || !MaybeColumns)
16993     return ExprError();
16994 
16995   TheCall->setType(
16996       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16997   return CallResult;
16998 }
16999 
17000 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17001                                                    ExprResult CallResult) {
17002   if (checkArgCount(*this, TheCall, 3))
17003     return ExprError();
17004 
17005   unsigned PtrArgIdx = 1;
17006   Expr *MatrixExpr = TheCall->getArg(0);
17007   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17008   Expr *StrideExpr = TheCall->getArg(2);
17009 
17010   bool ArgError = false;
17011 
17012   {
17013     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17014     if (MatrixConv.isInvalid())
17015       return MatrixConv;
17016     MatrixExpr = MatrixConv.get();
17017     TheCall->setArg(0, MatrixExpr);
17018   }
17019   if (MatrixExpr->isTypeDependent()) {
17020     TheCall->setType(Context.DependentTy);
17021     return TheCall;
17022   }
17023 
17024   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17025   if (!MatrixTy) {
17026     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17027         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17028     ArgError = true;
17029   }
17030 
17031   {
17032     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17033     if (PtrConv.isInvalid())
17034       return PtrConv;
17035     PtrExpr = PtrConv.get();
17036     TheCall->setArg(1, PtrExpr);
17037     if (PtrExpr->isTypeDependent()) {
17038       TheCall->setType(Context.DependentTy);
17039       return TheCall;
17040     }
17041   }
17042 
17043   // Check pointer argument.
17044   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17045   if (!PtrTy) {
17046     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17047         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17048     ArgError = true;
17049   } else {
17050     QualType ElementTy = PtrTy->getPointeeType();
17051     if (ElementTy.isConstQualified()) {
17052       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17053       ArgError = true;
17054     }
17055     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17056     if (MatrixTy &&
17057         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17058       Diag(PtrExpr->getBeginLoc(),
17059            diag::err_builtin_matrix_pointer_arg_mismatch)
17060           << ElementTy << MatrixTy->getElementType();
17061       ArgError = true;
17062     }
17063   }
17064 
17065   // Apply default Lvalue conversions and convert the stride expression to
17066   // size_t.
17067   {
17068     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17069     if (StrideConv.isInvalid())
17070       return StrideConv;
17071 
17072     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17073     if (StrideConv.isInvalid())
17074       return StrideConv;
17075     StrideExpr = StrideConv.get();
17076     TheCall->setArg(2, StrideExpr);
17077   }
17078 
17079   // Check stride argument.
17080   if (MatrixTy) {
17081     if (Optional<llvm::APSInt> Value =
17082             StrideExpr->getIntegerConstantExpr(Context)) {
17083       uint64_t Stride = Value->getZExtValue();
17084       if (Stride < MatrixTy->getNumRows()) {
17085         Diag(StrideExpr->getBeginLoc(),
17086              diag::err_builtin_matrix_stride_too_small);
17087         ArgError = true;
17088       }
17089     }
17090   }
17091 
17092   if (ArgError)
17093     return ExprError();
17094 
17095   return CallResult;
17096 }
17097 
17098 /// \brief Enforce the bounds of a TCB
17099 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17100 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17101 /// and enforce_tcb_leaf attributes.
17102 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17103                                const FunctionDecl *Callee) {
17104   const FunctionDecl *Caller = getCurFunctionDecl();
17105 
17106   // Calls to builtins are not enforced.
17107   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17108       Callee->getBuiltinID() != 0)
17109     return;
17110 
17111   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17112   // all TCBs the callee is a part of.
17113   llvm::StringSet<> CalleeTCBs;
17114   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17115            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17116   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17117            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17118 
17119   // Go through the TCBs the caller is a part of and emit warnings if Caller
17120   // is in a TCB that the Callee is not.
17121   for_each(
17122       Caller->specific_attrs<EnforceTCBAttr>(),
17123       [&](const auto *A) {
17124         StringRef CallerTCB = A->getTCBName();
17125         if (CalleeTCBs.count(CallerTCB) == 0) {
17126           this->Diag(TheCall->getExprLoc(),
17127                      diag::warn_tcb_enforcement_violation) << Callee
17128                                                            << CallerTCB;
17129         }
17130       });
17131 }
17132