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     analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
450     if (FW.getHowSpecified() !=
451         analyze_format_string::OptionalAmount::HowSpecified::Constant)
452       return true;
453 
454     unsigned SourceSize = FW.getConstantAmount() + NulByte;
455 
456     Optional<llvm::APSInt> 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   bool UseDABAttr = false;
656   const FunctionDecl *UseDecl = FD;
657 
658   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
659   if (DABAttr) {
660     UseDecl = DABAttr->getFunction();
661     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
662     UseDABAttr = true;
663   }
664 
665   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
666 
667   if (!BuiltinID)
668     return;
669 
670   const TargetInfo &TI = getASTContext().getTargetInfo();
671   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
672 
673   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
674     // If we refer to a diagnose_as_builtin attribute, we need to change the
675     // argument index to refer to the arguments of the called function. Unless
676     // the index is out of bounds, which presumably means it's a variadic
677     // function.
678     if (!UseDABAttr)
679       return Index;
680     unsigned DABIndices = DABAttr->argIndices_size();
681     unsigned NewIndex = Index < DABIndices
682                             ? DABAttr->argIndices_begin()[Index]
683                             : Index - DABIndices + FD->getNumParams();
684     if (NewIndex >= TheCall->getNumArgs())
685       return llvm::None;
686     return NewIndex;
687   };
688 
689   auto ComputeExplicitObjectSizeArgument =
690       [&](unsigned Index) -> Optional<llvm::APSInt> {
691     Optional<unsigned> IndexOptional = TranslateIndex(Index);
692     if (!IndexOptional)
693       return llvm::None;
694     unsigned NewIndex = IndexOptional.getValue();
695     Expr::EvalResult Result;
696     Expr *SizeArg = TheCall->getArg(NewIndex);
697     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
698       return llvm::None;
699     llvm::APSInt Integer = Result.Val.getInt();
700     Integer.setIsUnsigned(true);
701     return Integer;
702   };
703 
704   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
705     // If the parameter has a pass_object_size attribute, then we should use its
706     // (potentially) more strict checking mode. Otherwise, conservatively assume
707     // type 0.
708     int BOSType = 0;
709     // This check can fail for variadic functions.
710     if (Index < FD->getNumParams()) {
711       if (const auto *POS =
712               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
713         BOSType = POS->getType();
714     }
715 
716     Optional<unsigned> IndexOptional = TranslateIndex(Index);
717     if (!IndexOptional)
718       return llvm::None;
719     unsigned NewIndex = IndexOptional.getValue();
720 
721     const Expr *ObjArg = TheCall->getArg(NewIndex);
722     uint64_t Result;
723     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
724       return llvm::None;
725 
726     // Get the object size in the target's size_t width.
727     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
728   };
729 
730   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
731     Optional<unsigned> IndexOptional = TranslateIndex(Index);
732     if (!IndexOptional)
733       return llvm::None;
734     unsigned NewIndex = IndexOptional.getValue();
735 
736     const Expr *ObjArg = TheCall->getArg(NewIndex);
737     uint64_t Result;
738     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
739       return llvm::None;
740     // Add 1 for null byte.
741     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
742   };
743 
744   Optional<llvm::APSInt> SourceSize;
745   Optional<llvm::APSInt> DestinationSize;
746   unsigned DiagID = 0;
747   bool IsChkVariant = false;
748 
749   auto GetFunctionName = [&]() {
750     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
751     // Skim off the details of whichever builtin was called to produce a better
752     // diagnostic, as it's unlikely that the user wrote the __builtin
753     // explicitly.
754     if (IsChkVariant) {
755       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
756       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
757     } else if (FunctionName.startswith("__builtin_")) {
758       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
759     }
760     return FunctionName;
761   };
762 
763   switch (BuiltinID) {
764   default:
765     return;
766   case Builtin::BI__builtin_strcpy:
767   case Builtin::BIstrcpy: {
768     DiagID = diag::warn_fortify_strlen_overflow;
769     SourceSize = ComputeStrLenArgument(1);
770     DestinationSize = ComputeSizeArgument(0);
771     break;
772   }
773 
774   case Builtin::BI__builtin___strcpy_chk: {
775     DiagID = diag::warn_fortify_strlen_overflow;
776     SourceSize = ComputeStrLenArgument(1);
777     DestinationSize = ComputeExplicitObjectSizeArgument(2);
778     IsChkVariant = true;
779     break;
780   }
781 
782   case Builtin::BIscanf:
783   case Builtin::BIfscanf:
784   case Builtin::BIsscanf: {
785     unsigned FormatIndex = 1;
786     unsigned DataIndex = 2;
787     if (BuiltinID == Builtin::BIscanf) {
788       FormatIndex = 0;
789       DataIndex = 1;
790     }
791 
792     const auto *FormatExpr =
793         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
794 
795     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
796     if (!Format)
797       return;
798 
799     if (!Format->isAscii() && !Format->isUTF8())
800       return;
801 
802     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
803                         unsigned SourceSize) {
804       DiagID = diag::warn_fortify_scanf_overflow;
805       unsigned Index = ArgIndex + DataIndex;
806       StringRef FunctionName = GetFunctionName();
807       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
808                           PDiag(DiagID) << FunctionName << (Index + 1)
809                                         << DestSize << SourceSize);
810     };
811 
812     StringRef FormatStrRef = Format->getString();
813     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
814       return ComputeSizeArgument(Index + DataIndex);
815     };
816     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
817     const char *FormatBytes = FormatStrRef.data();
818     const ConstantArrayType *T =
819         Context.getAsConstantArrayType(Format->getType());
820     assert(T && "String literal not of constant array type!");
821     size_t TypeSize = T->getSize().getZExtValue();
822 
823     // In case there's a null byte somewhere.
824     size_t StrLen =
825         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
826 
827     analyze_format_string::ParseScanfString(H, FormatBytes,
828                                             FormatBytes + StrLen, getLangOpts(),
829                                             Context.getTargetInfo());
830 
831     // Unlike the other cases, in this one we have already issued the diagnostic
832     // here, so no need to continue (because unlike the other cases, here the
833     // diagnostic refers to the argument number).
834     return;
835   }
836 
837   case Builtin::BIsprintf:
838   case Builtin::BI__builtin___sprintf_chk: {
839     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
840     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
841 
842     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
843 
844       if (!Format->isAscii() && !Format->isUTF8())
845         return;
846 
847       StringRef FormatStrRef = Format->getString();
848       EstimateSizeFormatHandler H(FormatStrRef);
849       const char *FormatBytes = FormatStrRef.data();
850       const ConstantArrayType *T =
851           Context.getAsConstantArrayType(Format->getType());
852       assert(T && "String literal not of constant array type!");
853       size_t TypeSize = T->getSize().getZExtValue();
854 
855       // In case there's a null byte somewhere.
856       size_t StrLen =
857           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
858       if (!analyze_format_string::ParsePrintfString(
859               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
860               Context.getTargetInfo(), false)) {
861         DiagID = diag::warn_fortify_source_format_overflow;
862         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
863                          .extOrTrunc(SizeTypeWidth);
864         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
865           DestinationSize = ComputeExplicitObjectSizeArgument(2);
866           IsChkVariant = true;
867         } else {
868           DestinationSize = ComputeSizeArgument(0);
869         }
870         break;
871       }
872     }
873     return;
874   }
875   case Builtin::BI__builtin___memcpy_chk:
876   case Builtin::BI__builtin___memmove_chk:
877   case Builtin::BI__builtin___memset_chk:
878   case Builtin::BI__builtin___strlcat_chk:
879   case Builtin::BI__builtin___strlcpy_chk:
880   case Builtin::BI__builtin___strncat_chk:
881   case Builtin::BI__builtin___strncpy_chk:
882   case Builtin::BI__builtin___stpncpy_chk:
883   case Builtin::BI__builtin___memccpy_chk:
884   case Builtin::BI__builtin___mempcpy_chk: {
885     DiagID = diag::warn_builtin_chk_overflow;
886     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
887     DestinationSize =
888         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
889     IsChkVariant = true;
890     break;
891   }
892 
893   case Builtin::BI__builtin___snprintf_chk:
894   case Builtin::BI__builtin___vsnprintf_chk: {
895     DiagID = diag::warn_builtin_chk_overflow;
896     SourceSize = ComputeExplicitObjectSizeArgument(1);
897     DestinationSize = ComputeExplicitObjectSizeArgument(3);
898     IsChkVariant = true;
899     break;
900   }
901 
902   case Builtin::BIstrncat:
903   case Builtin::BI__builtin_strncat:
904   case Builtin::BIstrncpy:
905   case Builtin::BI__builtin_strncpy:
906   case Builtin::BIstpncpy:
907   case Builtin::BI__builtin_stpncpy: {
908     // Whether these functions overflow depends on the runtime strlen of the
909     // string, not just the buffer size, so emitting the "always overflow"
910     // diagnostic isn't quite right. We should still diagnose passing a buffer
911     // size larger than the destination buffer though; this is a runtime abort
912     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
913     DiagID = diag::warn_fortify_source_size_mismatch;
914     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
915     DestinationSize = ComputeSizeArgument(0);
916     break;
917   }
918 
919   case Builtin::BImemcpy:
920   case Builtin::BI__builtin_memcpy:
921   case Builtin::BImemmove:
922   case Builtin::BI__builtin_memmove:
923   case Builtin::BImemset:
924   case Builtin::BI__builtin_memset:
925   case Builtin::BImempcpy:
926   case Builtin::BI__builtin_mempcpy: {
927     DiagID = diag::warn_fortify_source_overflow;
928     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
929     DestinationSize = ComputeSizeArgument(0);
930     break;
931   }
932   case Builtin::BIsnprintf:
933   case Builtin::BI__builtin_snprintf:
934   case Builtin::BIvsnprintf:
935   case Builtin::BI__builtin_vsnprintf: {
936     DiagID = diag::warn_fortify_source_size_mismatch;
937     SourceSize = ComputeExplicitObjectSizeArgument(1);
938     DestinationSize = ComputeSizeArgument(0);
939     break;
940   }
941   }
942 
943   if (!SourceSize || !DestinationSize ||
944       llvm::APSInt::compareValues(SourceSize.getValue(),
945                                   DestinationSize.getValue()) <= 0)
946     return;
947 
948   StringRef FunctionName = GetFunctionName();
949 
950   SmallString<16> DestinationStr;
951   SmallString<16> SourceStr;
952   DestinationSize->toString(DestinationStr, /*Radix=*/10);
953   SourceSize->toString(SourceStr, /*Radix=*/10);
954   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
955                       PDiag(DiagID)
956                           << FunctionName << DestinationStr << SourceStr);
957 }
958 
959 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
960                                      Scope::ScopeFlags NeededScopeFlags,
961                                      unsigned DiagID) {
962   // Scopes aren't available during instantiation. Fortunately, builtin
963   // functions cannot be template args so they cannot be formed through template
964   // instantiation. Therefore checking once during the parse is sufficient.
965   if (SemaRef.inTemplateInstantiation())
966     return false;
967 
968   Scope *S = SemaRef.getCurScope();
969   while (S && !S->isSEHExceptScope())
970     S = S->getParent();
971   if (!S || !(S->getFlags() & NeededScopeFlags)) {
972     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
973     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
974         << DRE->getDecl()->getIdentifier();
975     return true;
976   }
977 
978   return false;
979 }
980 
981 static inline bool isBlockPointer(Expr *Arg) {
982   return Arg->getType()->isBlockPointerType();
983 }
984 
985 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
986 /// void*, which is a requirement of device side enqueue.
987 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
988   const BlockPointerType *BPT =
989       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
990   ArrayRef<QualType> Params =
991       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
992   unsigned ArgCounter = 0;
993   bool IllegalParams = false;
994   // Iterate through the block parameters until either one is found that is not
995   // a local void*, or the block is valid.
996   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
997        I != E; ++I, ++ArgCounter) {
998     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
999         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1000             LangAS::opencl_local) {
1001       // Get the location of the error. If a block literal has been passed
1002       // (BlockExpr) then we can point straight to the offending argument,
1003       // else we just point to the variable reference.
1004       SourceLocation ErrorLoc;
1005       if (isa<BlockExpr>(BlockArg)) {
1006         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1007         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1008       } else if (isa<DeclRefExpr>(BlockArg)) {
1009         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1010       }
1011       S.Diag(ErrorLoc,
1012              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1013       IllegalParams = true;
1014     }
1015   }
1016 
1017   return IllegalParams;
1018 }
1019 
1020 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1021   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
1022     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1023         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
1024     return true;
1025   }
1026   return false;
1027 }
1028 
1029 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1030   if (checkArgCount(S, TheCall, 2))
1031     return true;
1032 
1033   if (checkOpenCLSubgroupExt(S, TheCall))
1034     return true;
1035 
1036   // First argument is an ndrange_t type.
1037   Expr *NDRangeArg = TheCall->getArg(0);
1038   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1039     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1040         << TheCall->getDirectCallee() << "'ndrange_t'";
1041     return true;
1042   }
1043 
1044   Expr *BlockArg = TheCall->getArg(1);
1045   if (!isBlockPointer(BlockArg)) {
1046     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1047         << TheCall->getDirectCallee() << "block";
1048     return true;
1049   }
1050   return checkOpenCLBlockArgs(S, BlockArg);
1051 }
1052 
1053 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1054 /// get_kernel_work_group_size
1055 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1056 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1057   if (checkArgCount(S, TheCall, 1))
1058     return true;
1059 
1060   Expr *BlockArg = TheCall->getArg(0);
1061   if (!isBlockPointer(BlockArg)) {
1062     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1063         << TheCall->getDirectCallee() << "block";
1064     return true;
1065   }
1066   return checkOpenCLBlockArgs(S, BlockArg);
1067 }
1068 
1069 /// Diagnose integer type and any valid implicit conversion to it.
1070 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1071                                       const QualType &IntType);
1072 
1073 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1074                                             unsigned Start, unsigned End) {
1075   bool IllegalParams = false;
1076   for (unsigned I = Start; I <= End; ++I)
1077     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1078                                               S.Context.getSizeType());
1079   return IllegalParams;
1080 }
1081 
1082 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1083 /// 'local void*' parameter of passed block.
1084 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1085                                            Expr *BlockArg,
1086                                            unsigned NumNonVarArgs) {
1087   const BlockPointerType *BPT =
1088       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1089   unsigned NumBlockParams =
1090       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1091   unsigned TotalNumArgs = TheCall->getNumArgs();
1092 
1093   // For each argument passed to the block, a corresponding uint needs to
1094   // be passed to describe the size of the local memory.
1095   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1096     S.Diag(TheCall->getBeginLoc(),
1097            diag::err_opencl_enqueue_kernel_local_size_args);
1098     return true;
1099   }
1100 
1101   // Check that the sizes of the local memory are specified by integers.
1102   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1103                                          TotalNumArgs - 1);
1104 }
1105 
1106 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1107 /// overload formats specified in Table 6.13.17.1.
1108 /// int enqueue_kernel(queue_t queue,
1109 ///                    kernel_enqueue_flags_t flags,
1110 ///                    const ndrange_t ndrange,
1111 ///                    void (^block)(void))
1112 /// int enqueue_kernel(queue_t queue,
1113 ///                    kernel_enqueue_flags_t flags,
1114 ///                    const ndrange_t ndrange,
1115 ///                    uint num_events_in_wait_list,
1116 ///                    clk_event_t *event_wait_list,
1117 ///                    clk_event_t *event_ret,
1118 ///                    void (^block)(void))
1119 /// int enqueue_kernel(queue_t queue,
1120 ///                    kernel_enqueue_flags_t flags,
1121 ///                    const ndrange_t ndrange,
1122 ///                    void (^block)(local void*, ...),
1123 ///                    uint size0, ...)
1124 /// int enqueue_kernel(queue_t queue,
1125 ///                    kernel_enqueue_flags_t flags,
1126 ///                    const ndrange_t ndrange,
1127 ///                    uint num_events_in_wait_list,
1128 ///                    clk_event_t *event_wait_list,
1129 ///                    clk_event_t *event_ret,
1130 ///                    void (^block)(local void*, ...),
1131 ///                    uint size0, ...)
1132 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1133   unsigned NumArgs = TheCall->getNumArgs();
1134 
1135   if (NumArgs < 4) {
1136     S.Diag(TheCall->getBeginLoc(),
1137            diag::err_typecheck_call_too_few_args_at_least)
1138         << 0 << 4 << NumArgs;
1139     return true;
1140   }
1141 
1142   Expr *Arg0 = TheCall->getArg(0);
1143   Expr *Arg1 = TheCall->getArg(1);
1144   Expr *Arg2 = TheCall->getArg(2);
1145   Expr *Arg3 = TheCall->getArg(3);
1146 
1147   // First argument always needs to be a queue_t type.
1148   if (!Arg0->getType()->isQueueT()) {
1149     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1150            diag::err_opencl_builtin_expected_type)
1151         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1152     return true;
1153   }
1154 
1155   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1156   if (!Arg1->getType()->isIntegerType()) {
1157     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1158            diag::err_opencl_builtin_expected_type)
1159         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1160     return true;
1161   }
1162 
1163   // Third argument is always an ndrange_t type.
1164   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1165     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1166            diag::err_opencl_builtin_expected_type)
1167         << TheCall->getDirectCallee() << "'ndrange_t'";
1168     return true;
1169   }
1170 
1171   // With four arguments, there is only one form that the function could be
1172   // called in: no events and no variable arguments.
1173   if (NumArgs == 4) {
1174     // check that the last argument is the right block type.
1175     if (!isBlockPointer(Arg3)) {
1176       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1177           << TheCall->getDirectCallee() << "block";
1178       return true;
1179     }
1180     // we have a block type, check the prototype
1181     const BlockPointerType *BPT =
1182         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1183     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1184       S.Diag(Arg3->getBeginLoc(),
1185              diag::err_opencl_enqueue_kernel_blocks_no_args);
1186       return true;
1187     }
1188     return false;
1189   }
1190   // we can have block + varargs.
1191   if (isBlockPointer(Arg3))
1192     return (checkOpenCLBlockArgs(S, Arg3) ||
1193             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1194   // last two cases with either exactly 7 args or 7 args and varargs.
1195   if (NumArgs >= 7) {
1196     // check common block argument.
1197     Expr *Arg6 = TheCall->getArg(6);
1198     if (!isBlockPointer(Arg6)) {
1199       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1200           << TheCall->getDirectCallee() << "block";
1201       return true;
1202     }
1203     if (checkOpenCLBlockArgs(S, Arg6))
1204       return true;
1205 
1206     // Forth argument has to be any integer type.
1207     if (!Arg3->getType()->isIntegerType()) {
1208       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1209              diag::err_opencl_builtin_expected_type)
1210           << TheCall->getDirectCallee() << "integer";
1211       return true;
1212     }
1213     // check remaining common arguments.
1214     Expr *Arg4 = TheCall->getArg(4);
1215     Expr *Arg5 = TheCall->getArg(5);
1216 
1217     // Fifth argument is always passed as a pointer to clk_event_t.
1218     if (!Arg4->isNullPointerConstant(S.Context,
1219                                      Expr::NPC_ValueDependentIsNotNull) &&
1220         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1221       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1222              diag::err_opencl_builtin_expected_type)
1223           << TheCall->getDirectCallee()
1224           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1225       return true;
1226     }
1227 
1228     // Sixth argument is always passed as a pointer to clk_event_t.
1229     if (!Arg5->isNullPointerConstant(S.Context,
1230                                      Expr::NPC_ValueDependentIsNotNull) &&
1231         !(Arg5->getType()->isPointerType() &&
1232           Arg5->getType()->getPointeeType()->isClkEventT())) {
1233       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1234              diag::err_opencl_builtin_expected_type)
1235           << TheCall->getDirectCallee()
1236           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1237       return true;
1238     }
1239 
1240     if (NumArgs == 7)
1241       return false;
1242 
1243     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1244   }
1245 
1246   // None of the specific case has been detected, give generic error
1247   S.Diag(TheCall->getBeginLoc(),
1248          diag::err_opencl_enqueue_kernel_incorrect_args);
1249   return true;
1250 }
1251 
1252 /// Returns OpenCL access qual.
1253 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1254     return D->getAttr<OpenCLAccessAttr>();
1255 }
1256 
1257 /// Returns true if pipe element type is different from the pointer.
1258 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1259   const Expr *Arg0 = Call->getArg(0);
1260   // First argument type should always be pipe.
1261   if (!Arg0->getType()->isPipeType()) {
1262     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1263         << Call->getDirectCallee() << Arg0->getSourceRange();
1264     return true;
1265   }
1266   OpenCLAccessAttr *AccessQual =
1267       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1268   // Validates the access qualifier is compatible with the call.
1269   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1270   // read_only and write_only, and assumed to be read_only if no qualifier is
1271   // specified.
1272   switch (Call->getDirectCallee()->getBuiltinID()) {
1273   case Builtin::BIread_pipe:
1274   case Builtin::BIreserve_read_pipe:
1275   case Builtin::BIcommit_read_pipe:
1276   case Builtin::BIwork_group_reserve_read_pipe:
1277   case Builtin::BIsub_group_reserve_read_pipe:
1278   case Builtin::BIwork_group_commit_read_pipe:
1279   case Builtin::BIsub_group_commit_read_pipe:
1280     if (!(!AccessQual || AccessQual->isReadOnly())) {
1281       S.Diag(Arg0->getBeginLoc(),
1282              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1283           << "read_only" << Arg0->getSourceRange();
1284       return true;
1285     }
1286     break;
1287   case Builtin::BIwrite_pipe:
1288   case Builtin::BIreserve_write_pipe:
1289   case Builtin::BIcommit_write_pipe:
1290   case Builtin::BIwork_group_reserve_write_pipe:
1291   case Builtin::BIsub_group_reserve_write_pipe:
1292   case Builtin::BIwork_group_commit_write_pipe:
1293   case Builtin::BIsub_group_commit_write_pipe:
1294     if (!(AccessQual && AccessQual->isWriteOnly())) {
1295       S.Diag(Arg0->getBeginLoc(),
1296              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1297           << "write_only" << Arg0->getSourceRange();
1298       return true;
1299     }
1300     break;
1301   default:
1302     break;
1303   }
1304   return false;
1305 }
1306 
1307 /// Returns true if pipe element type is different from the pointer.
1308 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1309   const Expr *Arg0 = Call->getArg(0);
1310   const Expr *ArgIdx = Call->getArg(Idx);
1311   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1312   const QualType EltTy = PipeTy->getElementType();
1313   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1314   // The Idx argument should be a pointer and the type of the pointer and
1315   // the type of pipe element should also be the same.
1316   if (!ArgTy ||
1317       !S.Context.hasSameType(
1318           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1319     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1320         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1321         << ArgIdx->getType() << ArgIdx->getSourceRange();
1322     return true;
1323   }
1324   return false;
1325 }
1326 
1327 // Performs semantic analysis for the read/write_pipe call.
1328 // \param S Reference to the semantic analyzer.
1329 // \param Call A pointer to the builtin call.
1330 // \return True if a semantic error has been found, false otherwise.
1331 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1332   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1333   // functions have two forms.
1334   switch (Call->getNumArgs()) {
1335   case 2:
1336     if (checkOpenCLPipeArg(S, Call))
1337       return true;
1338     // The call with 2 arguments should be
1339     // read/write_pipe(pipe T, T*).
1340     // Check packet type T.
1341     if (checkOpenCLPipePacketType(S, Call, 1))
1342       return true;
1343     break;
1344 
1345   case 4: {
1346     if (checkOpenCLPipeArg(S, Call))
1347       return true;
1348     // The call with 4 arguments should be
1349     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1350     // Check reserve_id_t.
1351     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1352       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1353           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1354           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1355       return true;
1356     }
1357 
1358     // Check the index.
1359     const Expr *Arg2 = Call->getArg(2);
1360     if (!Arg2->getType()->isIntegerType() &&
1361         !Arg2->getType()->isUnsignedIntegerType()) {
1362       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1363           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1364           << Arg2->getType() << Arg2->getSourceRange();
1365       return true;
1366     }
1367 
1368     // Check packet type T.
1369     if (checkOpenCLPipePacketType(S, Call, 3))
1370       return true;
1371   } break;
1372   default:
1373     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1374         << Call->getDirectCallee() << Call->getSourceRange();
1375     return true;
1376   }
1377 
1378   return false;
1379 }
1380 
1381 // Performs a semantic analysis on the {work_group_/sub_group_
1382 //        /_}reserve_{read/write}_pipe
1383 // \param S Reference to the semantic analyzer.
1384 // \param Call The call to the builtin function to be analyzed.
1385 // \return True if a semantic error was found, false otherwise.
1386 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1387   if (checkArgCount(S, Call, 2))
1388     return true;
1389 
1390   if (checkOpenCLPipeArg(S, Call))
1391     return true;
1392 
1393   // Check the reserve size.
1394   if (!Call->getArg(1)->getType()->isIntegerType() &&
1395       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1396     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1397         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1398         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1399     return true;
1400   }
1401 
1402   // Since return type of reserve_read/write_pipe built-in function is
1403   // reserve_id_t, which is not defined in the builtin def file , we used int
1404   // as return type and need to override the return type of these functions.
1405   Call->setType(S.Context.OCLReserveIDTy);
1406 
1407   return false;
1408 }
1409 
1410 // Performs a semantic analysis on {work_group_/sub_group_
1411 //        /_}commit_{read/write}_pipe
1412 // \param S Reference to the semantic analyzer.
1413 // \param Call The call to the builtin function to be analyzed.
1414 // \return True if a semantic error was found, false otherwise.
1415 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1416   if (checkArgCount(S, Call, 2))
1417     return true;
1418 
1419   if (checkOpenCLPipeArg(S, Call))
1420     return true;
1421 
1422   // Check reserve_id_t.
1423   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1424     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1425         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1426         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1427     return true;
1428   }
1429 
1430   return false;
1431 }
1432 
1433 // Performs a semantic analysis on the call to built-in Pipe
1434 //        Query Functions.
1435 // \param S Reference to the semantic analyzer.
1436 // \param Call The call to the builtin function to be analyzed.
1437 // \return True if a semantic error was found, false otherwise.
1438 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1439   if (checkArgCount(S, Call, 1))
1440     return true;
1441 
1442   if (!Call->getArg(0)->getType()->isPipeType()) {
1443     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1444         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1445     return true;
1446   }
1447 
1448   return false;
1449 }
1450 
1451 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1452 // Performs semantic analysis for the to_global/local/private call.
1453 // \param S Reference to the semantic analyzer.
1454 // \param BuiltinID ID of the builtin function.
1455 // \param Call A pointer to the builtin call.
1456 // \return True if a semantic error has been found, false otherwise.
1457 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1458                                     CallExpr *Call) {
1459   if (checkArgCount(S, Call, 1))
1460     return true;
1461 
1462   auto RT = Call->getArg(0)->getType();
1463   if (!RT->isPointerType() || RT->getPointeeType()
1464       .getAddressSpace() == LangAS::opencl_constant) {
1465     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1466         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1467     return true;
1468   }
1469 
1470   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1471     S.Diag(Call->getArg(0)->getBeginLoc(),
1472            diag::warn_opencl_generic_address_space_arg)
1473         << Call->getDirectCallee()->getNameInfo().getAsString()
1474         << Call->getArg(0)->getSourceRange();
1475   }
1476 
1477   RT = RT->getPointeeType();
1478   auto Qual = RT.getQualifiers();
1479   switch (BuiltinID) {
1480   case Builtin::BIto_global:
1481     Qual.setAddressSpace(LangAS::opencl_global);
1482     break;
1483   case Builtin::BIto_local:
1484     Qual.setAddressSpace(LangAS::opencl_local);
1485     break;
1486   case Builtin::BIto_private:
1487     Qual.setAddressSpace(LangAS::opencl_private);
1488     break;
1489   default:
1490     llvm_unreachable("Invalid builtin function");
1491   }
1492   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1493       RT.getUnqualifiedType(), Qual)));
1494 
1495   return false;
1496 }
1497 
1498 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1499   if (checkArgCount(S, TheCall, 1))
1500     return ExprError();
1501 
1502   // Compute __builtin_launder's parameter type from the argument.
1503   // The parameter type is:
1504   //  * The type of the argument if it's not an array or function type,
1505   //  Otherwise,
1506   //  * The decayed argument type.
1507   QualType ParamTy = [&]() {
1508     QualType ArgTy = TheCall->getArg(0)->getType();
1509     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1510       return S.Context.getPointerType(Ty->getElementType());
1511     if (ArgTy->isFunctionType()) {
1512       return S.Context.getPointerType(ArgTy);
1513     }
1514     return ArgTy;
1515   }();
1516 
1517   TheCall->setType(ParamTy);
1518 
1519   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1520     if (!ParamTy->isPointerType())
1521       return 0;
1522     if (ParamTy->isFunctionPointerType())
1523       return 1;
1524     if (ParamTy->isVoidPointerType())
1525       return 2;
1526     return llvm::Optional<unsigned>{};
1527   }();
1528   if (DiagSelect.hasValue()) {
1529     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1530         << DiagSelect.getValue() << TheCall->getSourceRange();
1531     return ExprError();
1532   }
1533 
1534   // We either have an incomplete class type, or we have a class template
1535   // whose instantiation has not been forced. Example:
1536   //
1537   //   template <class T> struct Foo { T value; };
1538   //   Foo<int> *p = nullptr;
1539   //   auto *d = __builtin_launder(p);
1540   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1541                             diag::err_incomplete_type))
1542     return ExprError();
1543 
1544   assert(ParamTy->getPointeeType()->isObjectType() &&
1545          "Unhandled non-object pointer case");
1546 
1547   InitializedEntity Entity =
1548       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1549   ExprResult Arg =
1550       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1551   if (Arg.isInvalid())
1552     return ExprError();
1553   TheCall->setArg(0, Arg.get());
1554 
1555   return TheCall;
1556 }
1557 
1558 // Emit an error and return true if the current architecture is not in the list
1559 // of supported architectures.
1560 static bool
1561 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1562                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1563   llvm::Triple::ArchType CurArch =
1564       S.getASTContext().getTargetInfo().getTriple().getArch();
1565   if (llvm::is_contained(SupportedArchs, CurArch))
1566     return false;
1567   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1568       << TheCall->getSourceRange();
1569   return true;
1570 }
1571 
1572 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1573                                  SourceLocation CallSiteLoc);
1574 
1575 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1576                                       CallExpr *TheCall) {
1577   switch (TI.getTriple().getArch()) {
1578   default:
1579     // Some builtins don't require additional checking, so just consider these
1580     // acceptable.
1581     return false;
1582   case llvm::Triple::arm:
1583   case llvm::Triple::armeb:
1584   case llvm::Triple::thumb:
1585   case llvm::Triple::thumbeb:
1586     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1587   case llvm::Triple::aarch64:
1588   case llvm::Triple::aarch64_32:
1589   case llvm::Triple::aarch64_be:
1590     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1591   case llvm::Triple::bpfeb:
1592   case llvm::Triple::bpfel:
1593     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1594   case llvm::Triple::hexagon:
1595     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1596   case llvm::Triple::mips:
1597   case llvm::Triple::mipsel:
1598   case llvm::Triple::mips64:
1599   case llvm::Triple::mips64el:
1600     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1601   case llvm::Triple::systemz:
1602     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1603   case llvm::Triple::x86:
1604   case llvm::Triple::x86_64:
1605     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1606   case llvm::Triple::ppc:
1607   case llvm::Triple::ppcle:
1608   case llvm::Triple::ppc64:
1609   case llvm::Triple::ppc64le:
1610     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1611   case llvm::Triple::amdgcn:
1612     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1613   case llvm::Triple::riscv32:
1614   case llvm::Triple::riscv64:
1615     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1616   }
1617 }
1618 
1619 ExprResult
1620 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1621                                CallExpr *TheCall) {
1622   ExprResult TheCallResult(TheCall);
1623 
1624   // Find out if any arguments are required to be integer constant expressions.
1625   unsigned ICEArguments = 0;
1626   ASTContext::GetBuiltinTypeError Error;
1627   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1628   if (Error != ASTContext::GE_None)
1629     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1630 
1631   // If any arguments are required to be ICE's, check and diagnose.
1632   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1633     // Skip arguments not required to be ICE's.
1634     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1635 
1636     llvm::APSInt Result;
1637     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1638       return true;
1639     ICEArguments &= ~(1 << ArgNo);
1640   }
1641 
1642   switch (BuiltinID) {
1643   case Builtin::BI__builtin___CFStringMakeConstantString:
1644     assert(TheCall->getNumArgs() == 1 &&
1645            "Wrong # arguments to builtin CFStringMakeConstantString");
1646     if (CheckObjCString(TheCall->getArg(0)))
1647       return ExprError();
1648     break;
1649   case Builtin::BI__builtin_ms_va_start:
1650   case Builtin::BI__builtin_stdarg_start:
1651   case Builtin::BI__builtin_va_start:
1652     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1653       return ExprError();
1654     break;
1655   case Builtin::BI__va_start: {
1656     switch (Context.getTargetInfo().getTriple().getArch()) {
1657     case llvm::Triple::aarch64:
1658     case llvm::Triple::arm:
1659     case llvm::Triple::thumb:
1660       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1661         return ExprError();
1662       break;
1663     default:
1664       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1665         return ExprError();
1666       break;
1667     }
1668     break;
1669   }
1670 
1671   // The acquire, release, and no fence variants are ARM and AArch64 only.
1672   case Builtin::BI_interlockedbittestandset_acq:
1673   case Builtin::BI_interlockedbittestandset_rel:
1674   case Builtin::BI_interlockedbittestandset_nf:
1675   case Builtin::BI_interlockedbittestandreset_acq:
1676   case Builtin::BI_interlockedbittestandreset_rel:
1677   case Builtin::BI_interlockedbittestandreset_nf:
1678     if (CheckBuiltinTargetSupport(
1679             *this, BuiltinID, TheCall,
1680             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1681       return ExprError();
1682     break;
1683 
1684   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1685   case Builtin::BI_bittest64:
1686   case Builtin::BI_bittestandcomplement64:
1687   case Builtin::BI_bittestandreset64:
1688   case Builtin::BI_bittestandset64:
1689   case Builtin::BI_interlockedbittestandreset64:
1690   case Builtin::BI_interlockedbittestandset64:
1691     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1692                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1693                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1694       return ExprError();
1695     break;
1696 
1697   case Builtin::BI__builtin_isgreater:
1698   case Builtin::BI__builtin_isgreaterequal:
1699   case Builtin::BI__builtin_isless:
1700   case Builtin::BI__builtin_islessequal:
1701   case Builtin::BI__builtin_islessgreater:
1702   case Builtin::BI__builtin_isunordered:
1703     if (SemaBuiltinUnorderedCompare(TheCall))
1704       return ExprError();
1705     break;
1706   case Builtin::BI__builtin_fpclassify:
1707     if (SemaBuiltinFPClassification(TheCall, 6))
1708       return ExprError();
1709     break;
1710   case Builtin::BI__builtin_isfinite:
1711   case Builtin::BI__builtin_isinf:
1712   case Builtin::BI__builtin_isinf_sign:
1713   case Builtin::BI__builtin_isnan:
1714   case Builtin::BI__builtin_isnormal:
1715   case Builtin::BI__builtin_signbit:
1716   case Builtin::BI__builtin_signbitf:
1717   case Builtin::BI__builtin_signbitl:
1718     if (SemaBuiltinFPClassification(TheCall, 1))
1719       return ExprError();
1720     break;
1721   case Builtin::BI__builtin_shufflevector:
1722     return SemaBuiltinShuffleVector(TheCall);
1723     // TheCall will be freed by the smart pointer here, but that's fine, since
1724     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1725   case Builtin::BI__builtin_prefetch:
1726     if (SemaBuiltinPrefetch(TheCall))
1727       return ExprError();
1728     break;
1729   case Builtin::BI__builtin_alloca_with_align:
1730     if (SemaBuiltinAllocaWithAlign(TheCall))
1731       return ExprError();
1732     LLVM_FALLTHROUGH;
1733   case Builtin::BI__builtin_alloca:
1734     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1735         << TheCall->getDirectCallee();
1736     break;
1737   case Builtin::BI__arithmetic_fence:
1738     if (SemaBuiltinArithmeticFence(TheCall))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__assume:
1742   case Builtin::BI__builtin_assume:
1743     if (SemaBuiltinAssume(TheCall))
1744       return ExprError();
1745     break;
1746   case Builtin::BI__builtin_assume_aligned:
1747     if (SemaBuiltinAssumeAligned(TheCall))
1748       return ExprError();
1749     break;
1750   case Builtin::BI__builtin_dynamic_object_size:
1751   case Builtin::BI__builtin_object_size:
1752     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1753       return ExprError();
1754     break;
1755   case Builtin::BI__builtin_longjmp:
1756     if (SemaBuiltinLongjmp(TheCall))
1757       return ExprError();
1758     break;
1759   case Builtin::BI__builtin_setjmp:
1760     if (SemaBuiltinSetjmp(TheCall))
1761       return ExprError();
1762     break;
1763   case Builtin::BI__builtin_classify_type:
1764     if (checkArgCount(*this, TheCall, 1)) return true;
1765     TheCall->setType(Context.IntTy);
1766     break;
1767   case Builtin::BI__builtin_complex:
1768     if (SemaBuiltinComplex(TheCall))
1769       return ExprError();
1770     break;
1771   case Builtin::BI__builtin_constant_p: {
1772     if (checkArgCount(*this, TheCall, 1)) return true;
1773     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1774     if (Arg.isInvalid()) return true;
1775     TheCall->setArg(0, Arg.get());
1776     TheCall->setType(Context.IntTy);
1777     break;
1778   }
1779   case Builtin::BI__builtin_launder:
1780     return SemaBuiltinLaunder(*this, TheCall);
1781   case Builtin::BI__sync_fetch_and_add:
1782   case Builtin::BI__sync_fetch_and_add_1:
1783   case Builtin::BI__sync_fetch_and_add_2:
1784   case Builtin::BI__sync_fetch_and_add_4:
1785   case Builtin::BI__sync_fetch_and_add_8:
1786   case Builtin::BI__sync_fetch_and_add_16:
1787   case Builtin::BI__sync_fetch_and_sub:
1788   case Builtin::BI__sync_fetch_and_sub_1:
1789   case Builtin::BI__sync_fetch_and_sub_2:
1790   case Builtin::BI__sync_fetch_and_sub_4:
1791   case Builtin::BI__sync_fetch_and_sub_8:
1792   case Builtin::BI__sync_fetch_and_sub_16:
1793   case Builtin::BI__sync_fetch_and_or:
1794   case Builtin::BI__sync_fetch_and_or_1:
1795   case Builtin::BI__sync_fetch_and_or_2:
1796   case Builtin::BI__sync_fetch_and_or_4:
1797   case Builtin::BI__sync_fetch_and_or_8:
1798   case Builtin::BI__sync_fetch_and_or_16:
1799   case Builtin::BI__sync_fetch_and_and:
1800   case Builtin::BI__sync_fetch_and_and_1:
1801   case Builtin::BI__sync_fetch_and_and_2:
1802   case Builtin::BI__sync_fetch_and_and_4:
1803   case Builtin::BI__sync_fetch_and_and_8:
1804   case Builtin::BI__sync_fetch_and_and_16:
1805   case Builtin::BI__sync_fetch_and_xor:
1806   case Builtin::BI__sync_fetch_and_xor_1:
1807   case Builtin::BI__sync_fetch_and_xor_2:
1808   case Builtin::BI__sync_fetch_and_xor_4:
1809   case Builtin::BI__sync_fetch_and_xor_8:
1810   case Builtin::BI__sync_fetch_and_xor_16:
1811   case Builtin::BI__sync_fetch_and_nand:
1812   case Builtin::BI__sync_fetch_and_nand_1:
1813   case Builtin::BI__sync_fetch_and_nand_2:
1814   case Builtin::BI__sync_fetch_and_nand_4:
1815   case Builtin::BI__sync_fetch_and_nand_8:
1816   case Builtin::BI__sync_fetch_and_nand_16:
1817   case Builtin::BI__sync_add_and_fetch:
1818   case Builtin::BI__sync_add_and_fetch_1:
1819   case Builtin::BI__sync_add_and_fetch_2:
1820   case Builtin::BI__sync_add_and_fetch_4:
1821   case Builtin::BI__sync_add_and_fetch_8:
1822   case Builtin::BI__sync_add_and_fetch_16:
1823   case Builtin::BI__sync_sub_and_fetch:
1824   case Builtin::BI__sync_sub_and_fetch_1:
1825   case Builtin::BI__sync_sub_and_fetch_2:
1826   case Builtin::BI__sync_sub_and_fetch_4:
1827   case Builtin::BI__sync_sub_and_fetch_8:
1828   case Builtin::BI__sync_sub_and_fetch_16:
1829   case Builtin::BI__sync_and_and_fetch:
1830   case Builtin::BI__sync_and_and_fetch_1:
1831   case Builtin::BI__sync_and_and_fetch_2:
1832   case Builtin::BI__sync_and_and_fetch_4:
1833   case Builtin::BI__sync_and_and_fetch_8:
1834   case Builtin::BI__sync_and_and_fetch_16:
1835   case Builtin::BI__sync_or_and_fetch:
1836   case Builtin::BI__sync_or_and_fetch_1:
1837   case Builtin::BI__sync_or_and_fetch_2:
1838   case Builtin::BI__sync_or_and_fetch_4:
1839   case Builtin::BI__sync_or_and_fetch_8:
1840   case Builtin::BI__sync_or_and_fetch_16:
1841   case Builtin::BI__sync_xor_and_fetch:
1842   case Builtin::BI__sync_xor_and_fetch_1:
1843   case Builtin::BI__sync_xor_and_fetch_2:
1844   case Builtin::BI__sync_xor_and_fetch_4:
1845   case Builtin::BI__sync_xor_and_fetch_8:
1846   case Builtin::BI__sync_xor_and_fetch_16:
1847   case Builtin::BI__sync_nand_and_fetch:
1848   case Builtin::BI__sync_nand_and_fetch_1:
1849   case Builtin::BI__sync_nand_and_fetch_2:
1850   case Builtin::BI__sync_nand_and_fetch_4:
1851   case Builtin::BI__sync_nand_and_fetch_8:
1852   case Builtin::BI__sync_nand_and_fetch_16:
1853   case Builtin::BI__sync_val_compare_and_swap:
1854   case Builtin::BI__sync_val_compare_and_swap_1:
1855   case Builtin::BI__sync_val_compare_and_swap_2:
1856   case Builtin::BI__sync_val_compare_and_swap_4:
1857   case Builtin::BI__sync_val_compare_and_swap_8:
1858   case Builtin::BI__sync_val_compare_and_swap_16:
1859   case Builtin::BI__sync_bool_compare_and_swap:
1860   case Builtin::BI__sync_bool_compare_and_swap_1:
1861   case Builtin::BI__sync_bool_compare_and_swap_2:
1862   case Builtin::BI__sync_bool_compare_and_swap_4:
1863   case Builtin::BI__sync_bool_compare_and_swap_8:
1864   case Builtin::BI__sync_bool_compare_and_swap_16:
1865   case Builtin::BI__sync_lock_test_and_set:
1866   case Builtin::BI__sync_lock_test_and_set_1:
1867   case Builtin::BI__sync_lock_test_and_set_2:
1868   case Builtin::BI__sync_lock_test_and_set_4:
1869   case Builtin::BI__sync_lock_test_and_set_8:
1870   case Builtin::BI__sync_lock_test_and_set_16:
1871   case Builtin::BI__sync_lock_release:
1872   case Builtin::BI__sync_lock_release_1:
1873   case Builtin::BI__sync_lock_release_2:
1874   case Builtin::BI__sync_lock_release_4:
1875   case Builtin::BI__sync_lock_release_8:
1876   case Builtin::BI__sync_lock_release_16:
1877   case Builtin::BI__sync_swap:
1878   case Builtin::BI__sync_swap_1:
1879   case Builtin::BI__sync_swap_2:
1880   case Builtin::BI__sync_swap_4:
1881   case Builtin::BI__sync_swap_8:
1882   case Builtin::BI__sync_swap_16:
1883     return SemaBuiltinAtomicOverloaded(TheCallResult);
1884   case Builtin::BI__sync_synchronize:
1885     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1886         << TheCall->getCallee()->getSourceRange();
1887     break;
1888   case Builtin::BI__builtin_nontemporal_load:
1889   case Builtin::BI__builtin_nontemporal_store:
1890     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1891   case Builtin::BI__builtin_memcpy_inline: {
1892     clang::Expr *SizeOp = TheCall->getArg(2);
1893     // We warn about copying to or from `nullptr` pointers when `size` is
1894     // greater than 0. When `size` is value dependent we cannot evaluate its
1895     // value so we bail out.
1896     if (SizeOp->isValueDependent())
1897       break;
1898     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1899       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1900       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1901     }
1902     break;
1903   }
1904 #define BUILTIN(ID, TYPE, ATTRS)
1905 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1906   case Builtin::BI##ID: \
1907     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1908 #include "clang/Basic/Builtins.def"
1909   case Builtin::BI__annotation:
1910     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BI__builtin_annotation:
1914     if (SemaBuiltinAnnotation(*this, TheCall))
1915       return ExprError();
1916     break;
1917   case Builtin::BI__builtin_addressof:
1918     if (SemaBuiltinAddressof(*this, TheCall))
1919       return ExprError();
1920     break;
1921   case Builtin::BI__builtin_is_aligned:
1922   case Builtin::BI__builtin_align_up:
1923   case Builtin::BI__builtin_align_down:
1924     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1925       return ExprError();
1926     break;
1927   case Builtin::BI__builtin_add_overflow:
1928   case Builtin::BI__builtin_sub_overflow:
1929   case Builtin::BI__builtin_mul_overflow:
1930     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1931       return ExprError();
1932     break;
1933   case Builtin::BI__builtin_operator_new:
1934   case Builtin::BI__builtin_operator_delete: {
1935     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1936     ExprResult Res =
1937         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1938     if (Res.isInvalid())
1939       CorrectDelayedTyposInExpr(TheCallResult.get());
1940     return Res;
1941   }
1942   case Builtin::BI__builtin_dump_struct: {
1943     // We first want to ensure we are called with 2 arguments
1944     if (checkArgCount(*this, TheCall, 2))
1945       return ExprError();
1946     // Ensure that the first argument is of type 'struct XX *'
1947     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1948     const QualType PtrArgType = PtrArg->getType();
1949     if (!PtrArgType->isPointerType() ||
1950         !PtrArgType->getPointeeType()->isRecordType()) {
1951       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1952           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1953           << "structure pointer";
1954       return ExprError();
1955     }
1956 
1957     // Ensure that the second argument is of type 'FunctionType'
1958     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1959     const QualType FnPtrArgType = FnPtrArg->getType();
1960     if (!FnPtrArgType->isPointerType()) {
1961       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1962           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1963           << FnPtrArgType << "'int (*)(const char *, ...)'";
1964       return ExprError();
1965     }
1966 
1967     const auto *FuncType =
1968         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1969 
1970     if (!FuncType) {
1971       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1972           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1973           << FnPtrArgType << "'int (*)(const char *, ...)'";
1974       return ExprError();
1975     }
1976 
1977     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1978       if (!FT->getNumParams()) {
1979         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1980             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1981             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1982         return ExprError();
1983       }
1984       QualType PT = FT->getParamType(0);
1985       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1986           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1987           !PT->getPointeeType().isConstQualified()) {
1988         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1989             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1990             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1991         return ExprError();
1992       }
1993     }
1994 
1995     TheCall->setType(Context.IntTy);
1996     break;
1997   }
1998   case Builtin::BI__builtin_expect_with_probability: {
1999     // We first want to ensure we are called with 3 arguments
2000     if (checkArgCount(*this, TheCall, 3))
2001       return ExprError();
2002     // then check probability is constant float in range [0.0, 1.0]
2003     const Expr *ProbArg = TheCall->getArg(2);
2004     SmallVector<PartialDiagnosticAt, 8> Notes;
2005     Expr::EvalResult Eval;
2006     Eval.Diag = &Notes;
2007     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2008         !Eval.Val.isFloat()) {
2009       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2010           << ProbArg->getSourceRange();
2011       for (const PartialDiagnosticAt &PDiag : Notes)
2012         Diag(PDiag.first, PDiag.second);
2013       return ExprError();
2014     }
2015     llvm::APFloat Probability = Eval.Val.getFloat();
2016     bool LoseInfo = false;
2017     Probability.convert(llvm::APFloat::IEEEdouble(),
2018                         llvm::RoundingMode::Dynamic, &LoseInfo);
2019     if (!(Probability >= llvm::APFloat(0.0) &&
2020           Probability <= llvm::APFloat(1.0))) {
2021       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2022           << ProbArg->getSourceRange();
2023       return ExprError();
2024     }
2025     break;
2026   }
2027   case Builtin::BI__builtin_preserve_access_index:
2028     if (SemaBuiltinPreserveAI(*this, TheCall))
2029       return ExprError();
2030     break;
2031   case Builtin::BI__builtin_call_with_static_chain:
2032     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2033       return ExprError();
2034     break;
2035   case Builtin::BI__exception_code:
2036   case Builtin::BI_exception_code:
2037     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2038                                  diag::err_seh___except_block))
2039       return ExprError();
2040     break;
2041   case Builtin::BI__exception_info:
2042   case Builtin::BI_exception_info:
2043     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2044                                  diag::err_seh___except_filter))
2045       return ExprError();
2046     break;
2047   case Builtin::BI__GetExceptionInfo:
2048     if (checkArgCount(*this, TheCall, 1))
2049       return ExprError();
2050 
2051     if (CheckCXXThrowOperand(
2052             TheCall->getBeginLoc(),
2053             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2054             TheCall))
2055       return ExprError();
2056 
2057     TheCall->setType(Context.VoidPtrTy);
2058     break;
2059   // OpenCL v2.0, s6.13.16 - Pipe functions
2060   case Builtin::BIread_pipe:
2061   case Builtin::BIwrite_pipe:
2062     // Since those two functions are declared with var args, we need a semantic
2063     // check for the argument.
2064     if (SemaBuiltinRWPipe(*this, TheCall))
2065       return ExprError();
2066     break;
2067   case Builtin::BIreserve_read_pipe:
2068   case Builtin::BIreserve_write_pipe:
2069   case Builtin::BIwork_group_reserve_read_pipe:
2070   case Builtin::BIwork_group_reserve_write_pipe:
2071     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2072       return ExprError();
2073     break;
2074   case Builtin::BIsub_group_reserve_read_pipe:
2075   case Builtin::BIsub_group_reserve_write_pipe:
2076     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2077         SemaBuiltinReserveRWPipe(*this, TheCall))
2078       return ExprError();
2079     break;
2080   case Builtin::BIcommit_read_pipe:
2081   case Builtin::BIcommit_write_pipe:
2082   case Builtin::BIwork_group_commit_read_pipe:
2083   case Builtin::BIwork_group_commit_write_pipe:
2084     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2085       return ExprError();
2086     break;
2087   case Builtin::BIsub_group_commit_read_pipe:
2088   case Builtin::BIsub_group_commit_write_pipe:
2089     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2090         SemaBuiltinCommitRWPipe(*this, TheCall))
2091       return ExprError();
2092     break;
2093   case Builtin::BIget_pipe_num_packets:
2094   case Builtin::BIget_pipe_max_packets:
2095     if (SemaBuiltinPipePackets(*this, TheCall))
2096       return ExprError();
2097     break;
2098   case Builtin::BIto_global:
2099   case Builtin::BIto_local:
2100   case Builtin::BIto_private:
2101     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2102       return ExprError();
2103     break;
2104   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2105   case Builtin::BIenqueue_kernel:
2106     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2107       return ExprError();
2108     break;
2109   case Builtin::BIget_kernel_work_group_size:
2110   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2111     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2112       return ExprError();
2113     break;
2114   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2115   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2116     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2117       return ExprError();
2118     break;
2119   case Builtin::BI__builtin_os_log_format:
2120     Cleanup.setExprNeedsCleanups(true);
2121     LLVM_FALLTHROUGH;
2122   case Builtin::BI__builtin_os_log_format_buffer_size:
2123     if (SemaBuiltinOSLogFormat(TheCall))
2124       return ExprError();
2125     break;
2126   case Builtin::BI__builtin_frame_address:
2127   case Builtin::BI__builtin_return_address: {
2128     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2129       return ExprError();
2130 
2131     // -Wframe-address warning if non-zero passed to builtin
2132     // return/frame address.
2133     Expr::EvalResult Result;
2134     if (!TheCall->getArg(0)->isValueDependent() &&
2135         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2136         Result.Val.getInt() != 0)
2137       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2138           << ((BuiltinID == Builtin::BI__builtin_return_address)
2139                   ? "__builtin_return_address"
2140                   : "__builtin_frame_address")
2141           << TheCall->getSourceRange();
2142     break;
2143   }
2144 
2145   // __builtin_elementwise_abs restricts the element type to signed integers or
2146   // floating point types only.
2147   case Builtin::BI__builtin_elementwise_abs: {
2148     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2149       return ExprError();
2150 
2151     QualType ArgTy = TheCall->getArg(0)->getType();
2152     QualType EltTy = ArgTy;
2153 
2154     if (auto *VecTy = EltTy->getAs<VectorType>())
2155       EltTy = VecTy->getElementType();
2156     if (EltTy->isUnsignedIntegerType()) {
2157       Diag(TheCall->getArg(0)->getBeginLoc(),
2158            diag::err_builtin_invalid_arg_type)
2159           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2160       return ExprError();
2161     }
2162     break;
2163   }
2164 
2165   // __builtin_elementwise_ceil restricts the element type to floating point
2166   // types only.
2167   case Builtin::BI__builtin_elementwise_ceil: {
2168     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2169       return ExprError();
2170 
2171     QualType ArgTy = TheCall->getArg(0)->getType();
2172     QualType EltTy = ArgTy;
2173 
2174     if (auto *VecTy = EltTy->getAs<VectorType>())
2175       EltTy = VecTy->getElementType();
2176     if (!EltTy->isFloatingType()) {
2177       Diag(TheCall->getArg(0)->getBeginLoc(),
2178            diag::err_builtin_invalid_arg_type)
2179           << 1 << /* float ty*/ 5 << ArgTy;
2180 
2181       return ExprError();
2182     }
2183     break;
2184   }
2185 
2186   case Builtin::BI__builtin_elementwise_min:
2187   case Builtin::BI__builtin_elementwise_max:
2188     if (SemaBuiltinElementwiseMath(TheCall))
2189       return ExprError();
2190     break;
2191   case Builtin::BI__builtin_reduce_max:
2192   case Builtin::BI__builtin_reduce_min:
2193     if (SemaBuiltinReduceMath(TheCall))
2194       return ExprError();
2195     break;
2196   case Builtin::BI__builtin_matrix_transpose:
2197     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2198 
2199   case Builtin::BI__builtin_matrix_column_major_load:
2200     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2201 
2202   case Builtin::BI__builtin_matrix_column_major_store:
2203     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2204 
2205   case Builtin::BI__builtin_get_device_side_mangled_name: {
2206     auto Check = [](CallExpr *TheCall) {
2207       if (TheCall->getNumArgs() != 1)
2208         return false;
2209       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2210       if (!DRE)
2211         return false;
2212       auto *D = DRE->getDecl();
2213       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2214         return false;
2215       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2216              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2217     };
2218     if (!Check(TheCall)) {
2219       Diag(TheCall->getBeginLoc(),
2220            diag::err_hip_invalid_args_builtin_mangled_name);
2221       return ExprError();
2222     }
2223   }
2224   }
2225 
2226   // Since the target specific builtins for each arch overlap, only check those
2227   // of the arch we are compiling for.
2228   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2229     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2230       assert(Context.getAuxTargetInfo() &&
2231              "Aux Target Builtin, but not an aux target?");
2232 
2233       if (CheckTSBuiltinFunctionCall(
2234               *Context.getAuxTargetInfo(),
2235               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2236         return ExprError();
2237     } else {
2238       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2239                                      TheCall))
2240         return ExprError();
2241     }
2242   }
2243 
2244   return TheCallResult;
2245 }
2246 
2247 // Get the valid immediate range for the specified NEON type code.
2248 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2249   NeonTypeFlags Type(t);
2250   int IsQuad = ForceQuad ? true : Type.isQuad();
2251   switch (Type.getEltType()) {
2252   case NeonTypeFlags::Int8:
2253   case NeonTypeFlags::Poly8:
2254     return shift ? 7 : (8 << IsQuad) - 1;
2255   case NeonTypeFlags::Int16:
2256   case NeonTypeFlags::Poly16:
2257     return shift ? 15 : (4 << IsQuad) - 1;
2258   case NeonTypeFlags::Int32:
2259     return shift ? 31 : (2 << IsQuad) - 1;
2260   case NeonTypeFlags::Int64:
2261   case NeonTypeFlags::Poly64:
2262     return shift ? 63 : (1 << IsQuad) - 1;
2263   case NeonTypeFlags::Poly128:
2264     return shift ? 127 : (1 << IsQuad) - 1;
2265   case NeonTypeFlags::Float16:
2266     assert(!shift && "cannot shift float types!");
2267     return (4 << IsQuad) - 1;
2268   case NeonTypeFlags::Float32:
2269     assert(!shift && "cannot shift float types!");
2270     return (2 << IsQuad) - 1;
2271   case NeonTypeFlags::Float64:
2272     assert(!shift && "cannot shift float types!");
2273     return (1 << IsQuad) - 1;
2274   case NeonTypeFlags::BFloat16:
2275     assert(!shift && "cannot shift float types!");
2276     return (4 << IsQuad) - 1;
2277   }
2278   llvm_unreachable("Invalid NeonTypeFlag!");
2279 }
2280 
2281 /// getNeonEltType - Return the QualType corresponding to the elements of
2282 /// the vector type specified by the NeonTypeFlags.  This is used to check
2283 /// the pointer arguments for Neon load/store intrinsics.
2284 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2285                                bool IsPolyUnsigned, bool IsInt64Long) {
2286   switch (Flags.getEltType()) {
2287   case NeonTypeFlags::Int8:
2288     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2289   case NeonTypeFlags::Int16:
2290     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2291   case NeonTypeFlags::Int32:
2292     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2293   case NeonTypeFlags::Int64:
2294     if (IsInt64Long)
2295       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2296     else
2297       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2298                                 : Context.LongLongTy;
2299   case NeonTypeFlags::Poly8:
2300     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2301   case NeonTypeFlags::Poly16:
2302     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2303   case NeonTypeFlags::Poly64:
2304     if (IsInt64Long)
2305       return Context.UnsignedLongTy;
2306     else
2307       return Context.UnsignedLongLongTy;
2308   case NeonTypeFlags::Poly128:
2309     break;
2310   case NeonTypeFlags::Float16:
2311     return Context.HalfTy;
2312   case NeonTypeFlags::Float32:
2313     return Context.FloatTy;
2314   case NeonTypeFlags::Float64:
2315     return Context.DoubleTy;
2316   case NeonTypeFlags::BFloat16:
2317     return Context.BFloat16Ty;
2318   }
2319   llvm_unreachable("Invalid NeonTypeFlag!");
2320 }
2321 
2322 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2323   // Range check SVE intrinsics that take immediate values.
2324   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2325 
2326   switch (BuiltinID) {
2327   default:
2328     return false;
2329 #define GET_SVE_IMMEDIATE_CHECK
2330 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2331 #undef GET_SVE_IMMEDIATE_CHECK
2332   }
2333 
2334   // Perform all the immediate checks for this builtin call.
2335   bool HasError = false;
2336   for (auto &I : ImmChecks) {
2337     int ArgNum, CheckTy, ElementSizeInBits;
2338     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2339 
2340     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2341 
2342     // Function that checks whether the operand (ArgNum) is an immediate
2343     // that is one of the predefined values.
2344     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2345                                    int ErrDiag) -> bool {
2346       // We can't check the value of a dependent argument.
2347       Expr *Arg = TheCall->getArg(ArgNum);
2348       if (Arg->isTypeDependent() || Arg->isValueDependent())
2349         return false;
2350 
2351       // Check constant-ness first.
2352       llvm::APSInt Imm;
2353       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2354         return true;
2355 
2356       if (!CheckImm(Imm.getSExtValue()))
2357         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2358       return false;
2359     };
2360 
2361     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2362     case SVETypeFlags::ImmCheck0_31:
2363       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2364         HasError = true;
2365       break;
2366     case SVETypeFlags::ImmCheck0_13:
2367       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2368         HasError = true;
2369       break;
2370     case SVETypeFlags::ImmCheck1_16:
2371       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2372         HasError = true;
2373       break;
2374     case SVETypeFlags::ImmCheck0_7:
2375       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2376         HasError = true;
2377       break;
2378     case SVETypeFlags::ImmCheckExtract:
2379       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2380                                       (2048 / ElementSizeInBits) - 1))
2381         HasError = true;
2382       break;
2383     case SVETypeFlags::ImmCheckShiftRight:
2384       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2385         HasError = true;
2386       break;
2387     case SVETypeFlags::ImmCheckShiftRightNarrow:
2388       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2389                                       ElementSizeInBits / 2))
2390         HasError = true;
2391       break;
2392     case SVETypeFlags::ImmCheckShiftLeft:
2393       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2394                                       ElementSizeInBits - 1))
2395         HasError = true;
2396       break;
2397     case SVETypeFlags::ImmCheckLaneIndex:
2398       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2399                                       (128 / (1 * ElementSizeInBits)) - 1))
2400         HasError = true;
2401       break;
2402     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2403       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2404                                       (128 / (2 * ElementSizeInBits)) - 1))
2405         HasError = true;
2406       break;
2407     case SVETypeFlags::ImmCheckLaneIndexDot:
2408       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2409                                       (128 / (4 * ElementSizeInBits)) - 1))
2410         HasError = true;
2411       break;
2412     case SVETypeFlags::ImmCheckComplexRot90_270:
2413       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2414                               diag::err_rotation_argument_to_cadd))
2415         HasError = true;
2416       break;
2417     case SVETypeFlags::ImmCheckComplexRotAll90:
2418       if (CheckImmediateInSet(
2419               [](int64_t V) {
2420                 return V == 0 || V == 90 || V == 180 || V == 270;
2421               },
2422               diag::err_rotation_argument_to_cmla))
2423         HasError = true;
2424       break;
2425     case SVETypeFlags::ImmCheck0_1:
2426       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2427         HasError = true;
2428       break;
2429     case SVETypeFlags::ImmCheck0_2:
2430       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2431         HasError = true;
2432       break;
2433     case SVETypeFlags::ImmCheck0_3:
2434       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2435         HasError = true;
2436       break;
2437     }
2438   }
2439 
2440   return HasError;
2441 }
2442 
2443 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2444                                         unsigned BuiltinID, CallExpr *TheCall) {
2445   llvm::APSInt Result;
2446   uint64_t mask = 0;
2447   unsigned TV = 0;
2448   int PtrArgNum = -1;
2449   bool HasConstPtr = false;
2450   switch (BuiltinID) {
2451 #define GET_NEON_OVERLOAD_CHECK
2452 #include "clang/Basic/arm_neon.inc"
2453 #include "clang/Basic/arm_fp16.inc"
2454 #undef GET_NEON_OVERLOAD_CHECK
2455   }
2456 
2457   // For NEON intrinsics which are overloaded on vector element type, validate
2458   // the immediate which specifies which variant to emit.
2459   unsigned ImmArg = TheCall->getNumArgs()-1;
2460   if (mask) {
2461     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2462       return true;
2463 
2464     TV = Result.getLimitedValue(64);
2465     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2466       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2467              << TheCall->getArg(ImmArg)->getSourceRange();
2468   }
2469 
2470   if (PtrArgNum >= 0) {
2471     // Check that pointer arguments have the specified type.
2472     Expr *Arg = TheCall->getArg(PtrArgNum);
2473     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2474       Arg = ICE->getSubExpr();
2475     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2476     QualType RHSTy = RHS.get()->getType();
2477 
2478     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2479     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2480                           Arch == llvm::Triple::aarch64_32 ||
2481                           Arch == llvm::Triple::aarch64_be;
2482     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2483     QualType EltTy =
2484         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2485     if (HasConstPtr)
2486       EltTy = EltTy.withConst();
2487     QualType LHSTy = Context.getPointerType(EltTy);
2488     AssignConvertType ConvTy;
2489     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2490     if (RHS.isInvalid())
2491       return true;
2492     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2493                                  RHS.get(), AA_Assigning))
2494       return true;
2495   }
2496 
2497   // For NEON intrinsics which take an immediate value as part of the
2498   // instruction, range check them here.
2499   unsigned i = 0, l = 0, u = 0;
2500   switch (BuiltinID) {
2501   default:
2502     return false;
2503   #define GET_NEON_IMMEDIATE_CHECK
2504   #include "clang/Basic/arm_neon.inc"
2505   #include "clang/Basic/arm_fp16.inc"
2506   #undef GET_NEON_IMMEDIATE_CHECK
2507   }
2508 
2509   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2510 }
2511 
2512 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2513   switch (BuiltinID) {
2514   default:
2515     return false;
2516   #include "clang/Basic/arm_mve_builtin_sema.inc"
2517   }
2518 }
2519 
2520 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2521                                        CallExpr *TheCall) {
2522   bool Err = false;
2523   switch (BuiltinID) {
2524   default:
2525     return false;
2526 #include "clang/Basic/arm_cde_builtin_sema.inc"
2527   }
2528 
2529   if (Err)
2530     return true;
2531 
2532   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2533 }
2534 
2535 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2536                                         const Expr *CoprocArg, bool WantCDE) {
2537   if (isConstantEvaluated())
2538     return false;
2539 
2540   // We can't check the value of a dependent argument.
2541   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2542     return false;
2543 
2544   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2545   int64_t CoprocNo = CoprocNoAP.getExtValue();
2546   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2547 
2548   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2549   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2550 
2551   if (IsCDECoproc != WantCDE)
2552     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2553            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2554 
2555   return false;
2556 }
2557 
2558 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2559                                         unsigned MaxWidth) {
2560   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2561           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2562           BuiltinID == ARM::BI__builtin_arm_strex ||
2563           BuiltinID == ARM::BI__builtin_arm_stlex ||
2564           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2565           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2566           BuiltinID == AArch64::BI__builtin_arm_strex ||
2567           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2568          "unexpected ARM builtin");
2569   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2570                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2571                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2572                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2573 
2574   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2575 
2576   // Ensure that we have the proper number of arguments.
2577   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2578     return true;
2579 
2580   // Inspect the pointer argument of the atomic builtin.  This should always be
2581   // a pointer type, whose element is an integral scalar or pointer type.
2582   // Because it is a pointer type, we don't have to worry about any implicit
2583   // casts here.
2584   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2585   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2586   if (PointerArgRes.isInvalid())
2587     return true;
2588   PointerArg = PointerArgRes.get();
2589 
2590   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2591   if (!pointerType) {
2592     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2593         << PointerArg->getType() << PointerArg->getSourceRange();
2594     return true;
2595   }
2596 
2597   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2598   // task is to insert the appropriate casts into the AST. First work out just
2599   // what the appropriate type is.
2600   QualType ValType = pointerType->getPointeeType();
2601   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2602   if (IsLdrex)
2603     AddrType.addConst();
2604 
2605   // Issue a warning if the cast is dodgy.
2606   CastKind CastNeeded = CK_NoOp;
2607   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2608     CastNeeded = CK_BitCast;
2609     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2610         << PointerArg->getType() << Context.getPointerType(AddrType)
2611         << AA_Passing << PointerArg->getSourceRange();
2612   }
2613 
2614   // Finally, do the cast and replace the argument with the corrected version.
2615   AddrType = Context.getPointerType(AddrType);
2616   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2617   if (PointerArgRes.isInvalid())
2618     return true;
2619   PointerArg = PointerArgRes.get();
2620 
2621   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2622 
2623   // In general, we allow ints, floats and pointers to be loaded and stored.
2624   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2625       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2626     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2627         << PointerArg->getType() << PointerArg->getSourceRange();
2628     return true;
2629   }
2630 
2631   // But ARM doesn't have instructions to deal with 128-bit versions.
2632   if (Context.getTypeSize(ValType) > MaxWidth) {
2633     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2634     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2635         << PointerArg->getType() << PointerArg->getSourceRange();
2636     return true;
2637   }
2638 
2639   switch (ValType.getObjCLifetime()) {
2640   case Qualifiers::OCL_None:
2641   case Qualifiers::OCL_ExplicitNone:
2642     // okay
2643     break;
2644 
2645   case Qualifiers::OCL_Weak:
2646   case Qualifiers::OCL_Strong:
2647   case Qualifiers::OCL_Autoreleasing:
2648     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2649         << ValType << PointerArg->getSourceRange();
2650     return true;
2651   }
2652 
2653   if (IsLdrex) {
2654     TheCall->setType(ValType);
2655     return false;
2656   }
2657 
2658   // Initialize the argument to be stored.
2659   ExprResult ValArg = TheCall->getArg(0);
2660   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2661       Context, ValType, /*consume*/ false);
2662   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2663   if (ValArg.isInvalid())
2664     return true;
2665   TheCall->setArg(0, ValArg.get());
2666 
2667   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2668   // but the custom checker bypasses all default analysis.
2669   TheCall->setType(Context.IntTy);
2670   return false;
2671 }
2672 
2673 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2674                                        CallExpr *TheCall) {
2675   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2676       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2677       BuiltinID == ARM::BI__builtin_arm_strex ||
2678       BuiltinID == ARM::BI__builtin_arm_stlex) {
2679     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2680   }
2681 
2682   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2683     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2684       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2685   }
2686 
2687   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2688       BuiltinID == ARM::BI__builtin_arm_wsr64)
2689     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2690 
2691   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2692       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2693       BuiltinID == ARM::BI__builtin_arm_wsr ||
2694       BuiltinID == ARM::BI__builtin_arm_wsrp)
2695     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2696 
2697   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2698     return true;
2699   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2700     return true;
2701   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2702     return true;
2703 
2704   // For intrinsics which take an immediate value as part of the instruction,
2705   // range check them here.
2706   // FIXME: VFP Intrinsics should error if VFP not present.
2707   switch (BuiltinID) {
2708   default: return false;
2709   case ARM::BI__builtin_arm_ssat:
2710     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2711   case ARM::BI__builtin_arm_usat:
2712     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2713   case ARM::BI__builtin_arm_ssat16:
2714     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2715   case ARM::BI__builtin_arm_usat16:
2716     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2717   case ARM::BI__builtin_arm_vcvtr_f:
2718   case ARM::BI__builtin_arm_vcvtr_d:
2719     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2720   case ARM::BI__builtin_arm_dmb:
2721   case ARM::BI__builtin_arm_dsb:
2722   case ARM::BI__builtin_arm_isb:
2723   case ARM::BI__builtin_arm_dbg:
2724     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2725   case ARM::BI__builtin_arm_cdp:
2726   case ARM::BI__builtin_arm_cdp2:
2727   case ARM::BI__builtin_arm_mcr:
2728   case ARM::BI__builtin_arm_mcr2:
2729   case ARM::BI__builtin_arm_mrc:
2730   case ARM::BI__builtin_arm_mrc2:
2731   case ARM::BI__builtin_arm_mcrr:
2732   case ARM::BI__builtin_arm_mcrr2:
2733   case ARM::BI__builtin_arm_mrrc:
2734   case ARM::BI__builtin_arm_mrrc2:
2735   case ARM::BI__builtin_arm_ldc:
2736   case ARM::BI__builtin_arm_ldcl:
2737   case ARM::BI__builtin_arm_ldc2:
2738   case ARM::BI__builtin_arm_ldc2l:
2739   case ARM::BI__builtin_arm_stc:
2740   case ARM::BI__builtin_arm_stcl:
2741   case ARM::BI__builtin_arm_stc2:
2742   case ARM::BI__builtin_arm_stc2l:
2743     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2744            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2745                                         /*WantCDE*/ false);
2746   }
2747 }
2748 
2749 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2750                                            unsigned BuiltinID,
2751                                            CallExpr *TheCall) {
2752   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2753       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2754       BuiltinID == AArch64::BI__builtin_arm_strex ||
2755       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2756     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2757   }
2758 
2759   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2760     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2761       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2762       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2763       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2764   }
2765 
2766   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2767       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2768     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2769 
2770   // Memory Tagging Extensions (MTE) Intrinsics
2771   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2772       BuiltinID == AArch64::BI__builtin_arm_addg ||
2773       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2774       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2775       BuiltinID == AArch64::BI__builtin_arm_stg ||
2776       BuiltinID == AArch64::BI__builtin_arm_subp) {
2777     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2778   }
2779 
2780   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2781       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2782       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2783       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2784     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2785 
2786   // Only check the valid encoding range. Any constant in this range would be
2787   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2788   // an exception for incorrect registers. This matches MSVC behavior.
2789   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2790       BuiltinID == AArch64::BI_WriteStatusReg)
2791     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2792 
2793   if (BuiltinID == AArch64::BI__getReg)
2794     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2795 
2796   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2797     return true;
2798 
2799   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2800     return true;
2801 
2802   // For intrinsics which take an immediate value as part of the instruction,
2803   // range check them here.
2804   unsigned i = 0, l = 0, u = 0;
2805   switch (BuiltinID) {
2806   default: return false;
2807   case AArch64::BI__builtin_arm_dmb:
2808   case AArch64::BI__builtin_arm_dsb:
2809   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2810   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2811   }
2812 
2813   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2814 }
2815 
2816 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2817   if (Arg->getType()->getAsPlaceholderType())
2818     return false;
2819 
2820   // The first argument needs to be a record field access.
2821   // If it is an array element access, we delay decision
2822   // to BPF backend to check whether the access is a
2823   // field access or not.
2824   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2825           isa<MemberExpr>(Arg->IgnoreParens()) ||
2826           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2827 }
2828 
2829 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2830                             QualType VectorTy, QualType EltTy) {
2831   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2832   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2833     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2834         << Call->getSourceRange() << VectorEltTy << EltTy;
2835     return false;
2836   }
2837   return true;
2838 }
2839 
2840 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2841   QualType ArgType = Arg->getType();
2842   if (ArgType->getAsPlaceholderType())
2843     return false;
2844 
2845   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2846   // format:
2847   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2848   //   2. <type> var;
2849   //      __builtin_preserve_type_info(var, flag);
2850   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2851       !isa<UnaryOperator>(Arg->IgnoreParens()))
2852     return false;
2853 
2854   // Typedef type.
2855   if (ArgType->getAs<TypedefType>())
2856     return true;
2857 
2858   // Record type or Enum type.
2859   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2860   if (const auto *RT = Ty->getAs<RecordType>()) {
2861     if (!RT->getDecl()->getDeclName().isEmpty())
2862       return true;
2863   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2864     if (!ET->getDecl()->getDeclName().isEmpty())
2865       return true;
2866   }
2867 
2868   return false;
2869 }
2870 
2871 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2872   QualType ArgType = Arg->getType();
2873   if (ArgType->getAsPlaceholderType())
2874     return false;
2875 
2876   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2877   // format:
2878   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2879   //                                 flag);
2880   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2881   if (!UO)
2882     return false;
2883 
2884   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2885   if (!CE)
2886     return false;
2887   if (CE->getCastKind() != CK_IntegralToPointer &&
2888       CE->getCastKind() != CK_NullToPointer)
2889     return false;
2890 
2891   // The integer must be from an EnumConstantDecl.
2892   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2893   if (!DR)
2894     return false;
2895 
2896   const EnumConstantDecl *Enumerator =
2897       dyn_cast<EnumConstantDecl>(DR->getDecl());
2898   if (!Enumerator)
2899     return false;
2900 
2901   // The type must be EnumType.
2902   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2903   const auto *ET = Ty->getAs<EnumType>();
2904   if (!ET)
2905     return false;
2906 
2907   // The enum value must be supported.
2908   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2909 }
2910 
2911 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2912                                        CallExpr *TheCall) {
2913   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2914           BuiltinID == BPF::BI__builtin_btf_type_id ||
2915           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2916           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2917          "unexpected BPF builtin");
2918 
2919   if (checkArgCount(*this, TheCall, 2))
2920     return true;
2921 
2922   // The second argument needs to be a constant int
2923   Expr *Arg = TheCall->getArg(1);
2924   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2925   diag::kind kind;
2926   if (!Value) {
2927     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2928       kind = diag::err_preserve_field_info_not_const;
2929     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2930       kind = diag::err_btf_type_id_not_const;
2931     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2932       kind = diag::err_preserve_type_info_not_const;
2933     else
2934       kind = diag::err_preserve_enum_value_not_const;
2935     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2936     return true;
2937   }
2938 
2939   // The first argument
2940   Arg = TheCall->getArg(0);
2941   bool InvalidArg = false;
2942   bool ReturnUnsignedInt = true;
2943   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2944     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2945       InvalidArg = true;
2946       kind = diag::err_preserve_field_info_not_field;
2947     }
2948   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2949     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2950       InvalidArg = true;
2951       kind = diag::err_preserve_type_info_invalid;
2952     }
2953   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2954     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2955       InvalidArg = true;
2956       kind = diag::err_preserve_enum_value_invalid;
2957     }
2958     ReturnUnsignedInt = false;
2959   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2960     ReturnUnsignedInt = false;
2961   }
2962 
2963   if (InvalidArg) {
2964     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2965     return true;
2966   }
2967 
2968   if (ReturnUnsignedInt)
2969     TheCall->setType(Context.UnsignedIntTy);
2970   else
2971     TheCall->setType(Context.UnsignedLongTy);
2972   return false;
2973 }
2974 
2975 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2976   struct ArgInfo {
2977     uint8_t OpNum;
2978     bool IsSigned;
2979     uint8_t BitWidth;
2980     uint8_t Align;
2981   };
2982   struct BuiltinInfo {
2983     unsigned BuiltinID;
2984     ArgInfo Infos[2];
2985   };
2986 
2987   static BuiltinInfo Infos[] = {
2988     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2989     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2990     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2991     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2992     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2993     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2994     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2995     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2996     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2997     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2998     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2999 
3000     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3001     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3002     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3003     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3004     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3005     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3006     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3007     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3008     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3009     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3010     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3011 
3012     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3013     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3014     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3015     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3016     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3017     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3018     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3019     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3020     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3021     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3022     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3023     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3024     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3025     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3026     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3027     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3028     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3029     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3030     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3031     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3032     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3033     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3034     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3035     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3036     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3037     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3038     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3039     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3040     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3041     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3042     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3043     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3044     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3045     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3046     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3047     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3048     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3049     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3050     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3051     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3052     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3053     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3054     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3055     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3056     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3057     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3058     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3059     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3060     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3061     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3062     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3063     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3064                                                       {{ 1, false, 6,  0 }} },
3065     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3066     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3067     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3068     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3069     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3070     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3071     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3072                                                       {{ 1, false, 5,  0 }} },
3073     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3074     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3075     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3076     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3077     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3078     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3079                                                        { 2, false, 5,  0 }} },
3080     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3081                                                        { 2, false, 6,  0 }} },
3082     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3083                                                        { 3, false, 5,  0 }} },
3084     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3085                                                        { 3, false, 6,  0 }} },
3086     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3087     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3088     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3089     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3090     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3091     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3092     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3093     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3094     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3095     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3096     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3097     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3098     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3099     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3100     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3101     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3102                                                       {{ 2, false, 4,  0 },
3103                                                        { 3, false, 5,  0 }} },
3104     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3105                                                       {{ 2, false, 4,  0 },
3106                                                        { 3, false, 5,  0 }} },
3107     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3108                                                       {{ 2, false, 4,  0 },
3109                                                        { 3, false, 5,  0 }} },
3110     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3111                                                       {{ 2, false, 4,  0 },
3112                                                        { 3, false, 5,  0 }} },
3113     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3114     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3115     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3116     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3117     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3118     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3119     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3120     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3121     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3122     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3123     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3124                                                        { 2, false, 5,  0 }} },
3125     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3126                                                        { 2, false, 6,  0 }} },
3127     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3128     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3129     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3130     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3132     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3133     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3134     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3135     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3136                                                       {{ 1, false, 4,  0 }} },
3137     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3138     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3139                                                       {{ 1, false, 4,  0 }} },
3140     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3141     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3143     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3145     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3147     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3149     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3155     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3158     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3160                                                       {{ 3, false, 1,  0 }} },
3161     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3163     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3164     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3165                                                       {{ 3, false, 1,  0 }} },
3166     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3167     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3170                                                       {{ 3, false, 1,  0 }} },
3171   };
3172 
3173   // Use a dynamically initialized static to sort the table exactly once on
3174   // first run.
3175   static const bool SortOnce =
3176       (llvm::sort(Infos,
3177                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3178                    return LHS.BuiltinID < RHS.BuiltinID;
3179                  }),
3180        true);
3181   (void)SortOnce;
3182 
3183   const BuiltinInfo *F = llvm::partition_point(
3184       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3185   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3186     return false;
3187 
3188   bool Error = false;
3189 
3190   for (const ArgInfo &A : F->Infos) {
3191     // Ignore empty ArgInfo elements.
3192     if (A.BitWidth == 0)
3193       continue;
3194 
3195     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3196     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3197     if (!A.Align) {
3198       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3199     } else {
3200       unsigned M = 1 << A.Align;
3201       Min *= M;
3202       Max *= M;
3203       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3204       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3205     }
3206   }
3207   return Error;
3208 }
3209 
3210 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3211                                            CallExpr *TheCall) {
3212   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3213 }
3214 
3215 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3216                                         unsigned BuiltinID, CallExpr *TheCall) {
3217   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3218          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3219 }
3220 
3221 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3222                                CallExpr *TheCall) {
3223 
3224   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3225       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3226     if (!TI.hasFeature("dsp"))
3227       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3228   }
3229 
3230   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3231       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3232     if (!TI.hasFeature("dspr2"))
3233       return Diag(TheCall->getBeginLoc(),
3234                   diag::err_mips_builtin_requires_dspr2);
3235   }
3236 
3237   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3238       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3239     if (!TI.hasFeature("msa"))
3240       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3241   }
3242 
3243   return false;
3244 }
3245 
3246 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3247 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3248 // ordering for DSP is unspecified. MSA is ordered by the data format used
3249 // by the underlying instruction i.e., df/m, df/n and then by size.
3250 //
3251 // FIXME: The size tests here should instead be tablegen'd along with the
3252 //        definitions from include/clang/Basic/BuiltinsMips.def.
3253 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3254 //        be too.
3255 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3256   unsigned i = 0, l = 0, u = 0, m = 0;
3257   switch (BuiltinID) {
3258   default: return false;
3259   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3260   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3261   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3262   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3263   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3264   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3265   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3266   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3267   // df/m field.
3268   // These intrinsics take an unsigned 3 bit immediate.
3269   case Mips::BI__builtin_msa_bclri_b:
3270   case Mips::BI__builtin_msa_bnegi_b:
3271   case Mips::BI__builtin_msa_bseti_b:
3272   case Mips::BI__builtin_msa_sat_s_b:
3273   case Mips::BI__builtin_msa_sat_u_b:
3274   case Mips::BI__builtin_msa_slli_b:
3275   case Mips::BI__builtin_msa_srai_b:
3276   case Mips::BI__builtin_msa_srari_b:
3277   case Mips::BI__builtin_msa_srli_b:
3278   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3279   case Mips::BI__builtin_msa_binsli_b:
3280   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3281   // These intrinsics take an unsigned 4 bit immediate.
3282   case Mips::BI__builtin_msa_bclri_h:
3283   case Mips::BI__builtin_msa_bnegi_h:
3284   case Mips::BI__builtin_msa_bseti_h:
3285   case Mips::BI__builtin_msa_sat_s_h:
3286   case Mips::BI__builtin_msa_sat_u_h:
3287   case Mips::BI__builtin_msa_slli_h:
3288   case Mips::BI__builtin_msa_srai_h:
3289   case Mips::BI__builtin_msa_srari_h:
3290   case Mips::BI__builtin_msa_srli_h:
3291   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3292   case Mips::BI__builtin_msa_binsli_h:
3293   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3294   // These intrinsics take an unsigned 5 bit immediate.
3295   // The first block of intrinsics actually have an unsigned 5 bit field,
3296   // not a df/n field.
3297   case Mips::BI__builtin_msa_cfcmsa:
3298   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3299   case Mips::BI__builtin_msa_clei_u_b:
3300   case Mips::BI__builtin_msa_clei_u_h:
3301   case Mips::BI__builtin_msa_clei_u_w:
3302   case Mips::BI__builtin_msa_clei_u_d:
3303   case Mips::BI__builtin_msa_clti_u_b:
3304   case Mips::BI__builtin_msa_clti_u_h:
3305   case Mips::BI__builtin_msa_clti_u_w:
3306   case Mips::BI__builtin_msa_clti_u_d:
3307   case Mips::BI__builtin_msa_maxi_u_b:
3308   case Mips::BI__builtin_msa_maxi_u_h:
3309   case Mips::BI__builtin_msa_maxi_u_w:
3310   case Mips::BI__builtin_msa_maxi_u_d:
3311   case Mips::BI__builtin_msa_mini_u_b:
3312   case Mips::BI__builtin_msa_mini_u_h:
3313   case Mips::BI__builtin_msa_mini_u_w:
3314   case Mips::BI__builtin_msa_mini_u_d:
3315   case Mips::BI__builtin_msa_addvi_b:
3316   case Mips::BI__builtin_msa_addvi_h:
3317   case Mips::BI__builtin_msa_addvi_w:
3318   case Mips::BI__builtin_msa_addvi_d:
3319   case Mips::BI__builtin_msa_bclri_w:
3320   case Mips::BI__builtin_msa_bnegi_w:
3321   case Mips::BI__builtin_msa_bseti_w:
3322   case Mips::BI__builtin_msa_sat_s_w:
3323   case Mips::BI__builtin_msa_sat_u_w:
3324   case Mips::BI__builtin_msa_slli_w:
3325   case Mips::BI__builtin_msa_srai_w:
3326   case Mips::BI__builtin_msa_srari_w:
3327   case Mips::BI__builtin_msa_srli_w:
3328   case Mips::BI__builtin_msa_srlri_w:
3329   case Mips::BI__builtin_msa_subvi_b:
3330   case Mips::BI__builtin_msa_subvi_h:
3331   case Mips::BI__builtin_msa_subvi_w:
3332   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3333   case Mips::BI__builtin_msa_binsli_w:
3334   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3335   // These intrinsics take an unsigned 6 bit immediate.
3336   case Mips::BI__builtin_msa_bclri_d:
3337   case Mips::BI__builtin_msa_bnegi_d:
3338   case Mips::BI__builtin_msa_bseti_d:
3339   case Mips::BI__builtin_msa_sat_s_d:
3340   case Mips::BI__builtin_msa_sat_u_d:
3341   case Mips::BI__builtin_msa_slli_d:
3342   case Mips::BI__builtin_msa_srai_d:
3343   case Mips::BI__builtin_msa_srari_d:
3344   case Mips::BI__builtin_msa_srli_d:
3345   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3346   case Mips::BI__builtin_msa_binsli_d:
3347   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3348   // These intrinsics take a signed 5 bit immediate.
3349   case Mips::BI__builtin_msa_ceqi_b:
3350   case Mips::BI__builtin_msa_ceqi_h:
3351   case Mips::BI__builtin_msa_ceqi_w:
3352   case Mips::BI__builtin_msa_ceqi_d:
3353   case Mips::BI__builtin_msa_clti_s_b:
3354   case Mips::BI__builtin_msa_clti_s_h:
3355   case Mips::BI__builtin_msa_clti_s_w:
3356   case Mips::BI__builtin_msa_clti_s_d:
3357   case Mips::BI__builtin_msa_clei_s_b:
3358   case Mips::BI__builtin_msa_clei_s_h:
3359   case Mips::BI__builtin_msa_clei_s_w:
3360   case Mips::BI__builtin_msa_clei_s_d:
3361   case Mips::BI__builtin_msa_maxi_s_b:
3362   case Mips::BI__builtin_msa_maxi_s_h:
3363   case Mips::BI__builtin_msa_maxi_s_w:
3364   case Mips::BI__builtin_msa_maxi_s_d:
3365   case Mips::BI__builtin_msa_mini_s_b:
3366   case Mips::BI__builtin_msa_mini_s_h:
3367   case Mips::BI__builtin_msa_mini_s_w:
3368   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3369   // These intrinsics take an unsigned 8 bit immediate.
3370   case Mips::BI__builtin_msa_andi_b:
3371   case Mips::BI__builtin_msa_nori_b:
3372   case Mips::BI__builtin_msa_ori_b:
3373   case Mips::BI__builtin_msa_shf_b:
3374   case Mips::BI__builtin_msa_shf_h:
3375   case Mips::BI__builtin_msa_shf_w:
3376   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3377   case Mips::BI__builtin_msa_bseli_b:
3378   case Mips::BI__builtin_msa_bmnzi_b:
3379   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3380   // df/n format
3381   // These intrinsics take an unsigned 4 bit immediate.
3382   case Mips::BI__builtin_msa_copy_s_b:
3383   case Mips::BI__builtin_msa_copy_u_b:
3384   case Mips::BI__builtin_msa_insve_b:
3385   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3386   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3387   // These intrinsics take an unsigned 3 bit immediate.
3388   case Mips::BI__builtin_msa_copy_s_h:
3389   case Mips::BI__builtin_msa_copy_u_h:
3390   case Mips::BI__builtin_msa_insve_h:
3391   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3392   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3393   // These intrinsics take an unsigned 2 bit immediate.
3394   case Mips::BI__builtin_msa_copy_s_w:
3395   case Mips::BI__builtin_msa_copy_u_w:
3396   case Mips::BI__builtin_msa_insve_w:
3397   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3398   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3399   // These intrinsics take an unsigned 1 bit immediate.
3400   case Mips::BI__builtin_msa_copy_s_d:
3401   case Mips::BI__builtin_msa_copy_u_d:
3402   case Mips::BI__builtin_msa_insve_d:
3403   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3404   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3405   // Memory offsets and immediate loads.
3406   // These intrinsics take a signed 10 bit immediate.
3407   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3408   case Mips::BI__builtin_msa_ldi_h:
3409   case Mips::BI__builtin_msa_ldi_w:
3410   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3411   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3412   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3413   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3414   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3415   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3416   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3417   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3418   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3419   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3420   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3421   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3422   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3423   }
3424 
3425   if (!m)
3426     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3427 
3428   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3429          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3430 }
3431 
3432 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3433 /// advancing the pointer over the consumed characters. The decoded type is
3434 /// returned. If the decoded type represents a constant integer with a
3435 /// constraint on its value then Mask is set to that value. The type descriptors
3436 /// used in Str are specific to PPC MMA builtins and are documented in the file
3437 /// defining the PPC builtins.
3438 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3439                                         unsigned &Mask) {
3440   bool RequireICE = false;
3441   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3442   switch (*Str++) {
3443   case 'V':
3444     return Context.getVectorType(Context.UnsignedCharTy, 16,
3445                                  VectorType::VectorKind::AltiVecVector);
3446   case 'i': {
3447     char *End;
3448     unsigned size = strtoul(Str, &End, 10);
3449     assert(End != Str && "Missing constant parameter constraint");
3450     Str = End;
3451     Mask = size;
3452     return Context.IntTy;
3453   }
3454   case 'W': {
3455     char *End;
3456     unsigned size = strtoul(Str, &End, 10);
3457     assert(End != Str && "Missing PowerPC MMA type size");
3458     Str = End;
3459     QualType Type;
3460     switch (size) {
3461   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3462     case size: Type = Context.Id##Ty; break;
3463   #include "clang/Basic/PPCTypes.def"
3464     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3465     }
3466     bool CheckVectorArgs = false;
3467     while (!CheckVectorArgs) {
3468       switch (*Str++) {
3469       case '*':
3470         Type = Context.getPointerType(Type);
3471         break;
3472       case 'C':
3473         Type = Type.withConst();
3474         break;
3475       default:
3476         CheckVectorArgs = true;
3477         --Str;
3478         break;
3479       }
3480     }
3481     return Type;
3482   }
3483   default:
3484     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3485   }
3486 }
3487 
3488 static bool isPPC_64Builtin(unsigned BuiltinID) {
3489   // These builtins only work on PPC 64bit targets.
3490   switch (BuiltinID) {
3491   case PPC::BI__builtin_divde:
3492   case PPC::BI__builtin_divdeu:
3493   case PPC::BI__builtin_bpermd:
3494   case PPC::BI__builtin_ppc_ldarx:
3495   case PPC::BI__builtin_ppc_stdcx:
3496   case PPC::BI__builtin_ppc_tdw:
3497   case PPC::BI__builtin_ppc_trapd:
3498   case PPC::BI__builtin_ppc_cmpeqb:
3499   case PPC::BI__builtin_ppc_setb:
3500   case PPC::BI__builtin_ppc_mulhd:
3501   case PPC::BI__builtin_ppc_mulhdu:
3502   case PPC::BI__builtin_ppc_maddhd:
3503   case PPC::BI__builtin_ppc_maddhdu:
3504   case PPC::BI__builtin_ppc_maddld:
3505   case PPC::BI__builtin_ppc_load8r:
3506   case PPC::BI__builtin_ppc_store8r:
3507   case PPC::BI__builtin_ppc_insert_exp:
3508   case PPC::BI__builtin_ppc_extract_sig:
3509   case PPC::BI__builtin_ppc_addex:
3510   case PPC::BI__builtin_darn:
3511   case PPC::BI__builtin_darn_raw:
3512   case PPC::BI__builtin_ppc_compare_and_swaplp:
3513   case PPC::BI__builtin_ppc_fetch_and_addlp:
3514   case PPC::BI__builtin_ppc_fetch_and_andlp:
3515   case PPC::BI__builtin_ppc_fetch_and_orlp:
3516   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3517     return true;
3518   }
3519   return false;
3520 }
3521 
3522 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3523                              StringRef FeatureToCheck, unsigned DiagID,
3524                              StringRef DiagArg = "") {
3525   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3526     return false;
3527 
3528   if (DiagArg.empty())
3529     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3530   else
3531     S.Diag(TheCall->getBeginLoc(), DiagID)
3532         << DiagArg << TheCall->getSourceRange();
3533 
3534   return true;
3535 }
3536 
3537 /// Returns true if the argument consists of one contiguous run of 1s with any
3538 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3539 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3540 /// since all 1s are not contiguous.
3541 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3542   llvm::APSInt Result;
3543   // We can't check the value of a dependent argument.
3544   Expr *Arg = TheCall->getArg(ArgNum);
3545   if (Arg->isTypeDependent() || Arg->isValueDependent())
3546     return false;
3547 
3548   // Check constant-ness first.
3549   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3550     return true;
3551 
3552   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3553   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3554     return false;
3555 
3556   return Diag(TheCall->getBeginLoc(),
3557               diag::err_argument_not_contiguous_bit_field)
3558          << ArgNum << Arg->getSourceRange();
3559 }
3560 
3561 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3562                                        CallExpr *TheCall) {
3563   unsigned i = 0, l = 0, u = 0;
3564   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3565   llvm::APSInt Result;
3566 
3567   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3568     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3569            << TheCall->getSourceRange();
3570 
3571   switch (BuiltinID) {
3572   default: return false;
3573   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3574   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3575     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3576            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3577   case PPC::BI__builtin_altivec_dss:
3578     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3579   case PPC::BI__builtin_tbegin:
3580   case PPC::BI__builtin_tend:
3581     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3582            SemaFeatureCheck(*this, TheCall, "htm",
3583                             diag::err_ppc_builtin_requires_htm);
3584   case PPC::BI__builtin_tsr:
3585     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3586            SemaFeatureCheck(*this, TheCall, "htm",
3587                             diag::err_ppc_builtin_requires_htm);
3588   case PPC::BI__builtin_tabortwc:
3589   case PPC::BI__builtin_tabortdc:
3590     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3591            SemaFeatureCheck(*this, TheCall, "htm",
3592                             diag::err_ppc_builtin_requires_htm);
3593   case PPC::BI__builtin_tabortwci:
3594   case PPC::BI__builtin_tabortdci:
3595     return SemaFeatureCheck(*this, TheCall, "htm",
3596                             diag::err_ppc_builtin_requires_htm) ||
3597            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3598             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3599   case PPC::BI__builtin_tabort:
3600   case PPC::BI__builtin_tcheck:
3601   case PPC::BI__builtin_treclaim:
3602   case PPC::BI__builtin_trechkpt:
3603   case PPC::BI__builtin_tendall:
3604   case PPC::BI__builtin_tresume:
3605   case PPC::BI__builtin_tsuspend:
3606   case PPC::BI__builtin_get_texasr:
3607   case PPC::BI__builtin_get_texasru:
3608   case PPC::BI__builtin_get_tfhar:
3609   case PPC::BI__builtin_get_tfiar:
3610   case PPC::BI__builtin_set_texasr:
3611   case PPC::BI__builtin_set_texasru:
3612   case PPC::BI__builtin_set_tfhar:
3613   case PPC::BI__builtin_set_tfiar:
3614   case PPC::BI__builtin_ttest:
3615     return SemaFeatureCheck(*this, TheCall, "htm",
3616                             diag::err_ppc_builtin_requires_htm);
3617   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3618   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3619   // extended double representation.
3620   case PPC::BI__builtin_unpack_longdouble:
3621     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3622       return true;
3623     LLVM_FALLTHROUGH;
3624   case PPC::BI__builtin_pack_longdouble:
3625     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3626       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3627              << "ibmlongdouble";
3628     return false;
3629   case PPC::BI__builtin_altivec_dst:
3630   case PPC::BI__builtin_altivec_dstt:
3631   case PPC::BI__builtin_altivec_dstst:
3632   case PPC::BI__builtin_altivec_dststt:
3633     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3634   case PPC::BI__builtin_vsx_xxpermdi:
3635   case PPC::BI__builtin_vsx_xxsldwi:
3636     return SemaBuiltinVSX(TheCall);
3637   case PPC::BI__builtin_divwe:
3638   case PPC::BI__builtin_divweu:
3639   case PPC::BI__builtin_divde:
3640   case PPC::BI__builtin_divdeu:
3641     return SemaFeatureCheck(*this, TheCall, "extdiv",
3642                             diag::err_ppc_builtin_only_on_arch, "7");
3643   case PPC::BI__builtin_bpermd:
3644     return SemaFeatureCheck(*this, TheCall, "bpermd",
3645                             diag::err_ppc_builtin_only_on_arch, "7");
3646   case PPC::BI__builtin_unpack_vector_int128:
3647     return SemaFeatureCheck(*this, TheCall, "vsx",
3648                             diag::err_ppc_builtin_only_on_arch, "7") ||
3649            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3650   case PPC::BI__builtin_pack_vector_int128:
3651     return SemaFeatureCheck(*this, TheCall, "vsx",
3652                             diag::err_ppc_builtin_only_on_arch, "7");
3653   case PPC::BI__builtin_altivec_vgnb:
3654      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3655   case PPC::BI__builtin_altivec_vec_replace_elt:
3656   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3657     QualType VecTy = TheCall->getArg(0)->getType();
3658     QualType EltTy = TheCall->getArg(1)->getType();
3659     unsigned Width = Context.getIntWidth(EltTy);
3660     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3661            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3662   }
3663   case PPC::BI__builtin_vsx_xxeval:
3664      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3665   case PPC::BI__builtin_altivec_vsldbi:
3666      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3667   case PPC::BI__builtin_altivec_vsrdbi:
3668      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3669   case PPC::BI__builtin_vsx_xxpermx:
3670      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3671   case PPC::BI__builtin_ppc_tw:
3672   case PPC::BI__builtin_ppc_tdw:
3673     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3674   case PPC::BI__builtin_ppc_cmpeqb:
3675   case PPC::BI__builtin_ppc_setb:
3676   case PPC::BI__builtin_ppc_maddhd:
3677   case PPC::BI__builtin_ppc_maddhdu:
3678   case PPC::BI__builtin_ppc_maddld:
3679     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3680                             diag::err_ppc_builtin_only_on_arch, "9");
3681   case PPC::BI__builtin_ppc_cmprb:
3682     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3683                             diag::err_ppc_builtin_only_on_arch, "9") ||
3684            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3685   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3686   // be a constant that represents a contiguous bit field.
3687   case PPC::BI__builtin_ppc_rlwnm:
3688     return SemaValueIsRunOfOnes(TheCall, 2);
3689   case PPC::BI__builtin_ppc_rlwimi:
3690   case PPC::BI__builtin_ppc_rldimi:
3691     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3692            SemaValueIsRunOfOnes(TheCall, 3);
3693   case PPC::BI__builtin_ppc_extract_exp:
3694   case PPC::BI__builtin_ppc_extract_sig:
3695   case PPC::BI__builtin_ppc_insert_exp:
3696     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3697                             diag::err_ppc_builtin_only_on_arch, "9");
3698   case PPC::BI__builtin_ppc_addex: {
3699     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3700                          diag::err_ppc_builtin_only_on_arch, "9") ||
3701         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3702       return true;
3703     // Output warning for reserved values 1 to 3.
3704     int ArgValue =
3705         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3706     if (ArgValue != 0)
3707       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3708           << ArgValue;
3709     return false;
3710   }
3711   case PPC::BI__builtin_ppc_mtfsb0:
3712   case PPC::BI__builtin_ppc_mtfsb1:
3713     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3714   case PPC::BI__builtin_ppc_mtfsf:
3715     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3716   case PPC::BI__builtin_ppc_mtfsfi:
3717     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3718            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3719   case PPC::BI__builtin_ppc_alignx:
3720     return SemaBuiltinConstantArgPower2(TheCall, 0);
3721   case PPC::BI__builtin_ppc_rdlam:
3722     return SemaValueIsRunOfOnes(TheCall, 2);
3723   case PPC::BI__builtin_ppc_icbt:
3724   case PPC::BI__builtin_ppc_sthcx:
3725   case PPC::BI__builtin_ppc_stbcx:
3726   case PPC::BI__builtin_ppc_lharx:
3727   case PPC::BI__builtin_ppc_lbarx:
3728     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3729                             diag::err_ppc_builtin_only_on_arch, "8");
3730   case PPC::BI__builtin_vsx_ldrmb:
3731   case PPC::BI__builtin_vsx_strmb:
3732     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3733                             diag::err_ppc_builtin_only_on_arch, "8") ||
3734            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3735   case PPC::BI__builtin_altivec_vcntmbb:
3736   case PPC::BI__builtin_altivec_vcntmbh:
3737   case PPC::BI__builtin_altivec_vcntmbw:
3738   case PPC::BI__builtin_altivec_vcntmbd:
3739     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3740   case PPC::BI__builtin_darn:
3741   case PPC::BI__builtin_darn_raw:
3742   case PPC::BI__builtin_darn_32:
3743     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3744                             diag::err_ppc_builtin_only_on_arch, "9");
3745   case PPC::BI__builtin_vsx_xxgenpcvbm:
3746   case PPC::BI__builtin_vsx_xxgenpcvhm:
3747   case PPC::BI__builtin_vsx_xxgenpcvwm:
3748   case PPC::BI__builtin_vsx_xxgenpcvdm:
3749     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3750   case PPC::BI__builtin_ppc_compare_exp_uo:
3751   case PPC::BI__builtin_ppc_compare_exp_lt:
3752   case PPC::BI__builtin_ppc_compare_exp_gt:
3753   case PPC::BI__builtin_ppc_compare_exp_eq:
3754     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3755                             diag::err_ppc_builtin_only_on_arch, "9") ||
3756            SemaFeatureCheck(*this, TheCall, "vsx",
3757                             diag::err_ppc_builtin_requires_vsx);
3758   case PPC::BI__builtin_ppc_test_data_class: {
3759     // Check if the first argument of the __builtin_ppc_test_data_class call is
3760     // valid. The argument must be either a 'float' or a 'double'.
3761     QualType ArgType = TheCall->getArg(0)->getType();
3762     if (ArgType != QualType(Context.FloatTy) &&
3763         ArgType != QualType(Context.DoubleTy))
3764       return Diag(TheCall->getBeginLoc(),
3765                   diag::err_ppc_invalid_test_data_class_type);
3766     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3767                             diag::err_ppc_builtin_only_on_arch, "9") ||
3768            SemaFeatureCheck(*this, TheCall, "vsx",
3769                             diag::err_ppc_builtin_requires_vsx) ||
3770            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3771   }
3772   case PPC::BI__builtin_ppc_load8r:
3773   case PPC::BI__builtin_ppc_store8r:
3774     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3775                             diag::err_ppc_builtin_only_on_arch, "7");
3776 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3777   case PPC::BI__builtin_##Name:                                                \
3778     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3779 #include "clang/Basic/BuiltinsPPC.def"
3780   }
3781   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3782 }
3783 
3784 // Check if the given type is a non-pointer PPC MMA type. This function is used
3785 // in Sema to prevent invalid uses of restricted PPC MMA types.
3786 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3787   if (Type->isPointerType() || Type->isArrayType())
3788     return false;
3789 
3790   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3791 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3792   if (false
3793 #include "clang/Basic/PPCTypes.def"
3794      ) {
3795     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3796     return true;
3797   }
3798   return false;
3799 }
3800 
3801 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3802                                           CallExpr *TheCall) {
3803   // position of memory order and scope arguments in the builtin
3804   unsigned OrderIndex, ScopeIndex;
3805   switch (BuiltinID) {
3806   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3807   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3808   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3809   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3810     OrderIndex = 2;
3811     ScopeIndex = 3;
3812     break;
3813   case AMDGPU::BI__builtin_amdgcn_fence:
3814     OrderIndex = 0;
3815     ScopeIndex = 1;
3816     break;
3817   default:
3818     return false;
3819   }
3820 
3821   ExprResult Arg = TheCall->getArg(OrderIndex);
3822   auto ArgExpr = Arg.get();
3823   Expr::EvalResult ArgResult;
3824 
3825   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3826     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3827            << ArgExpr->getType();
3828   auto Ord = ArgResult.Val.getInt().getZExtValue();
3829 
3830   // Check validity of memory ordering as per C11 / C++11's memody model.
3831   // Only fence needs check. Atomic dec/inc allow all memory orders.
3832   if (!llvm::isValidAtomicOrderingCABI(Ord))
3833     return Diag(ArgExpr->getBeginLoc(),
3834                 diag::warn_atomic_op_has_invalid_memory_order)
3835            << ArgExpr->getSourceRange();
3836   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3837   case llvm::AtomicOrderingCABI::relaxed:
3838   case llvm::AtomicOrderingCABI::consume:
3839     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3840       return Diag(ArgExpr->getBeginLoc(),
3841                   diag::warn_atomic_op_has_invalid_memory_order)
3842              << ArgExpr->getSourceRange();
3843     break;
3844   case llvm::AtomicOrderingCABI::acquire:
3845   case llvm::AtomicOrderingCABI::release:
3846   case llvm::AtomicOrderingCABI::acq_rel:
3847   case llvm::AtomicOrderingCABI::seq_cst:
3848     break;
3849   }
3850 
3851   Arg = TheCall->getArg(ScopeIndex);
3852   ArgExpr = Arg.get();
3853   Expr::EvalResult ArgResult1;
3854   // Check that sync scope is a constant literal
3855   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3856     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3857            << ArgExpr->getType();
3858 
3859   return false;
3860 }
3861 
3862 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3863   llvm::APSInt Result;
3864 
3865   // We can't check the value of a dependent argument.
3866   Expr *Arg = TheCall->getArg(ArgNum);
3867   if (Arg->isTypeDependent() || Arg->isValueDependent())
3868     return false;
3869 
3870   // Check constant-ness first.
3871   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3872     return true;
3873 
3874   int64_t Val = Result.getSExtValue();
3875   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3876     return false;
3877 
3878   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3879          << Arg->getSourceRange();
3880 }
3881 
3882 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3883                                          unsigned BuiltinID,
3884                                          CallExpr *TheCall) {
3885   // CodeGenFunction can also detect this, but this gives a better error
3886   // message.
3887   bool FeatureMissing = false;
3888   SmallVector<StringRef> ReqFeatures;
3889   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3890   Features.split(ReqFeatures, ',');
3891 
3892   // Check if each required feature is included
3893   for (StringRef F : ReqFeatures) {
3894     if (TI.hasFeature(F))
3895       continue;
3896 
3897     // If the feature is 64bit, alter the string so it will print better in
3898     // the diagnostic.
3899     if (F == "64bit")
3900       F = "RV64";
3901 
3902     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3903     F.consume_front("experimental-");
3904     std::string FeatureStr = F.str();
3905     FeatureStr[0] = std::toupper(FeatureStr[0]);
3906 
3907     // Error message
3908     FeatureMissing = true;
3909     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3910         << TheCall->getSourceRange() << StringRef(FeatureStr);
3911   }
3912 
3913   if (FeatureMissing)
3914     return true;
3915 
3916   switch (BuiltinID) {
3917   case RISCVVector::BI__builtin_rvv_vsetvli:
3918     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3919            CheckRISCVLMUL(TheCall, 2);
3920   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3921     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3922            CheckRISCVLMUL(TheCall, 1);
3923   }
3924 
3925   return false;
3926 }
3927 
3928 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3929                                            CallExpr *TheCall) {
3930   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3931     Expr *Arg = TheCall->getArg(0);
3932     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3933       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3934         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3935                << Arg->getSourceRange();
3936   }
3937 
3938   // For intrinsics which take an immediate value as part of the instruction,
3939   // range check them here.
3940   unsigned i = 0, l = 0, u = 0;
3941   switch (BuiltinID) {
3942   default: return false;
3943   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3944   case SystemZ::BI__builtin_s390_verimb:
3945   case SystemZ::BI__builtin_s390_verimh:
3946   case SystemZ::BI__builtin_s390_verimf:
3947   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3948   case SystemZ::BI__builtin_s390_vfaeb:
3949   case SystemZ::BI__builtin_s390_vfaeh:
3950   case SystemZ::BI__builtin_s390_vfaef:
3951   case SystemZ::BI__builtin_s390_vfaebs:
3952   case SystemZ::BI__builtin_s390_vfaehs:
3953   case SystemZ::BI__builtin_s390_vfaefs:
3954   case SystemZ::BI__builtin_s390_vfaezb:
3955   case SystemZ::BI__builtin_s390_vfaezh:
3956   case SystemZ::BI__builtin_s390_vfaezf:
3957   case SystemZ::BI__builtin_s390_vfaezbs:
3958   case SystemZ::BI__builtin_s390_vfaezhs:
3959   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3960   case SystemZ::BI__builtin_s390_vfisb:
3961   case SystemZ::BI__builtin_s390_vfidb:
3962     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3963            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3964   case SystemZ::BI__builtin_s390_vftcisb:
3965   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3966   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3967   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3968   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3969   case SystemZ::BI__builtin_s390_vstrcb:
3970   case SystemZ::BI__builtin_s390_vstrch:
3971   case SystemZ::BI__builtin_s390_vstrcf:
3972   case SystemZ::BI__builtin_s390_vstrczb:
3973   case SystemZ::BI__builtin_s390_vstrczh:
3974   case SystemZ::BI__builtin_s390_vstrczf:
3975   case SystemZ::BI__builtin_s390_vstrcbs:
3976   case SystemZ::BI__builtin_s390_vstrchs:
3977   case SystemZ::BI__builtin_s390_vstrcfs:
3978   case SystemZ::BI__builtin_s390_vstrczbs:
3979   case SystemZ::BI__builtin_s390_vstrczhs:
3980   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3981   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3982   case SystemZ::BI__builtin_s390_vfminsb:
3983   case SystemZ::BI__builtin_s390_vfmaxsb:
3984   case SystemZ::BI__builtin_s390_vfmindb:
3985   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3986   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3987   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3988   case SystemZ::BI__builtin_s390_vclfnhs:
3989   case SystemZ::BI__builtin_s390_vclfnls:
3990   case SystemZ::BI__builtin_s390_vcfn:
3991   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3992   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3993   }
3994   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3995 }
3996 
3997 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3998 /// This checks that the target supports __builtin_cpu_supports and
3999 /// that the string argument is constant and valid.
4000 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4001                                    CallExpr *TheCall) {
4002   Expr *Arg = TheCall->getArg(0);
4003 
4004   // Check if the argument is a string literal.
4005   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4006     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4007            << Arg->getSourceRange();
4008 
4009   // Check the contents of the string.
4010   StringRef Feature =
4011       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4012   if (!TI.validateCpuSupports(Feature))
4013     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4014            << Arg->getSourceRange();
4015   return false;
4016 }
4017 
4018 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4019 /// This checks that the target supports __builtin_cpu_is and
4020 /// that the string argument is constant and valid.
4021 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4022   Expr *Arg = TheCall->getArg(0);
4023 
4024   // Check if the argument is a string literal.
4025   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4026     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4027            << Arg->getSourceRange();
4028 
4029   // Check the contents of the string.
4030   StringRef Feature =
4031       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4032   if (!TI.validateCpuIs(Feature))
4033     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4034            << Arg->getSourceRange();
4035   return false;
4036 }
4037 
4038 // Check if the rounding mode is legal.
4039 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4040   // Indicates if this instruction has rounding control or just SAE.
4041   bool HasRC = false;
4042 
4043   unsigned ArgNum = 0;
4044   switch (BuiltinID) {
4045   default:
4046     return false;
4047   case X86::BI__builtin_ia32_vcvttsd2si32:
4048   case X86::BI__builtin_ia32_vcvttsd2si64:
4049   case X86::BI__builtin_ia32_vcvttsd2usi32:
4050   case X86::BI__builtin_ia32_vcvttsd2usi64:
4051   case X86::BI__builtin_ia32_vcvttss2si32:
4052   case X86::BI__builtin_ia32_vcvttss2si64:
4053   case X86::BI__builtin_ia32_vcvttss2usi32:
4054   case X86::BI__builtin_ia32_vcvttss2usi64:
4055   case X86::BI__builtin_ia32_vcvttsh2si32:
4056   case X86::BI__builtin_ia32_vcvttsh2si64:
4057   case X86::BI__builtin_ia32_vcvttsh2usi32:
4058   case X86::BI__builtin_ia32_vcvttsh2usi64:
4059     ArgNum = 1;
4060     break;
4061   case X86::BI__builtin_ia32_maxpd512:
4062   case X86::BI__builtin_ia32_maxps512:
4063   case X86::BI__builtin_ia32_minpd512:
4064   case X86::BI__builtin_ia32_minps512:
4065   case X86::BI__builtin_ia32_maxph512:
4066   case X86::BI__builtin_ia32_minph512:
4067     ArgNum = 2;
4068     break;
4069   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4070   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4071   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4072   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4073   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4074   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4075   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4076   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4077   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4078   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4079   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4080   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4081   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4082   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4083   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4084   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4085   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4086   case X86::BI__builtin_ia32_exp2pd_mask:
4087   case X86::BI__builtin_ia32_exp2ps_mask:
4088   case X86::BI__builtin_ia32_getexppd512_mask:
4089   case X86::BI__builtin_ia32_getexpps512_mask:
4090   case X86::BI__builtin_ia32_getexpph512_mask:
4091   case X86::BI__builtin_ia32_rcp28pd_mask:
4092   case X86::BI__builtin_ia32_rcp28ps_mask:
4093   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4094   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4095   case X86::BI__builtin_ia32_vcomisd:
4096   case X86::BI__builtin_ia32_vcomiss:
4097   case X86::BI__builtin_ia32_vcomish:
4098   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4099     ArgNum = 3;
4100     break;
4101   case X86::BI__builtin_ia32_cmppd512_mask:
4102   case X86::BI__builtin_ia32_cmpps512_mask:
4103   case X86::BI__builtin_ia32_cmpsd_mask:
4104   case X86::BI__builtin_ia32_cmpss_mask:
4105   case X86::BI__builtin_ia32_cmpsh_mask:
4106   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4107   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4108   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4109   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4110   case X86::BI__builtin_ia32_getexpss128_round_mask:
4111   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4112   case X86::BI__builtin_ia32_getmantpd512_mask:
4113   case X86::BI__builtin_ia32_getmantps512_mask:
4114   case X86::BI__builtin_ia32_getmantph512_mask:
4115   case X86::BI__builtin_ia32_maxsd_round_mask:
4116   case X86::BI__builtin_ia32_maxss_round_mask:
4117   case X86::BI__builtin_ia32_maxsh_round_mask:
4118   case X86::BI__builtin_ia32_minsd_round_mask:
4119   case X86::BI__builtin_ia32_minss_round_mask:
4120   case X86::BI__builtin_ia32_minsh_round_mask:
4121   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4122   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4123   case X86::BI__builtin_ia32_reducepd512_mask:
4124   case X86::BI__builtin_ia32_reduceps512_mask:
4125   case X86::BI__builtin_ia32_reduceph512_mask:
4126   case X86::BI__builtin_ia32_rndscalepd_mask:
4127   case X86::BI__builtin_ia32_rndscaleps_mask:
4128   case X86::BI__builtin_ia32_rndscaleph_mask:
4129   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4130   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4131     ArgNum = 4;
4132     break;
4133   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4134   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4135   case X86::BI__builtin_ia32_fixupimmps512_mask:
4136   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4137   case X86::BI__builtin_ia32_fixupimmsd_mask:
4138   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4139   case X86::BI__builtin_ia32_fixupimmss_mask:
4140   case X86::BI__builtin_ia32_fixupimmss_maskz:
4141   case X86::BI__builtin_ia32_getmantsd_round_mask:
4142   case X86::BI__builtin_ia32_getmantss_round_mask:
4143   case X86::BI__builtin_ia32_getmantsh_round_mask:
4144   case X86::BI__builtin_ia32_rangepd512_mask:
4145   case X86::BI__builtin_ia32_rangeps512_mask:
4146   case X86::BI__builtin_ia32_rangesd128_round_mask:
4147   case X86::BI__builtin_ia32_rangess128_round_mask:
4148   case X86::BI__builtin_ia32_reducesd_mask:
4149   case X86::BI__builtin_ia32_reducess_mask:
4150   case X86::BI__builtin_ia32_reducesh_mask:
4151   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4152   case X86::BI__builtin_ia32_rndscaless_round_mask:
4153   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4154     ArgNum = 5;
4155     break;
4156   case X86::BI__builtin_ia32_vcvtsd2si64:
4157   case X86::BI__builtin_ia32_vcvtsd2si32:
4158   case X86::BI__builtin_ia32_vcvtsd2usi32:
4159   case X86::BI__builtin_ia32_vcvtsd2usi64:
4160   case X86::BI__builtin_ia32_vcvtss2si32:
4161   case X86::BI__builtin_ia32_vcvtss2si64:
4162   case X86::BI__builtin_ia32_vcvtss2usi32:
4163   case X86::BI__builtin_ia32_vcvtss2usi64:
4164   case X86::BI__builtin_ia32_vcvtsh2si32:
4165   case X86::BI__builtin_ia32_vcvtsh2si64:
4166   case X86::BI__builtin_ia32_vcvtsh2usi32:
4167   case X86::BI__builtin_ia32_vcvtsh2usi64:
4168   case X86::BI__builtin_ia32_sqrtpd512:
4169   case X86::BI__builtin_ia32_sqrtps512:
4170   case X86::BI__builtin_ia32_sqrtph512:
4171     ArgNum = 1;
4172     HasRC = true;
4173     break;
4174   case X86::BI__builtin_ia32_addph512:
4175   case X86::BI__builtin_ia32_divph512:
4176   case X86::BI__builtin_ia32_mulph512:
4177   case X86::BI__builtin_ia32_subph512:
4178   case X86::BI__builtin_ia32_addpd512:
4179   case X86::BI__builtin_ia32_addps512:
4180   case X86::BI__builtin_ia32_divpd512:
4181   case X86::BI__builtin_ia32_divps512:
4182   case X86::BI__builtin_ia32_mulpd512:
4183   case X86::BI__builtin_ia32_mulps512:
4184   case X86::BI__builtin_ia32_subpd512:
4185   case X86::BI__builtin_ia32_subps512:
4186   case X86::BI__builtin_ia32_cvtsi2sd64:
4187   case X86::BI__builtin_ia32_cvtsi2ss32:
4188   case X86::BI__builtin_ia32_cvtsi2ss64:
4189   case X86::BI__builtin_ia32_cvtusi2sd64:
4190   case X86::BI__builtin_ia32_cvtusi2ss32:
4191   case X86::BI__builtin_ia32_cvtusi2ss64:
4192   case X86::BI__builtin_ia32_vcvtusi2sh:
4193   case X86::BI__builtin_ia32_vcvtusi642sh:
4194   case X86::BI__builtin_ia32_vcvtsi2sh:
4195   case X86::BI__builtin_ia32_vcvtsi642sh:
4196     ArgNum = 2;
4197     HasRC = true;
4198     break;
4199   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4200   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4201   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4202   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4203   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4204   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4205   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4206   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4207   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4208   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4209   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4210   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4211   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4212   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4213   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4214   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4215   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4216   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4217   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4218   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4219   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4220   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4221   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4222   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4223   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4224   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4225   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4226   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4227   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4228     ArgNum = 3;
4229     HasRC = true;
4230     break;
4231   case X86::BI__builtin_ia32_addsh_round_mask:
4232   case X86::BI__builtin_ia32_addss_round_mask:
4233   case X86::BI__builtin_ia32_addsd_round_mask:
4234   case X86::BI__builtin_ia32_divsh_round_mask:
4235   case X86::BI__builtin_ia32_divss_round_mask:
4236   case X86::BI__builtin_ia32_divsd_round_mask:
4237   case X86::BI__builtin_ia32_mulsh_round_mask:
4238   case X86::BI__builtin_ia32_mulss_round_mask:
4239   case X86::BI__builtin_ia32_mulsd_round_mask:
4240   case X86::BI__builtin_ia32_subsh_round_mask:
4241   case X86::BI__builtin_ia32_subss_round_mask:
4242   case X86::BI__builtin_ia32_subsd_round_mask:
4243   case X86::BI__builtin_ia32_scalefph512_mask:
4244   case X86::BI__builtin_ia32_scalefpd512_mask:
4245   case X86::BI__builtin_ia32_scalefps512_mask:
4246   case X86::BI__builtin_ia32_scalefsd_round_mask:
4247   case X86::BI__builtin_ia32_scalefss_round_mask:
4248   case X86::BI__builtin_ia32_scalefsh_round_mask:
4249   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4250   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4251   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4252   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4253   case X86::BI__builtin_ia32_sqrtss_round_mask:
4254   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4255   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4256   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4257   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4258   case X86::BI__builtin_ia32_vfmaddss3_mask:
4259   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4260   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4261   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4262   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4263   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4264   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4265   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4266   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4267   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4268   case X86::BI__builtin_ia32_vfmaddps512_mask:
4269   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4270   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4271   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4272   case X86::BI__builtin_ia32_vfmaddph512_mask:
4273   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4274   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4275   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4276   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4277   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4278   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4279   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4280   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4281   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4282   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4283   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4284   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4285   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4286   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4287   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4288   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4289   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4290   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4291   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4292   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4293   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4294   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4295   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4296   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4297   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4298   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4299   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4300   case X86::BI__builtin_ia32_vfmulcsh_mask:
4301   case X86::BI__builtin_ia32_vfmulcph512_mask:
4302   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4303   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4304     ArgNum = 4;
4305     HasRC = true;
4306     break;
4307   }
4308 
4309   llvm::APSInt Result;
4310 
4311   // We can't check the value of a dependent argument.
4312   Expr *Arg = TheCall->getArg(ArgNum);
4313   if (Arg->isTypeDependent() || Arg->isValueDependent())
4314     return false;
4315 
4316   // Check constant-ness first.
4317   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4318     return true;
4319 
4320   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4321   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4322   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4323   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4324   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4325       Result == 8/*ROUND_NO_EXC*/ ||
4326       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4327       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4328     return false;
4329 
4330   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4331          << Arg->getSourceRange();
4332 }
4333 
4334 // Check if the gather/scatter scale is legal.
4335 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4336                                              CallExpr *TheCall) {
4337   unsigned ArgNum = 0;
4338   switch (BuiltinID) {
4339   default:
4340     return false;
4341   case X86::BI__builtin_ia32_gatherpfdpd:
4342   case X86::BI__builtin_ia32_gatherpfdps:
4343   case X86::BI__builtin_ia32_gatherpfqpd:
4344   case X86::BI__builtin_ia32_gatherpfqps:
4345   case X86::BI__builtin_ia32_scatterpfdpd:
4346   case X86::BI__builtin_ia32_scatterpfdps:
4347   case X86::BI__builtin_ia32_scatterpfqpd:
4348   case X86::BI__builtin_ia32_scatterpfqps:
4349     ArgNum = 3;
4350     break;
4351   case X86::BI__builtin_ia32_gatherd_pd:
4352   case X86::BI__builtin_ia32_gatherd_pd256:
4353   case X86::BI__builtin_ia32_gatherq_pd:
4354   case X86::BI__builtin_ia32_gatherq_pd256:
4355   case X86::BI__builtin_ia32_gatherd_ps:
4356   case X86::BI__builtin_ia32_gatherd_ps256:
4357   case X86::BI__builtin_ia32_gatherq_ps:
4358   case X86::BI__builtin_ia32_gatherq_ps256:
4359   case X86::BI__builtin_ia32_gatherd_q:
4360   case X86::BI__builtin_ia32_gatherd_q256:
4361   case X86::BI__builtin_ia32_gatherq_q:
4362   case X86::BI__builtin_ia32_gatherq_q256:
4363   case X86::BI__builtin_ia32_gatherd_d:
4364   case X86::BI__builtin_ia32_gatherd_d256:
4365   case X86::BI__builtin_ia32_gatherq_d:
4366   case X86::BI__builtin_ia32_gatherq_d256:
4367   case X86::BI__builtin_ia32_gather3div2df:
4368   case X86::BI__builtin_ia32_gather3div2di:
4369   case X86::BI__builtin_ia32_gather3div4df:
4370   case X86::BI__builtin_ia32_gather3div4di:
4371   case X86::BI__builtin_ia32_gather3div4sf:
4372   case X86::BI__builtin_ia32_gather3div4si:
4373   case X86::BI__builtin_ia32_gather3div8sf:
4374   case X86::BI__builtin_ia32_gather3div8si:
4375   case X86::BI__builtin_ia32_gather3siv2df:
4376   case X86::BI__builtin_ia32_gather3siv2di:
4377   case X86::BI__builtin_ia32_gather3siv4df:
4378   case X86::BI__builtin_ia32_gather3siv4di:
4379   case X86::BI__builtin_ia32_gather3siv4sf:
4380   case X86::BI__builtin_ia32_gather3siv4si:
4381   case X86::BI__builtin_ia32_gather3siv8sf:
4382   case X86::BI__builtin_ia32_gather3siv8si:
4383   case X86::BI__builtin_ia32_gathersiv8df:
4384   case X86::BI__builtin_ia32_gathersiv16sf:
4385   case X86::BI__builtin_ia32_gatherdiv8df:
4386   case X86::BI__builtin_ia32_gatherdiv16sf:
4387   case X86::BI__builtin_ia32_gathersiv8di:
4388   case X86::BI__builtin_ia32_gathersiv16si:
4389   case X86::BI__builtin_ia32_gatherdiv8di:
4390   case X86::BI__builtin_ia32_gatherdiv16si:
4391   case X86::BI__builtin_ia32_scatterdiv2df:
4392   case X86::BI__builtin_ia32_scatterdiv2di:
4393   case X86::BI__builtin_ia32_scatterdiv4df:
4394   case X86::BI__builtin_ia32_scatterdiv4di:
4395   case X86::BI__builtin_ia32_scatterdiv4sf:
4396   case X86::BI__builtin_ia32_scatterdiv4si:
4397   case X86::BI__builtin_ia32_scatterdiv8sf:
4398   case X86::BI__builtin_ia32_scatterdiv8si:
4399   case X86::BI__builtin_ia32_scattersiv2df:
4400   case X86::BI__builtin_ia32_scattersiv2di:
4401   case X86::BI__builtin_ia32_scattersiv4df:
4402   case X86::BI__builtin_ia32_scattersiv4di:
4403   case X86::BI__builtin_ia32_scattersiv4sf:
4404   case X86::BI__builtin_ia32_scattersiv4si:
4405   case X86::BI__builtin_ia32_scattersiv8sf:
4406   case X86::BI__builtin_ia32_scattersiv8si:
4407   case X86::BI__builtin_ia32_scattersiv8df:
4408   case X86::BI__builtin_ia32_scattersiv16sf:
4409   case X86::BI__builtin_ia32_scatterdiv8df:
4410   case X86::BI__builtin_ia32_scatterdiv16sf:
4411   case X86::BI__builtin_ia32_scattersiv8di:
4412   case X86::BI__builtin_ia32_scattersiv16si:
4413   case X86::BI__builtin_ia32_scatterdiv8di:
4414   case X86::BI__builtin_ia32_scatterdiv16si:
4415     ArgNum = 4;
4416     break;
4417   }
4418 
4419   llvm::APSInt Result;
4420 
4421   // We can't check the value of a dependent argument.
4422   Expr *Arg = TheCall->getArg(ArgNum);
4423   if (Arg->isTypeDependent() || Arg->isValueDependent())
4424     return false;
4425 
4426   // Check constant-ness first.
4427   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4428     return true;
4429 
4430   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4431     return false;
4432 
4433   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4434          << Arg->getSourceRange();
4435 }
4436 
4437 enum { TileRegLow = 0, TileRegHigh = 7 };
4438 
4439 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4440                                              ArrayRef<int> ArgNums) {
4441   for (int ArgNum : ArgNums) {
4442     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4443       return true;
4444   }
4445   return false;
4446 }
4447 
4448 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4449                                         ArrayRef<int> ArgNums) {
4450   // Because the max number of tile register is TileRegHigh + 1, so here we use
4451   // each bit to represent the usage of them in bitset.
4452   std::bitset<TileRegHigh + 1> ArgValues;
4453   for (int ArgNum : ArgNums) {
4454     Expr *Arg = TheCall->getArg(ArgNum);
4455     if (Arg->isTypeDependent() || Arg->isValueDependent())
4456       continue;
4457 
4458     llvm::APSInt Result;
4459     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4460       return true;
4461     int ArgExtValue = Result.getExtValue();
4462     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4463            "Incorrect tile register num.");
4464     if (ArgValues.test(ArgExtValue))
4465       return Diag(TheCall->getBeginLoc(),
4466                   diag::err_x86_builtin_tile_arg_duplicate)
4467              << TheCall->getArg(ArgNum)->getSourceRange();
4468     ArgValues.set(ArgExtValue);
4469   }
4470   return false;
4471 }
4472 
4473 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4474                                                 ArrayRef<int> ArgNums) {
4475   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4476          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4477 }
4478 
4479 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4480   switch (BuiltinID) {
4481   default:
4482     return false;
4483   case X86::BI__builtin_ia32_tileloadd64:
4484   case X86::BI__builtin_ia32_tileloaddt164:
4485   case X86::BI__builtin_ia32_tilestored64:
4486   case X86::BI__builtin_ia32_tilezero:
4487     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4488   case X86::BI__builtin_ia32_tdpbssd:
4489   case X86::BI__builtin_ia32_tdpbsud:
4490   case X86::BI__builtin_ia32_tdpbusd:
4491   case X86::BI__builtin_ia32_tdpbuud:
4492   case X86::BI__builtin_ia32_tdpbf16ps:
4493     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4494   }
4495 }
4496 static bool isX86_32Builtin(unsigned BuiltinID) {
4497   // These builtins only work on x86-32 targets.
4498   switch (BuiltinID) {
4499   case X86::BI__builtin_ia32_readeflags_u32:
4500   case X86::BI__builtin_ia32_writeeflags_u32:
4501     return true;
4502   }
4503 
4504   return false;
4505 }
4506 
4507 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4508                                        CallExpr *TheCall) {
4509   if (BuiltinID == X86::BI__builtin_cpu_supports)
4510     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4511 
4512   if (BuiltinID == X86::BI__builtin_cpu_is)
4513     return SemaBuiltinCpuIs(*this, TI, TheCall);
4514 
4515   // Check for 32-bit only builtins on a 64-bit target.
4516   const llvm::Triple &TT = TI.getTriple();
4517   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4518     return Diag(TheCall->getCallee()->getBeginLoc(),
4519                 diag::err_32_bit_builtin_64_bit_tgt);
4520 
4521   // If the intrinsic has rounding or SAE make sure its valid.
4522   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4523     return true;
4524 
4525   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4526   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4527     return true;
4528 
4529   // If the intrinsic has a tile arguments, make sure they are valid.
4530   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4531     return true;
4532 
4533   // For intrinsics which take an immediate value as part of the instruction,
4534   // range check them here.
4535   int i = 0, l = 0, u = 0;
4536   switch (BuiltinID) {
4537   default:
4538     return false;
4539   case X86::BI__builtin_ia32_vec_ext_v2si:
4540   case X86::BI__builtin_ia32_vec_ext_v2di:
4541   case X86::BI__builtin_ia32_vextractf128_pd256:
4542   case X86::BI__builtin_ia32_vextractf128_ps256:
4543   case X86::BI__builtin_ia32_vextractf128_si256:
4544   case X86::BI__builtin_ia32_extract128i256:
4545   case X86::BI__builtin_ia32_extractf64x4_mask:
4546   case X86::BI__builtin_ia32_extracti64x4_mask:
4547   case X86::BI__builtin_ia32_extractf32x8_mask:
4548   case X86::BI__builtin_ia32_extracti32x8_mask:
4549   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4550   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4551   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4552   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4553     i = 1; l = 0; u = 1;
4554     break;
4555   case X86::BI__builtin_ia32_vec_set_v2di:
4556   case X86::BI__builtin_ia32_vinsertf128_pd256:
4557   case X86::BI__builtin_ia32_vinsertf128_ps256:
4558   case X86::BI__builtin_ia32_vinsertf128_si256:
4559   case X86::BI__builtin_ia32_insert128i256:
4560   case X86::BI__builtin_ia32_insertf32x8:
4561   case X86::BI__builtin_ia32_inserti32x8:
4562   case X86::BI__builtin_ia32_insertf64x4:
4563   case X86::BI__builtin_ia32_inserti64x4:
4564   case X86::BI__builtin_ia32_insertf64x2_256:
4565   case X86::BI__builtin_ia32_inserti64x2_256:
4566   case X86::BI__builtin_ia32_insertf32x4_256:
4567   case X86::BI__builtin_ia32_inserti32x4_256:
4568     i = 2; l = 0; u = 1;
4569     break;
4570   case X86::BI__builtin_ia32_vpermilpd:
4571   case X86::BI__builtin_ia32_vec_ext_v4hi:
4572   case X86::BI__builtin_ia32_vec_ext_v4si:
4573   case X86::BI__builtin_ia32_vec_ext_v4sf:
4574   case X86::BI__builtin_ia32_vec_ext_v4di:
4575   case X86::BI__builtin_ia32_extractf32x4_mask:
4576   case X86::BI__builtin_ia32_extracti32x4_mask:
4577   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4578   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4579     i = 1; l = 0; u = 3;
4580     break;
4581   case X86::BI_mm_prefetch:
4582   case X86::BI__builtin_ia32_vec_ext_v8hi:
4583   case X86::BI__builtin_ia32_vec_ext_v8si:
4584     i = 1; l = 0; u = 7;
4585     break;
4586   case X86::BI__builtin_ia32_sha1rnds4:
4587   case X86::BI__builtin_ia32_blendpd:
4588   case X86::BI__builtin_ia32_shufpd:
4589   case X86::BI__builtin_ia32_vec_set_v4hi:
4590   case X86::BI__builtin_ia32_vec_set_v4si:
4591   case X86::BI__builtin_ia32_vec_set_v4di:
4592   case X86::BI__builtin_ia32_shuf_f32x4_256:
4593   case X86::BI__builtin_ia32_shuf_f64x2_256:
4594   case X86::BI__builtin_ia32_shuf_i32x4_256:
4595   case X86::BI__builtin_ia32_shuf_i64x2_256:
4596   case X86::BI__builtin_ia32_insertf64x2_512:
4597   case X86::BI__builtin_ia32_inserti64x2_512:
4598   case X86::BI__builtin_ia32_insertf32x4:
4599   case X86::BI__builtin_ia32_inserti32x4:
4600     i = 2; l = 0; u = 3;
4601     break;
4602   case X86::BI__builtin_ia32_vpermil2pd:
4603   case X86::BI__builtin_ia32_vpermil2pd256:
4604   case X86::BI__builtin_ia32_vpermil2ps:
4605   case X86::BI__builtin_ia32_vpermil2ps256:
4606     i = 3; l = 0; u = 3;
4607     break;
4608   case X86::BI__builtin_ia32_cmpb128_mask:
4609   case X86::BI__builtin_ia32_cmpw128_mask:
4610   case X86::BI__builtin_ia32_cmpd128_mask:
4611   case X86::BI__builtin_ia32_cmpq128_mask:
4612   case X86::BI__builtin_ia32_cmpb256_mask:
4613   case X86::BI__builtin_ia32_cmpw256_mask:
4614   case X86::BI__builtin_ia32_cmpd256_mask:
4615   case X86::BI__builtin_ia32_cmpq256_mask:
4616   case X86::BI__builtin_ia32_cmpb512_mask:
4617   case X86::BI__builtin_ia32_cmpw512_mask:
4618   case X86::BI__builtin_ia32_cmpd512_mask:
4619   case X86::BI__builtin_ia32_cmpq512_mask:
4620   case X86::BI__builtin_ia32_ucmpb128_mask:
4621   case X86::BI__builtin_ia32_ucmpw128_mask:
4622   case X86::BI__builtin_ia32_ucmpd128_mask:
4623   case X86::BI__builtin_ia32_ucmpq128_mask:
4624   case X86::BI__builtin_ia32_ucmpb256_mask:
4625   case X86::BI__builtin_ia32_ucmpw256_mask:
4626   case X86::BI__builtin_ia32_ucmpd256_mask:
4627   case X86::BI__builtin_ia32_ucmpq256_mask:
4628   case X86::BI__builtin_ia32_ucmpb512_mask:
4629   case X86::BI__builtin_ia32_ucmpw512_mask:
4630   case X86::BI__builtin_ia32_ucmpd512_mask:
4631   case X86::BI__builtin_ia32_ucmpq512_mask:
4632   case X86::BI__builtin_ia32_vpcomub:
4633   case X86::BI__builtin_ia32_vpcomuw:
4634   case X86::BI__builtin_ia32_vpcomud:
4635   case X86::BI__builtin_ia32_vpcomuq:
4636   case X86::BI__builtin_ia32_vpcomb:
4637   case X86::BI__builtin_ia32_vpcomw:
4638   case X86::BI__builtin_ia32_vpcomd:
4639   case X86::BI__builtin_ia32_vpcomq:
4640   case X86::BI__builtin_ia32_vec_set_v8hi:
4641   case X86::BI__builtin_ia32_vec_set_v8si:
4642     i = 2; l = 0; u = 7;
4643     break;
4644   case X86::BI__builtin_ia32_vpermilpd256:
4645   case X86::BI__builtin_ia32_roundps:
4646   case X86::BI__builtin_ia32_roundpd:
4647   case X86::BI__builtin_ia32_roundps256:
4648   case X86::BI__builtin_ia32_roundpd256:
4649   case X86::BI__builtin_ia32_getmantpd128_mask:
4650   case X86::BI__builtin_ia32_getmantpd256_mask:
4651   case X86::BI__builtin_ia32_getmantps128_mask:
4652   case X86::BI__builtin_ia32_getmantps256_mask:
4653   case X86::BI__builtin_ia32_getmantpd512_mask:
4654   case X86::BI__builtin_ia32_getmantps512_mask:
4655   case X86::BI__builtin_ia32_getmantph128_mask:
4656   case X86::BI__builtin_ia32_getmantph256_mask:
4657   case X86::BI__builtin_ia32_getmantph512_mask:
4658   case X86::BI__builtin_ia32_vec_ext_v16qi:
4659   case X86::BI__builtin_ia32_vec_ext_v16hi:
4660     i = 1; l = 0; u = 15;
4661     break;
4662   case X86::BI__builtin_ia32_pblendd128:
4663   case X86::BI__builtin_ia32_blendps:
4664   case X86::BI__builtin_ia32_blendpd256:
4665   case X86::BI__builtin_ia32_shufpd256:
4666   case X86::BI__builtin_ia32_roundss:
4667   case X86::BI__builtin_ia32_roundsd:
4668   case X86::BI__builtin_ia32_rangepd128_mask:
4669   case X86::BI__builtin_ia32_rangepd256_mask:
4670   case X86::BI__builtin_ia32_rangepd512_mask:
4671   case X86::BI__builtin_ia32_rangeps128_mask:
4672   case X86::BI__builtin_ia32_rangeps256_mask:
4673   case X86::BI__builtin_ia32_rangeps512_mask:
4674   case X86::BI__builtin_ia32_getmantsd_round_mask:
4675   case X86::BI__builtin_ia32_getmantss_round_mask:
4676   case X86::BI__builtin_ia32_getmantsh_round_mask:
4677   case X86::BI__builtin_ia32_vec_set_v16qi:
4678   case X86::BI__builtin_ia32_vec_set_v16hi:
4679     i = 2; l = 0; u = 15;
4680     break;
4681   case X86::BI__builtin_ia32_vec_ext_v32qi:
4682     i = 1; l = 0; u = 31;
4683     break;
4684   case X86::BI__builtin_ia32_cmpps:
4685   case X86::BI__builtin_ia32_cmpss:
4686   case X86::BI__builtin_ia32_cmppd:
4687   case X86::BI__builtin_ia32_cmpsd:
4688   case X86::BI__builtin_ia32_cmpps256:
4689   case X86::BI__builtin_ia32_cmppd256:
4690   case X86::BI__builtin_ia32_cmpps128_mask:
4691   case X86::BI__builtin_ia32_cmppd128_mask:
4692   case X86::BI__builtin_ia32_cmpps256_mask:
4693   case X86::BI__builtin_ia32_cmppd256_mask:
4694   case X86::BI__builtin_ia32_cmpps512_mask:
4695   case X86::BI__builtin_ia32_cmppd512_mask:
4696   case X86::BI__builtin_ia32_cmpsd_mask:
4697   case X86::BI__builtin_ia32_cmpss_mask:
4698   case X86::BI__builtin_ia32_vec_set_v32qi:
4699     i = 2; l = 0; u = 31;
4700     break;
4701   case X86::BI__builtin_ia32_permdf256:
4702   case X86::BI__builtin_ia32_permdi256:
4703   case X86::BI__builtin_ia32_permdf512:
4704   case X86::BI__builtin_ia32_permdi512:
4705   case X86::BI__builtin_ia32_vpermilps:
4706   case X86::BI__builtin_ia32_vpermilps256:
4707   case X86::BI__builtin_ia32_vpermilpd512:
4708   case X86::BI__builtin_ia32_vpermilps512:
4709   case X86::BI__builtin_ia32_pshufd:
4710   case X86::BI__builtin_ia32_pshufd256:
4711   case X86::BI__builtin_ia32_pshufd512:
4712   case X86::BI__builtin_ia32_pshufhw:
4713   case X86::BI__builtin_ia32_pshufhw256:
4714   case X86::BI__builtin_ia32_pshufhw512:
4715   case X86::BI__builtin_ia32_pshuflw:
4716   case X86::BI__builtin_ia32_pshuflw256:
4717   case X86::BI__builtin_ia32_pshuflw512:
4718   case X86::BI__builtin_ia32_vcvtps2ph:
4719   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4720   case X86::BI__builtin_ia32_vcvtps2ph256:
4721   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4722   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4723   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4724   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4725   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4726   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4727   case X86::BI__builtin_ia32_rndscaleps_mask:
4728   case X86::BI__builtin_ia32_rndscalepd_mask:
4729   case X86::BI__builtin_ia32_rndscaleph_mask:
4730   case X86::BI__builtin_ia32_reducepd128_mask:
4731   case X86::BI__builtin_ia32_reducepd256_mask:
4732   case X86::BI__builtin_ia32_reducepd512_mask:
4733   case X86::BI__builtin_ia32_reduceps128_mask:
4734   case X86::BI__builtin_ia32_reduceps256_mask:
4735   case X86::BI__builtin_ia32_reduceps512_mask:
4736   case X86::BI__builtin_ia32_reduceph128_mask:
4737   case X86::BI__builtin_ia32_reduceph256_mask:
4738   case X86::BI__builtin_ia32_reduceph512_mask:
4739   case X86::BI__builtin_ia32_prold512:
4740   case X86::BI__builtin_ia32_prolq512:
4741   case X86::BI__builtin_ia32_prold128:
4742   case X86::BI__builtin_ia32_prold256:
4743   case X86::BI__builtin_ia32_prolq128:
4744   case X86::BI__builtin_ia32_prolq256:
4745   case X86::BI__builtin_ia32_prord512:
4746   case X86::BI__builtin_ia32_prorq512:
4747   case X86::BI__builtin_ia32_prord128:
4748   case X86::BI__builtin_ia32_prord256:
4749   case X86::BI__builtin_ia32_prorq128:
4750   case X86::BI__builtin_ia32_prorq256:
4751   case X86::BI__builtin_ia32_fpclasspd128_mask:
4752   case X86::BI__builtin_ia32_fpclasspd256_mask:
4753   case X86::BI__builtin_ia32_fpclassps128_mask:
4754   case X86::BI__builtin_ia32_fpclassps256_mask:
4755   case X86::BI__builtin_ia32_fpclassps512_mask:
4756   case X86::BI__builtin_ia32_fpclasspd512_mask:
4757   case X86::BI__builtin_ia32_fpclassph128_mask:
4758   case X86::BI__builtin_ia32_fpclassph256_mask:
4759   case X86::BI__builtin_ia32_fpclassph512_mask:
4760   case X86::BI__builtin_ia32_fpclasssd_mask:
4761   case X86::BI__builtin_ia32_fpclassss_mask:
4762   case X86::BI__builtin_ia32_fpclasssh_mask:
4763   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4764   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4765   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4766   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4767   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4768   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4769   case X86::BI__builtin_ia32_kshiftliqi:
4770   case X86::BI__builtin_ia32_kshiftlihi:
4771   case X86::BI__builtin_ia32_kshiftlisi:
4772   case X86::BI__builtin_ia32_kshiftlidi:
4773   case X86::BI__builtin_ia32_kshiftriqi:
4774   case X86::BI__builtin_ia32_kshiftrihi:
4775   case X86::BI__builtin_ia32_kshiftrisi:
4776   case X86::BI__builtin_ia32_kshiftridi:
4777     i = 1; l = 0; u = 255;
4778     break;
4779   case X86::BI__builtin_ia32_vperm2f128_pd256:
4780   case X86::BI__builtin_ia32_vperm2f128_ps256:
4781   case X86::BI__builtin_ia32_vperm2f128_si256:
4782   case X86::BI__builtin_ia32_permti256:
4783   case X86::BI__builtin_ia32_pblendw128:
4784   case X86::BI__builtin_ia32_pblendw256:
4785   case X86::BI__builtin_ia32_blendps256:
4786   case X86::BI__builtin_ia32_pblendd256:
4787   case X86::BI__builtin_ia32_palignr128:
4788   case X86::BI__builtin_ia32_palignr256:
4789   case X86::BI__builtin_ia32_palignr512:
4790   case X86::BI__builtin_ia32_alignq512:
4791   case X86::BI__builtin_ia32_alignd512:
4792   case X86::BI__builtin_ia32_alignd128:
4793   case X86::BI__builtin_ia32_alignd256:
4794   case X86::BI__builtin_ia32_alignq128:
4795   case X86::BI__builtin_ia32_alignq256:
4796   case X86::BI__builtin_ia32_vcomisd:
4797   case X86::BI__builtin_ia32_vcomiss:
4798   case X86::BI__builtin_ia32_shuf_f32x4:
4799   case X86::BI__builtin_ia32_shuf_f64x2:
4800   case X86::BI__builtin_ia32_shuf_i32x4:
4801   case X86::BI__builtin_ia32_shuf_i64x2:
4802   case X86::BI__builtin_ia32_shufpd512:
4803   case X86::BI__builtin_ia32_shufps:
4804   case X86::BI__builtin_ia32_shufps256:
4805   case X86::BI__builtin_ia32_shufps512:
4806   case X86::BI__builtin_ia32_dbpsadbw128:
4807   case X86::BI__builtin_ia32_dbpsadbw256:
4808   case X86::BI__builtin_ia32_dbpsadbw512:
4809   case X86::BI__builtin_ia32_vpshldd128:
4810   case X86::BI__builtin_ia32_vpshldd256:
4811   case X86::BI__builtin_ia32_vpshldd512:
4812   case X86::BI__builtin_ia32_vpshldq128:
4813   case X86::BI__builtin_ia32_vpshldq256:
4814   case X86::BI__builtin_ia32_vpshldq512:
4815   case X86::BI__builtin_ia32_vpshldw128:
4816   case X86::BI__builtin_ia32_vpshldw256:
4817   case X86::BI__builtin_ia32_vpshldw512:
4818   case X86::BI__builtin_ia32_vpshrdd128:
4819   case X86::BI__builtin_ia32_vpshrdd256:
4820   case X86::BI__builtin_ia32_vpshrdd512:
4821   case X86::BI__builtin_ia32_vpshrdq128:
4822   case X86::BI__builtin_ia32_vpshrdq256:
4823   case X86::BI__builtin_ia32_vpshrdq512:
4824   case X86::BI__builtin_ia32_vpshrdw128:
4825   case X86::BI__builtin_ia32_vpshrdw256:
4826   case X86::BI__builtin_ia32_vpshrdw512:
4827     i = 2; l = 0; u = 255;
4828     break;
4829   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4830   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4831   case X86::BI__builtin_ia32_fixupimmps512_mask:
4832   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4833   case X86::BI__builtin_ia32_fixupimmsd_mask:
4834   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4835   case X86::BI__builtin_ia32_fixupimmss_mask:
4836   case X86::BI__builtin_ia32_fixupimmss_maskz:
4837   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4838   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4839   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4840   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4841   case X86::BI__builtin_ia32_fixupimmps128_mask:
4842   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4843   case X86::BI__builtin_ia32_fixupimmps256_mask:
4844   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4845   case X86::BI__builtin_ia32_pternlogd512_mask:
4846   case X86::BI__builtin_ia32_pternlogd512_maskz:
4847   case X86::BI__builtin_ia32_pternlogq512_mask:
4848   case X86::BI__builtin_ia32_pternlogq512_maskz:
4849   case X86::BI__builtin_ia32_pternlogd128_mask:
4850   case X86::BI__builtin_ia32_pternlogd128_maskz:
4851   case X86::BI__builtin_ia32_pternlogd256_mask:
4852   case X86::BI__builtin_ia32_pternlogd256_maskz:
4853   case X86::BI__builtin_ia32_pternlogq128_mask:
4854   case X86::BI__builtin_ia32_pternlogq128_maskz:
4855   case X86::BI__builtin_ia32_pternlogq256_mask:
4856   case X86::BI__builtin_ia32_pternlogq256_maskz:
4857     i = 3; l = 0; u = 255;
4858     break;
4859   case X86::BI__builtin_ia32_gatherpfdpd:
4860   case X86::BI__builtin_ia32_gatherpfdps:
4861   case X86::BI__builtin_ia32_gatherpfqpd:
4862   case X86::BI__builtin_ia32_gatherpfqps:
4863   case X86::BI__builtin_ia32_scatterpfdpd:
4864   case X86::BI__builtin_ia32_scatterpfdps:
4865   case X86::BI__builtin_ia32_scatterpfqpd:
4866   case X86::BI__builtin_ia32_scatterpfqps:
4867     i = 4; l = 2; u = 3;
4868     break;
4869   case X86::BI__builtin_ia32_reducesd_mask:
4870   case X86::BI__builtin_ia32_reducess_mask:
4871   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4872   case X86::BI__builtin_ia32_rndscaless_round_mask:
4873   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4874   case X86::BI__builtin_ia32_reducesh_mask:
4875     i = 4; l = 0; u = 255;
4876     break;
4877   }
4878 
4879   // Note that we don't force a hard error on the range check here, allowing
4880   // template-generated or macro-generated dead code to potentially have out-of-
4881   // range values. These need to code generate, but don't need to necessarily
4882   // make any sense. We use a warning that defaults to an error.
4883   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4884 }
4885 
4886 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4887 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4888 /// Returns true when the format fits the function and the FormatStringInfo has
4889 /// been populated.
4890 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4891                                FormatStringInfo *FSI) {
4892   FSI->HasVAListArg = Format->getFirstArg() == 0;
4893   FSI->FormatIdx = Format->getFormatIdx() - 1;
4894   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4895 
4896   // The way the format attribute works in GCC, the implicit this argument
4897   // of member functions is counted. However, it doesn't appear in our own
4898   // lists, so decrement format_idx in that case.
4899   if (IsCXXMember) {
4900     if(FSI->FormatIdx == 0)
4901       return false;
4902     --FSI->FormatIdx;
4903     if (FSI->FirstDataArg != 0)
4904       --FSI->FirstDataArg;
4905   }
4906   return true;
4907 }
4908 
4909 /// Checks if a the given expression evaluates to null.
4910 ///
4911 /// Returns true if the value evaluates to null.
4912 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4913   // If the expression has non-null type, it doesn't evaluate to null.
4914   if (auto nullability
4915         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4916     if (*nullability == NullabilityKind::NonNull)
4917       return false;
4918   }
4919 
4920   // As a special case, transparent unions initialized with zero are
4921   // considered null for the purposes of the nonnull attribute.
4922   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4923     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4924       if (const CompoundLiteralExpr *CLE =
4925           dyn_cast<CompoundLiteralExpr>(Expr))
4926         if (const InitListExpr *ILE =
4927             dyn_cast<InitListExpr>(CLE->getInitializer()))
4928           Expr = ILE->getInit(0);
4929   }
4930 
4931   bool Result;
4932   return (!Expr->isValueDependent() &&
4933           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4934           !Result);
4935 }
4936 
4937 static void CheckNonNullArgument(Sema &S,
4938                                  const Expr *ArgExpr,
4939                                  SourceLocation CallSiteLoc) {
4940   if (CheckNonNullExpr(S, ArgExpr))
4941     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4942                           S.PDiag(diag::warn_null_arg)
4943                               << ArgExpr->getSourceRange());
4944 }
4945 
4946 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4947   FormatStringInfo FSI;
4948   if ((GetFormatStringType(Format) == FST_NSString) &&
4949       getFormatStringInfo(Format, false, &FSI)) {
4950     Idx = FSI.FormatIdx;
4951     return true;
4952   }
4953   return false;
4954 }
4955 
4956 /// Diagnose use of %s directive in an NSString which is being passed
4957 /// as formatting string to formatting method.
4958 static void
4959 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4960                                         const NamedDecl *FDecl,
4961                                         Expr **Args,
4962                                         unsigned NumArgs) {
4963   unsigned Idx = 0;
4964   bool Format = false;
4965   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4966   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4967     Idx = 2;
4968     Format = true;
4969   }
4970   else
4971     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4972       if (S.GetFormatNSStringIdx(I, Idx)) {
4973         Format = true;
4974         break;
4975       }
4976     }
4977   if (!Format || NumArgs <= Idx)
4978     return;
4979   const Expr *FormatExpr = Args[Idx];
4980   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4981     FormatExpr = CSCE->getSubExpr();
4982   const StringLiteral *FormatString;
4983   if (const ObjCStringLiteral *OSL =
4984       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4985     FormatString = OSL->getString();
4986   else
4987     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4988   if (!FormatString)
4989     return;
4990   if (S.FormatStringHasSArg(FormatString)) {
4991     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4992       << "%s" << 1 << 1;
4993     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4994       << FDecl->getDeclName();
4995   }
4996 }
4997 
4998 /// Determine whether the given type has a non-null nullability annotation.
4999 static bool isNonNullType(ASTContext &ctx, QualType type) {
5000   if (auto nullability = type->getNullability(ctx))
5001     return *nullability == NullabilityKind::NonNull;
5002 
5003   return false;
5004 }
5005 
5006 static void CheckNonNullArguments(Sema &S,
5007                                   const NamedDecl *FDecl,
5008                                   const FunctionProtoType *Proto,
5009                                   ArrayRef<const Expr *> Args,
5010                                   SourceLocation CallSiteLoc) {
5011   assert((FDecl || Proto) && "Need a function declaration or prototype");
5012 
5013   // Already checked by by constant evaluator.
5014   if (S.isConstantEvaluated())
5015     return;
5016   // Check the attributes attached to the method/function itself.
5017   llvm::SmallBitVector NonNullArgs;
5018   if (FDecl) {
5019     // Handle the nonnull attribute on the function/method declaration itself.
5020     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5021       if (!NonNull->args_size()) {
5022         // Easy case: all pointer arguments are nonnull.
5023         for (const auto *Arg : Args)
5024           if (S.isValidPointerAttrType(Arg->getType()))
5025             CheckNonNullArgument(S, Arg, CallSiteLoc);
5026         return;
5027       }
5028 
5029       for (const ParamIdx &Idx : NonNull->args()) {
5030         unsigned IdxAST = Idx.getASTIndex();
5031         if (IdxAST >= Args.size())
5032           continue;
5033         if (NonNullArgs.empty())
5034           NonNullArgs.resize(Args.size());
5035         NonNullArgs.set(IdxAST);
5036       }
5037     }
5038   }
5039 
5040   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5041     // Handle the nonnull attribute on the parameters of the
5042     // function/method.
5043     ArrayRef<ParmVarDecl*> parms;
5044     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5045       parms = FD->parameters();
5046     else
5047       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5048 
5049     unsigned ParamIndex = 0;
5050     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5051          I != E; ++I, ++ParamIndex) {
5052       const ParmVarDecl *PVD = *I;
5053       if (PVD->hasAttr<NonNullAttr>() ||
5054           isNonNullType(S.Context, PVD->getType())) {
5055         if (NonNullArgs.empty())
5056           NonNullArgs.resize(Args.size());
5057 
5058         NonNullArgs.set(ParamIndex);
5059       }
5060     }
5061   } else {
5062     // If we have a non-function, non-method declaration but no
5063     // function prototype, try to dig out the function prototype.
5064     if (!Proto) {
5065       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5066         QualType type = VD->getType().getNonReferenceType();
5067         if (auto pointerType = type->getAs<PointerType>())
5068           type = pointerType->getPointeeType();
5069         else if (auto blockType = type->getAs<BlockPointerType>())
5070           type = blockType->getPointeeType();
5071         // FIXME: data member pointers?
5072 
5073         // Dig out the function prototype, if there is one.
5074         Proto = type->getAs<FunctionProtoType>();
5075       }
5076     }
5077 
5078     // Fill in non-null argument information from the nullability
5079     // information on the parameter types (if we have them).
5080     if (Proto) {
5081       unsigned Index = 0;
5082       for (auto paramType : Proto->getParamTypes()) {
5083         if (isNonNullType(S.Context, paramType)) {
5084           if (NonNullArgs.empty())
5085             NonNullArgs.resize(Args.size());
5086 
5087           NonNullArgs.set(Index);
5088         }
5089 
5090         ++Index;
5091       }
5092     }
5093   }
5094 
5095   // Check for non-null arguments.
5096   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5097        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5098     if (NonNullArgs[ArgIndex])
5099       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5100   }
5101 }
5102 
5103 /// Warn if a pointer or reference argument passed to a function points to an
5104 /// object that is less aligned than the parameter. This can happen when
5105 /// creating a typedef with a lower alignment than the original type and then
5106 /// calling functions defined in terms of the original type.
5107 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5108                              StringRef ParamName, QualType ArgTy,
5109                              QualType ParamTy) {
5110 
5111   // If a function accepts a pointer or reference type
5112   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5113     return;
5114 
5115   // If the parameter is a pointer type, get the pointee type for the
5116   // argument too. If the parameter is a reference type, don't try to get
5117   // the pointee type for the argument.
5118   if (ParamTy->isPointerType())
5119     ArgTy = ArgTy->getPointeeType();
5120 
5121   // Remove reference or pointer
5122   ParamTy = ParamTy->getPointeeType();
5123 
5124   // Find expected alignment, and the actual alignment of the passed object.
5125   // getTypeAlignInChars requires complete types
5126   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5127       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5128       ArgTy->isUndeducedType())
5129     return;
5130 
5131   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5132   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5133 
5134   // If the argument is less aligned than the parameter, there is a
5135   // potential alignment issue.
5136   if (ArgAlign < ParamAlign)
5137     Diag(Loc, diag::warn_param_mismatched_alignment)
5138         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5139         << ParamName << (FDecl != nullptr) << FDecl;
5140 }
5141 
5142 /// Handles the checks for format strings, non-POD arguments to vararg
5143 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5144 /// attributes.
5145 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5146                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5147                      bool IsMemberFunction, SourceLocation Loc,
5148                      SourceRange Range, VariadicCallType CallType) {
5149   // FIXME: We should check as much as we can in the template definition.
5150   if (CurContext->isDependentContext())
5151     return;
5152 
5153   // Printf and scanf checking.
5154   llvm::SmallBitVector CheckedVarArgs;
5155   if (FDecl) {
5156     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5157       // Only create vector if there are format attributes.
5158       CheckedVarArgs.resize(Args.size());
5159 
5160       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5161                            CheckedVarArgs);
5162     }
5163   }
5164 
5165   // Refuse POD arguments that weren't caught by the format string
5166   // checks above.
5167   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5168   if (CallType != VariadicDoesNotApply &&
5169       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5170     unsigned NumParams = Proto ? Proto->getNumParams()
5171                        : FDecl && isa<FunctionDecl>(FDecl)
5172                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5173                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5174                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5175                        : 0;
5176 
5177     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5178       // Args[ArgIdx] can be null in malformed code.
5179       if (const Expr *Arg = Args[ArgIdx]) {
5180         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5181           checkVariadicArgument(Arg, CallType);
5182       }
5183     }
5184   }
5185 
5186   if (FDecl || Proto) {
5187     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5188 
5189     // Type safety checking.
5190     if (FDecl) {
5191       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5192         CheckArgumentWithTypeTag(I, Args, Loc);
5193     }
5194   }
5195 
5196   // Check that passed arguments match the alignment of original arguments.
5197   // Try to get the missing prototype from the declaration.
5198   if (!Proto && FDecl) {
5199     const auto *FT = FDecl->getFunctionType();
5200     if (isa_and_nonnull<FunctionProtoType>(FT))
5201       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5202   }
5203   if (Proto) {
5204     // For variadic functions, we may have more args than parameters.
5205     // For some K&R functions, we may have less args than parameters.
5206     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5207     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5208       // Args[ArgIdx] can be null in malformed code.
5209       if (const Expr *Arg = Args[ArgIdx]) {
5210         if (Arg->containsErrors())
5211           continue;
5212 
5213         QualType ParamTy = Proto->getParamType(ArgIdx);
5214         QualType ArgTy = Arg->getType();
5215         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5216                           ArgTy, ParamTy);
5217       }
5218     }
5219   }
5220 
5221   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5222     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5223     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5224     if (!Arg->isValueDependent()) {
5225       Expr::EvalResult Align;
5226       if (Arg->EvaluateAsInt(Align, Context)) {
5227         const llvm::APSInt &I = Align.Val.getInt();
5228         if (!I.isPowerOf2())
5229           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5230               << Arg->getSourceRange();
5231 
5232         if (I > Sema::MaximumAlignment)
5233           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5234               << Arg->getSourceRange() << Sema::MaximumAlignment;
5235       }
5236     }
5237   }
5238 
5239   if (FD)
5240     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5241 }
5242 
5243 /// CheckConstructorCall - Check a constructor call for correctness and safety
5244 /// properties not enforced by the C type system.
5245 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5246                                 ArrayRef<const Expr *> Args,
5247                                 const FunctionProtoType *Proto,
5248                                 SourceLocation Loc) {
5249   VariadicCallType CallType =
5250       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5251 
5252   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5253   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5254                     Context.getPointerType(Ctor->getThisObjectType()));
5255 
5256   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5257             Loc, SourceRange(), CallType);
5258 }
5259 
5260 /// CheckFunctionCall - Check a direct function call for various correctness
5261 /// and safety properties not strictly enforced by the C type system.
5262 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5263                              const FunctionProtoType *Proto) {
5264   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5265                               isa<CXXMethodDecl>(FDecl);
5266   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5267                           IsMemberOperatorCall;
5268   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5269                                                   TheCall->getCallee());
5270   Expr** Args = TheCall->getArgs();
5271   unsigned NumArgs = TheCall->getNumArgs();
5272 
5273   Expr *ImplicitThis = nullptr;
5274   if (IsMemberOperatorCall) {
5275     // If this is a call to a member operator, hide the first argument
5276     // from checkCall.
5277     // FIXME: Our choice of AST representation here is less than ideal.
5278     ImplicitThis = Args[0];
5279     ++Args;
5280     --NumArgs;
5281   } else if (IsMemberFunction)
5282     ImplicitThis =
5283         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5284 
5285   if (ImplicitThis) {
5286     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5287     // used.
5288     QualType ThisType = ImplicitThis->getType();
5289     if (!ThisType->isPointerType()) {
5290       assert(!ThisType->isReferenceType());
5291       ThisType = Context.getPointerType(ThisType);
5292     }
5293 
5294     QualType ThisTypeFromDecl =
5295         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5296 
5297     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5298                       ThisTypeFromDecl);
5299   }
5300 
5301   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5302             IsMemberFunction, TheCall->getRParenLoc(),
5303             TheCall->getCallee()->getSourceRange(), CallType);
5304 
5305   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5306   // None of the checks below are needed for functions that don't have
5307   // simple names (e.g., C++ conversion functions).
5308   if (!FnInfo)
5309     return false;
5310 
5311   CheckTCBEnforcement(TheCall, FDecl);
5312 
5313   CheckAbsoluteValueFunction(TheCall, FDecl);
5314   CheckMaxUnsignedZero(TheCall, FDecl);
5315 
5316   if (getLangOpts().ObjC)
5317     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5318 
5319   unsigned CMId = FDecl->getMemoryFunctionKind();
5320 
5321   // Handle memory setting and copying functions.
5322   switch (CMId) {
5323   case 0:
5324     return false;
5325   case Builtin::BIstrlcpy: // fallthrough
5326   case Builtin::BIstrlcat:
5327     CheckStrlcpycatArguments(TheCall, FnInfo);
5328     break;
5329   case Builtin::BIstrncat:
5330     CheckStrncatArguments(TheCall, FnInfo);
5331     break;
5332   case Builtin::BIfree:
5333     CheckFreeArguments(TheCall);
5334     break;
5335   default:
5336     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5337   }
5338 
5339   return false;
5340 }
5341 
5342 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5343                                ArrayRef<const Expr *> Args) {
5344   VariadicCallType CallType =
5345       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5346 
5347   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5348             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5349             CallType);
5350 
5351   return false;
5352 }
5353 
5354 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5355                             const FunctionProtoType *Proto) {
5356   QualType Ty;
5357   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5358     Ty = V->getType().getNonReferenceType();
5359   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5360     Ty = F->getType().getNonReferenceType();
5361   else
5362     return false;
5363 
5364   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5365       !Ty->isFunctionProtoType())
5366     return false;
5367 
5368   VariadicCallType CallType;
5369   if (!Proto || !Proto->isVariadic()) {
5370     CallType = VariadicDoesNotApply;
5371   } else if (Ty->isBlockPointerType()) {
5372     CallType = VariadicBlock;
5373   } else { // Ty->isFunctionPointerType()
5374     CallType = VariadicFunction;
5375   }
5376 
5377   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5378             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5379             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5380             TheCall->getCallee()->getSourceRange(), CallType);
5381 
5382   return false;
5383 }
5384 
5385 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5386 /// such as function pointers returned from functions.
5387 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5388   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5389                                                   TheCall->getCallee());
5390   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5391             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5392             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5393             TheCall->getCallee()->getSourceRange(), CallType);
5394 
5395   return false;
5396 }
5397 
5398 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5399   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5400     return false;
5401 
5402   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5403   switch (Op) {
5404   case AtomicExpr::AO__c11_atomic_init:
5405   case AtomicExpr::AO__opencl_atomic_init:
5406     llvm_unreachable("There is no ordering argument for an init");
5407 
5408   case AtomicExpr::AO__c11_atomic_load:
5409   case AtomicExpr::AO__opencl_atomic_load:
5410   case AtomicExpr::AO__hip_atomic_load:
5411   case AtomicExpr::AO__atomic_load_n:
5412   case AtomicExpr::AO__atomic_load:
5413     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5414            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5415 
5416   case AtomicExpr::AO__c11_atomic_store:
5417   case AtomicExpr::AO__opencl_atomic_store:
5418   case AtomicExpr::AO__hip_atomic_store:
5419   case AtomicExpr::AO__atomic_store:
5420   case AtomicExpr::AO__atomic_store_n:
5421     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5422            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5423            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5424 
5425   default:
5426     return true;
5427   }
5428 }
5429 
5430 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5431                                          AtomicExpr::AtomicOp Op) {
5432   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5433   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5434   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5435   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5436                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5437                          Op);
5438 }
5439 
5440 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5441                                  SourceLocation RParenLoc, MultiExprArg Args,
5442                                  AtomicExpr::AtomicOp Op,
5443                                  AtomicArgumentOrder ArgOrder) {
5444   // All the non-OpenCL operations take one of the following forms.
5445   // The OpenCL operations take the __c11 forms with one extra argument for
5446   // synchronization scope.
5447   enum {
5448     // C    __c11_atomic_init(A *, C)
5449     Init,
5450 
5451     // C    __c11_atomic_load(A *, int)
5452     Load,
5453 
5454     // void __atomic_load(A *, CP, int)
5455     LoadCopy,
5456 
5457     // void __atomic_store(A *, CP, int)
5458     Copy,
5459 
5460     // C    __c11_atomic_add(A *, M, int)
5461     Arithmetic,
5462 
5463     // C    __atomic_exchange_n(A *, CP, int)
5464     Xchg,
5465 
5466     // void __atomic_exchange(A *, C *, CP, int)
5467     GNUXchg,
5468 
5469     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5470     C11CmpXchg,
5471 
5472     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5473     GNUCmpXchg
5474   } Form = Init;
5475 
5476   const unsigned NumForm = GNUCmpXchg + 1;
5477   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5478   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5479   // where:
5480   //   C is an appropriate type,
5481   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5482   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5483   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5484   //   the int parameters are for orderings.
5485 
5486   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5487       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5488       "need to update code for modified forms");
5489   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5490                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5491                         AtomicExpr::AO__atomic_load,
5492                 "need to update code for modified C11 atomics");
5493   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5494                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5495   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5496                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5497   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5498                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5499                IsOpenCL;
5500   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5501              Op == AtomicExpr::AO__atomic_store_n ||
5502              Op == AtomicExpr::AO__atomic_exchange_n ||
5503              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5504   bool IsAddSub = false;
5505 
5506   switch (Op) {
5507   case AtomicExpr::AO__c11_atomic_init:
5508   case AtomicExpr::AO__opencl_atomic_init:
5509     Form = Init;
5510     break;
5511 
5512   case AtomicExpr::AO__c11_atomic_load:
5513   case AtomicExpr::AO__opencl_atomic_load:
5514   case AtomicExpr::AO__hip_atomic_load:
5515   case AtomicExpr::AO__atomic_load_n:
5516     Form = Load;
5517     break;
5518 
5519   case AtomicExpr::AO__atomic_load:
5520     Form = LoadCopy;
5521     break;
5522 
5523   case AtomicExpr::AO__c11_atomic_store:
5524   case AtomicExpr::AO__opencl_atomic_store:
5525   case AtomicExpr::AO__hip_atomic_store:
5526   case AtomicExpr::AO__atomic_store:
5527   case AtomicExpr::AO__atomic_store_n:
5528     Form = Copy;
5529     break;
5530   case AtomicExpr::AO__hip_atomic_fetch_add:
5531   case AtomicExpr::AO__hip_atomic_fetch_min:
5532   case AtomicExpr::AO__hip_atomic_fetch_max:
5533   case AtomicExpr::AO__c11_atomic_fetch_add:
5534   case AtomicExpr::AO__c11_atomic_fetch_sub:
5535   case AtomicExpr::AO__opencl_atomic_fetch_add:
5536   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5537   case AtomicExpr::AO__atomic_fetch_add:
5538   case AtomicExpr::AO__atomic_fetch_sub:
5539   case AtomicExpr::AO__atomic_add_fetch:
5540   case AtomicExpr::AO__atomic_sub_fetch:
5541     IsAddSub = true;
5542     Form = Arithmetic;
5543     break;
5544   case AtomicExpr::AO__c11_atomic_fetch_and:
5545   case AtomicExpr::AO__c11_atomic_fetch_or:
5546   case AtomicExpr::AO__c11_atomic_fetch_xor:
5547   case AtomicExpr::AO__hip_atomic_fetch_and:
5548   case AtomicExpr::AO__hip_atomic_fetch_or:
5549   case AtomicExpr::AO__hip_atomic_fetch_xor:
5550   case AtomicExpr::AO__c11_atomic_fetch_nand:
5551   case AtomicExpr::AO__opencl_atomic_fetch_and:
5552   case AtomicExpr::AO__opencl_atomic_fetch_or:
5553   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5554   case AtomicExpr::AO__atomic_fetch_and:
5555   case AtomicExpr::AO__atomic_fetch_or:
5556   case AtomicExpr::AO__atomic_fetch_xor:
5557   case AtomicExpr::AO__atomic_fetch_nand:
5558   case AtomicExpr::AO__atomic_and_fetch:
5559   case AtomicExpr::AO__atomic_or_fetch:
5560   case AtomicExpr::AO__atomic_xor_fetch:
5561   case AtomicExpr::AO__atomic_nand_fetch:
5562     Form = Arithmetic;
5563     break;
5564   case AtomicExpr::AO__c11_atomic_fetch_min:
5565   case AtomicExpr::AO__c11_atomic_fetch_max:
5566   case AtomicExpr::AO__opencl_atomic_fetch_min:
5567   case AtomicExpr::AO__opencl_atomic_fetch_max:
5568   case AtomicExpr::AO__atomic_min_fetch:
5569   case AtomicExpr::AO__atomic_max_fetch:
5570   case AtomicExpr::AO__atomic_fetch_min:
5571   case AtomicExpr::AO__atomic_fetch_max:
5572     Form = Arithmetic;
5573     break;
5574 
5575   case AtomicExpr::AO__c11_atomic_exchange:
5576   case AtomicExpr::AO__hip_atomic_exchange:
5577   case AtomicExpr::AO__opencl_atomic_exchange:
5578   case AtomicExpr::AO__atomic_exchange_n:
5579     Form = Xchg;
5580     break;
5581 
5582   case AtomicExpr::AO__atomic_exchange:
5583     Form = GNUXchg;
5584     break;
5585 
5586   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5587   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5588   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5589   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5590   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5591   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5592     Form = C11CmpXchg;
5593     break;
5594 
5595   case AtomicExpr::AO__atomic_compare_exchange:
5596   case AtomicExpr::AO__atomic_compare_exchange_n:
5597     Form = GNUCmpXchg;
5598     break;
5599   }
5600 
5601   unsigned AdjustedNumArgs = NumArgs[Form];
5602   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5603     ++AdjustedNumArgs;
5604   // Check we have the right number of arguments.
5605   if (Args.size() < AdjustedNumArgs) {
5606     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5607         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5608         << ExprRange;
5609     return ExprError();
5610   } else if (Args.size() > AdjustedNumArgs) {
5611     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5612          diag::err_typecheck_call_too_many_args)
5613         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5614         << ExprRange;
5615     return ExprError();
5616   }
5617 
5618   // Inspect the first argument of the atomic operation.
5619   Expr *Ptr = Args[0];
5620   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5621   if (ConvertedPtr.isInvalid())
5622     return ExprError();
5623 
5624   Ptr = ConvertedPtr.get();
5625   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5626   if (!pointerType) {
5627     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5628         << Ptr->getType() << Ptr->getSourceRange();
5629     return ExprError();
5630   }
5631 
5632   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5633   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5634   QualType ValType = AtomTy; // 'C'
5635   if (IsC11) {
5636     if (!AtomTy->isAtomicType()) {
5637       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5638           << Ptr->getType() << Ptr->getSourceRange();
5639       return ExprError();
5640     }
5641     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5642         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5643       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5644           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5645           << Ptr->getSourceRange();
5646       return ExprError();
5647     }
5648     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5649   } else if (Form != Load && Form != LoadCopy) {
5650     if (ValType.isConstQualified()) {
5651       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5652           << Ptr->getType() << Ptr->getSourceRange();
5653       return ExprError();
5654     }
5655   }
5656 
5657   // For an arithmetic operation, the implied arithmetic must be well-formed.
5658   if (Form == Arithmetic) {
5659     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5660     // trivial type errors.
5661     auto IsAllowedValueType = [&](QualType ValType) {
5662       if (ValType->isIntegerType())
5663         return true;
5664       if (ValType->isPointerType())
5665         return true;
5666       if (!ValType->isFloatingType())
5667         return false;
5668       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5669       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5670           &Context.getTargetInfo().getLongDoubleFormat() ==
5671               &llvm::APFloat::x87DoubleExtended())
5672         return false;
5673       return true;
5674     };
5675     if (IsAddSub && !IsAllowedValueType(ValType)) {
5676       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5677           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5678       return ExprError();
5679     }
5680     if (!IsAddSub && !ValType->isIntegerType()) {
5681       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5682           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5683       return ExprError();
5684     }
5685     if (IsC11 && ValType->isPointerType() &&
5686         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5687                             diag::err_incomplete_type)) {
5688       return ExprError();
5689     }
5690   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5691     // For __atomic_*_n operations, the value type must be a scalar integral or
5692     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5693     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5694         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5695     return ExprError();
5696   }
5697 
5698   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5699       !AtomTy->isScalarType()) {
5700     // For GNU atomics, require a trivially-copyable type. This is not part of
5701     // the GNU atomics specification but we enforce it for consistency with
5702     // other atomics which generally all require a trivially-copyable type. This
5703     // is because atomics just copy bits.
5704     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5705         << Ptr->getType() << Ptr->getSourceRange();
5706     return ExprError();
5707   }
5708 
5709   switch (ValType.getObjCLifetime()) {
5710   case Qualifiers::OCL_None:
5711   case Qualifiers::OCL_ExplicitNone:
5712     // okay
5713     break;
5714 
5715   case Qualifiers::OCL_Weak:
5716   case Qualifiers::OCL_Strong:
5717   case Qualifiers::OCL_Autoreleasing:
5718     // FIXME: Can this happen? By this point, ValType should be known
5719     // to be trivially copyable.
5720     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5721         << ValType << Ptr->getSourceRange();
5722     return ExprError();
5723   }
5724 
5725   // All atomic operations have an overload which takes a pointer to a volatile
5726   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5727   // into the result or the other operands. Similarly atomic_load takes a
5728   // pointer to a const 'A'.
5729   ValType.removeLocalVolatile();
5730   ValType.removeLocalConst();
5731   QualType ResultType = ValType;
5732   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5733       Form == Init)
5734     ResultType = Context.VoidTy;
5735   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5736     ResultType = Context.BoolTy;
5737 
5738   // The type of a parameter passed 'by value'. In the GNU atomics, such
5739   // arguments are actually passed as pointers.
5740   QualType ByValType = ValType; // 'CP'
5741   bool IsPassedByAddress = false;
5742   if (!IsC11 && !IsHIP && !IsN) {
5743     ByValType = Ptr->getType();
5744     IsPassedByAddress = true;
5745   }
5746 
5747   SmallVector<Expr *, 5> APIOrderedArgs;
5748   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5749     APIOrderedArgs.push_back(Args[0]);
5750     switch (Form) {
5751     case Init:
5752     case Load:
5753       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5754       break;
5755     case LoadCopy:
5756     case Copy:
5757     case Arithmetic:
5758     case Xchg:
5759       APIOrderedArgs.push_back(Args[2]); // Val1
5760       APIOrderedArgs.push_back(Args[1]); // Order
5761       break;
5762     case GNUXchg:
5763       APIOrderedArgs.push_back(Args[2]); // Val1
5764       APIOrderedArgs.push_back(Args[3]); // Val2
5765       APIOrderedArgs.push_back(Args[1]); // Order
5766       break;
5767     case C11CmpXchg:
5768       APIOrderedArgs.push_back(Args[2]); // Val1
5769       APIOrderedArgs.push_back(Args[4]); // Val2
5770       APIOrderedArgs.push_back(Args[1]); // Order
5771       APIOrderedArgs.push_back(Args[3]); // OrderFail
5772       break;
5773     case GNUCmpXchg:
5774       APIOrderedArgs.push_back(Args[2]); // Val1
5775       APIOrderedArgs.push_back(Args[4]); // Val2
5776       APIOrderedArgs.push_back(Args[5]); // Weak
5777       APIOrderedArgs.push_back(Args[1]); // Order
5778       APIOrderedArgs.push_back(Args[3]); // OrderFail
5779       break;
5780     }
5781   } else
5782     APIOrderedArgs.append(Args.begin(), Args.end());
5783 
5784   // The first argument's non-CV pointer type is used to deduce the type of
5785   // subsequent arguments, except for:
5786   //  - weak flag (always converted to bool)
5787   //  - memory order (always converted to int)
5788   //  - scope  (always converted to int)
5789   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5790     QualType Ty;
5791     if (i < NumVals[Form] + 1) {
5792       switch (i) {
5793       case 0:
5794         // The first argument is always a pointer. It has a fixed type.
5795         // It is always dereferenced, a nullptr is undefined.
5796         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5797         // Nothing else to do: we already know all we want about this pointer.
5798         continue;
5799       case 1:
5800         // The second argument is the non-atomic operand. For arithmetic, this
5801         // is always passed by value, and for a compare_exchange it is always
5802         // passed by address. For the rest, GNU uses by-address and C11 uses
5803         // by-value.
5804         assert(Form != Load);
5805         if (Form == Arithmetic && ValType->isPointerType())
5806           Ty = Context.getPointerDiffType();
5807         else if (Form == Init || Form == Arithmetic)
5808           Ty = ValType;
5809         else if (Form == Copy || Form == Xchg) {
5810           if (IsPassedByAddress) {
5811             // The value pointer is always dereferenced, a nullptr is undefined.
5812             CheckNonNullArgument(*this, APIOrderedArgs[i],
5813                                  ExprRange.getBegin());
5814           }
5815           Ty = ByValType;
5816         } else {
5817           Expr *ValArg = APIOrderedArgs[i];
5818           // The value pointer is always dereferenced, a nullptr is undefined.
5819           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5820           LangAS AS = LangAS::Default;
5821           // Keep address space of non-atomic pointer type.
5822           if (const PointerType *PtrTy =
5823                   ValArg->getType()->getAs<PointerType>()) {
5824             AS = PtrTy->getPointeeType().getAddressSpace();
5825           }
5826           Ty = Context.getPointerType(
5827               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5828         }
5829         break;
5830       case 2:
5831         // The third argument to compare_exchange / GNU exchange is the desired
5832         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5833         if (IsPassedByAddress)
5834           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5835         Ty = ByValType;
5836         break;
5837       case 3:
5838         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5839         Ty = Context.BoolTy;
5840         break;
5841       }
5842     } else {
5843       // The order(s) and scope are always converted to int.
5844       Ty = Context.IntTy;
5845     }
5846 
5847     InitializedEntity Entity =
5848         InitializedEntity::InitializeParameter(Context, Ty, false);
5849     ExprResult Arg = APIOrderedArgs[i];
5850     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5851     if (Arg.isInvalid())
5852       return true;
5853     APIOrderedArgs[i] = Arg.get();
5854   }
5855 
5856   // Permute the arguments into a 'consistent' order.
5857   SmallVector<Expr*, 5> SubExprs;
5858   SubExprs.push_back(Ptr);
5859   switch (Form) {
5860   case Init:
5861     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5862     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5863     break;
5864   case Load:
5865     SubExprs.push_back(APIOrderedArgs[1]); // Order
5866     break;
5867   case LoadCopy:
5868   case Copy:
5869   case Arithmetic:
5870   case Xchg:
5871     SubExprs.push_back(APIOrderedArgs[2]); // Order
5872     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5873     break;
5874   case GNUXchg:
5875     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5876     SubExprs.push_back(APIOrderedArgs[3]); // Order
5877     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5878     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5879     break;
5880   case C11CmpXchg:
5881     SubExprs.push_back(APIOrderedArgs[3]); // Order
5882     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5883     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5884     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5885     break;
5886   case GNUCmpXchg:
5887     SubExprs.push_back(APIOrderedArgs[4]); // Order
5888     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5889     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5890     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5891     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5892     break;
5893   }
5894 
5895   if (SubExprs.size() >= 2 && Form != Init) {
5896     if (Optional<llvm::APSInt> Result =
5897             SubExprs[1]->getIntegerConstantExpr(Context))
5898       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5899         Diag(SubExprs[1]->getBeginLoc(),
5900              diag::warn_atomic_op_has_invalid_memory_order)
5901             << SubExprs[1]->getSourceRange();
5902   }
5903 
5904   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5905     auto *Scope = Args[Args.size() - 1];
5906     if (Optional<llvm::APSInt> Result =
5907             Scope->getIntegerConstantExpr(Context)) {
5908       if (!ScopeModel->isValid(Result->getZExtValue()))
5909         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5910             << Scope->getSourceRange();
5911     }
5912     SubExprs.push_back(Scope);
5913   }
5914 
5915   AtomicExpr *AE = new (Context)
5916       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5917 
5918   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5919        Op == AtomicExpr::AO__c11_atomic_store ||
5920        Op == AtomicExpr::AO__opencl_atomic_load ||
5921        Op == AtomicExpr::AO__hip_atomic_load ||
5922        Op == AtomicExpr::AO__opencl_atomic_store ||
5923        Op == AtomicExpr::AO__hip_atomic_store) &&
5924       Context.AtomicUsesUnsupportedLibcall(AE))
5925     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5926         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5927              Op == AtomicExpr::AO__opencl_atomic_load ||
5928              Op == AtomicExpr::AO__hip_atomic_load)
5929                 ? 0
5930                 : 1);
5931 
5932   if (ValType->isBitIntType()) {
5933     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5934     return ExprError();
5935   }
5936 
5937   return AE;
5938 }
5939 
5940 /// checkBuiltinArgument - Given a call to a builtin function, perform
5941 /// normal type-checking on the given argument, updating the call in
5942 /// place.  This is useful when a builtin function requires custom
5943 /// type-checking for some of its arguments but not necessarily all of
5944 /// them.
5945 ///
5946 /// Returns true on error.
5947 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5948   FunctionDecl *Fn = E->getDirectCallee();
5949   assert(Fn && "builtin call without direct callee!");
5950 
5951   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5952   InitializedEntity Entity =
5953     InitializedEntity::InitializeParameter(S.Context, Param);
5954 
5955   ExprResult Arg = E->getArg(0);
5956   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5957   if (Arg.isInvalid())
5958     return true;
5959 
5960   E->setArg(ArgIndex, Arg.get());
5961   return false;
5962 }
5963 
5964 /// We have a call to a function like __sync_fetch_and_add, which is an
5965 /// overloaded function based on the pointer type of its first argument.
5966 /// The main BuildCallExpr routines have already promoted the types of
5967 /// arguments because all of these calls are prototyped as void(...).
5968 ///
5969 /// This function goes through and does final semantic checking for these
5970 /// builtins, as well as generating any warnings.
5971 ExprResult
5972 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5973   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5974   Expr *Callee = TheCall->getCallee();
5975   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5976   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5977 
5978   // Ensure that we have at least one argument to do type inference from.
5979   if (TheCall->getNumArgs() < 1) {
5980     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5981         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5982     return ExprError();
5983   }
5984 
5985   // Inspect the first argument of the atomic builtin.  This should always be
5986   // a pointer type, whose element is an integral scalar or pointer type.
5987   // Because it is a pointer type, we don't have to worry about any implicit
5988   // casts here.
5989   // FIXME: We don't allow floating point scalars as input.
5990   Expr *FirstArg = TheCall->getArg(0);
5991   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5992   if (FirstArgResult.isInvalid())
5993     return ExprError();
5994   FirstArg = FirstArgResult.get();
5995   TheCall->setArg(0, FirstArg);
5996 
5997   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5998   if (!pointerType) {
5999     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6000         << FirstArg->getType() << FirstArg->getSourceRange();
6001     return ExprError();
6002   }
6003 
6004   QualType ValType = pointerType->getPointeeType();
6005   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6006       !ValType->isBlockPointerType()) {
6007     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6008         << FirstArg->getType() << FirstArg->getSourceRange();
6009     return ExprError();
6010   }
6011 
6012   if (ValType.isConstQualified()) {
6013     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6014         << FirstArg->getType() << FirstArg->getSourceRange();
6015     return ExprError();
6016   }
6017 
6018   switch (ValType.getObjCLifetime()) {
6019   case Qualifiers::OCL_None:
6020   case Qualifiers::OCL_ExplicitNone:
6021     // okay
6022     break;
6023 
6024   case Qualifiers::OCL_Weak:
6025   case Qualifiers::OCL_Strong:
6026   case Qualifiers::OCL_Autoreleasing:
6027     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6028         << ValType << FirstArg->getSourceRange();
6029     return ExprError();
6030   }
6031 
6032   // Strip any qualifiers off ValType.
6033   ValType = ValType.getUnqualifiedType();
6034 
6035   // The majority of builtins return a value, but a few have special return
6036   // types, so allow them to override appropriately below.
6037   QualType ResultType = ValType;
6038 
6039   // We need to figure out which concrete builtin this maps onto.  For example,
6040   // __sync_fetch_and_add with a 2 byte object turns into
6041   // __sync_fetch_and_add_2.
6042 #define BUILTIN_ROW(x) \
6043   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6044     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6045 
6046   static const unsigned BuiltinIndices[][5] = {
6047     BUILTIN_ROW(__sync_fetch_and_add),
6048     BUILTIN_ROW(__sync_fetch_and_sub),
6049     BUILTIN_ROW(__sync_fetch_and_or),
6050     BUILTIN_ROW(__sync_fetch_and_and),
6051     BUILTIN_ROW(__sync_fetch_and_xor),
6052     BUILTIN_ROW(__sync_fetch_and_nand),
6053 
6054     BUILTIN_ROW(__sync_add_and_fetch),
6055     BUILTIN_ROW(__sync_sub_and_fetch),
6056     BUILTIN_ROW(__sync_and_and_fetch),
6057     BUILTIN_ROW(__sync_or_and_fetch),
6058     BUILTIN_ROW(__sync_xor_and_fetch),
6059     BUILTIN_ROW(__sync_nand_and_fetch),
6060 
6061     BUILTIN_ROW(__sync_val_compare_and_swap),
6062     BUILTIN_ROW(__sync_bool_compare_and_swap),
6063     BUILTIN_ROW(__sync_lock_test_and_set),
6064     BUILTIN_ROW(__sync_lock_release),
6065     BUILTIN_ROW(__sync_swap)
6066   };
6067 #undef BUILTIN_ROW
6068 
6069   // Determine the index of the size.
6070   unsigned SizeIndex;
6071   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6072   case 1: SizeIndex = 0; break;
6073   case 2: SizeIndex = 1; break;
6074   case 4: SizeIndex = 2; break;
6075   case 8: SizeIndex = 3; break;
6076   case 16: SizeIndex = 4; break;
6077   default:
6078     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6079         << FirstArg->getType() << FirstArg->getSourceRange();
6080     return ExprError();
6081   }
6082 
6083   // Each of these builtins has one pointer argument, followed by some number of
6084   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6085   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6086   // as the number of fixed args.
6087   unsigned BuiltinID = FDecl->getBuiltinID();
6088   unsigned BuiltinIndex, NumFixed = 1;
6089   bool WarnAboutSemanticsChange = false;
6090   switch (BuiltinID) {
6091   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6092   case Builtin::BI__sync_fetch_and_add:
6093   case Builtin::BI__sync_fetch_and_add_1:
6094   case Builtin::BI__sync_fetch_and_add_2:
6095   case Builtin::BI__sync_fetch_and_add_4:
6096   case Builtin::BI__sync_fetch_and_add_8:
6097   case Builtin::BI__sync_fetch_and_add_16:
6098     BuiltinIndex = 0;
6099     break;
6100 
6101   case Builtin::BI__sync_fetch_and_sub:
6102   case Builtin::BI__sync_fetch_and_sub_1:
6103   case Builtin::BI__sync_fetch_and_sub_2:
6104   case Builtin::BI__sync_fetch_and_sub_4:
6105   case Builtin::BI__sync_fetch_and_sub_8:
6106   case Builtin::BI__sync_fetch_and_sub_16:
6107     BuiltinIndex = 1;
6108     break;
6109 
6110   case Builtin::BI__sync_fetch_and_or:
6111   case Builtin::BI__sync_fetch_and_or_1:
6112   case Builtin::BI__sync_fetch_and_or_2:
6113   case Builtin::BI__sync_fetch_and_or_4:
6114   case Builtin::BI__sync_fetch_and_or_8:
6115   case Builtin::BI__sync_fetch_and_or_16:
6116     BuiltinIndex = 2;
6117     break;
6118 
6119   case Builtin::BI__sync_fetch_and_and:
6120   case Builtin::BI__sync_fetch_and_and_1:
6121   case Builtin::BI__sync_fetch_and_and_2:
6122   case Builtin::BI__sync_fetch_and_and_4:
6123   case Builtin::BI__sync_fetch_and_and_8:
6124   case Builtin::BI__sync_fetch_and_and_16:
6125     BuiltinIndex = 3;
6126     break;
6127 
6128   case Builtin::BI__sync_fetch_and_xor:
6129   case Builtin::BI__sync_fetch_and_xor_1:
6130   case Builtin::BI__sync_fetch_and_xor_2:
6131   case Builtin::BI__sync_fetch_and_xor_4:
6132   case Builtin::BI__sync_fetch_and_xor_8:
6133   case Builtin::BI__sync_fetch_and_xor_16:
6134     BuiltinIndex = 4;
6135     break;
6136 
6137   case Builtin::BI__sync_fetch_and_nand:
6138   case Builtin::BI__sync_fetch_and_nand_1:
6139   case Builtin::BI__sync_fetch_and_nand_2:
6140   case Builtin::BI__sync_fetch_and_nand_4:
6141   case Builtin::BI__sync_fetch_and_nand_8:
6142   case Builtin::BI__sync_fetch_and_nand_16:
6143     BuiltinIndex = 5;
6144     WarnAboutSemanticsChange = true;
6145     break;
6146 
6147   case Builtin::BI__sync_add_and_fetch:
6148   case Builtin::BI__sync_add_and_fetch_1:
6149   case Builtin::BI__sync_add_and_fetch_2:
6150   case Builtin::BI__sync_add_and_fetch_4:
6151   case Builtin::BI__sync_add_and_fetch_8:
6152   case Builtin::BI__sync_add_and_fetch_16:
6153     BuiltinIndex = 6;
6154     break;
6155 
6156   case Builtin::BI__sync_sub_and_fetch:
6157   case Builtin::BI__sync_sub_and_fetch_1:
6158   case Builtin::BI__sync_sub_and_fetch_2:
6159   case Builtin::BI__sync_sub_and_fetch_4:
6160   case Builtin::BI__sync_sub_and_fetch_8:
6161   case Builtin::BI__sync_sub_and_fetch_16:
6162     BuiltinIndex = 7;
6163     break;
6164 
6165   case Builtin::BI__sync_and_and_fetch:
6166   case Builtin::BI__sync_and_and_fetch_1:
6167   case Builtin::BI__sync_and_and_fetch_2:
6168   case Builtin::BI__sync_and_and_fetch_4:
6169   case Builtin::BI__sync_and_and_fetch_8:
6170   case Builtin::BI__sync_and_and_fetch_16:
6171     BuiltinIndex = 8;
6172     break;
6173 
6174   case Builtin::BI__sync_or_and_fetch:
6175   case Builtin::BI__sync_or_and_fetch_1:
6176   case Builtin::BI__sync_or_and_fetch_2:
6177   case Builtin::BI__sync_or_and_fetch_4:
6178   case Builtin::BI__sync_or_and_fetch_8:
6179   case Builtin::BI__sync_or_and_fetch_16:
6180     BuiltinIndex = 9;
6181     break;
6182 
6183   case Builtin::BI__sync_xor_and_fetch:
6184   case Builtin::BI__sync_xor_and_fetch_1:
6185   case Builtin::BI__sync_xor_and_fetch_2:
6186   case Builtin::BI__sync_xor_and_fetch_4:
6187   case Builtin::BI__sync_xor_and_fetch_8:
6188   case Builtin::BI__sync_xor_and_fetch_16:
6189     BuiltinIndex = 10;
6190     break;
6191 
6192   case Builtin::BI__sync_nand_and_fetch:
6193   case Builtin::BI__sync_nand_and_fetch_1:
6194   case Builtin::BI__sync_nand_and_fetch_2:
6195   case Builtin::BI__sync_nand_and_fetch_4:
6196   case Builtin::BI__sync_nand_and_fetch_8:
6197   case Builtin::BI__sync_nand_and_fetch_16:
6198     BuiltinIndex = 11;
6199     WarnAboutSemanticsChange = true;
6200     break;
6201 
6202   case Builtin::BI__sync_val_compare_and_swap:
6203   case Builtin::BI__sync_val_compare_and_swap_1:
6204   case Builtin::BI__sync_val_compare_and_swap_2:
6205   case Builtin::BI__sync_val_compare_and_swap_4:
6206   case Builtin::BI__sync_val_compare_and_swap_8:
6207   case Builtin::BI__sync_val_compare_and_swap_16:
6208     BuiltinIndex = 12;
6209     NumFixed = 2;
6210     break;
6211 
6212   case Builtin::BI__sync_bool_compare_and_swap:
6213   case Builtin::BI__sync_bool_compare_and_swap_1:
6214   case Builtin::BI__sync_bool_compare_and_swap_2:
6215   case Builtin::BI__sync_bool_compare_and_swap_4:
6216   case Builtin::BI__sync_bool_compare_and_swap_8:
6217   case Builtin::BI__sync_bool_compare_and_swap_16:
6218     BuiltinIndex = 13;
6219     NumFixed = 2;
6220     ResultType = Context.BoolTy;
6221     break;
6222 
6223   case Builtin::BI__sync_lock_test_and_set:
6224   case Builtin::BI__sync_lock_test_and_set_1:
6225   case Builtin::BI__sync_lock_test_and_set_2:
6226   case Builtin::BI__sync_lock_test_and_set_4:
6227   case Builtin::BI__sync_lock_test_and_set_8:
6228   case Builtin::BI__sync_lock_test_and_set_16:
6229     BuiltinIndex = 14;
6230     break;
6231 
6232   case Builtin::BI__sync_lock_release:
6233   case Builtin::BI__sync_lock_release_1:
6234   case Builtin::BI__sync_lock_release_2:
6235   case Builtin::BI__sync_lock_release_4:
6236   case Builtin::BI__sync_lock_release_8:
6237   case Builtin::BI__sync_lock_release_16:
6238     BuiltinIndex = 15;
6239     NumFixed = 0;
6240     ResultType = Context.VoidTy;
6241     break;
6242 
6243   case Builtin::BI__sync_swap:
6244   case Builtin::BI__sync_swap_1:
6245   case Builtin::BI__sync_swap_2:
6246   case Builtin::BI__sync_swap_4:
6247   case Builtin::BI__sync_swap_8:
6248   case Builtin::BI__sync_swap_16:
6249     BuiltinIndex = 16;
6250     break;
6251   }
6252 
6253   // Now that we know how many fixed arguments we expect, first check that we
6254   // have at least that many.
6255   if (TheCall->getNumArgs() < 1+NumFixed) {
6256     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6257         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6258         << Callee->getSourceRange();
6259     return ExprError();
6260   }
6261 
6262   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6263       << Callee->getSourceRange();
6264 
6265   if (WarnAboutSemanticsChange) {
6266     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6267         << Callee->getSourceRange();
6268   }
6269 
6270   // Get the decl for the concrete builtin from this, we can tell what the
6271   // concrete integer type we should convert to is.
6272   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6273   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6274   FunctionDecl *NewBuiltinDecl;
6275   if (NewBuiltinID == BuiltinID)
6276     NewBuiltinDecl = FDecl;
6277   else {
6278     // Perform builtin lookup to avoid redeclaring it.
6279     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6280     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6281     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6282     assert(Res.getFoundDecl());
6283     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6284     if (!NewBuiltinDecl)
6285       return ExprError();
6286   }
6287 
6288   // The first argument --- the pointer --- has a fixed type; we
6289   // deduce the types of the rest of the arguments accordingly.  Walk
6290   // the remaining arguments, converting them to the deduced value type.
6291   for (unsigned i = 0; i != NumFixed; ++i) {
6292     ExprResult Arg = TheCall->getArg(i+1);
6293 
6294     // GCC does an implicit conversion to the pointer or integer ValType.  This
6295     // can fail in some cases (1i -> int**), check for this error case now.
6296     // Initialize the argument.
6297     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6298                                                    ValType, /*consume*/ false);
6299     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6300     if (Arg.isInvalid())
6301       return ExprError();
6302 
6303     // Okay, we have something that *can* be converted to the right type.  Check
6304     // to see if there is a potentially weird extension going on here.  This can
6305     // happen when you do an atomic operation on something like an char* and
6306     // pass in 42.  The 42 gets converted to char.  This is even more strange
6307     // for things like 45.123 -> char, etc.
6308     // FIXME: Do this check.
6309     TheCall->setArg(i+1, Arg.get());
6310   }
6311 
6312   // Create a new DeclRefExpr to refer to the new decl.
6313   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6314       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6315       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6316       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6317 
6318   // Set the callee in the CallExpr.
6319   // FIXME: This loses syntactic information.
6320   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6321   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6322                                               CK_BuiltinFnToFnPtr);
6323   TheCall->setCallee(PromotedCall.get());
6324 
6325   // Change the result type of the call to match the original value type. This
6326   // is arbitrary, but the codegen for these builtins ins design to handle it
6327   // gracefully.
6328   TheCall->setType(ResultType);
6329 
6330   // Prohibit problematic uses of bit-precise integer types with atomic
6331   // builtins. The arguments would have already been converted to the first
6332   // argument's type, so only need to check the first argument.
6333   const auto *BitIntValType = ValType->getAs<BitIntType>();
6334   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6335     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6336     return ExprError();
6337   }
6338 
6339   return TheCallResult;
6340 }
6341 
6342 /// SemaBuiltinNontemporalOverloaded - We have a call to
6343 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6344 /// overloaded function based on the pointer type of its last argument.
6345 ///
6346 /// This function goes through and does final semantic checking for these
6347 /// builtins.
6348 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6349   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6350   DeclRefExpr *DRE =
6351       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6352   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6353   unsigned BuiltinID = FDecl->getBuiltinID();
6354   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6355           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6356          "Unexpected nontemporal load/store builtin!");
6357   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6358   unsigned numArgs = isStore ? 2 : 1;
6359 
6360   // Ensure that we have the proper number of arguments.
6361   if (checkArgCount(*this, TheCall, numArgs))
6362     return ExprError();
6363 
6364   // Inspect the last argument of the nontemporal builtin.  This should always
6365   // be a pointer type, from which we imply the type of the memory access.
6366   // Because it is a pointer type, we don't have to worry about any implicit
6367   // casts here.
6368   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6369   ExprResult PointerArgResult =
6370       DefaultFunctionArrayLvalueConversion(PointerArg);
6371 
6372   if (PointerArgResult.isInvalid())
6373     return ExprError();
6374   PointerArg = PointerArgResult.get();
6375   TheCall->setArg(numArgs - 1, PointerArg);
6376 
6377   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6378   if (!pointerType) {
6379     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6380         << PointerArg->getType() << PointerArg->getSourceRange();
6381     return ExprError();
6382   }
6383 
6384   QualType ValType = pointerType->getPointeeType();
6385 
6386   // Strip any qualifiers off ValType.
6387   ValType = ValType.getUnqualifiedType();
6388   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6389       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6390       !ValType->isVectorType()) {
6391     Diag(DRE->getBeginLoc(),
6392          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6393         << PointerArg->getType() << PointerArg->getSourceRange();
6394     return ExprError();
6395   }
6396 
6397   if (!isStore) {
6398     TheCall->setType(ValType);
6399     return TheCallResult;
6400   }
6401 
6402   ExprResult ValArg = TheCall->getArg(0);
6403   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6404       Context, ValType, /*consume*/ false);
6405   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6406   if (ValArg.isInvalid())
6407     return ExprError();
6408 
6409   TheCall->setArg(0, ValArg.get());
6410   TheCall->setType(Context.VoidTy);
6411   return TheCallResult;
6412 }
6413 
6414 /// CheckObjCString - Checks that the argument to the builtin
6415 /// CFString constructor is correct
6416 /// Note: It might also make sense to do the UTF-16 conversion here (would
6417 /// simplify the backend).
6418 bool Sema::CheckObjCString(Expr *Arg) {
6419   Arg = Arg->IgnoreParenCasts();
6420   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6421 
6422   if (!Literal || !Literal->isAscii()) {
6423     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6424         << Arg->getSourceRange();
6425     return true;
6426   }
6427 
6428   if (Literal->containsNonAsciiOrNull()) {
6429     StringRef String = Literal->getString();
6430     unsigned NumBytes = String.size();
6431     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6432     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6433     llvm::UTF16 *ToPtr = &ToBuf[0];
6434 
6435     llvm::ConversionResult Result =
6436         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6437                                  ToPtr + NumBytes, llvm::strictConversion);
6438     // Check for conversion failure.
6439     if (Result != llvm::conversionOK)
6440       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6441           << Arg->getSourceRange();
6442   }
6443   return false;
6444 }
6445 
6446 /// CheckObjCString - Checks that the format string argument to the os_log()
6447 /// and os_trace() functions is correct, and converts it to const char *.
6448 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6449   Arg = Arg->IgnoreParenCasts();
6450   auto *Literal = dyn_cast<StringLiteral>(Arg);
6451   if (!Literal) {
6452     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6453       Literal = ObjcLiteral->getString();
6454     }
6455   }
6456 
6457   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6458     return ExprError(
6459         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6460         << Arg->getSourceRange());
6461   }
6462 
6463   ExprResult Result(Literal);
6464   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6465   InitializedEntity Entity =
6466       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6467   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6468   return Result;
6469 }
6470 
6471 /// Check that the user is calling the appropriate va_start builtin for the
6472 /// target and calling convention.
6473 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6474   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6475   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6476   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6477                     TT.getArch() == llvm::Triple::aarch64_32);
6478   bool IsWindows = TT.isOSWindows();
6479   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6480   if (IsX64 || IsAArch64) {
6481     CallingConv CC = CC_C;
6482     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6483       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6484     if (IsMSVAStart) {
6485       // Don't allow this in System V ABI functions.
6486       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6487         return S.Diag(Fn->getBeginLoc(),
6488                       diag::err_ms_va_start_used_in_sysv_function);
6489     } else {
6490       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6491       // On x64 Windows, don't allow this in System V ABI functions.
6492       // (Yes, that means there's no corresponding way to support variadic
6493       // System V ABI functions on Windows.)
6494       if ((IsWindows && CC == CC_X86_64SysV) ||
6495           (!IsWindows && CC == CC_Win64))
6496         return S.Diag(Fn->getBeginLoc(),
6497                       diag::err_va_start_used_in_wrong_abi_function)
6498                << !IsWindows;
6499     }
6500     return false;
6501   }
6502 
6503   if (IsMSVAStart)
6504     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6505   return false;
6506 }
6507 
6508 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6509                                              ParmVarDecl **LastParam = nullptr) {
6510   // Determine whether the current function, block, or obj-c method is variadic
6511   // and get its parameter list.
6512   bool IsVariadic = false;
6513   ArrayRef<ParmVarDecl *> Params;
6514   DeclContext *Caller = S.CurContext;
6515   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6516     IsVariadic = Block->isVariadic();
6517     Params = Block->parameters();
6518   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6519     IsVariadic = FD->isVariadic();
6520     Params = FD->parameters();
6521   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6522     IsVariadic = MD->isVariadic();
6523     // FIXME: This isn't correct for methods (results in bogus warning).
6524     Params = MD->parameters();
6525   } else if (isa<CapturedDecl>(Caller)) {
6526     // We don't support va_start in a CapturedDecl.
6527     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6528     return true;
6529   } else {
6530     // This must be some other declcontext that parses exprs.
6531     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6532     return true;
6533   }
6534 
6535   if (!IsVariadic) {
6536     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6537     return true;
6538   }
6539 
6540   if (LastParam)
6541     *LastParam = Params.empty() ? nullptr : Params.back();
6542 
6543   return false;
6544 }
6545 
6546 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6547 /// for validity.  Emit an error and return true on failure; return false
6548 /// on success.
6549 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6550   Expr *Fn = TheCall->getCallee();
6551 
6552   if (checkVAStartABI(*this, BuiltinID, Fn))
6553     return true;
6554 
6555   if (checkArgCount(*this, TheCall, 2))
6556     return true;
6557 
6558   // Type-check the first argument normally.
6559   if (checkBuiltinArgument(*this, TheCall, 0))
6560     return true;
6561 
6562   // Check that the current function is variadic, and get its last parameter.
6563   ParmVarDecl *LastParam;
6564   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6565     return true;
6566 
6567   // Verify that the second argument to the builtin is the last argument of the
6568   // current function or method.
6569   bool SecondArgIsLastNamedArgument = false;
6570   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6571 
6572   // These are valid if SecondArgIsLastNamedArgument is false after the next
6573   // block.
6574   QualType Type;
6575   SourceLocation ParamLoc;
6576   bool IsCRegister = false;
6577 
6578   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6579     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6580       SecondArgIsLastNamedArgument = PV == LastParam;
6581 
6582       Type = PV->getType();
6583       ParamLoc = PV->getLocation();
6584       IsCRegister =
6585           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6586     }
6587   }
6588 
6589   if (!SecondArgIsLastNamedArgument)
6590     Diag(TheCall->getArg(1)->getBeginLoc(),
6591          diag::warn_second_arg_of_va_start_not_last_named_param);
6592   else if (IsCRegister || Type->isReferenceType() ||
6593            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6594              // Promotable integers are UB, but enumerations need a bit of
6595              // extra checking to see what their promotable type actually is.
6596              if (!Type->isPromotableIntegerType())
6597                return false;
6598              if (!Type->isEnumeralType())
6599                return true;
6600              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6601              return !(ED &&
6602                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6603            }()) {
6604     unsigned Reason = 0;
6605     if (Type->isReferenceType())  Reason = 1;
6606     else if (IsCRegister)         Reason = 2;
6607     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6608     Diag(ParamLoc, diag::note_parameter_type) << Type;
6609   }
6610 
6611   TheCall->setType(Context.VoidTy);
6612   return false;
6613 }
6614 
6615 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6616   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6617     const LangOptions &LO = getLangOpts();
6618 
6619     if (LO.CPlusPlus)
6620       return Arg->getType()
6621                  .getCanonicalType()
6622                  .getTypePtr()
6623                  ->getPointeeType()
6624                  .withoutLocalFastQualifiers() == Context.CharTy;
6625 
6626     // In C, allow aliasing through `char *`, this is required for AArch64 at
6627     // least.
6628     return true;
6629   };
6630 
6631   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6632   //                 const char *named_addr);
6633 
6634   Expr *Func = Call->getCallee();
6635 
6636   if (Call->getNumArgs() < 3)
6637     return Diag(Call->getEndLoc(),
6638                 diag::err_typecheck_call_too_few_args_at_least)
6639            << 0 /*function call*/ << 3 << Call->getNumArgs();
6640 
6641   // Type-check the first argument normally.
6642   if (checkBuiltinArgument(*this, Call, 0))
6643     return true;
6644 
6645   // Check that the current function is variadic.
6646   if (checkVAStartIsInVariadicFunction(*this, Func))
6647     return true;
6648 
6649   // __va_start on Windows does not validate the parameter qualifiers
6650 
6651   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6652   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6653 
6654   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6655   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6656 
6657   const QualType &ConstCharPtrTy =
6658       Context.getPointerType(Context.CharTy.withConst());
6659   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6660     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6661         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6662         << 0                                      /* qualifier difference */
6663         << 3                                      /* parameter mismatch */
6664         << 2 << Arg1->getType() << ConstCharPtrTy;
6665 
6666   const QualType SizeTy = Context.getSizeType();
6667   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6668     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6669         << Arg2->getType() << SizeTy << 1 /* different class */
6670         << 0                              /* qualifier difference */
6671         << 3                              /* parameter mismatch */
6672         << 3 << Arg2->getType() << SizeTy;
6673 
6674   return false;
6675 }
6676 
6677 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6678 /// friends.  This is declared to take (...), so we have to check everything.
6679 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6680   if (checkArgCount(*this, TheCall, 2))
6681     return true;
6682 
6683   ExprResult OrigArg0 = TheCall->getArg(0);
6684   ExprResult OrigArg1 = TheCall->getArg(1);
6685 
6686   // Do standard promotions between the two arguments, returning their common
6687   // type.
6688   QualType Res = UsualArithmeticConversions(
6689       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6690   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6691     return true;
6692 
6693   // Make sure any conversions are pushed back into the call; this is
6694   // type safe since unordered compare builtins are declared as "_Bool
6695   // foo(...)".
6696   TheCall->setArg(0, OrigArg0.get());
6697   TheCall->setArg(1, OrigArg1.get());
6698 
6699   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6700     return false;
6701 
6702   // If the common type isn't a real floating type, then the arguments were
6703   // invalid for this operation.
6704   if (Res.isNull() || !Res->isRealFloatingType())
6705     return Diag(OrigArg0.get()->getBeginLoc(),
6706                 diag::err_typecheck_call_invalid_ordered_compare)
6707            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6708            << SourceRange(OrigArg0.get()->getBeginLoc(),
6709                           OrigArg1.get()->getEndLoc());
6710 
6711   return false;
6712 }
6713 
6714 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6715 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6716 /// to check everything. We expect the last argument to be a floating point
6717 /// value.
6718 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6719   if (checkArgCount(*this, TheCall, NumArgs))
6720     return true;
6721 
6722   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6723   // on all preceding parameters just being int.  Try all of those.
6724   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6725     Expr *Arg = TheCall->getArg(i);
6726 
6727     if (Arg->isTypeDependent())
6728       return false;
6729 
6730     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6731 
6732     if (Res.isInvalid())
6733       return true;
6734     TheCall->setArg(i, Res.get());
6735   }
6736 
6737   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6738 
6739   if (OrigArg->isTypeDependent())
6740     return false;
6741 
6742   // Usual Unary Conversions will convert half to float, which we want for
6743   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6744   // type how it is, but do normal L->Rvalue conversions.
6745   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6746     OrigArg = UsualUnaryConversions(OrigArg).get();
6747   else
6748     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6749   TheCall->setArg(NumArgs - 1, OrigArg);
6750 
6751   // This operation requires a non-_Complex floating-point number.
6752   if (!OrigArg->getType()->isRealFloatingType())
6753     return Diag(OrigArg->getBeginLoc(),
6754                 diag::err_typecheck_call_invalid_unary_fp)
6755            << OrigArg->getType() << OrigArg->getSourceRange();
6756 
6757   return false;
6758 }
6759 
6760 /// Perform semantic analysis for a call to __builtin_complex.
6761 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6762   if (checkArgCount(*this, TheCall, 2))
6763     return true;
6764 
6765   bool Dependent = false;
6766   for (unsigned I = 0; I != 2; ++I) {
6767     Expr *Arg = TheCall->getArg(I);
6768     QualType T = Arg->getType();
6769     if (T->isDependentType()) {
6770       Dependent = true;
6771       continue;
6772     }
6773 
6774     // Despite supporting _Complex int, GCC requires a real floating point type
6775     // for the operands of __builtin_complex.
6776     if (!T->isRealFloatingType()) {
6777       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6778              << Arg->getType() << Arg->getSourceRange();
6779     }
6780 
6781     ExprResult Converted = DefaultLvalueConversion(Arg);
6782     if (Converted.isInvalid())
6783       return true;
6784     TheCall->setArg(I, Converted.get());
6785   }
6786 
6787   if (Dependent) {
6788     TheCall->setType(Context.DependentTy);
6789     return false;
6790   }
6791 
6792   Expr *Real = TheCall->getArg(0);
6793   Expr *Imag = TheCall->getArg(1);
6794   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6795     return Diag(Real->getBeginLoc(),
6796                 diag::err_typecheck_call_different_arg_types)
6797            << Real->getType() << Imag->getType()
6798            << Real->getSourceRange() << Imag->getSourceRange();
6799   }
6800 
6801   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6802   // don't allow this builtin to form those types either.
6803   // FIXME: Should we allow these types?
6804   if (Real->getType()->isFloat16Type())
6805     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6806            << "_Float16";
6807   if (Real->getType()->isHalfType())
6808     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6809            << "half";
6810 
6811   TheCall->setType(Context.getComplexType(Real->getType()));
6812   return false;
6813 }
6814 
6815 // Customized Sema Checking for VSX builtins that have the following signature:
6816 // vector [...] builtinName(vector [...], vector [...], const int);
6817 // Which takes the same type of vectors (any legal vector type) for the first
6818 // two arguments and takes compile time constant for the third argument.
6819 // Example builtins are :
6820 // vector double vec_xxpermdi(vector double, vector double, int);
6821 // vector short vec_xxsldwi(vector short, vector short, int);
6822 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6823   unsigned ExpectedNumArgs = 3;
6824   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6825     return true;
6826 
6827   // Check the third argument is a compile time constant
6828   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6829     return Diag(TheCall->getBeginLoc(),
6830                 diag::err_vsx_builtin_nonconstant_argument)
6831            << 3 /* argument index */ << TheCall->getDirectCallee()
6832            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6833                           TheCall->getArg(2)->getEndLoc());
6834 
6835   QualType Arg1Ty = TheCall->getArg(0)->getType();
6836   QualType Arg2Ty = TheCall->getArg(1)->getType();
6837 
6838   // Check the type of argument 1 and argument 2 are vectors.
6839   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6840   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6841       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6842     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6843            << TheCall->getDirectCallee()
6844            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6845                           TheCall->getArg(1)->getEndLoc());
6846   }
6847 
6848   // Check the first two arguments are the same type.
6849   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6850     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6851            << TheCall->getDirectCallee()
6852            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6853                           TheCall->getArg(1)->getEndLoc());
6854   }
6855 
6856   // When default clang type checking is turned off and the customized type
6857   // checking is used, the returning type of the function must be explicitly
6858   // set. Otherwise it is _Bool by default.
6859   TheCall->setType(Arg1Ty);
6860 
6861   return false;
6862 }
6863 
6864 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6865 // This is declared to take (...), so we have to check everything.
6866 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6867   if (TheCall->getNumArgs() < 2)
6868     return ExprError(Diag(TheCall->getEndLoc(),
6869                           diag::err_typecheck_call_too_few_args_at_least)
6870                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6871                      << TheCall->getSourceRange());
6872 
6873   // Determine which of the following types of shufflevector we're checking:
6874   // 1) unary, vector mask: (lhs, mask)
6875   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6876   QualType resType = TheCall->getArg(0)->getType();
6877   unsigned numElements = 0;
6878 
6879   if (!TheCall->getArg(0)->isTypeDependent() &&
6880       !TheCall->getArg(1)->isTypeDependent()) {
6881     QualType LHSType = TheCall->getArg(0)->getType();
6882     QualType RHSType = TheCall->getArg(1)->getType();
6883 
6884     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6885       return ExprError(
6886           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6887           << TheCall->getDirectCallee()
6888           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6889                          TheCall->getArg(1)->getEndLoc()));
6890 
6891     numElements = LHSType->castAs<VectorType>()->getNumElements();
6892     unsigned numResElements = TheCall->getNumArgs() - 2;
6893 
6894     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6895     // with mask.  If so, verify that RHS is an integer vector type with the
6896     // same number of elts as lhs.
6897     if (TheCall->getNumArgs() == 2) {
6898       if (!RHSType->hasIntegerRepresentation() ||
6899           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6900         return ExprError(Diag(TheCall->getBeginLoc(),
6901                               diag::err_vec_builtin_incompatible_vector)
6902                          << TheCall->getDirectCallee()
6903                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6904                                         TheCall->getArg(1)->getEndLoc()));
6905     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6906       return ExprError(Diag(TheCall->getBeginLoc(),
6907                             diag::err_vec_builtin_incompatible_vector)
6908                        << TheCall->getDirectCallee()
6909                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6910                                       TheCall->getArg(1)->getEndLoc()));
6911     } else if (numElements != numResElements) {
6912       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6913       resType = Context.getVectorType(eltType, numResElements,
6914                                       VectorType::GenericVector);
6915     }
6916   }
6917 
6918   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6919     if (TheCall->getArg(i)->isTypeDependent() ||
6920         TheCall->getArg(i)->isValueDependent())
6921       continue;
6922 
6923     Optional<llvm::APSInt> Result;
6924     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6925       return ExprError(Diag(TheCall->getBeginLoc(),
6926                             diag::err_shufflevector_nonconstant_argument)
6927                        << TheCall->getArg(i)->getSourceRange());
6928 
6929     // Allow -1 which will be translated to undef in the IR.
6930     if (Result->isSigned() && Result->isAllOnes())
6931       continue;
6932 
6933     if (Result->getActiveBits() > 64 ||
6934         Result->getZExtValue() >= numElements * 2)
6935       return ExprError(Diag(TheCall->getBeginLoc(),
6936                             diag::err_shufflevector_argument_too_large)
6937                        << TheCall->getArg(i)->getSourceRange());
6938   }
6939 
6940   SmallVector<Expr*, 32> exprs;
6941 
6942   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6943     exprs.push_back(TheCall->getArg(i));
6944     TheCall->setArg(i, nullptr);
6945   }
6946 
6947   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6948                                          TheCall->getCallee()->getBeginLoc(),
6949                                          TheCall->getRParenLoc());
6950 }
6951 
6952 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6953 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6954                                        SourceLocation BuiltinLoc,
6955                                        SourceLocation RParenLoc) {
6956   ExprValueKind VK = VK_PRValue;
6957   ExprObjectKind OK = OK_Ordinary;
6958   QualType DstTy = TInfo->getType();
6959   QualType SrcTy = E->getType();
6960 
6961   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6962     return ExprError(Diag(BuiltinLoc,
6963                           diag::err_convertvector_non_vector)
6964                      << E->getSourceRange());
6965   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6966     return ExprError(Diag(BuiltinLoc,
6967                           diag::err_convertvector_non_vector_type));
6968 
6969   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6970     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6971     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6972     if (SrcElts != DstElts)
6973       return ExprError(Diag(BuiltinLoc,
6974                             diag::err_convertvector_incompatible_vector)
6975                        << E->getSourceRange());
6976   }
6977 
6978   return new (Context)
6979       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6980 }
6981 
6982 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6983 // This is declared to take (const void*, ...) and can take two
6984 // optional constant int args.
6985 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6986   unsigned NumArgs = TheCall->getNumArgs();
6987 
6988   if (NumArgs > 3)
6989     return Diag(TheCall->getEndLoc(),
6990                 diag::err_typecheck_call_too_many_args_at_most)
6991            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6992 
6993   // Argument 0 is checked for us and the remaining arguments must be
6994   // constant integers.
6995   for (unsigned i = 1; i != NumArgs; ++i)
6996     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6997       return true;
6998 
6999   return false;
7000 }
7001 
7002 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7003 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7004   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7005     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7006            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7007   if (checkArgCount(*this, TheCall, 1))
7008     return true;
7009   Expr *Arg = TheCall->getArg(0);
7010   if (Arg->isInstantiationDependent())
7011     return false;
7012 
7013   QualType ArgTy = Arg->getType();
7014   if (!ArgTy->hasFloatingRepresentation())
7015     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7016            << ArgTy;
7017   if (Arg->isLValue()) {
7018     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7019     TheCall->setArg(0, FirstArg.get());
7020   }
7021   TheCall->setType(TheCall->getArg(0)->getType());
7022   return false;
7023 }
7024 
7025 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7026 // __assume does not evaluate its arguments, and should warn if its argument
7027 // has side effects.
7028 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7029   Expr *Arg = TheCall->getArg(0);
7030   if (Arg->isInstantiationDependent()) return false;
7031 
7032   if (Arg->HasSideEffects(Context))
7033     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7034         << Arg->getSourceRange()
7035         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7036 
7037   return false;
7038 }
7039 
7040 /// Handle __builtin_alloca_with_align. This is declared
7041 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7042 /// than 8.
7043 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7044   // The alignment must be a constant integer.
7045   Expr *Arg = TheCall->getArg(1);
7046 
7047   // We can't check the value of a dependent argument.
7048   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7049     if (const auto *UE =
7050             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7051       if (UE->getKind() == UETT_AlignOf ||
7052           UE->getKind() == UETT_PreferredAlignOf)
7053         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7054             << Arg->getSourceRange();
7055 
7056     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7057 
7058     if (!Result.isPowerOf2())
7059       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7060              << Arg->getSourceRange();
7061 
7062     if (Result < Context.getCharWidth())
7063       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7064              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7065 
7066     if (Result > std::numeric_limits<int32_t>::max())
7067       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7068              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7069   }
7070 
7071   return false;
7072 }
7073 
7074 /// Handle __builtin_assume_aligned. This is declared
7075 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7076 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7077   unsigned NumArgs = TheCall->getNumArgs();
7078 
7079   if (NumArgs > 3)
7080     return Diag(TheCall->getEndLoc(),
7081                 diag::err_typecheck_call_too_many_args_at_most)
7082            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7083 
7084   // The alignment must be a constant integer.
7085   Expr *Arg = TheCall->getArg(1);
7086 
7087   // We can't check the value of a dependent argument.
7088   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7089     llvm::APSInt Result;
7090     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7091       return true;
7092 
7093     if (!Result.isPowerOf2())
7094       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7095              << Arg->getSourceRange();
7096 
7097     if (Result > Sema::MaximumAlignment)
7098       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7099           << Arg->getSourceRange() << Sema::MaximumAlignment;
7100   }
7101 
7102   if (NumArgs > 2) {
7103     ExprResult Arg(TheCall->getArg(2));
7104     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7105       Context.getSizeType(), false);
7106     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7107     if (Arg.isInvalid()) return true;
7108     TheCall->setArg(2, Arg.get());
7109   }
7110 
7111   return false;
7112 }
7113 
7114 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7115   unsigned BuiltinID =
7116       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7117   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7118 
7119   unsigned NumArgs = TheCall->getNumArgs();
7120   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7121   if (NumArgs < NumRequiredArgs) {
7122     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7123            << 0 /* function call */ << NumRequiredArgs << NumArgs
7124            << TheCall->getSourceRange();
7125   }
7126   if (NumArgs >= NumRequiredArgs + 0x100) {
7127     return Diag(TheCall->getEndLoc(),
7128                 diag::err_typecheck_call_too_many_args_at_most)
7129            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7130            << TheCall->getSourceRange();
7131   }
7132   unsigned i = 0;
7133 
7134   // For formatting call, check buffer arg.
7135   if (!IsSizeCall) {
7136     ExprResult Arg(TheCall->getArg(i));
7137     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7138         Context, Context.VoidPtrTy, false);
7139     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7140     if (Arg.isInvalid())
7141       return true;
7142     TheCall->setArg(i, Arg.get());
7143     i++;
7144   }
7145 
7146   // Check string literal arg.
7147   unsigned FormatIdx = i;
7148   {
7149     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7150     if (Arg.isInvalid())
7151       return true;
7152     TheCall->setArg(i, Arg.get());
7153     i++;
7154   }
7155 
7156   // Make sure variadic args are scalar.
7157   unsigned FirstDataArg = i;
7158   while (i < NumArgs) {
7159     ExprResult Arg = DefaultVariadicArgumentPromotion(
7160         TheCall->getArg(i), VariadicFunction, nullptr);
7161     if (Arg.isInvalid())
7162       return true;
7163     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7164     if (ArgSize.getQuantity() >= 0x100) {
7165       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7166              << i << (int)ArgSize.getQuantity() << 0xff
7167              << TheCall->getSourceRange();
7168     }
7169     TheCall->setArg(i, Arg.get());
7170     i++;
7171   }
7172 
7173   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7174   // call to avoid duplicate diagnostics.
7175   if (!IsSizeCall) {
7176     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7177     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7178     bool Success = CheckFormatArguments(
7179         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7180         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7181         CheckedVarArgs);
7182     if (!Success)
7183       return true;
7184   }
7185 
7186   if (IsSizeCall) {
7187     TheCall->setType(Context.getSizeType());
7188   } else {
7189     TheCall->setType(Context.VoidPtrTy);
7190   }
7191   return false;
7192 }
7193 
7194 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7195 /// TheCall is a constant expression.
7196 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7197                                   llvm::APSInt &Result) {
7198   Expr *Arg = TheCall->getArg(ArgNum);
7199   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7200   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7201 
7202   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7203 
7204   Optional<llvm::APSInt> R;
7205   if (!(R = Arg->getIntegerConstantExpr(Context)))
7206     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7207            << FDecl->getDeclName() << Arg->getSourceRange();
7208   Result = *R;
7209   return false;
7210 }
7211 
7212 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7213 /// TheCall is a constant expression in the range [Low, High].
7214 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7215                                        int Low, int High, bool RangeIsError) {
7216   if (isConstantEvaluated())
7217     return false;
7218   llvm::APSInt Result;
7219 
7220   // We can't check the value of a dependent argument.
7221   Expr *Arg = TheCall->getArg(ArgNum);
7222   if (Arg->isTypeDependent() || Arg->isValueDependent())
7223     return false;
7224 
7225   // Check constant-ness first.
7226   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7227     return true;
7228 
7229   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7230     if (RangeIsError)
7231       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7232              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7233     else
7234       // Defer the warning until we know if the code will be emitted so that
7235       // dead code can ignore this.
7236       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7237                           PDiag(diag::warn_argument_invalid_range)
7238                               << toString(Result, 10) << Low << High
7239                               << Arg->getSourceRange());
7240   }
7241 
7242   return false;
7243 }
7244 
7245 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7246 /// TheCall is a constant expression is a multiple of Num..
7247 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7248                                           unsigned Num) {
7249   llvm::APSInt Result;
7250 
7251   // We can't check the value of a dependent argument.
7252   Expr *Arg = TheCall->getArg(ArgNum);
7253   if (Arg->isTypeDependent() || Arg->isValueDependent())
7254     return false;
7255 
7256   // Check constant-ness first.
7257   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7258     return true;
7259 
7260   if (Result.getSExtValue() % Num != 0)
7261     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7262            << Num << Arg->getSourceRange();
7263 
7264   return false;
7265 }
7266 
7267 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7268 /// constant expression representing a power of 2.
7269 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7270   llvm::APSInt Result;
7271 
7272   // We can't check the value of a dependent argument.
7273   Expr *Arg = TheCall->getArg(ArgNum);
7274   if (Arg->isTypeDependent() || Arg->isValueDependent())
7275     return false;
7276 
7277   // Check constant-ness first.
7278   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7279     return true;
7280 
7281   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7282   // and only if x is a power of 2.
7283   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7284     return false;
7285 
7286   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7287          << Arg->getSourceRange();
7288 }
7289 
7290 static bool IsShiftedByte(llvm::APSInt Value) {
7291   if (Value.isNegative())
7292     return false;
7293 
7294   // Check if it's a shifted byte, by shifting it down
7295   while (true) {
7296     // If the value fits in the bottom byte, the check passes.
7297     if (Value < 0x100)
7298       return true;
7299 
7300     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7301     // fails.
7302     if ((Value & 0xFF) != 0)
7303       return false;
7304 
7305     // If the bottom 8 bits are all 0, but something above that is nonzero,
7306     // then shifting the value right by 8 bits won't affect whether it's a
7307     // shifted byte or not. So do that, and go round again.
7308     Value >>= 8;
7309   }
7310 }
7311 
7312 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7313 /// a constant expression representing an arbitrary byte value shifted left by
7314 /// a multiple of 8 bits.
7315 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7316                                              unsigned ArgBits) {
7317   llvm::APSInt Result;
7318 
7319   // We can't check the value of a dependent argument.
7320   Expr *Arg = TheCall->getArg(ArgNum);
7321   if (Arg->isTypeDependent() || Arg->isValueDependent())
7322     return false;
7323 
7324   // Check constant-ness first.
7325   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7326     return true;
7327 
7328   // Truncate to the given size.
7329   Result = Result.getLoBits(ArgBits);
7330   Result.setIsUnsigned(true);
7331 
7332   if (IsShiftedByte(Result))
7333     return false;
7334 
7335   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7336          << Arg->getSourceRange();
7337 }
7338 
7339 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7340 /// TheCall is a constant expression representing either a shifted byte value,
7341 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7342 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7343 /// Arm MVE intrinsics.
7344 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7345                                                    int ArgNum,
7346                                                    unsigned ArgBits) {
7347   llvm::APSInt Result;
7348 
7349   // We can't check the value of a dependent argument.
7350   Expr *Arg = TheCall->getArg(ArgNum);
7351   if (Arg->isTypeDependent() || Arg->isValueDependent())
7352     return false;
7353 
7354   // Check constant-ness first.
7355   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7356     return true;
7357 
7358   // Truncate to the given size.
7359   Result = Result.getLoBits(ArgBits);
7360   Result.setIsUnsigned(true);
7361 
7362   // Check to see if it's in either of the required forms.
7363   if (IsShiftedByte(Result) ||
7364       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7365     return false;
7366 
7367   return Diag(TheCall->getBeginLoc(),
7368               diag::err_argument_not_shifted_byte_or_xxff)
7369          << Arg->getSourceRange();
7370 }
7371 
7372 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7373 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7374   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7375     if (checkArgCount(*this, TheCall, 2))
7376       return true;
7377     Expr *Arg0 = TheCall->getArg(0);
7378     Expr *Arg1 = TheCall->getArg(1);
7379 
7380     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7381     if (FirstArg.isInvalid())
7382       return true;
7383     QualType FirstArgType = FirstArg.get()->getType();
7384     if (!FirstArgType->isAnyPointerType())
7385       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7386                << "first" << FirstArgType << Arg0->getSourceRange();
7387     TheCall->setArg(0, FirstArg.get());
7388 
7389     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7390     if (SecArg.isInvalid())
7391       return true;
7392     QualType SecArgType = SecArg.get()->getType();
7393     if (!SecArgType->isIntegerType())
7394       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7395                << "second" << SecArgType << Arg1->getSourceRange();
7396 
7397     // Derive the return type from the pointer argument.
7398     TheCall->setType(FirstArgType);
7399     return false;
7400   }
7401 
7402   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7403     if (checkArgCount(*this, TheCall, 2))
7404       return true;
7405 
7406     Expr *Arg0 = TheCall->getArg(0);
7407     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7408     if (FirstArg.isInvalid())
7409       return true;
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     TheCall->setType(FirstArgType);
7418 
7419     // Second arg must be an constant in range [0,15]
7420     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7421   }
7422 
7423   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7424     if (checkArgCount(*this, TheCall, 2))
7425       return true;
7426     Expr *Arg0 = TheCall->getArg(0);
7427     Expr *Arg1 = TheCall->getArg(1);
7428 
7429     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7430     if (FirstArg.isInvalid())
7431       return true;
7432     QualType FirstArgType = FirstArg.get()->getType();
7433     if (!FirstArgType->isAnyPointerType())
7434       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7435                << "first" << FirstArgType << Arg0->getSourceRange();
7436 
7437     QualType SecArgType = Arg1->getType();
7438     if (!SecArgType->isIntegerType())
7439       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7440                << "second" << SecArgType << Arg1->getSourceRange();
7441     TheCall->setType(Context.IntTy);
7442     return false;
7443   }
7444 
7445   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7446       BuiltinID == AArch64::BI__builtin_arm_stg) {
7447     if (checkArgCount(*this, TheCall, 1))
7448       return true;
7449     Expr *Arg0 = TheCall->getArg(0);
7450     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7451     if (FirstArg.isInvalid())
7452       return true;
7453 
7454     QualType FirstArgType = FirstArg.get()->getType();
7455     if (!FirstArgType->isAnyPointerType())
7456       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7457                << "first" << FirstArgType << Arg0->getSourceRange();
7458     TheCall->setArg(0, FirstArg.get());
7459 
7460     // Derive the return type from the pointer argument.
7461     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7462       TheCall->setType(FirstArgType);
7463     return false;
7464   }
7465 
7466   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7467     Expr *ArgA = TheCall->getArg(0);
7468     Expr *ArgB = TheCall->getArg(1);
7469 
7470     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7471     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7472 
7473     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7474       return true;
7475 
7476     QualType ArgTypeA = ArgExprA.get()->getType();
7477     QualType ArgTypeB = ArgExprB.get()->getType();
7478 
7479     auto isNull = [&] (Expr *E) -> bool {
7480       return E->isNullPointerConstant(
7481                         Context, Expr::NPC_ValueDependentIsNotNull); };
7482 
7483     // argument should be either a pointer or null
7484     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7485       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7486         << "first" << ArgTypeA << ArgA->getSourceRange();
7487 
7488     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7489       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7490         << "second" << ArgTypeB << ArgB->getSourceRange();
7491 
7492     // Ensure Pointee types are compatible
7493     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7494         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7495       QualType pointeeA = ArgTypeA->getPointeeType();
7496       QualType pointeeB = ArgTypeB->getPointeeType();
7497       if (!Context.typesAreCompatible(
7498              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7499              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7500         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7501           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7502           << ArgB->getSourceRange();
7503       }
7504     }
7505 
7506     // at least one argument should be pointer type
7507     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7508       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7509         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7510 
7511     if (isNull(ArgA)) // adopt type of the other pointer
7512       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7513 
7514     if (isNull(ArgB))
7515       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7516 
7517     TheCall->setArg(0, ArgExprA.get());
7518     TheCall->setArg(1, ArgExprB.get());
7519     TheCall->setType(Context.LongLongTy);
7520     return false;
7521   }
7522   assert(false && "Unhandled ARM MTE intrinsic");
7523   return true;
7524 }
7525 
7526 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7527 /// TheCall is an ARM/AArch64 special register string literal.
7528 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7529                                     int ArgNum, unsigned ExpectedFieldNum,
7530                                     bool AllowName) {
7531   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7532                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7533                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7534                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7535                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7536                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7537   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7538                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7539                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7540                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7541                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7542                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7543   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7544 
7545   // We can't check the value of a dependent argument.
7546   Expr *Arg = TheCall->getArg(ArgNum);
7547   if (Arg->isTypeDependent() || Arg->isValueDependent())
7548     return false;
7549 
7550   // Check if the argument is a string literal.
7551   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7552     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7553            << Arg->getSourceRange();
7554 
7555   // Check the type of special register given.
7556   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7557   SmallVector<StringRef, 6> Fields;
7558   Reg.split(Fields, ":");
7559 
7560   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7561     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7562            << Arg->getSourceRange();
7563 
7564   // If the string is the name of a register then we cannot check that it is
7565   // valid here but if the string is of one the forms described in ACLE then we
7566   // can check that the supplied fields are integers and within the valid
7567   // ranges.
7568   if (Fields.size() > 1) {
7569     bool FiveFields = Fields.size() == 5;
7570 
7571     bool ValidString = true;
7572     if (IsARMBuiltin) {
7573       ValidString &= Fields[0].startswith_insensitive("cp") ||
7574                      Fields[0].startswith_insensitive("p");
7575       if (ValidString)
7576         Fields[0] = Fields[0].drop_front(
7577             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7578 
7579       ValidString &= Fields[2].startswith_insensitive("c");
7580       if (ValidString)
7581         Fields[2] = Fields[2].drop_front(1);
7582 
7583       if (FiveFields) {
7584         ValidString &= Fields[3].startswith_insensitive("c");
7585         if (ValidString)
7586           Fields[3] = Fields[3].drop_front(1);
7587       }
7588     }
7589 
7590     SmallVector<int, 5> Ranges;
7591     if (FiveFields)
7592       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7593     else
7594       Ranges.append({15, 7, 15});
7595 
7596     for (unsigned i=0; i<Fields.size(); ++i) {
7597       int IntField;
7598       ValidString &= !Fields[i].getAsInteger(10, IntField);
7599       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7600     }
7601 
7602     if (!ValidString)
7603       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7604              << Arg->getSourceRange();
7605   } else if (IsAArch64Builtin && Fields.size() == 1) {
7606     // If the register name is one of those that appear in the condition below
7607     // and the special register builtin being used is one of the write builtins,
7608     // then we require that the argument provided for writing to the register
7609     // is an integer constant expression. This is because it will be lowered to
7610     // an MSR (immediate) instruction, so we need to know the immediate at
7611     // compile time.
7612     if (TheCall->getNumArgs() != 2)
7613       return false;
7614 
7615     std::string RegLower = Reg.lower();
7616     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7617         RegLower != "pan" && RegLower != "uao")
7618       return false;
7619 
7620     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7621   }
7622 
7623   return false;
7624 }
7625 
7626 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7627 /// Emit an error and return true on failure; return false on success.
7628 /// TypeStr is a string containing the type descriptor of the value returned by
7629 /// the builtin and the descriptors of the expected type of the arguments.
7630 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7631                                  const char *TypeStr) {
7632 
7633   assert((TypeStr[0] != '\0') &&
7634          "Invalid types in PPC MMA builtin declaration");
7635 
7636   switch (BuiltinID) {
7637   default:
7638     // This function is called in CheckPPCBuiltinFunctionCall where the
7639     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7640     // we are isolating the pair vector memop builtins that can be used with mma
7641     // off so the default case is every builtin that requires mma and paired
7642     // vector memops.
7643     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7644                          diag::err_ppc_builtin_only_on_arch, "10") ||
7645         SemaFeatureCheck(*this, TheCall, "mma",
7646                          diag::err_ppc_builtin_only_on_arch, "10"))
7647       return true;
7648     break;
7649   case PPC::BI__builtin_vsx_lxvp:
7650   case PPC::BI__builtin_vsx_stxvp:
7651   case PPC::BI__builtin_vsx_assemble_pair:
7652   case PPC::BI__builtin_vsx_disassemble_pair:
7653     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7654                          diag::err_ppc_builtin_only_on_arch, "10"))
7655       return true;
7656     break;
7657   }
7658 
7659   unsigned Mask = 0;
7660   unsigned ArgNum = 0;
7661 
7662   // The first type in TypeStr is the type of the value returned by the
7663   // builtin. So we first read that type and change the type of TheCall.
7664   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7665   TheCall->setType(type);
7666 
7667   while (*TypeStr != '\0') {
7668     Mask = 0;
7669     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7670     if (ArgNum >= TheCall->getNumArgs()) {
7671       ArgNum++;
7672       break;
7673     }
7674 
7675     Expr *Arg = TheCall->getArg(ArgNum);
7676     QualType PassedType = Arg->getType();
7677     QualType StrippedRVType = PassedType.getCanonicalType();
7678 
7679     // Strip Restrict/Volatile qualifiers.
7680     if (StrippedRVType.isRestrictQualified() ||
7681         StrippedRVType.isVolatileQualified())
7682       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7683 
7684     // The only case where the argument type and expected type are allowed to
7685     // mismatch is if the argument type is a non-void pointer (or array) and
7686     // expected type is a void pointer.
7687     if (StrippedRVType != ExpectedType)
7688       if (!(ExpectedType->isVoidPointerType() &&
7689             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7690         return Diag(Arg->getBeginLoc(),
7691                     diag::err_typecheck_convert_incompatible)
7692                << PassedType << ExpectedType << 1 << 0 << 0;
7693 
7694     // If the value of the Mask is not 0, we have a constraint in the size of
7695     // the integer argument so here we ensure the argument is a constant that
7696     // is in the valid range.
7697     if (Mask != 0 &&
7698         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7699       return true;
7700 
7701     ArgNum++;
7702   }
7703 
7704   // In case we exited early from the previous loop, there are other types to
7705   // read from TypeStr. So we need to read them all to ensure we have the right
7706   // number of arguments in TheCall and if it is not the case, to display a
7707   // better error message.
7708   while (*TypeStr != '\0') {
7709     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7710     ArgNum++;
7711   }
7712   if (checkArgCount(*this, TheCall, ArgNum))
7713     return true;
7714 
7715   return false;
7716 }
7717 
7718 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7719 /// This checks that the target supports __builtin_longjmp and
7720 /// that val is a constant 1.
7721 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7722   if (!Context.getTargetInfo().hasSjLjLowering())
7723     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7724            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7725 
7726   Expr *Arg = TheCall->getArg(1);
7727   llvm::APSInt Result;
7728 
7729   // TODO: This is less than ideal. Overload this to take a value.
7730   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7731     return true;
7732 
7733   if (Result != 1)
7734     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7735            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7736 
7737   return false;
7738 }
7739 
7740 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7741 /// This checks that the target supports __builtin_setjmp.
7742 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7743   if (!Context.getTargetInfo().hasSjLjLowering())
7744     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7745            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7746   return false;
7747 }
7748 
7749 namespace {
7750 
7751 class UncoveredArgHandler {
7752   enum { Unknown = -1, AllCovered = -2 };
7753 
7754   signed FirstUncoveredArg = Unknown;
7755   SmallVector<const Expr *, 4> DiagnosticExprs;
7756 
7757 public:
7758   UncoveredArgHandler() = default;
7759 
7760   bool hasUncoveredArg() const {
7761     return (FirstUncoveredArg >= 0);
7762   }
7763 
7764   unsigned getUncoveredArg() const {
7765     assert(hasUncoveredArg() && "no uncovered argument");
7766     return FirstUncoveredArg;
7767   }
7768 
7769   void setAllCovered() {
7770     // A string has been found with all arguments covered, so clear out
7771     // the diagnostics.
7772     DiagnosticExprs.clear();
7773     FirstUncoveredArg = AllCovered;
7774   }
7775 
7776   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7777     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7778 
7779     // Don't update if a previous string covers all arguments.
7780     if (FirstUncoveredArg == AllCovered)
7781       return;
7782 
7783     // UncoveredArgHandler tracks the highest uncovered argument index
7784     // and with it all the strings that match this index.
7785     if (NewFirstUncoveredArg == FirstUncoveredArg)
7786       DiagnosticExprs.push_back(StrExpr);
7787     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7788       DiagnosticExprs.clear();
7789       DiagnosticExprs.push_back(StrExpr);
7790       FirstUncoveredArg = NewFirstUncoveredArg;
7791     }
7792   }
7793 
7794   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7795 };
7796 
7797 enum StringLiteralCheckType {
7798   SLCT_NotALiteral,
7799   SLCT_UncheckedLiteral,
7800   SLCT_CheckedLiteral
7801 };
7802 
7803 } // namespace
7804 
7805 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7806                                      BinaryOperatorKind BinOpKind,
7807                                      bool AddendIsRight) {
7808   unsigned BitWidth = Offset.getBitWidth();
7809   unsigned AddendBitWidth = Addend.getBitWidth();
7810   // There might be negative interim results.
7811   if (Addend.isUnsigned()) {
7812     Addend = Addend.zext(++AddendBitWidth);
7813     Addend.setIsSigned(true);
7814   }
7815   // Adjust the bit width of the APSInts.
7816   if (AddendBitWidth > BitWidth) {
7817     Offset = Offset.sext(AddendBitWidth);
7818     BitWidth = AddendBitWidth;
7819   } else if (BitWidth > AddendBitWidth) {
7820     Addend = Addend.sext(BitWidth);
7821   }
7822 
7823   bool Ov = false;
7824   llvm::APSInt ResOffset = Offset;
7825   if (BinOpKind == BO_Add)
7826     ResOffset = Offset.sadd_ov(Addend, Ov);
7827   else {
7828     assert(AddendIsRight && BinOpKind == BO_Sub &&
7829            "operator must be add or sub with addend on the right");
7830     ResOffset = Offset.ssub_ov(Addend, Ov);
7831   }
7832 
7833   // We add an offset to a pointer here so we should support an offset as big as
7834   // possible.
7835   if (Ov) {
7836     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7837            "index (intermediate) result too big");
7838     Offset = Offset.sext(2 * BitWidth);
7839     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7840     return;
7841   }
7842 
7843   Offset = ResOffset;
7844 }
7845 
7846 namespace {
7847 
7848 // This is a wrapper class around StringLiteral to support offsetted string
7849 // literals as format strings. It takes the offset into account when returning
7850 // the string and its length or the source locations to display notes correctly.
7851 class FormatStringLiteral {
7852   const StringLiteral *FExpr;
7853   int64_t Offset;
7854 
7855  public:
7856   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7857       : FExpr(fexpr), Offset(Offset) {}
7858 
7859   StringRef getString() const {
7860     return FExpr->getString().drop_front(Offset);
7861   }
7862 
7863   unsigned getByteLength() const {
7864     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7865   }
7866 
7867   unsigned getLength() const { return FExpr->getLength() - Offset; }
7868   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7869 
7870   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7871 
7872   QualType getType() const { return FExpr->getType(); }
7873 
7874   bool isAscii() const { return FExpr->isAscii(); }
7875   bool isWide() const { return FExpr->isWide(); }
7876   bool isUTF8() const { return FExpr->isUTF8(); }
7877   bool isUTF16() const { return FExpr->isUTF16(); }
7878   bool isUTF32() const { return FExpr->isUTF32(); }
7879   bool isPascal() const { return FExpr->isPascal(); }
7880 
7881   SourceLocation getLocationOfByte(
7882       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7883       const TargetInfo &Target, unsigned *StartToken = nullptr,
7884       unsigned *StartTokenByteOffset = nullptr) const {
7885     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7886                                     StartToken, StartTokenByteOffset);
7887   }
7888 
7889   SourceLocation getBeginLoc() const LLVM_READONLY {
7890     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7891   }
7892 
7893   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7894 };
7895 
7896 }  // namespace
7897 
7898 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7899                               const Expr *OrigFormatExpr,
7900                               ArrayRef<const Expr *> Args,
7901                               bool HasVAListArg, unsigned format_idx,
7902                               unsigned firstDataArg,
7903                               Sema::FormatStringType Type,
7904                               bool inFunctionCall,
7905                               Sema::VariadicCallType CallType,
7906                               llvm::SmallBitVector &CheckedVarArgs,
7907                               UncoveredArgHandler &UncoveredArg,
7908                               bool IgnoreStringsWithoutSpecifiers);
7909 
7910 // Determine if an expression is a string literal or constant string.
7911 // If this function returns false on the arguments to a function expecting a
7912 // format string, we will usually need to emit a warning.
7913 // True string literals are then checked by CheckFormatString.
7914 static StringLiteralCheckType
7915 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7916                       bool HasVAListArg, unsigned format_idx,
7917                       unsigned firstDataArg, Sema::FormatStringType Type,
7918                       Sema::VariadicCallType CallType, bool InFunctionCall,
7919                       llvm::SmallBitVector &CheckedVarArgs,
7920                       UncoveredArgHandler &UncoveredArg,
7921                       llvm::APSInt Offset,
7922                       bool IgnoreStringsWithoutSpecifiers = false) {
7923   if (S.isConstantEvaluated())
7924     return SLCT_NotALiteral;
7925  tryAgain:
7926   assert(Offset.isSigned() && "invalid offset");
7927 
7928   if (E->isTypeDependent() || E->isValueDependent())
7929     return SLCT_NotALiteral;
7930 
7931   E = E->IgnoreParenCasts();
7932 
7933   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7934     // Technically -Wformat-nonliteral does not warn about this case.
7935     // The behavior of printf and friends in this case is implementation
7936     // dependent.  Ideally if the format string cannot be null then
7937     // it should have a 'nonnull' attribute in the function prototype.
7938     return SLCT_UncheckedLiteral;
7939 
7940   switch (E->getStmtClass()) {
7941   case Stmt::BinaryConditionalOperatorClass:
7942   case Stmt::ConditionalOperatorClass: {
7943     // The expression is a literal if both sub-expressions were, and it was
7944     // completely checked only if both sub-expressions were checked.
7945     const AbstractConditionalOperator *C =
7946         cast<AbstractConditionalOperator>(E);
7947 
7948     // Determine whether it is necessary to check both sub-expressions, for
7949     // example, because the condition expression is a constant that can be
7950     // evaluated at compile time.
7951     bool CheckLeft = true, CheckRight = true;
7952 
7953     bool Cond;
7954     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7955                                                  S.isConstantEvaluated())) {
7956       if (Cond)
7957         CheckRight = false;
7958       else
7959         CheckLeft = false;
7960     }
7961 
7962     // We need to maintain the offsets for the right and the left hand side
7963     // separately to check if every possible indexed expression is a valid
7964     // string literal. They might have different offsets for different string
7965     // literals in the end.
7966     StringLiteralCheckType Left;
7967     if (!CheckLeft)
7968       Left = SLCT_UncheckedLiteral;
7969     else {
7970       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7971                                    HasVAListArg, format_idx, firstDataArg,
7972                                    Type, CallType, InFunctionCall,
7973                                    CheckedVarArgs, UncoveredArg, Offset,
7974                                    IgnoreStringsWithoutSpecifiers);
7975       if (Left == SLCT_NotALiteral || !CheckRight) {
7976         return Left;
7977       }
7978     }
7979 
7980     StringLiteralCheckType Right = checkFormatStringExpr(
7981         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7982         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7983         IgnoreStringsWithoutSpecifiers);
7984 
7985     return (CheckLeft && Left < Right) ? Left : Right;
7986   }
7987 
7988   case Stmt::ImplicitCastExprClass:
7989     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7990     goto tryAgain;
7991 
7992   case Stmt::OpaqueValueExprClass:
7993     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7994       E = src;
7995       goto tryAgain;
7996     }
7997     return SLCT_NotALiteral;
7998 
7999   case Stmt::PredefinedExprClass:
8000     // While __func__, etc., are technically not string literals, they
8001     // cannot contain format specifiers and thus are not a security
8002     // liability.
8003     return SLCT_UncheckedLiteral;
8004 
8005   case Stmt::DeclRefExprClass: {
8006     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8007 
8008     // As an exception, do not flag errors for variables binding to
8009     // const string literals.
8010     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8011       bool isConstant = false;
8012       QualType T = DR->getType();
8013 
8014       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8015         isConstant = AT->getElementType().isConstant(S.Context);
8016       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8017         isConstant = T.isConstant(S.Context) &&
8018                      PT->getPointeeType().isConstant(S.Context);
8019       } else if (T->isObjCObjectPointerType()) {
8020         // In ObjC, there is usually no "const ObjectPointer" type,
8021         // so don't check if the pointee type is constant.
8022         isConstant = T.isConstant(S.Context);
8023       }
8024 
8025       if (isConstant) {
8026         if (const Expr *Init = VD->getAnyInitializer()) {
8027           // Look through initializers like const char c[] = { "foo" }
8028           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8029             if (InitList->isStringLiteralInit())
8030               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8031           }
8032           return checkFormatStringExpr(S, Init, Args,
8033                                        HasVAListArg, format_idx,
8034                                        firstDataArg, Type, CallType,
8035                                        /*InFunctionCall*/ false, CheckedVarArgs,
8036                                        UncoveredArg, Offset);
8037         }
8038       }
8039 
8040       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8041       // special check to see if the format string is a function parameter
8042       // of the function calling the printf function.  If the function
8043       // has an attribute indicating it is a printf-like function, then we
8044       // should suppress warnings concerning non-literals being used in a call
8045       // to a vprintf function.  For example:
8046       //
8047       // void
8048       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8049       //      va_list ap;
8050       //      va_start(ap, fmt);
8051       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8052       //      ...
8053       // }
8054       if (HasVAListArg) {
8055         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8056           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8057             int PVIndex = PV->getFunctionScopeIndex() + 1;
8058             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8059               // adjust for implicit parameter
8060               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8061                 if (MD->isInstance())
8062                   ++PVIndex;
8063               // We also check if the formats are compatible.
8064               // We can't pass a 'scanf' string to a 'printf' function.
8065               if (PVIndex == PVFormat->getFormatIdx() &&
8066                   Type == S.GetFormatStringType(PVFormat))
8067                 return SLCT_UncheckedLiteral;
8068             }
8069           }
8070         }
8071       }
8072     }
8073 
8074     return SLCT_NotALiteral;
8075   }
8076 
8077   case Stmt::CallExprClass:
8078   case Stmt::CXXMemberCallExprClass: {
8079     const CallExpr *CE = cast<CallExpr>(E);
8080     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8081       bool IsFirst = true;
8082       StringLiteralCheckType CommonResult;
8083       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8084         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8085         StringLiteralCheckType Result = checkFormatStringExpr(
8086             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8087             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8088             IgnoreStringsWithoutSpecifiers);
8089         if (IsFirst) {
8090           CommonResult = Result;
8091           IsFirst = false;
8092         }
8093       }
8094       if (!IsFirst)
8095         return CommonResult;
8096 
8097       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8098         unsigned BuiltinID = FD->getBuiltinID();
8099         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8100             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8101           const Expr *Arg = CE->getArg(0);
8102           return checkFormatStringExpr(S, Arg, Args,
8103                                        HasVAListArg, format_idx,
8104                                        firstDataArg, Type, CallType,
8105                                        InFunctionCall, CheckedVarArgs,
8106                                        UncoveredArg, Offset,
8107                                        IgnoreStringsWithoutSpecifiers);
8108         }
8109       }
8110     }
8111 
8112     return SLCT_NotALiteral;
8113   }
8114   case Stmt::ObjCMessageExprClass: {
8115     const auto *ME = cast<ObjCMessageExpr>(E);
8116     if (const auto *MD = ME->getMethodDecl()) {
8117       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8118         // As a special case heuristic, if we're using the method -[NSBundle
8119         // localizedStringForKey:value:table:], ignore any key strings that lack
8120         // format specifiers. The idea is that if the key doesn't have any
8121         // format specifiers then its probably just a key to map to the
8122         // localized strings. If it does have format specifiers though, then its
8123         // likely that the text of the key is the format string in the
8124         // programmer's language, and should be checked.
8125         const ObjCInterfaceDecl *IFace;
8126         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8127             IFace->getIdentifier()->isStr("NSBundle") &&
8128             MD->getSelector().isKeywordSelector(
8129                 {"localizedStringForKey", "value", "table"})) {
8130           IgnoreStringsWithoutSpecifiers = true;
8131         }
8132 
8133         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8134         return checkFormatStringExpr(
8135             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8136             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8137             IgnoreStringsWithoutSpecifiers);
8138       }
8139     }
8140 
8141     return SLCT_NotALiteral;
8142   }
8143   case Stmt::ObjCStringLiteralClass:
8144   case Stmt::StringLiteralClass: {
8145     const StringLiteral *StrE = nullptr;
8146 
8147     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8148       StrE = ObjCFExpr->getString();
8149     else
8150       StrE = cast<StringLiteral>(E);
8151 
8152     if (StrE) {
8153       if (Offset.isNegative() || Offset > StrE->getLength()) {
8154         // TODO: It would be better to have an explicit warning for out of
8155         // bounds literals.
8156         return SLCT_NotALiteral;
8157       }
8158       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8159       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8160                         firstDataArg, Type, InFunctionCall, CallType,
8161                         CheckedVarArgs, UncoveredArg,
8162                         IgnoreStringsWithoutSpecifiers);
8163       return SLCT_CheckedLiteral;
8164     }
8165 
8166     return SLCT_NotALiteral;
8167   }
8168   case Stmt::BinaryOperatorClass: {
8169     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8170 
8171     // A string literal + an int offset is still a string literal.
8172     if (BinOp->isAdditiveOp()) {
8173       Expr::EvalResult LResult, RResult;
8174 
8175       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8176           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8177       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8178           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8179 
8180       if (LIsInt != RIsInt) {
8181         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8182 
8183         if (LIsInt) {
8184           if (BinOpKind == BO_Add) {
8185             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8186             E = BinOp->getRHS();
8187             goto tryAgain;
8188           }
8189         } else {
8190           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8191           E = BinOp->getLHS();
8192           goto tryAgain;
8193         }
8194       }
8195     }
8196 
8197     return SLCT_NotALiteral;
8198   }
8199   case Stmt::UnaryOperatorClass: {
8200     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8201     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8202     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8203       Expr::EvalResult IndexResult;
8204       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8205                                        Expr::SE_NoSideEffects,
8206                                        S.isConstantEvaluated())) {
8207         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8208                    /*RHS is int*/ true);
8209         E = ASE->getBase();
8210         goto tryAgain;
8211       }
8212     }
8213 
8214     return SLCT_NotALiteral;
8215   }
8216 
8217   default:
8218     return SLCT_NotALiteral;
8219   }
8220 }
8221 
8222 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8223   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8224       .Case("scanf", FST_Scanf)
8225       .Cases("printf", "printf0", FST_Printf)
8226       .Cases("NSString", "CFString", FST_NSString)
8227       .Case("strftime", FST_Strftime)
8228       .Case("strfmon", FST_Strfmon)
8229       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8230       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8231       .Case("os_trace", FST_OSLog)
8232       .Case("os_log", FST_OSLog)
8233       .Default(FST_Unknown);
8234 }
8235 
8236 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8237 /// functions) for correct use of format strings.
8238 /// Returns true if a format string has been fully checked.
8239 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8240                                 ArrayRef<const Expr *> Args,
8241                                 bool IsCXXMember,
8242                                 VariadicCallType CallType,
8243                                 SourceLocation Loc, SourceRange Range,
8244                                 llvm::SmallBitVector &CheckedVarArgs) {
8245   FormatStringInfo FSI;
8246   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8247     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8248                                 FSI.FirstDataArg, GetFormatStringType(Format),
8249                                 CallType, Loc, Range, CheckedVarArgs);
8250   return false;
8251 }
8252 
8253 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8254                                 bool HasVAListArg, unsigned format_idx,
8255                                 unsigned firstDataArg, FormatStringType Type,
8256                                 VariadicCallType CallType,
8257                                 SourceLocation Loc, SourceRange Range,
8258                                 llvm::SmallBitVector &CheckedVarArgs) {
8259   // CHECK: printf/scanf-like function is called with no format string.
8260   if (format_idx >= Args.size()) {
8261     Diag(Loc, diag::warn_missing_format_string) << Range;
8262     return false;
8263   }
8264 
8265   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8266 
8267   // CHECK: format string is not a string literal.
8268   //
8269   // Dynamically generated format strings are difficult to
8270   // automatically vet at compile time.  Requiring that format strings
8271   // are string literals: (1) permits the checking of format strings by
8272   // the compiler and thereby (2) can practically remove the source of
8273   // many format string exploits.
8274 
8275   // Format string can be either ObjC string (e.g. @"%d") or
8276   // C string (e.g. "%d")
8277   // ObjC string uses the same format specifiers as C string, so we can use
8278   // the same format string checking logic for both ObjC and C strings.
8279   UncoveredArgHandler UncoveredArg;
8280   StringLiteralCheckType CT =
8281       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8282                             format_idx, firstDataArg, Type, CallType,
8283                             /*IsFunctionCall*/ true, CheckedVarArgs,
8284                             UncoveredArg,
8285                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8286 
8287   // Generate a diagnostic where an uncovered argument is detected.
8288   if (UncoveredArg.hasUncoveredArg()) {
8289     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8290     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8291     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8292   }
8293 
8294   if (CT != SLCT_NotALiteral)
8295     // Literal format string found, check done!
8296     return CT == SLCT_CheckedLiteral;
8297 
8298   // Strftime is particular as it always uses a single 'time' argument,
8299   // so it is safe to pass a non-literal string.
8300   if (Type == FST_Strftime)
8301     return false;
8302 
8303   // Do not emit diag when the string param is a macro expansion and the
8304   // format is either NSString or CFString. This is a hack to prevent
8305   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8306   // which are usually used in place of NS and CF string literals.
8307   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8308   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8309     return false;
8310 
8311   // If there are no arguments specified, warn with -Wformat-security, otherwise
8312   // warn only with -Wformat-nonliteral.
8313   if (Args.size() == firstDataArg) {
8314     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8315       << OrigFormatExpr->getSourceRange();
8316     switch (Type) {
8317     default:
8318       break;
8319     case FST_Kprintf:
8320     case FST_FreeBSDKPrintf:
8321     case FST_Printf:
8322       Diag(FormatLoc, diag::note_format_security_fixit)
8323         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8324       break;
8325     case FST_NSString:
8326       Diag(FormatLoc, diag::note_format_security_fixit)
8327         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8328       break;
8329     }
8330   } else {
8331     Diag(FormatLoc, diag::warn_format_nonliteral)
8332       << OrigFormatExpr->getSourceRange();
8333   }
8334   return false;
8335 }
8336 
8337 namespace {
8338 
8339 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8340 protected:
8341   Sema &S;
8342   const FormatStringLiteral *FExpr;
8343   const Expr *OrigFormatExpr;
8344   const Sema::FormatStringType FSType;
8345   const unsigned FirstDataArg;
8346   const unsigned NumDataArgs;
8347   const char *Beg; // Start of format string.
8348   const bool HasVAListArg;
8349   ArrayRef<const Expr *> Args;
8350   unsigned FormatIdx;
8351   llvm::SmallBitVector CoveredArgs;
8352   bool usesPositionalArgs = false;
8353   bool atFirstArg = true;
8354   bool inFunctionCall;
8355   Sema::VariadicCallType CallType;
8356   llvm::SmallBitVector &CheckedVarArgs;
8357   UncoveredArgHandler &UncoveredArg;
8358 
8359 public:
8360   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8361                      const Expr *origFormatExpr,
8362                      const Sema::FormatStringType type, unsigned firstDataArg,
8363                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8364                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8365                      bool inFunctionCall, Sema::VariadicCallType callType,
8366                      llvm::SmallBitVector &CheckedVarArgs,
8367                      UncoveredArgHandler &UncoveredArg)
8368       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8369         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8370         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8371         inFunctionCall(inFunctionCall), CallType(callType),
8372         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8373     CoveredArgs.resize(numDataArgs);
8374     CoveredArgs.reset();
8375   }
8376 
8377   void DoneProcessing();
8378 
8379   void HandleIncompleteSpecifier(const char *startSpecifier,
8380                                  unsigned specifierLen) override;
8381 
8382   void HandleInvalidLengthModifier(
8383                            const analyze_format_string::FormatSpecifier &FS,
8384                            const analyze_format_string::ConversionSpecifier &CS,
8385                            const char *startSpecifier, unsigned specifierLen,
8386                            unsigned DiagID);
8387 
8388   void HandleNonStandardLengthModifier(
8389                     const analyze_format_string::FormatSpecifier &FS,
8390                     const char *startSpecifier, unsigned specifierLen);
8391 
8392   void HandleNonStandardConversionSpecifier(
8393                     const analyze_format_string::ConversionSpecifier &CS,
8394                     const char *startSpecifier, unsigned specifierLen);
8395 
8396   void HandlePosition(const char *startPos, unsigned posLen) override;
8397 
8398   void HandleInvalidPosition(const char *startSpecifier,
8399                              unsigned specifierLen,
8400                              analyze_format_string::PositionContext p) override;
8401 
8402   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8403 
8404   void HandleNullChar(const char *nullCharacter) override;
8405 
8406   template <typename Range>
8407   static void
8408   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8409                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8410                        bool IsStringLocation, Range StringRange,
8411                        ArrayRef<FixItHint> Fixit = None);
8412 
8413 protected:
8414   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8415                                         const char *startSpec,
8416                                         unsigned specifierLen,
8417                                         const char *csStart, unsigned csLen);
8418 
8419   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8420                                          const char *startSpec,
8421                                          unsigned specifierLen);
8422 
8423   SourceRange getFormatStringRange();
8424   CharSourceRange getSpecifierRange(const char *startSpecifier,
8425                                     unsigned specifierLen);
8426   SourceLocation getLocationOfByte(const char *x);
8427 
8428   const Expr *getDataArg(unsigned i) const;
8429 
8430   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8431                     const analyze_format_string::ConversionSpecifier &CS,
8432                     const char *startSpecifier, unsigned specifierLen,
8433                     unsigned argIndex);
8434 
8435   template <typename Range>
8436   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8437                             bool IsStringLocation, Range StringRange,
8438                             ArrayRef<FixItHint> Fixit = None);
8439 };
8440 
8441 } // namespace
8442 
8443 SourceRange CheckFormatHandler::getFormatStringRange() {
8444   return OrigFormatExpr->getSourceRange();
8445 }
8446 
8447 CharSourceRange CheckFormatHandler::
8448 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8449   SourceLocation Start = getLocationOfByte(startSpecifier);
8450   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8451 
8452   // Advance the end SourceLocation by one due to half-open ranges.
8453   End = End.getLocWithOffset(1);
8454 
8455   return CharSourceRange::getCharRange(Start, End);
8456 }
8457 
8458 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8459   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8460                                   S.getLangOpts(), S.Context.getTargetInfo());
8461 }
8462 
8463 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8464                                                    unsigned specifierLen){
8465   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8466                        getLocationOfByte(startSpecifier),
8467                        /*IsStringLocation*/true,
8468                        getSpecifierRange(startSpecifier, specifierLen));
8469 }
8470 
8471 void CheckFormatHandler::HandleInvalidLengthModifier(
8472     const analyze_format_string::FormatSpecifier &FS,
8473     const analyze_format_string::ConversionSpecifier &CS,
8474     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8475   using namespace analyze_format_string;
8476 
8477   const LengthModifier &LM = FS.getLengthModifier();
8478   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8479 
8480   // See if we know how to fix this length modifier.
8481   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8482   if (FixedLM) {
8483     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8484                          getLocationOfByte(LM.getStart()),
8485                          /*IsStringLocation*/true,
8486                          getSpecifierRange(startSpecifier, specifierLen));
8487 
8488     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8489       << FixedLM->toString()
8490       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8491 
8492   } else {
8493     FixItHint Hint;
8494     if (DiagID == diag::warn_format_nonsensical_length)
8495       Hint = FixItHint::CreateRemoval(LMRange);
8496 
8497     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8498                          getLocationOfByte(LM.getStart()),
8499                          /*IsStringLocation*/true,
8500                          getSpecifierRange(startSpecifier, specifierLen),
8501                          Hint);
8502   }
8503 }
8504 
8505 void CheckFormatHandler::HandleNonStandardLengthModifier(
8506     const analyze_format_string::FormatSpecifier &FS,
8507     const char *startSpecifier, unsigned specifierLen) {
8508   using namespace analyze_format_string;
8509 
8510   const LengthModifier &LM = FS.getLengthModifier();
8511   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8512 
8513   // See if we know how to fix this length modifier.
8514   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8515   if (FixedLM) {
8516     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8517                            << LM.toString() << 0,
8518                          getLocationOfByte(LM.getStart()),
8519                          /*IsStringLocation*/true,
8520                          getSpecifierRange(startSpecifier, specifierLen));
8521 
8522     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8523       << FixedLM->toString()
8524       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8525 
8526   } else {
8527     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8528                            << LM.toString() << 0,
8529                          getLocationOfByte(LM.getStart()),
8530                          /*IsStringLocation*/true,
8531                          getSpecifierRange(startSpecifier, specifierLen));
8532   }
8533 }
8534 
8535 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8536     const analyze_format_string::ConversionSpecifier &CS,
8537     const char *startSpecifier, unsigned specifierLen) {
8538   using namespace analyze_format_string;
8539 
8540   // See if we know how to fix this conversion specifier.
8541   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8542   if (FixedCS) {
8543     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8544                           << CS.toString() << /*conversion specifier*/1,
8545                          getLocationOfByte(CS.getStart()),
8546                          /*IsStringLocation*/true,
8547                          getSpecifierRange(startSpecifier, specifierLen));
8548 
8549     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8550     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8551       << FixedCS->toString()
8552       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8553   } else {
8554     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8555                           << CS.toString() << /*conversion specifier*/1,
8556                          getLocationOfByte(CS.getStart()),
8557                          /*IsStringLocation*/true,
8558                          getSpecifierRange(startSpecifier, specifierLen));
8559   }
8560 }
8561 
8562 void CheckFormatHandler::HandlePosition(const char *startPos,
8563                                         unsigned posLen) {
8564   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8565                                getLocationOfByte(startPos),
8566                                /*IsStringLocation*/true,
8567                                getSpecifierRange(startPos, posLen));
8568 }
8569 
8570 void
8571 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8572                                      analyze_format_string::PositionContext p) {
8573   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8574                          << (unsigned) p,
8575                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8576                        getSpecifierRange(startPos, posLen));
8577 }
8578 
8579 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8580                                             unsigned posLen) {
8581   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8582                                getLocationOfByte(startPos),
8583                                /*IsStringLocation*/true,
8584                                getSpecifierRange(startPos, posLen));
8585 }
8586 
8587 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8588   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8589     // The presence of a null character is likely an error.
8590     EmitFormatDiagnostic(
8591       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8592       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8593       getFormatStringRange());
8594   }
8595 }
8596 
8597 // Note that this may return NULL if there was an error parsing or building
8598 // one of the argument expressions.
8599 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8600   return Args[FirstDataArg + i];
8601 }
8602 
8603 void CheckFormatHandler::DoneProcessing() {
8604   // Does the number of data arguments exceed the number of
8605   // format conversions in the format string?
8606   if (!HasVAListArg) {
8607       // Find any arguments that weren't covered.
8608     CoveredArgs.flip();
8609     signed notCoveredArg = CoveredArgs.find_first();
8610     if (notCoveredArg >= 0) {
8611       assert((unsigned)notCoveredArg < NumDataArgs);
8612       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8613     } else {
8614       UncoveredArg.setAllCovered();
8615     }
8616   }
8617 }
8618 
8619 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8620                                    const Expr *ArgExpr) {
8621   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8622          "Invalid state");
8623 
8624   if (!ArgExpr)
8625     return;
8626 
8627   SourceLocation Loc = ArgExpr->getBeginLoc();
8628 
8629   if (S.getSourceManager().isInSystemMacro(Loc))
8630     return;
8631 
8632   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8633   for (auto E : DiagnosticExprs)
8634     PDiag << E->getSourceRange();
8635 
8636   CheckFormatHandler::EmitFormatDiagnostic(
8637                                   S, IsFunctionCall, DiagnosticExprs[0],
8638                                   PDiag, Loc, /*IsStringLocation*/false,
8639                                   DiagnosticExprs[0]->getSourceRange());
8640 }
8641 
8642 bool
8643 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8644                                                      SourceLocation Loc,
8645                                                      const char *startSpec,
8646                                                      unsigned specifierLen,
8647                                                      const char *csStart,
8648                                                      unsigned csLen) {
8649   bool keepGoing = true;
8650   if (argIndex < NumDataArgs) {
8651     // Consider the argument coverered, even though the specifier doesn't
8652     // make sense.
8653     CoveredArgs.set(argIndex);
8654   }
8655   else {
8656     // If argIndex exceeds the number of data arguments we
8657     // don't issue a warning because that is just a cascade of warnings (and
8658     // they may have intended '%%' anyway). We don't want to continue processing
8659     // the format string after this point, however, as we will like just get
8660     // gibberish when trying to match arguments.
8661     keepGoing = false;
8662   }
8663 
8664   StringRef Specifier(csStart, csLen);
8665 
8666   // If the specifier in non-printable, it could be the first byte of a UTF-8
8667   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8668   // hex value.
8669   std::string CodePointStr;
8670   if (!llvm::sys::locale::isPrint(*csStart)) {
8671     llvm::UTF32 CodePoint;
8672     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8673     const llvm::UTF8 *E =
8674         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8675     llvm::ConversionResult Result =
8676         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8677 
8678     if (Result != llvm::conversionOK) {
8679       unsigned char FirstChar = *csStart;
8680       CodePoint = (llvm::UTF32)FirstChar;
8681     }
8682 
8683     llvm::raw_string_ostream OS(CodePointStr);
8684     if (CodePoint < 256)
8685       OS << "\\x" << llvm::format("%02x", CodePoint);
8686     else if (CodePoint <= 0xFFFF)
8687       OS << "\\u" << llvm::format("%04x", CodePoint);
8688     else
8689       OS << "\\U" << llvm::format("%08x", CodePoint);
8690     OS.flush();
8691     Specifier = CodePointStr;
8692   }
8693 
8694   EmitFormatDiagnostic(
8695       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8696       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8697 
8698   return keepGoing;
8699 }
8700 
8701 void
8702 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8703                                                       const char *startSpec,
8704                                                       unsigned specifierLen) {
8705   EmitFormatDiagnostic(
8706     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8707     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8708 }
8709 
8710 bool
8711 CheckFormatHandler::CheckNumArgs(
8712   const analyze_format_string::FormatSpecifier &FS,
8713   const analyze_format_string::ConversionSpecifier &CS,
8714   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8715 
8716   if (argIndex >= NumDataArgs) {
8717     PartialDiagnostic PDiag = FS.usesPositionalArg()
8718       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8719            << (argIndex+1) << NumDataArgs)
8720       : S.PDiag(diag::warn_printf_insufficient_data_args);
8721     EmitFormatDiagnostic(
8722       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8723       getSpecifierRange(startSpecifier, specifierLen));
8724 
8725     // Since more arguments than conversion tokens are given, by extension
8726     // all arguments are covered, so mark this as so.
8727     UncoveredArg.setAllCovered();
8728     return false;
8729   }
8730   return true;
8731 }
8732 
8733 template<typename Range>
8734 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8735                                               SourceLocation Loc,
8736                                               bool IsStringLocation,
8737                                               Range StringRange,
8738                                               ArrayRef<FixItHint> FixIt) {
8739   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8740                        Loc, IsStringLocation, StringRange, FixIt);
8741 }
8742 
8743 /// If the format string is not within the function call, emit a note
8744 /// so that the function call and string are in diagnostic messages.
8745 ///
8746 /// \param InFunctionCall if true, the format string is within the function
8747 /// call and only one diagnostic message will be produced.  Otherwise, an
8748 /// extra note will be emitted pointing to location of the format string.
8749 ///
8750 /// \param ArgumentExpr the expression that is passed as the format string
8751 /// argument in the function call.  Used for getting locations when two
8752 /// diagnostics are emitted.
8753 ///
8754 /// \param PDiag the callee should already have provided any strings for the
8755 /// diagnostic message.  This function only adds locations and fixits
8756 /// to diagnostics.
8757 ///
8758 /// \param Loc primary location for diagnostic.  If two diagnostics are
8759 /// required, one will be at Loc and a new SourceLocation will be created for
8760 /// the other one.
8761 ///
8762 /// \param IsStringLocation if true, Loc points to the format string should be
8763 /// used for the note.  Otherwise, Loc points to the argument list and will
8764 /// be used with PDiag.
8765 ///
8766 /// \param StringRange some or all of the string to highlight.  This is
8767 /// templated so it can accept either a CharSourceRange or a SourceRange.
8768 ///
8769 /// \param FixIt optional fix it hint for the format string.
8770 template <typename Range>
8771 void CheckFormatHandler::EmitFormatDiagnostic(
8772     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8773     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8774     Range StringRange, ArrayRef<FixItHint> FixIt) {
8775   if (InFunctionCall) {
8776     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8777     D << StringRange;
8778     D << FixIt;
8779   } else {
8780     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8781       << ArgumentExpr->getSourceRange();
8782 
8783     const Sema::SemaDiagnosticBuilder &Note =
8784       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8785              diag::note_format_string_defined);
8786 
8787     Note << StringRange;
8788     Note << FixIt;
8789   }
8790 }
8791 
8792 //===--- CHECK: Printf format string checking ------------------------------===//
8793 
8794 namespace {
8795 
8796 class CheckPrintfHandler : public CheckFormatHandler {
8797 public:
8798   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8799                      const Expr *origFormatExpr,
8800                      const Sema::FormatStringType type, unsigned firstDataArg,
8801                      unsigned numDataArgs, bool isObjC, const char *beg,
8802                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8803                      unsigned formatIdx, bool inFunctionCall,
8804                      Sema::VariadicCallType CallType,
8805                      llvm::SmallBitVector &CheckedVarArgs,
8806                      UncoveredArgHandler &UncoveredArg)
8807       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8808                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8809                            inFunctionCall, CallType, CheckedVarArgs,
8810                            UncoveredArg) {}
8811 
8812   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8813 
8814   /// Returns true if '%@' specifiers are allowed in the format string.
8815   bool allowsObjCArg() const {
8816     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8817            FSType == Sema::FST_OSTrace;
8818   }
8819 
8820   bool HandleInvalidPrintfConversionSpecifier(
8821                                       const analyze_printf::PrintfSpecifier &FS,
8822                                       const char *startSpecifier,
8823                                       unsigned specifierLen) override;
8824 
8825   void handleInvalidMaskType(StringRef MaskType) override;
8826 
8827   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8828                              const char *startSpecifier,
8829                              unsigned specifierLen) override;
8830   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8831                        const char *StartSpecifier,
8832                        unsigned SpecifierLen,
8833                        const Expr *E);
8834 
8835   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8836                     const char *startSpecifier, unsigned specifierLen);
8837   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8838                            const analyze_printf::OptionalAmount &Amt,
8839                            unsigned type,
8840                            const char *startSpecifier, unsigned specifierLen);
8841   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8842                   const analyze_printf::OptionalFlag &flag,
8843                   const char *startSpecifier, unsigned specifierLen);
8844   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8845                          const analyze_printf::OptionalFlag &ignoredFlag,
8846                          const analyze_printf::OptionalFlag &flag,
8847                          const char *startSpecifier, unsigned specifierLen);
8848   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8849                            const Expr *E);
8850 
8851   void HandleEmptyObjCModifierFlag(const char *startFlag,
8852                                    unsigned flagLen) override;
8853 
8854   void HandleInvalidObjCModifierFlag(const char *startFlag,
8855                                             unsigned flagLen) override;
8856 
8857   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8858                                            const char *flagsEnd,
8859                                            const char *conversionPosition)
8860                                              override;
8861 };
8862 
8863 } // namespace
8864 
8865 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8866                                       const analyze_printf::PrintfSpecifier &FS,
8867                                       const char *startSpecifier,
8868                                       unsigned specifierLen) {
8869   const analyze_printf::PrintfConversionSpecifier &CS =
8870     FS.getConversionSpecifier();
8871 
8872   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8873                                           getLocationOfByte(CS.getStart()),
8874                                           startSpecifier, specifierLen,
8875                                           CS.getStart(), CS.getLength());
8876 }
8877 
8878 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8879   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8880 }
8881 
8882 bool CheckPrintfHandler::HandleAmount(
8883                                const analyze_format_string::OptionalAmount &Amt,
8884                                unsigned k, const char *startSpecifier,
8885                                unsigned specifierLen) {
8886   if (Amt.hasDataArgument()) {
8887     if (!HasVAListArg) {
8888       unsigned argIndex = Amt.getArgIndex();
8889       if (argIndex >= NumDataArgs) {
8890         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8891                                << k,
8892                              getLocationOfByte(Amt.getStart()),
8893                              /*IsStringLocation*/true,
8894                              getSpecifierRange(startSpecifier, specifierLen));
8895         // Don't do any more checking.  We will just emit
8896         // spurious errors.
8897         return false;
8898       }
8899 
8900       // Type check the data argument.  It should be an 'int'.
8901       // Although not in conformance with C99, we also allow the argument to be
8902       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8903       // doesn't emit a warning for that case.
8904       CoveredArgs.set(argIndex);
8905       const Expr *Arg = getDataArg(argIndex);
8906       if (!Arg)
8907         return false;
8908 
8909       QualType T = Arg->getType();
8910 
8911       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8912       assert(AT.isValid());
8913 
8914       if (!AT.matchesType(S.Context, T)) {
8915         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8916                                << k << AT.getRepresentativeTypeName(S.Context)
8917                                << T << Arg->getSourceRange(),
8918                              getLocationOfByte(Amt.getStart()),
8919                              /*IsStringLocation*/true,
8920                              getSpecifierRange(startSpecifier, specifierLen));
8921         // Don't do any more checking.  We will just emit
8922         // spurious errors.
8923         return false;
8924       }
8925     }
8926   }
8927   return true;
8928 }
8929 
8930 void CheckPrintfHandler::HandleInvalidAmount(
8931                                       const analyze_printf::PrintfSpecifier &FS,
8932                                       const analyze_printf::OptionalAmount &Amt,
8933                                       unsigned type,
8934                                       const char *startSpecifier,
8935                                       unsigned specifierLen) {
8936   const analyze_printf::PrintfConversionSpecifier &CS =
8937     FS.getConversionSpecifier();
8938 
8939   FixItHint fixit =
8940     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8941       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8942                                  Amt.getConstantLength()))
8943       : FixItHint();
8944 
8945   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8946                          << type << CS.toString(),
8947                        getLocationOfByte(Amt.getStart()),
8948                        /*IsStringLocation*/true,
8949                        getSpecifierRange(startSpecifier, specifierLen),
8950                        fixit);
8951 }
8952 
8953 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8954                                     const analyze_printf::OptionalFlag &flag,
8955                                     const char *startSpecifier,
8956                                     unsigned specifierLen) {
8957   // Warn about pointless flag with a fixit removal.
8958   const analyze_printf::PrintfConversionSpecifier &CS =
8959     FS.getConversionSpecifier();
8960   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8961                          << flag.toString() << CS.toString(),
8962                        getLocationOfByte(flag.getPosition()),
8963                        /*IsStringLocation*/true,
8964                        getSpecifierRange(startSpecifier, specifierLen),
8965                        FixItHint::CreateRemoval(
8966                          getSpecifierRange(flag.getPosition(), 1)));
8967 }
8968 
8969 void CheckPrintfHandler::HandleIgnoredFlag(
8970                                 const analyze_printf::PrintfSpecifier &FS,
8971                                 const analyze_printf::OptionalFlag &ignoredFlag,
8972                                 const analyze_printf::OptionalFlag &flag,
8973                                 const char *startSpecifier,
8974                                 unsigned specifierLen) {
8975   // Warn about ignored flag with a fixit removal.
8976   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8977                          << ignoredFlag.toString() << flag.toString(),
8978                        getLocationOfByte(ignoredFlag.getPosition()),
8979                        /*IsStringLocation*/true,
8980                        getSpecifierRange(startSpecifier, specifierLen),
8981                        FixItHint::CreateRemoval(
8982                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8983 }
8984 
8985 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8986                                                      unsigned flagLen) {
8987   // Warn about an empty flag.
8988   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8989                        getLocationOfByte(startFlag),
8990                        /*IsStringLocation*/true,
8991                        getSpecifierRange(startFlag, flagLen));
8992 }
8993 
8994 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8995                                                        unsigned flagLen) {
8996   // Warn about an invalid flag.
8997   auto Range = getSpecifierRange(startFlag, flagLen);
8998   StringRef flag(startFlag, flagLen);
8999   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9000                       getLocationOfByte(startFlag),
9001                       /*IsStringLocation*/true,
9002                       Range, FixItHint::CreateRemoval(Range));
9003 }
9004 
9005 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9006     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9007     // Warn about using '[...]' without a '@' conversion.
9008     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9009     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9010     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9011                          getLocationOfByte(conversionPosition),
9012                          /*IsStringLocation*/true,
9013                          Range, FixItHint::CreateRemoval(Range));
9014 }
9015 
9016 // Determines if the specified is a C++ class or struct containing
9017 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9018 // "c_str()").
9019 template<typename MemberKind>
9020 static llvm::SmallPtrSet<MemberKind*, 1>
9021 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9022   const RecordType *RT = Ty->getAs<RecordType>();
9023   llvm::SmallPtrSet<MemberKind*, 1> Results;
9024 
9025   if (!RT)
9026     return Results;
9027   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9028   if (!RD || !RD->getDefinition())
9029     return Results;
9030 
9031   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9032                  Sema::LookupMemberName);
9033   R.suppressDiagnostics();
9034 
9035   // We just need to include all members of the right kind turned up by the
9036   // filter, at this point.
9037   if (S.LookupQualifiedName(R, RT->getDecl()))
9038     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9039       NamedDecl *decl = (*I)->getUnderlyingDecl();
9040       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9041         Results.insert(FK);
9042     }
9043   return Results;
9044 }
9045 
9046 /// Check if we could call '.c_str()' on an object.
9047 ///
9048 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9049 /// allow the call, or if it would be ambiguous).
9050 bool Sema::hasCStrMethod(const Expr *E) {
9051   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9052 
9053   MethodSet Results =
9054       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9055   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9056        MI != ME; ++MI)
9057     if ((*MI)->getMinRequiredArguments() == 0)
9058       return true;
9059   return false;
9060 }
9061 
9062 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9063 // better diagnostic if so. AT is assumed to be valid.
9064 // Returns true when a c_str() conversion method is found.
9065 bool CheckPrintfHandler::checkForCStrMembers(
9066     const analyze_printf::ArgType &AT, const Expr *E) {
9067   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9068 
9069   MethodSet Results =
9070       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9071 
9072   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9073        MI != ME; ++MI) {
9074     const CXXMethodDecl *Method = *MI;
9075     if (Method->getMinRequiredArguments() == 0 &&
9076         AT.matchesType(S.Context, Method->getReturnType())) {
9077       // FIXME: Suggest parens if the expression needs them.
9078       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9079       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9080           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9081       return true;
9082     }
9083   }
9084 
9085   return false;
9086 }
9087 
9088 bool
9089 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
9090                                             &FS,
9091                                           const char *startSpecifier,
9092                                           unsigned specifierLen) {
9093   using namespace analyze_format_string;
9094   using namespace analyze_printf;
9095 
9096   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9097 
9098   if (FS.consumesDataArgument()) {
9099     if (atFirstArg) {
9100         atFirstArg = false;
9101         usesPositionalArgs = FS.usesPositionalArg();
9102     }
9103     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9104       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9105                                         startSpecifier, specifierLen);
9106       return false;
9107     }
9108   }
9109 
9110   // First check if the field width, precision, and conversion specifier
9111   // have matching data arguments.
9112   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9113                     startSpecifier, specifierLen)) {
9114     return false;
9115   }
9116 
9117   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9118                     startSpecifier, specifierLen)) {
9119     return false;
9120   }
9121 
9122   if (!CS.consumesDataArgument()) {
9123     // FIXME: Technically specifying a precision or field width here
9124     // makes no sense.  Worth issuing a warning at some point.
9125     return true;
9126   }
9127 
9128   // Consume the argument.
9129   unsigned argIndex = FS.getArgIndex();
9130   if (argIndex < NumDataArgs) {
9131     // The check to see if the argIndex is valid will come later.
9132     // We set the bit here because we may exit early from this
9133     // function if we encounter some other error.
9134     CoveredArgs.set(argIndex);
9135   }
9136 
9137   // FreeBSD kernel extensions.
9138   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9139       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9140     // We need at least two arguments.
9141     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9142       return false;
9143 
9144     // Claim the second argument.
9145     CoveredArgs.set(argIndex + 1);
9146 
9147     // Type check the first argument (int for %b, pointer for %D)
9148     const Expr *Ex = getDataArg(argIndex);
9149     const analyze_printf::ArgType &AT =
9150       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9151         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9152     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9153       EmitFormatDiagnostic(
9154           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9155               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9156               << false << Ex->getSourceRange(),
9157           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9158           getSpecifierRange(startSpecifier, specifierLen));
9159 
9160     // Type check the second argument (char * for both %b and %D)
9161     Ex = getDataArg(argIndex + 1);
9162     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9163     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9164       EmitFormatDiagnostic(
9165           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9166               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9167               << false << Ex->getSourceRange(),
9168           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9169           getSpecifierRange(startSpecifier, specifierLen));
9170 
9171      return true;
9172   }
9173 
9174   // Check for using an Objective-C specific conversion specifier
9175   // in a non-ObjC literal.
9176   if (!allowsObjCArg() && CS.isObjCArg()) {
9177     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9178                                                   specifierLen);
9179   }
9180 
9181   // %P can only be used with os_log.
9182   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9183     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9184                                                   specifierLen);
9185   }
9186 
9187   // %n is not allowed with os_log.
9188   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9189     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9190                          getLocationOfByte(CS.getStart()),
9191                          /*IsStringLocation*/ false,
9192                          getSpecifierRange(startSpecifier, specifierLen));
9193 
9194     return true;
9195   }
9196 
9197   // Only scalars are allowed for os_trace.
9198   if (FSType == Sema::FST_OSTrace &&
9199       (CS.getKind() == ConversionSpecifier::PArg ||
9200        CS.getKind() == ConversionSpecifier::sArg ||
9201        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9202     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9203                                                   specifierLen);
9204   }
9205 
9206   // Check for use of public/private annotation outside of os_log().
9207   if (FSType != Sema::FST_OSLog) {
9208     if (FS.isPublic().isSet()) {
9209       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9210                                << "public",
9211                            getLocationOfByte(FS.isPublic().getPosition()),
9212                            /*IsStringLocation*/ false,
9213                            getSpecifierRange(startSpecifier, specifierLen));
9214     }
9215     if (FS.isPrivate().isSet()) {
9216       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9217                                << "private",
9218                            getLocationOfByte(FS.isPrivate().getPosition()),
9219                            /*IsStringLocation*/ false,
9220                            getSpecifierRange(startSpecifier, specifierLen));
9221     }
9222   }
9223 
9224   // Check for invalid use of field width
9225   if (!FS.hasValidFieldWidth()) {
9226     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9227         startSpecifier, specifierLen);
9228   }
9229 
9230   // Check for invalid use of precision
9231   if (!FS.hasValidPrecision()) {
9232     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9233         startSpecifier, specifierLen);
9234   }
9235 
9236   // Precision is mandatory for %P specifier.
9237   if (CS.getKind() == ConversionSpecifier::PArg &&
9238       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9239     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9240                          getLocationOfByte(startSpecifier),
9241                          /*IsStringLocation*/ false,
9242                          getSpecifierRange(startSpecifier, specifierLen));
9243   }
9244 
9245   // Check each flag does not conflict with any other component.
9246   if (!FS.hasValidThousandsGroupingPrefix())
9247     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9248   if (!FS.hasValidLeadingZeros())
9249     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9250   if (!FS.hasValidPlusPrefix())
9251     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9252   if (!FS.hasValidSpacePrefix())
9253     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9254   if (!FS.hasValidAlternativeForm())
9255     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9256   if (!FS.hasValidLeftJustified())
9257     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9258 
9259   // Check that flags are not ignored by another flag
9260   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9261     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9262         startSpecifier, specifierLen);
9263   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9264     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9265             startSpecifier, specifierLen);
9266 
9267   // Check the length modifier is valid with the given conversion specifier.
9268   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9269                                  S.getLangOpts()))
9270     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9271                                 diag::warn_format_nonsensical_length);
9272   else if (!FS.hasStandardLengthModifier())
9273     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9274   else if (!FS.hasStandardLengthConversionCombination())
9275     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9276                                 diag::warn_format_non_standard_conversion_spec);
9277 
9278   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9279     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9280 
9281   // The remaining checks depend on the data arguments.
9282   if (HasVAListArg)
9283     return true;
9284 
9285   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9286     return false;
9287 
9288   const Expr *Arg = getDataArg(argIndex);
9289   if (!Arg)
9290     return true;
9291 
9292   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9293 }
9294 
9295 static bool requiresParensToAddCast(const Expr *E) {
9296   // FIXME: We should have a general way to reason about operator
9297   // precedence and whether parens are actually needed here.
9298   // Take care of a few common cases where they aren't.
9299   const Expr *Inside = E->IgnoreImpCasts();
9300   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9301     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9302 
9303   switch (Inside->getStmtClass()) {
9304   case Stmt::ArraySubscriptExprClass:
9305   case Stmt::CallExprClass:
9306   case Stmt::CharacterLiteralClass:
9307   case Stmt::CXXBoolLiteralExprClass:
9308   case Stmt::DeclRefExprClass:
9309   case Stmt::FloatingLiteralClass:
9310   case Stmt::IntegerLiteralClass:
9311   case Stmt::MemberExprClass:
9312   case Stmt::ObjCArrayLiteralClass:
9313   case Stmt::ObjCBoolLiteralExprClass:
9314   case Stmt::ObjCBoxedExprClass:
9315   case Stmt::ObjCDictionaryLiteralClass:
9316   case Stmt::ObjCEncodeExprClass:
9317   case Stmt::ObjCIvarRefExprClass:
9318   case Stmt::ObjCMessageExprClass:
9319   case Stmt::ObjCPropertyRefExprClass:
9320   case Stmt::ObjCStringLiteralClass:
9321   case Stmt::ObjCSubscriptRefExprClass:
9322   case Stmt::ParenExprClass:
9323   case Stmt::StringLiteralClass:
9324   case Stmt::UnaryOperatorClass:
9325     return false;
9326   default:
9327     return true;
9328   }
9329 }
9330 
9331 static std::pair<QualType, StringRef>
9332 shouldNotPrintDirectly(const ASTContext &Context,
9333                        QualType IntendedTy,
9334                        const Expr *E) {
9335   // Use a 'while' to peel off layers of typedefs.
9336   QualType TyTy = IntendedTy;
9337   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9338     StringRef Name = UserTy->getDecl()->getName();
9339     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9340       .Case("CFIndex", Context.getNSIntegerType())
9341       .Case("NSInteger", Context.getNSIntegerType())
9342       .Case("NSUInteger", Context.getNSUIntegerType())
9343       .Case("SInt32", Context.IntTy)
9344       .Case("UInt32", Context.UnsignedIntTy)
9345       .Default(QualType());
9346 
9347     if (!CastTy.isNull())
9348       return std::make_pair(CastTy, Name);
9349 
9350     TyTy = UserTy->desugar();
9351   }
9352 
9353   // Strip parens if necessary.
9354   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9355     return shouldNotPrintDirectly(Context,
9356                                   PE->getSubExpr()->getType(),
9357                                   PE->getSubExpr());
9358 
9359   // If this is a conditional expression, then its result type is constructed
9360   // via usual arithmetic conversions and thus there might be no necessary
9361   // typedef sugar there.  Recurse to operands to check for NSInteger &
9362   // Co. usage condition.
9363   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9364     QualType TrueTy, FalseTy;
9365     StringRef TrueName, FalseName;
9366 
9367     std::tie(TrueTy, TrueName) =
9368       shouldNotPrintDirectly(Context,
9369                              CO->getTrueExpr()->getType(),
9370                              CO->getTrueExpr());
9371     std::tie(FalseTy, FalseName) =
9372       shouldNotPrintDirectly(Context,
9373                              CO->getFalseExpr()->getType(),
9374                              CO->getFalseExpr());
9375 
9376     if (TrueTy == FalseTy)
9377       return std::make_pair(TrueTy, TrueName);
9378     else if (TrueTy.isNull())
9379       return std::make_pair(FalseTy, FalseName);
9380     else if (FalseTy.isNull())
9381       return std::make_pair(TrueTy, TrueName);
9382   }
9383 
9384   return std::make_pair(QualType(), StringRef());
9385 }
9386 
9387 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9388 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9389 /// type do not count.
9390 static bool
9391 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9392   QualType From = ICE->getSubExpr()->getType();
9393   QualType To = ICE->getType();
9394   // It's an integer promotion if the destination type is the promoted
9395   // source type.
9396   if (ICE->getCastKind() == CK_IntegralCast &&
9397       From->isPromotableIntegerType() &&
9398       S.Context.getPromotedIntegerType(From) == To)
9399     return true;
9400   // Look through vector types, since we do default argument promotion for
9401   // those in OpenCL.
9402   if (const auto *VecTy = From->getAs<ExtVectorType>())
9403     From = VecTy->getElementType();
9404   if (const auto *VecTy = To->getAs<ExtVectorType>())
9405     To = VecTy->getElementType();
9406   // It's a floating promotion if the source type is a lower rank.
9407   return ICE->getCastKind() == CK_FloatingCast &&
9408          S.Context.getFloatingTypeOrder(From, To) < 0;
9409 }
9410 
9411 bool
9412 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9413                                     const char *StartSpecifier,
9414                                     unsigned SpecifierLen,
9415                                     const Expr *E) {
9416   using namespace analyze_format_string;
9417   using namespace analyze_printf;
9418 
9419   // Now type check the data expression that matches the
9420   // format specifier.
9421   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9422   if (!AT.isValid())
9423     return true;
9424 
9425   QualType ExprTy = E->getType();
9426   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9427     ExprTy = TET->getUnderlyingExpr()->getType();
9428   }
9429 
9430   // Diagnose attempts to print a boolean value as a character. Unlike other
9431   // -Wformat diagnostics, this is fine from a type perspective, but it still
9432   // doesn't make sense.
9433   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9434       E->isKnownToHaveBooleanValue()) {
9435     const CharSourceRange &CSR =
9436         getSpecifierRange(StartSpecifier, SpecifierLen);
9437     SmallString<4> FSString;
9438     llvm::raw_svector_ostream os(FSString);
9439     FS.toString(os);
9440     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9441                              << FSString,
9442                          E->getExprLoc(), false, CSR);
9443     return true;
9444   }
9445 
9446   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9447   if (Match == analyze_printf::ArgType::Match)
9448     return true;
9449 
9450   // Look through argument promotions for our error message's reported type.
9451   // This includes the integral and floating promotions, but excludes array
9452   // and function pointer decay (seeing that an argument intended to be a
9453   // string has type 'char [6]' is probably more confusing than 'char *') and
9454   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9455   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9456     if (isArithmeticArgumentPromotion(S, ICE)) {
9457       E = ICE->getSubExpr();
9458       ExprTy = E->getType();
9459 
9460       // Check if we didn't match because of an implicit cast from a 'char'
9461       // or 'short' to an 'int'.  This is done because printf is a varargs
9462       // function.
9463       if (ICE->getType() == S.Context.IntTy ||
9464           ICE->getType() == S.Context.UnsignedIntTy) {
9465         // All further checking is done on the subexpression
9466         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9467             AT.matchesType(S.Context, ExprTy);
9468         if (ImplicitMatch == analyze_printf::ArgType::Match)
9469           return true;
9470         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9471             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9472           Match = ImplicitMatch;
9473       }
9474     }
9475   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9476     // Special case for 'a', which has type 'int' in C.
9477     // Note, however, that we do /not/ want to treat multibyte constants like
9478     // 'MooV' as characters! This form is deprecated but still exists. In
9479     // addition, don't treat expressions as of type 'char' if one byte length
9480     // modifier is provided.
9481     if (ExprTy == S.Context.IntTy &&
9482         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9483       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9484         ExprTy = S.Context.CharTy;
9485   }
9486 
9487   // Look through enums to their underlying type.
9488   bool IsEnum = false;
9489   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9490     ExprTy = EnumTy->getDecl()->getIntegerType();
9491     IsEnum = true;
9492   }
9493 
9494   // %C in an Objective-C context prints a unichar, not a wchar_t.
9495   // If the argument is an integer of some kind, believe the %C and suggest
9496   // a cast instead of changing the conversion specifier.
9497   QualType IntendedTy = ExprTy;
9498   if (isObjCContext() &&
9499       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9500     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9501         !ExprTy->isCharType()) {
9502       // 'unichar' is defined as a typedef of unsigned short, but we should
9503       // prefer using the typedef if it is visible.
9504       IntendedTy = S.Context.UnsignedShortTy;
9505 
9506       // While we are here, check if the value is an IntegerLiteral that happens
9507       // to be within the valid range.
9508       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9509         const llvm::APInt &V = IL->getValue();
9510         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9511           return true;
9512       }
9513 
9514       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9515                           Sema::LookupOrdinaryName);
9516       if (S.LookupName(Result, S.getCurScope())) {
9517         NamedDecl *ND = Result.getFoundDecl();
9518         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9519           if (TD->getUnderlyingType() == IntendedTy)
9520             IntendedTy = S.Context.getTypedefType(TD);
9521       }
9522     }
9523   }
9524 
9525   // Special-case some of Darwin's platform-independence types by suggesting
9526   // casts to primitive types that are known to be large enough.
9527   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9528   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9529     QualType CastTy;
9530     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9531     if (!CastTy.isNull()) {
9532       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9533       // (long in ASTContext). Only complain to pedants.
9534       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9535           (AT.isSizeT() || AT.isPtrdiffT()) &&
9536           AT.matchesType(S.Context, CastTy))
9537         Match = ArgType::NoMatchPedantic;
9538       IntendedTy = CastTy;
9539       ShouldNotPrintDirectly = true;
9540     }
9541   }
9542 
9543   // We may be able to offer a FixItHint if it is a supported type.
9544   PrintfSpecifier fixedFS = FS;
9545   bool Success =
9546       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9547 
9548   if (Success) {
9549     // Get the fix string from the fixed format specifier
9550     SmallString<16> buf;
9551     llvm::raw_svector_ostream os(buf);
9552     fixedFS.toString(os);
9553 
9554     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9555 
9556     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9557       unsigned Diag;
9558       switch (Match) {
9559       case ArgType::Match: llvm_unreachable("expected non-matching");
9560       case ArgType::NoMatchPedantic:
9561         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9562         break;
9563       case ArgType::NoMatchTypeConfusion:
9564         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9565         break;
9566       case ArgType::NoMatch:
9567         Diag = diag::warn_format_conversion_argument_type_mismatch;
9568         break;
9569       }
9570 
9571       // In this case, the specifier is wrong and should be changed to match
9572       // the argument.
9573       EmitFormatDiagnostic(S.PDiag(Diag)
9574                                << AT.getRepresentativeTypeName(S.Context)
9575                                << IntendedTy << IsEnum << E->getSourceRange(),
9576                            E->getBeginLoc(),
9577                            /*IsStringLocation*/ false, SpecRange,
9578                            FixItHint::CreateReplacement(SpecRange, os.str()));
9579     } else {
9580       // The canonical type for formatting this value is different from the
9581       // actual type of the expression. (This occurs, for example, with Darwin's
9582       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9583       // should be printed as 'long' for 64-bit compatibility.)
9584       // Rather than emitting a normal format/argument mismatch, we want to
9585       // add a cast to the recommended type (and correct the format string
9586       // if necessary).
9587       SmallString<16> CastBuf;
9588       llvm::raw_svector_ostream CastFix(CastBuf);
9589       CastFix << "(";
9590       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9591       CastFix << ")";
9592 
9593       SmallVector<FixItHint,4> Hints;
9594       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9595         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9596 
9597       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9598         // If there's already a cast present, just replace it.
9599         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9600         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9601 
9602       } else if (!requiresParensToAddCast(E)) {
9603         // If the expression has high enough precedence,
9604         // just write the C-style cast.
9605         Hints.push_back(
9606             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9607       } else {
9608         // Otherwise, add parens around the expression as well as the cast.
9609         CastFix << "(";
9610         Hints.push_back(
9611             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9612 
9613         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9614         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9615       }
9616 
9617       if (ShouldNotPrintDirectly) {
9618         // The expression has a type that should not be printed directly.
9619         // We extract the name from the typedef because we don't want to show
9620         // the underlying type in the diagnostic.
9621         StringRef Name;
9622         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9623           Name = TypedefTy->getDecl()->getName();
9624         else
9625           Name = CastTyName;
9626         unsigned Diag = Match == ArgType::NoMatchPedantic
9627                             ? diag::warn_format_argument_needs_cast_pedantic
9628                             : diag::warn_format_argument_needs_cast;
9629         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9630                                            << E->getSourceRange(),
9631                              E->getBeginLoc(), /*IsStringLocation=*/false,
9632                              SpecRange, Hints);
9633       } else {
9634         // In this case, the expression could be printed using a different
9635         // specifier, but we've decided that the specifier is probably correct
9636         // and we should cast instead. Just use the normal warning message.
9637         EmitFormatDiagnostic(
9638             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9639                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9640                 << E->getSourceRange(),
9641             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9642       }
9643     }
9644   } else {
9645     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9646                                                    SpecifierLen);
9647     // Since the warning for passing non-POD types to variadic functions
9648     // was deferred until now, we emit a warning for non-POD
9649     // arguments here.
9650     switch (S.isValidVarArgType(ExprTy)) {
9651     case Sema::VAK_Valid:
9652     case Sema::VAK_ValidInCXX11: {
9653       unsigned Diag;
9654       switch (Match) {
9655       case ArgType::Match: llvm_unreachable("expected non-matching");
9656       case ArgType::NoMatchPedantic:
9657         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9658         break;
9659       case ArgType::NoMatchTypeConfusion:
9660         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9661         break;
9662       case ArgType::NoMatch:
9663         Diag = diag::warn_format_conversion_argument_type_mismatch;
9664         break;
9665       }
9666 
9667       EmitFormatDiagnostic(
9668           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9669                         << IsEnum << CSR << E->getSourceRange(),
9670           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9671       break;
9672     }
9673     case Sema::VAK_Undefined:
9674     case Sema::VAK_MSVCUndefined:
9675       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9676                                << S.getLangOpts().CPlusPlus11 << ExprTy
9677                                << CallType
9678                                << AT.getRepresentativeTypeName(S.Context) << CSR
9679                                << E->getSourceRange(),
9680                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9681       checkForCStrMembers(AT, E);
9682       break;
9683 
9684     case Sema::VAK_Invalid:
9685       if (ExprTy->isObjCObjectType())
9686         EmitFormatDiagnostic(
9687             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9688                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9689                 << AT.getRepresentativeTypeName(S.Context) << CSR
9690                 << E->getSourceRange(),
9691             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9692       else
9693         // FIXME: If this is an initializer list, suggest removing the braces
9694         // or inserting a cast to the target type.
9695         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9696             << isa<InitListExpr>(E) << ExprTy << CallType
9697             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9698       break;
9699     }
9700 
9701     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9702            "format string specifier index out of range");
9703     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9704   }
9705 
9706   return true;
9707 }
9708 
9709 //===--- CHECK: Scanf format string checking ------------------------------===//
9710 
9711 namespace {
9712 
9713 class CheckScanfHandler : public CheckFormatHandler {
9714 public:
9715   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9716                     const Expr *origFormatExpr, Sema::FormatStringType type,
9717                     unsigned firstDataArg, unsigned numDataArgs,
9718                     const char *beg, bool hasVAListArg,
9719                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9720                     bool inFunctionCall, Sema::VariadicCallType CallType,
9721                     llvm::SmallBitVector &CheckedVarArgs,
9722                     UncoveredArgHandler &UncoveredArg)
9723       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9724                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9725                            inFunctionCall, CallType, CheckedVarArgs,
9726                            UncoveredArg) {}
9727 
9728   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9729                             const char *startSpecifier,
9730                             unsigned specifierLen) override;
9731 
9732   bool HandleInvalidScanfConversionSpecifier(
9733           const analyze_scanf::ScanfSpecifier &FS,
9734           const char *startSpecifier,
9735           unsigned specifierLen) override;
9736 
9737   void HandleIncompleteScanList(const char *start, const char *end) override;
9738 };
9739 
9740 } // namespace
9741 
9742 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9743                                                  const char *end) {
9744   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9745                        getLocationOfByte(end), /*IsStringLocation*/true,
9746                        getSpecifierRange(start, end - start));
9747 }
9748 
9749 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9750                                         const analyze_scanf::ScanfSpecifier &FS,
9751                                         const char *startSpecifier,
9752                                         unsigned specifierLen) {
9753   const analyze_scanf::ScanfConversionSpecifier &CS =
9754     FS.getConversionSpecifier();
9755 
9756   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9757                                           getLocationOfByte(CS.getStart()),
9758                                           startSpecifier, specifierLen,
9759                                           CS.getStart(), CS.getLength());
9760 }
9761 
9762 bool CheckScanfHandler::HandleScanfSpecifier(
9763                                        const analyze_scanf::ScanfSpecifier &FS,
9764                                        const char *startSpecifier,
9765                                        unsigned specifierLen) {
9766   using namespace analyze_scanf;
9767   using namespace analyze_format_string;
9768 
9769   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9770 
9771   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9772   // be used to decide if we are using positional arguments consistently.
9773   if (FS.consumesDataArgument()) {
9774     if (atFirstArg) {
9775       atFirstArg = false;
9776       usesPositionalArgs = FS.usesPositionalArg();
9777     }
9778     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9779       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9780                                         startSpecifier, specifierLen);
9781       return false;
9782     }
9783   }
9784 
9785   // Check if the field with is non-zero.
9786   const OptionalAmount &Amt = FS.getFieldWidth();
9787   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9788     if (Amt.getConstantAmount() == 0) {
9789       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9790                                                    Amt.getConstantLength());
9791       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9792                            getLocationOfByte(Amt.getStart()),
9793                            /*IsStringLocation*/true, R,
9794                            FixItHint::CreateRemoval(R));
9795     }
9796   }
9797 
9798   if (!FS.consumesDataArgument()) {
9799     // FIXME: Technically specifying a precision or field width here
9800     // makes no sense.  Worth issuing a warning at some point.
9801     return true;
9802   }
9803 
9804   // Consume the argument.
9805   unsigned argIndex = FS.getArgIndex();
9806   if (argIndex < NumDataArgs) {
9807       // The check to see if the argIndex is valid will come later.
9808       // We set the bit here because we may exit early from this
9809       // function if we encounter some other error.
9810     CoveredArgs.set(argIndex);
9811   }
9812 
9813   // Check the length modifier is valid with the given conversion specifier.
9814   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9815                                  S.getLangOpts()))
9816     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9817                                 diag::warn_format_nonsensical_length);
9818   else if (!FS.hasStandardLengthModifier())
9819     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9820   else if (!FS.hasStandardLengthConversionCombination())
9821     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9822                                 diag::warn_format_non_standard_conversion_spec);
9823 
9824   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9825     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9826 
9827   // The remaining checks depend on the data arguments.
9828   if (HasVAListArg)
9829     return true;
9830 
9831   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9832     return false;
9833 
9834   // Check that the argument type matches the format specifier.
9835   const Expr *Ex = getDataArg(argIndex);
9836   if (!Ex)
9837     return true;
9838 
9839   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9840 
9841   if (!AT.isValid()) {
9842     return true;
9843   }
9844 
9845   analyze_format_string::ArgType::MatchKind Match =
9846       AT.matchesType(S.Context, Ex->getType());
9847   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9848   if (Match == analyze_format_string::ArgType::Match)
9849     return true;
9850 
9851   ScanfSpecifier fixedFS = FS;
9852   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9853                                  S.getLangOpts(), S.Context);
9854 
9855   unsigned Diag =
9856       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9857                : diag::warn_format_conversion_argument_type_mismatch;
9858 
9859   if (Success) {
9860     // Get the fix string from the fixed format specifier.
9861     SmallString<128> buf;
9862     llvm::raw_svector_ostream os(buf);
9863     fixedFS.toString(os);
9864 
9865     EmitFormatDiagnostic(
9866         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9867                       << Ex->getType() << false << Ex->getSourceRange(),
9868         Ex->getBeginLoc(),
9869         /*IsStringLocation*/ false,
9870         getSpecifierRange(startSpecifier, specifierLen),
9871         FixItHint::CreateReplacement(
9872             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9873   } else {
9874     EmitFormatDiagnostic(S.PDiag(Diag)
9875                              << AT.getRepresentativeTypeName(S.Context)
9876                              << Ex->getType() << false << Ex->getSourceRange(),
9877                          Ex->getBeginLoc(),
9878                          /*IsStringLocation*/ false,
9879                          getSpecifierRange(startSpecifier, specifierLen));
9880   }
9881 
9882   return true;
9883 }
9884 
9885 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9886                               const Expr *OrigFormatExpr,
9887                               ArrayRef<const Expr *> Args,
9888                               bool HasVAListArg, unsigned format_idx,
9889                               unsigned firstDataArg,
9890                               Sema::FormatStringType Type,
9891                               bool inFunctionCall,
9892                               Sema::VariadicCallType CallType,
9893                               llvm::SmallBitVector &CheckedVarArgs,
9894                               UncoveredArgHandler &UncoveredArg,
9895                               bool IgnoreStringsWithoutSpecifiers) {
9896   // CHECK: is the format string a wide literal?
9897   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9898     CheckFormatHandler::EmitFormatDiagnostic(
9899         S, inFunctionCall, Args[format_idx],
9900         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9901         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9902     return;
9903   }
9904 
9905   // Str - The format string.  NOTE: this is NOT null-terminated!
9906   StringRef StrRef = FExpr->getString();
9907   const char *Str = StrRef.data();
9908   // Account for cases where the string literal is truncated in a declaration.
9909   const ConstantArrayType *T =
9910     S.Context.getAsConstantArrayType(FExpr->getType());
9911   assert(T && "String literal not of constant array type!");
9912   size_t TypeSize = T->getSize().getZExtValue();
9913   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9914   const unsigned numDataArgs = Args.size() - firstDataArg;
9915 
9916   if (IgnoreStringsWithoutSpecifiers &&
9917       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9918           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9919     return;
9920 
9921   // Emit a warning if the string literal is truncated and does not contain an
9922   // embedded null character.
9923   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9924     CheckFormatHandler::EmitFormatDiagnostic(
9925         S, inFunctionCall, Args[format_idx],
9926         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9927         FExpr->getBeginLoc(),
9928         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9929     return;
9930   }
9931 
9932   // CHECK: empty format string?
9933   if (StrLen == 0 && numDataArgs > 0) {
9934     CheckFormatHandler::EmitFormatDiagnostic(
9935         S, inFunctionCall, Args[format_idx],
9936         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9937         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9938     return;
9939   }
9940 
9941   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9942       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9943       Type == Sema::FST_OSTrace) {
9944     CheckPrintfHandler H(
9945         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9946         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9947         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9948         CheckedVarArgs, UncoveredArg);
9949 
9950     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9951                                                   S.getLangOpts(),
9952                                                   S.Context.getTargetInfo(),
9953                                             Type == Sema::FST_FreeBSDKPrintf))
9954       H.DoneProcessing();
9955   } else if (Type == Sema::FST_Scanf) {
9956     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9957                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9958                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9959 
9960     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9961                                                  S.getLangOpts(),
9962                                                  S.Context.getTargetInfo()))
9963       H.DoneProcessing();
9964   } // TODO: handle other formats
9965 }
9966 
9967 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9968   // Str - The format string.  NOTE: this is NOT null-terminated!
9969   StringRef StrRef = FExpr->getString();
9970   const char *Str = StrRef.data();
9971   // Account for cases where the string literal is truncated in a declaration.
9972   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9973   assert(T && "String literal not of constant array type!");
9974   size_t TypeSize = T->getSize().getZExtValue();
9975   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9976   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9977                                                          getLangOpts(),
9978                                                          Context.getTargetInfo());
9979 }
9980 
9981 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9982 
9983 // Returns the related absolute value function that is larger, of 0 if one
9984 // does not exist.
9985 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9986   switch (AbsFunction) {
9987   default:
9988     return 0;
9989 
9990   case Builtin::BI__builtin_abs:
9991     return Builtin::BI__builtin_labs;
9992   case Builtin::BI__builtin_labs:
9993     return Builtin::BI__builtin_llabs;
9994   case Builtin::BI__builtin_llabs:
9995     return 0;
9996 
9997   case Builtin::BI__builtin_fabsf:
9998     return Builtin::BI__builtin_fabs;
9999   case Builtin::BI__builtin_fabs:
10000     return Builtin::BI__builtin_fabsl;
10001   case Builtin::BI__builtin_fabsl:
10002     return 0;
10003 
10004   case Builtin::BI__builtin_cabsf:
10005     return Builtin::BI__builtin_cabs;
10006   case Builtin::BI__builtin_cabs:
10007     return Builtin::BI__builtin_cabsl;
10008   case Builtin::BI__builtin_cabsl:
10009     return 0;
10010 
10011   case Builtin::BIabs:
10012     return Builtin::BIlabs;
10013   case Builtin::BIlabs:
10014     return Builtin::BIllabs;
10015   case Builtin::BIllabs:
10016     return 0;
10017 
10018   case Builtin::BIfabsf:
10019     return Builtin::BIfabs;
10020   case Builtin::BIfabs:
10021     return Builtin::BIfabsl;
10022   case Builtin::BIfabsl:
10023     return 0;
10024 
10025   case Builtin::BIcabsf:
10026    return Builtin::BIcabs;
10027   case Builtin::BIcabs:
10028     return Builtin::BIcabsl;
10029   case Builtin::BIcabsl:
10030     return 0;
10031   }
10032 }
10033 
10034 // Returns the argument type of the absolute value function.
10035 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10036                                              unsigned AbsType) {
10037   if (AbsType == 0)
10038     return QualType();
10039 
10040   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10041   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10042   if (Error != ASTContext::GE_None)
10043     return QualType();
10044 
10045   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10046   if (!FT)
10047     return QualType();
10048 
10049   if (FT->getNumParams() != 1)
10050     return QualType();
10051 
10052   return FT->getParamType(0);
10053 }
10054 
10055 // Returns the best absolute value function, or zero, based on type and
10056 // current absolute value function.
10057 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10058                                    unsigned AbsFunctionKind) {
10059   unsigned BestKind = 0;
10060   uint64_t ArgSize = Context.getTypeSize(ArgType);
10061   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10062        Kind = getLargerAbsoluteValueFunction(Kind)) {
10063     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10064     if (Context.getTypeSize(ParamType) >= ArgSize) {
10065       if (BestKind == 0)
10066         BestKind = Kind;
10067       else if (Context.hasSameType(ParamType, ArgType)) {
10068         BestKind = Kind;
10069         break;
10070       }
10071     }
10072   }
10073   return BestKind;
10074 }
10075 
10076 enum AbsoluteValueKind {
10077   AVK_Integer,
10078   AVK_Floating,
10079   AVK_Complex
10080 };
10081 
10082 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10083   if (T->isIntegralOrEnumerationType())
10084     return AVK_Integer;
10085   if (T->isRealFloatingType())
10086     return AVK_Floating;
10087   if (T->isAnyComplexType())
10088     return AVK_Complex;
10089 
10090   llvm_unreachable("Type not integer, floating, or complex");
10091 }
10092 
10093 // Changes the absolute value function to a different type.  Preserves whether
10094 // the function is a builtin.
10095 static unsigned changeAbsFunction(unsigned AbsKind,
10096                                   AbsoluteValueKind ValueKind) {
10097   switch (ValueKind) {
10098   case AVK_Integer:
10099     switch (AbsKind) {
10100     default:
10101       return 0;
10102     case Builtin::BI__builtin_fabsf:
10103     case Builtin::BI__builtin_fabs:
10104     case Builtin::BI__builtin_fabsl:
10105     case Builtin::BI__builtin_cabsf:
10106     case Builtin::BI__builtin_cabs:
10107     case Builtin::BI__builtin_cabsl:
10108       return Builtin::BI__builtin_abs;
10109     case Builtin::BIfabsf:
10110     case Builtin::BIfabs:
10111     case Builtin::BIfabsl:
10112     case Builtin::BIcabsf:
10113     case Builtin::BIcabs:
10114     case Builtin::BIcabsl:
10115       return Builtin::BIabs;
10116     }
10117   case AVK_Floating:
10118     switch (AbsKind) {
10119     default:
10120       return 0;
10121     case Builtin::BI__builtin_abs:
10122     case Builtin::BI__builtin_labs:
10123     case Builtin::BI__builtin_llabs:
10124     case Builtin::BI__builtin_cabsf:
10125     case Builtin::BI__builtin_cabs:
10126     case Builtin::BI__builtin_cabsl:
10127       return Builtin::BI__builtin_fabsf;
10128     case Builtin::BIabs:
10129     case Builtin::BIlabs:
10130     case Builtin::BIllabs:
10131     case Builtin::BIcabsf:
10132     case Builtin::BIcabs:
10133     case Builtin::BIcabsl:
10134       return Builtin::BIfabsf;
10135     }
10136   case AVK_Complex:
10137     switch (AbsKind) {
10138     default:
10139       return 0;
10140     case Builtin::BI__builtin_abs:
10141     case Builtin::BI__builtin_labs:
10142     case Builtin::BI__builtin_llabs:
10143     case Builtin::BI__builtin_fabsf:
10144     case Builtin::BI__builtin_fabs:
10145     case Builtin::BI__builtin_fabsl:
10146       return Builtin::BI__builtin_cabsf;
10147     case Builtin::BIabs:
10148     case Builtin::BIlabs:
10149     case Builtin::BIllabs:
10150     case Builtin::BIfabsf:
10151     case Builtin::BIfabs:
10152     case Builtin::BIfabsl:
10153       return Builtin::BIcabsf;
10154     }
10155   }
10156   llvm_unreachable("Unable to convert function");
10157 }
10158 
10159 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10160   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10161   if (!FnInfo)
10162     return 0;
10163 
10164   switch (FDecl->getBuiltinID()) {
10165   default:
10166     return 0;
10167   case Builtin::BI__builtin_abs:
10168   case Builtin::BI__builtin_fabs:
10169   case Builtin::BI__builtin_fabsf:
10170   case Builtin::BI__builtin_fabsl:
10171   case Builtin::BI__builtin_labs:
10172   case Builtin::BI__builtin_llabs:
10173   case Builtin::BI__builtin_cabs:
10174   case Builtin::BI__builtin_cabsf:
10175   case Builtin::BI__builtin_cabsl:
10176   case Builtin::BIabs:
10177   case Builtin::BIlabs:
10178   case Builtin::BIllabs:
10179   case Builtin::BIfabs:
10180   case Builtin::BIfabsf:
10181   case Builtin::BIfabsl:
10182   case Builtin::BIcabs:
10183   case Builtin::BIcabsf:
10184   case Builtin::BIcabsl:
10185     return FDecl->getBuiltinID();
10186   }
10187   llvm_unreachable("Unknown Builtin type");
10188 }
10189 
10190 // If the replacement is valid, emit a note with replacement function.
10191 // Additionally, suggest including the proper header if not already included.
10192 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10193                             unsigned AbsKind, QualType ArgType) {
10194   bool EmitHeaderHint = true;
10195   const char *HeaderName = nullptr;
10196   const char *FunctionName = nullptr;
10197   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10198     FunctionName = "std::abs";
10199     if (ArgType->isIntegralOrEnumerationType()) {
10200       HeaderName = "cstdlib";
10201     } else if (ArgType->isRealFloatingType()) {
10202       HeaderName = "cmath";
10203     } else {
10204       llvm_unreachable("Invalid Type");
10205     }
10206 
10207     // Lookup all std::abs
10208     if (NamespaceDecl *Std = S.getStdNamespace()) {
10209       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10210       R.suppressDiagnostics();
10211       S.LookupQualifiedName(R, Std);
10212 
10213       for (const auto *I : R) {
10214         const FunctionDecl *FDecl = nullptr;
10215         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10216           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10217         } else {
10218           FDecl = dyn_cast<FunctionDecl>(I);
10219         }
10220         if (!FDecl)
10221           continue;
10222 
10223         // Found std::abs(), check that they are the right ones.
10224         if (FDecl->getNumParams() != 1)
10225           continue;
10226 
10227         // Check that the parameter type can handle the argument.
10228         QualType ParamType = FDecl->getParamDecl(0)->getType();
10229         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10230             S.Context.getTypeSize(ArgType) <=
10231                 S.Context.getTypeSize(ParamType)) {
10232           // Found a function, don't need the header hint.
10233           EmitHeaderHint = false;
10234           break;
10235         }
10236       }
10237     }
10238   } else {
10239     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10240     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10241 
10242     if (HeaderName) {
10243       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10244       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10245       R.suppressDiagnostics();
10246       S.LookupName(R, S.getCurScope());
10247 
10248       if (R.isSingleResult()) {
10249         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10250         if (FD && FD->getBuiltinID() == AbsKind) {
10251           EmitHeaderHint = false;
10252         } else {
10253           return;
10254         }
10255       } else if (!R.empty()) {
10256         return;
10257       }
10258     }
10259   }
10260 
10261   S.Diag(Loc, diag::note_replace_abs_function)
10262       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10263 
10264   if (!HeaderName)
10265     return;
10266 
10267   if (!EmitHeaderHint)
10268     return;
10269 
10270   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10271                                                     << FunctionName;
10272 }
10273 
10274 template <std::size_t StrLen>
10275 static bool IsStdFunction(const FunctionDecl *FDecl,
10276                           const char (&Str)[StrLen]) {
10277   if (!FDecl)
10278     return false;
10279   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10280     return false;
10281   if (!FDecl->isInStdNamespace())
10282     return false;
10283 
10284   return true;
10285 }
10286 
10287 // Warn when using the wrong abs() function.
10288 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10289                                       const FunctionDecl *FDecl) {
10290   if (Call->getNumArgs() != 1)
10291     return;
10292 
10293   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10294   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10295   if (AbsKind == 0 && !IsStdAbs)
10296     return;
10297 
10298   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10299   QualType ParamType = Call->getArg(0)->getType();
10300 
10301   // Unsigned types cannot be negative.  Suggest removing the absolute value
10302   // function call.
10303   if (ArgType->isUnsignedIntegerType()) {
10304     const char *FunctionName =
10305         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10306     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10307     Diag(Call->getExprLoc(), diag::note_remove_abs)
10308         << FunctionName
10309         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10310     return;
10311   }
10312 
10313   // Taking the absolute value of a pointer is very suspicious, they probably
10314   // wanted to index into an array, dereference a pointer, call a function, etc.
10315   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10316     unsigned DiagType = 0;
10317     if (ArgType->isFunctionType())
10318       DiagType = 1;
10319     else if (ArgType->isArrayType())
10320       DiagType = 2;
10321 
10322     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10323     return;
10324   }
10325 
10326   // std::abs has overloads which prevent most of the absolute value problems
10327   // from occurring.
10328   if (IsStdAbs)
10329     return;
10330 
10331   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10332   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10333 
10334   // The argument and parameter are the same kind.  Check if they are the right
10335   // size.
10336   if (ArgValueKind == ParamValueKind) {
10337     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10338       return;
10339 
10340     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10341     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10342         << FDecl << ArgType << ParamType;
10343 
10344     if (NewAbsKind == 0)
10345       return;
10346 
10347     emitReplacement(*this, Call->getExprLoc(),
10348                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10349     return;
10350   }
10351 
10352   // ArgValueKind != ParamValueKind
10353   // The wrong type of absolute value function was used.  Attempt to find the
10354   // proper one.
10355   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10356   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10357   if (NewAbsKind == 0)
10358     return;
10359 
10360   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10361       << FDecl << ParamValueKind << ArgValueKind;
10362 
10363   emitReplacement(*this, Call->getExprLoc(),
10364                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10365 }
10366 
10367 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10368 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10369                                 const FunctionDecl *FDecl) {
10370   if (!Call || !FDecl) return;
10371 
10372   // Ignore template specializations and macros.
10373   if (inTemplateInstantiation()) return;
10374   if (Call->getExprLoc().isMacroID()) return;
10375 
10376   // Only care about the one template argument, two function parameter std::max
10377   if (Call->getNumArgs() != 2) return;
10378   if (!IsStdFunction(FDecl, "max")) return;
10379   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10380   if (!ArgList) return;
10381   if (ArgList->size() != 1) return;
10382 
10383   // Check that template type argument is unsigned integer.
10384   const auto& TA = ArgList->get(0);
10385   if (TA.getKind() != TemplateArgument::Type) return;
10386   QualType ArgType = TA.getAsType();
10387   if (!ArgType->isUnsignedIntegerType()) return;
10388 
10389   // See if either argument is a literal zero.
10390   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10391     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10392     if (!MTE) return false;
10393     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10394     if (!Num) return false;
10395     if (Num->getValue() != 0) return false;
10396     return true;
10397   };
10398 
10399   const Expr *FirstArg = Call->getArg(0);
10400   const Expr *SecondArg = Call->getArg(1);
10401   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10402   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10403 
10404   // Only warn when exactly one argument is zero.
10405   if (IsFirstArgZero == IsSecondArgZero) return;
10406 
10407   SourceRange FirstRange = FirstArg->getSourceRange();
10408   SourceRange SecondRange = SecondArg->getSourceRange();
10409 
10410   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10411 
10412   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10413       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10414 
10415   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10416   SourceRange RemovalRange;
10417   if (IsFirstArgZero) {
10418     RemovalRange = SourceRange(FirstRange.getBegin(),
10419                                SecondRange.getBegin().getLocWithOffset(-1));
10420   } else {
10421     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10422                                SecondRange.getEnd());
10423   }
10424 
10425   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10426         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10427         << FixItHint::CreateRemoval(RemovalRange);
10428 }
10429 
10430 //===--- CHECK: Standard memory functions ---------------------------------===//
10431 
10432 /// Takes the expression passed to the size_t parameter of functions
10433 /// such as memcmp, strncat, etc and warns if it's a comparison.
10434 ///
10435 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10436 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10437                                            IdentifierInfo *FnName,
10438                                            SourceLocation FnLoc,
10439                                            SourceLocation RParenLoc) {
10440   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10441   if (!Size)
10442     return false;
10443 
10444   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10445   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10446     return false;
10447 
10448   SourceRange SizeRange = Size->getSourceRange();
10449   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10450       << SizeRange << FnName;
10451   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10452       << FnName
10453       << FixItHint::CreateInsertion(
10454              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10455       << FixItHint::CreateRemoval(RParenLoc);
10456   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10457       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10458       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10459                                     ")");
10460 
10461   return true;
10462 }
10463 
10464 /// Determine whether the given type is or contains a dynamic class type
10465 /// (e.g., whether it has a vtable).
10466 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10467                                                      bool &IsContained) {
10468   // Look through array types while ignoring qualifiers.
10469   const Type *Ty = T->getBaseElementTypeUnsafe();
10470   IsContained = false;
10471 
10472   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10473   RD = RD ? RD->getDefinition() : nullptr;
10474   if (!RD || RD->isInvalidDecl())
10475     return nullptr;
10476 
10477   if (RD->isDynamicClass())
10478     return RD;
10479 
10480   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10481   // It's impossible for a class to transitively contain itself by value, so
10482   // infinite recursion is impossible.
10483   for (auto *FD : RD->fields()) {
10484     bool SubContained;
10485     if (const CXXRecordDecl *ContainedRD =
10486             getContainedDynamicClass(FD->getType(), SubContained)) {
10487       IsContained = true;
10488       return ContainedRD;
10489     }
10490   }
10491 
10492   return nullptr;
10493 }
10494 
10495 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10496   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10497     if (Unary->getKind() == UETT_SizeOf)
10498       return Unary;
10499   return nullptr;
10500 }
10501 
10502 /// If E is a sizeof expression, returns its argument expression,
10503 /// otherwise returns NULL.
10504 static const Expr *getSizeOfExprArg(const Expr *E) {
10505   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10506     if (!SizeOf->isArgumentType())
10507       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10508   return nullptr;
10509 }
10510 
10511 /// If E is a sizeof expression, returns its argument type.
10512 static QualType getSizeOfArgType(const Expr *E) {
10513   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10514     return SizeOf->getTypeOfArgument();
10515   return QualType();
10516 }
10517 
10518 namespace {
10519 
10520 struct SearchNonTrivialToInitializeField
10521     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10522   using Super =
10523       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10524 
10525   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10526 
10527   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10528                      SourceLocation SL) {
10529     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10530       asDerived().visitArray(PDIK, AT, SL);
10531       return;
10532     }
10533 
10534     Super::visitWithKind(PDIK, FT, SL);
10535   }
10536 
10537   void visitARCStrong(QualType FT, SourceLocation SL) {
10538     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10539   }
10540   void visitARCWeak(QualType FT, SourceLocation SL) {
10541     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10542   }
10543   void visitStruct(QualType FT, SourceLocation SL) {
10544     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10545       visit(FD->getType(), FD->getLocation());
10546   }
10547   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10548                   const ArrayType *AT, SourceLocation SL) {
10549     visit(getContext().getBaseElementType(AT), SL);
10550   }
10551   void visitTrivial(QualType FT, SourceLocation SL) {}
10552 
10553   static void diag(QualType RT, const Expr *E, Sema &S) {
10554     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10555   }
10556 
10557   ASTContext &getContext() { return S.getASTContext(); }
10558 
10559   const Expr *E;
10560   Sema &S;
10561 };
10562 
10563 struct SearchNonTrivialToCopyField
10564     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10565   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10566 
10567   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10568 
10569   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10570                      SourceLocation SL) {
10571     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10572       asDerived().visitArray(PCK, AT, SL);
10573       return;
10574     }
10575 
10576     Super::visitWithKind(PCK, FT, SL);
10577   }
10578 
10579   void visitARCStrong(QualType FT, SourceLocation SL) {
10580     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10581   }
10582   void visitARCWeak(QualType FT, SourceLocation SL) {
10583     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10584   }
10585   void visitStruct(QualType FT, SourceLocation SL) {
10586     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10587       visit(FD->getType(), FD->getLocation());
10588   }
10589   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10590                   SourceLocation SL) {
10591     visit(getContext().getBaseElementType(AT), SL);
10592   }
10593   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10594                 SourceLocation SL) {}
10595   void visitTrivial(QualType FT, SourceLocation SL) {}
10596   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10597 
10598   static void diag(QualType RT, const Expr *E, Sema &S) {
10599     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10600   }
10601 
10602   ASTContext &getContext() { return S.getASTContext(); }
10603 
10604   const Expr *E;
10605   Sema &S;
10606 };
10607 
10608 }
10609 
10610 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10611 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10612   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10613 
10614   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10615     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10616       return false;
10617 
10618     return doesExprLikelyComputeSize(BO->getLHS()) ||
10619            doesExprLikelyComputeSize(BO->getRHS());
10620   }
10621 
10622   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10623 }
10624 
10625 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10626 ///
10627 /// \code
10628 ///   #define MACRO 0
10629 ///   foo(MACRO);
10630 ///   foo(0);
10631 /// \endcode
10632 ///
10633 /// This should return true for the first call to foo, but not for the second
10634 /// (regardless of whether foo is a macro or function).
10635 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10636                                         SourceLocation CallLoc,
10637                                         SourceLocation ArgLoc) {
10638   if (!CallLoc.isMacroID())
10639     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10640 
10641   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10642          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10643 }
10644 
10645 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10646 /// last two arguments transposed.
10647 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10648   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10649     return;
10650 
10651   const Expr *SizeArg =
10652     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10653 
10654   auto isLiteralZero = [](const Expr *E) {
10655     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10656   };
10657 
10658   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10659   SourceLocation CallLoc = Call->getRParenLoc();
10660   SourceManager &SM = S.getSourceManager();
10661   if (isLiteralZero(SizeArg) &&
10662       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10663 
10664     SourceLocation DiagLoc = SizeArg->getExprLoc();
10665 
10666     // Some platforms #define bzero to __builtin_memset. See if this is the
10667     // case, and if so, emit a better diagnostic.
10668     if (BId == Builtin::BIbzero ||
10669         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10670                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10671       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10672       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10673     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10674       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10675       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10676     }
10677     return;
10678   }
10679 
10680   // If the second argument to a memset is a sizeof expression and the third
10681   // isn't, this is also likely an error. This should catch
10682   // 'memset(buf, sizeof(buf), 0xff)'.
10683   if (BId == Builtin::BImemset &&
10684       doesExprLikelyComputeSize(Call->getArg(1)) &&
10685       !doesExprLikelyComputeSize(Call->getArg(2))) {
10686     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10687     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10688     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10689     return;
10690   }
10691 }
10692 
10693 /// Check for dangerous or invalid arguments to memset().
10694 ///
10695 /// This issues warnings on known problematic, dangerous or unspecified
10696 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10697 /// function calls.
10698 ///
10699 /// \param Call The call expression to diagnose.
10700 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10701                                    unsigned BId,
10702                                    IdentifierInfo *FnName) {
10703   assert(BId != 0);
10704 
10705   // It is possible to have a non-standard definition of memset.  Validate
10706   // we have enough arguments, and if not, abort further checking.
10707   unsigned ExpectedNumArgs =
10708       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10709   if (Call->getNumArgs() < ExpectedNumArgs)
10710     return;
10711 
10712   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10713                       BId == Builtin::BIstrndup ? 1 : 2);
10714   unsigned LenArg =
10715       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10716   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10717 
10718   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10719                                      Call->getBeginLoc(), Call->getRParenLoc()))
10720     return;
10721 
10722   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10723   CheckMemaccessSize(*this, BId, Call);
10724 
10725   // We have special checking when the length is a sizeof expression.
10726   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10727   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10728   llvm::FoldingSetNodeID SizeOfArgID;
10729 
10730   // Although widely used, 'bzero' is not a standard function. Be more strict
10731   // with the argument types before allowing diagnostics and only allow the
10732   // form bzero(ptr, sizeof(...)).
10733   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10734   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10735     return;
10736 
10737   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10738     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10739     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10740 
10741     QualType DestTy = Dest->getType();
10742     QualType PointeeTy;
10743     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10744       PointeeTy = DestPtrTy->getPointeeType();
10745 
10746       // Never warn about void type pointers. This can be used to suppress
10747       // false positives.
10748       if (PointeeTy->isVoidType())
10749         continue;
10750 
10751       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10752       // actually comparing the expressions for equality. Because computing the
10753       // expression IDs can be expensive, we only do this if the diagnostic is
10754       // enabled.
10755       if (SizeOfArg &&
10756           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10757                            SizeOfArg->getExprLoc())) {
10758         // We only compute IDs for expressions if the warning is enabled, and
10759         // cache the sizeof arg's ID.
10760         if (SizeOfArgID == llvm::FoldingSetNodeID())
10761           SizeOfArg->Profile(SizeOfArgID, Context, true);
10762         llvm::FoldingSetNodeID DestID;
10763         Dest->Profile(DestID, Context, true);
10764         if (DestID == SizeOfArgID) {
10765           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10766           //       over sizeof(src) as well.
10767           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10768           StringRef ReadableName = FnName->getName();
10769 
10770           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10771             if (UnaryOp->getOpcode() == UO_AddrOf)
10772               ActionIdx = 1; // If its an address-of operator, just remove it.
10773           if (!PointeeTy->isIncompleteType() &&
10774               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10775             ActionIdx = 2; // If the pointee's size is sizeof(char),
10776                            // suggest an explicit length.
10777 
10778           // If the function is defined as a builtin macro, do not show macro
10779           // expansion.
10780           SourceLocation SL = SizeOfArg->getExprLoc();
10781           SourceRange DSR = Dest->getSourceRange();
10782           SourceRange SSR = SizeOfArg->getSourceRange();
10783           SourceManager &SM = getSourceManager();
10784 
10785           if (SM.isMacroArgExpansion(SL)) {
10786             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10787             SL = SM.getSpellingLoc(SL);
10788             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10789                              SM.getSpellingLoc(DSR.getEnd()));
10790             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10791                              SM.getSpellingLoc(SSR.getEnd()));
10792           }
10793 
10794           DiagRuntimeBehavior(SL, SizeOfArg,
10795                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10796                                 << ReadableName
10797                                 << PointeeTy
10798                                 << DestTy
10799                                 << DSR
10800                                 << SSR);
10801           DiagRuntimeBehavior(SL, SizeOfArg,
10802                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10803                                 << ActionIdx
10804                                 << SSR);
10805 
10806           break;
10807         }
10808       }
10809 
10810       // Also check for cases where the sizeof argument is the exact same
10811       // type as the memory argument, and where it points to a user-defined
10812       // record type.
10813       if (SizeOfArgTy != QualType()) {
10814         if (PointeeTy->isRecordType() &&
10815             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10816           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10817                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10818                                 << FnName << SizeOfArgTy << ArgIdx
10819                                 << PointeeTy << Dest->getSourceRange()
10820                                 << LenExpr->getSourceRange());
10821           break;
10822         }
10823       }
10824     } else if (DestTy->isArrayType()) {
10825       PointeeTy = DestTy;
10826     }
10827 
10828     if (PointeeTy == QualType())
10829       continue;
10830 
10831     // Always complain about dynamic classes.
10832     bool IsContained;
10833     if (const CXXRecordDecl *ContainedRD =
10834             getContainedDynamicClass(PointeeTy, IsContained)) {
10835 
10836       unsigned OperationType = 0;
10837       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10838       // "overwritten" if we're warning about the destination for any call
10839       // but memcmp; otherwise a verb appropriate to the call.
10840       if (ArgIdx != 0 || IsCmp) {
10841         if (BId == Builtin::BImemcpy)
10842           OperationType = 1;
10843         else if(BId == Builtin::BImemmove)
10844           OperationType = 2;
10845         else if (IsCmp)
10846           OperationType = 3;
10847       }
10848 
10849       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10850                           PDiag(diag::warn_dyn_class_memaccess)
10851                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10852                               << IsContained << ContainedRD << OperationType
10853                               << Call->getCallee()->getSourceRange());
10854     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10855              BId != Builtin::BImemset)
10856       DiagRuntimeBehavior(
10857         Dest->getExprLoc(), Dest,
10858         PDiag(diag::warn_arc_object_memaccess)
10859           << ArgIdx << FnName << PointeeTy
10860           << Call->getCallee()->getSourceRange());
10861     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10862       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10863           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10864         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10865                             PDiag(diag::warn_cstruct_memaccess)
10866                                 << ArgIdx << FnName << PointeeTy << 0);
10867         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10868       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10869                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10870         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10871                             PDiag(diag::warn_cstruct_memaccess)
10872                                 << ArgIdx << FnName << PointeeTy << 1);
10873         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10874       } else {
10875         continue;
10876       }
10877     } else
10878       continue;
10879 
10880     DiagRuntimeBehavior(
10881       Dest->getExprLoc(), Dest,
10882       PDiag(diag::note_bad_memaccess_silence)
10883         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10884     break;
10885   }
10886 }
10887 
10888 // A little helper routine: ignore addition and subtraction of integer literals.
10889 // This intentionally does not ignore all integer constant expressions because
10890 // we don't want to remove sizeof().
10891 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10892   Ex = Ex->IgnoreParenCasts();
10893 
10894   while (true) {
10895     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10896     if (!BO || !BO->isAdditiveOp())
10897       break;
10898 
10899     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10900     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10901 
10902     if (isa<IntegerLiteral>(RHS))
10903       Ex = LHS;
10904     else if (isa<IntegerLiteral>(LHS))
10905       Ex = RHS;
10906     else
10907       break;
10908   }
10909 
10910   return Ex;
10911 }
10912 
10913 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10914                                                       ASTContext &Context) {
10915   // Only handle constant-sized or VLAs, but not flexible members.
10916   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10917     // Only issue the FIXIT for arrays of size > 1.
10918     if (CAT->getSize().getSExtValue() <= 1)
10919       return false;
10920   } else if (!Ty->isVariableArrayType()) {
10921     return false;
10922   }
10923   return true;
10924 }
10925 
10926 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10927 // be the size of the source, instead of the destination.
10928 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10929                                     IdentifierInfo *FnName) {
10930 
10931   // Don't crash if the user has the wrong number of arguments
10932   unsigned NumArgs = Call->getNumArgs();
10933   if ((NumArgs != 3) && (NumArgs != 4))
10934     return;
10935 
10936   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10937   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10938   const Expr *CompareWithSrc = nullptr;
10939 
10940   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10941                                      Call->getBeginLoc(), Call->getRParenLoc()))
10942     return;
10943 
10944   // Look for 'strlcpy(dst, x, sizeof(x))'
10945   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10946     CompareWithSrc = Ex;
10947   else {
10948     // Look for 'strlcpy(dst, x, strlen(x))'
10949     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10950       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10951           SizeCall->getNumArgs() == 1)
10952         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10953     }
10954   }
10955 
10956   if (!CompareWithSrc)
10957     return;
10958 
10959   // Determine if the argument to sizeof/strlen is equal to the source
10960   // argument.  In principle there's all kinds of things you could do
10961   // here, for instance creating an == expression and evaluating it with
10962   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10963   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10964   if (!SrcArgDRE)
10965     return;
10966 
10967   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10968   if (!CompareWithSrcDRE ||
10969       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10970     return;
10971 
10972   const Expr *OriginalSizeArg = Call->getArg(2);
10973   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10974       << OriginalSizeArg->getSourceRange() << FnName;
10975 
10976   // Output a FIXIT hint if the destination is an array (rather than a
10977   // pointer to an array).  This could be enhanced to handle some
10978   // pointers if we know the actual size, like if DstArg is 'array+2'
10979   // we could say 'sizeof(array)-2'.
10980   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10981   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10982     return;
10983 
10984   SmallString<128> sizeString;
10985   llvm::raw_svector_ostream OS(sizeString);
10986   OS << "sizeof(";
10987   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10988   OS << ")";
10989 
10990   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10991       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10992                                       OS.str());
10993 }
10994 
10995 /// Check if two expressions refer to the same declaration.
10996 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10997   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10998     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10999       return D1->getDecl() == D2->getDecl();
11000   return false;
11001 }
11002 
11003 static const Expr *getStrlenExprArg(const Expr *E) {
11004   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11005     const FunctionDecl *FD = CE->getDirectCallee();
11006     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11007       return nullptr;
11008     return CE->getArg(0)->IgnoreParenCasts();
11009   }
11010   return nullptr;
11011 }
11012 
11013 // Warn on anti-patterns as the 'size' argument to strncat.
11014 // The correct size argument should look like following:
11015 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11016 void Sema::CheckStrncatArguments(const CallExpr *CE,
11017                                  IdentifierInfo *FnName) {
11018   // Don't crash if the user has the wrong number of arguments.
11019   if (CE->getNumArgs() < 3)
11020     return;
11021   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11022   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11023   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11024 
11025   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11026                                      CE->getRParenLoc()))
11027     return;
11028 
11029   // Identify common expressions, which are wrongly used as the size argument
11030   // to strncat and may lead to buffer overflows.
11031   unsigned PatternType = 0;
11032   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11033     // - sizeof(dst)
11034     if (referToTheSameDecl(SizeOfArg, DstArg))
11035       PatternType = 1;
11036     // - sizeof(src)
11037     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11038       PatternType = 2;
11039   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11040     if (BE->getOpcode() == BO_Sub) {
11041       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11042       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11043       // - sizeof(dst) - strlen(dst)
11044       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11045           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11046         PatternType = 1;
11047       // - sizeof(src) - (anything)
11048       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11049         PatternType = 2;
11050     }
11051   }
11052 
11053   if (PatternType == 0)
11054     return;
11055 
11056   // Generate the diagnostic.
11057   SourceLocation SL = LenArg->getBeginLoc();
11058   SourceRange SR = LenArg->getSourceRange();
11059   SourceManager &SM = getSourceManager();
11060 
11061   // If the function is defined as a builtin macro, do not show macro expansion.
11062   if (SM.isMacroArgExpansion(SL)) {
11063     SL = SM.getSpellingLoc(SL);
11064     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11065                      SM.getSpellingLoc(SR.getEnd()));
11066   }
11067 
11068   // Check if the destination is an array (rather than a pointer to an array).
11069   QualType DstTy = DstArg->getType();
11070   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11071                                                                     Context);
11072   if (!isKnownSizeArray) {
11073     if (PatternType == 1)
11074       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11075     else
11076       Diag(SL, diag::warn_strncat_src_size) << SR;
11077     return;
11078   }
11079 
11080   if (PatternType == 1)
11081     Diag(SL, diag::warn_strncat_large_size) << SR;
11082   else
11083     Diag(SL, diag::warn_strncat_src_size) << SR;
11084 
11085   SmallString<128> sizeString;
11086   llvm::raw_svector_ostream OS(sizeString);
11087   OS << "sizeof(";
11088   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11089   OS << ") - ";
11090   OS << "strlen(";
11091   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11092   OS << ") - 1";
11093 
11094   Diag(SL, diag::note_strncat_wrong_size)
11095     << FixItHint::CreateReplacement(SR, OS.str());
11096 }
11097 
11098 namespace {
11099 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11100                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11101   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11102     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11103         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11104     return;
11105   }
11106 }
11107 
11108 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11109                                  const UnaryOperator *UnaryExpr) {
11110   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11111     const Decl *D = Lvalue->getDecl();
11112     if (isa<DeclaratorDecl>(D))
11113       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11114         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11115   }
11116 
11117   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11118     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11119                                       Lvalue->getMemberDecl());
11120 }
11121 
11122 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11123                             const UnaryOperator *UnaryExpr) {
11124   const auto *Lambda = dyn_cast<LambdaExpr>(
11125       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11126   if (!Lambda)
11127     return;
11128 
11129   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11130       << CalleeName << 2 /*object: lambda expression*/;
11131 }
11132 
11133 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11134                                   const DeclRefExpr *Lvalue) {
11135   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11136   if (Var == nullptr)
11137     return;
11138 
11139   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11140       << CalleeName << 0 /*object: */ << Var;
11141 }
11142 
11143 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11144                             const CastExpr *Cast) {
11145   SmallString<128> SizeString;
11146   llvm::raw_svector_ostream OS(SizeString);
11147 
11148   clang::CastKind Kind = Cast->getCastKind();
11149   if (Kind == clang::CK_BitCast &&
11150       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11151     return;
11152   if (Kind == clang::CK_IntegralToPointer &&
11153       !isa<IntegerLiteral>(
11154           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11155     return;
11156 
11157   switch (Cast->getCastKind()) {
11158   case clang::CK_BitCast:
11159   case clang::CK_IntegralToPointer:
11160   case clang::CK_FunctionToPointerDecay:
11161     OS << '\'';
11162     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11163     OS << '\'';
11164     break;
11165   default:
11166     return;
11167   }
11168 
11169   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11170       << CalleeName << 0 /*object: */ << OS.str();
11171 }
11172 } // namespace
11173 
11174 /// Alerts the user that they are attempting to free a non-malloc'd object.
11175 void Sema::CheckFreeArguments(const CallExpr *E) {
11176   const std::string CalleeName =
11177       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11178 
11179   { // Prefer something that doesn't involve a cast to make things simpler.
11180     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11181     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11182       switch (UnaryExpr->getOpcode()) {
11183       case UnaryOperator::Opcode::UO_AddrOf:
11184         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11185       case UnaryOperator::Opcode::UO_Plus:
11186         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11187       default:
11188         break;
11189       }
11190 
11191     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11192       if (Lvalue->getType()->isArrayType())
11193         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11194 
11195     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11196       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11197           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11198       return;
11199     }
11200 
11201     if (isa<BlockExpr>(Arg)) {
11202       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11203           << CalleeName << 1 /*object: block*/;
11204       return;
11205     }
11206   }
11207   // Maybe the cast was important, check after the other cases.
11208   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11209     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11210 }
11211 
11212 void
11213 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11214                          SourceLocation ReturnLoc,
11215                          bool isObjCMethod,
11216                          const AttrVec *Attrs,
11217                          const FunctionDecl *FD) {
11218   // Check if the return value is null but should not be.
11219   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11220        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11221       CheckNonNullExpr(*this, RetValExp))
11222     Diag(ReturnLoc, diag::warn_null_ret)
11223       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11224 
11225   // C++11 [basic.stc.dynamic.allocation]p4:
11226   //   If an allocation function declared with a non-throwing
11227   //   exception-specification fails to allocate storage, it shall return
11228   //   a null pointer. Any other allocation function that fails to allocate
11229   //   storage shall indicate failure only by throwing an exception [...]
11230   if (FD) {
11231     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11232     if (Op == OO_New || Op == OO_Array_New) {
11233       const FunctionProtoType *Proto
11234         = FD->getType()->castAs<FunctionProtoType>();
11235       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11236           CheckNonNullExpr(*this, RetValExp))
11237         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11238           << FD << getLangOpts().CPlusPlus11;
11239     }
11240   }
11241 
11242   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11243   // here prevent the user from using a PPC MMA type as trailing return type.
11244   if (Context.getTargetInfo().getTriple().isPPC64())
11245     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11246 }
11247 
11248 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11249 
11250 /// Check for comparisons of floating point operands using != and ==.
11251 /// Issue a warning if these are no self-comparisons, as they are not likely
11252 /// to do what the programmer intended.
11253 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11254   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11255   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11256 
11257   // Special case: check for x == x (which is OK).
11258   // Do not emit warnings for such cases.
11259   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11260     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11261       if (DRL->getDecl() == DRR->getDecl())
11262         return;
11263 
11264   // Special case: check for comparisons against literals that can be exactly
11265   //  represented by APFloat.  In such cases, do not emit a warning.  This
11266   //  is a heuristic: often comparison against such literals are used to
11267   //  detect if a value in a variable has not changed.  This clearly can
11268   //  lead to false negatives.
11269   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11270     if (FLL->isExact())
11271       return;
11272   } else
11273     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11274       if (FLR->isExact())
11275         return;
11276 
11277   // Check for comparisons with builtin types.
11278   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11279     if (CL->getBuiltinCallee())
11280       return;
11281 
11282   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11283     if (CR->getBuiltinCallee())
11284       return;
11285 
11286   // Emit the diagnostic.
11287   Diag(Loc, diag::warn_floatingpoint_eq)
11288     << LHS->getSourceRange() << RHS->getSourceRange();
11289 }
11290 
11291 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11292 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11293 
11294 namespace {
11295 
11296 /// Structure recording the 'active' range of an integer-valued
11297 /// expression.
11298 struct IntRange {
11299   /// The number of bits active in the int. Note that this includes exactly one
11300   /// sign bit if !NonNegative.
11301   unsigned Width;
11302 
11303   /// True if the int is known not to have negative values. If so, all leading
11304   /// bits before Width are known zero, otherwise they are known to be the
11305   /// same as the MSB within Width.
11306   bool NonNegative;
11307 
11308   IntRange(unsigned Width, bool NonNegative)
11309       : Width(Width), NonNegative(NonNegative) {}
11310 
11311   /// Number of bits excluding the sign bit.
11312   unsigned valueBits() const {
11313     return NonNegative ? Width : Width - 1;
11314   }
11315 
11316   /// Returns the range of the bool type.
11317   static IntRange forBoolType() {
11318     return IntRange(1, true);
11319   }
11320 
11321   /// Returns the range of an opaque value of the given integral type.
11322   static IntRange forValueOfType(ASTContext &C, QualType T) {
11323     return forValueOfCanonicalType(C,
11324                           T->getCanonicalTypeInternal().getTypePtr());
11325   }
11326 
11327   /// Returns the range of an opaque value of a canonical integral type.
11328   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11329     assert(T->isCanonicalUnqualified());
11330 
11331     if (const VectorType *VT = dyn_cast<VectorType>(T))
11332       T = VT->getElementType().getTypePtr();
11333     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11334       T = CT->getElementType().getTypePtr();
11335     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11336       T = AT->getValueType().getTypePtr();
11337 
11338     if (!C.getLangOpts().CPlusPlus) {
11339       // For enum types in C code, use the underlying datatype.
11340       if (const EnumType *ET = dyn_cast<EnumType>(T))
11341         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11342     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11343       // For enum types in C++, use the known bit width of the enumerators.
11344       EnumDecl *Enum = ET->getDecl();
11345       // In C++11, enums can have a fixed underlying type. Use this type to
11346       // compute the range.
11347       if (Enum->isFixed()) {
11348         return IntRange(C.getIntWidth(QualType(T, 0)),
11349                         !ET->isSignedIntegerOrEnumerationType());
11350       }
11351 
11352       unsigned NumPositive = Enum->getNumPositiveBits();
11353       unsigned NumNegative = Enum->getNumNegativeBits();
11354 
11355       if (NumNegative == 0)
11356         return IntRange(NumPositive, true/*NonNegative*/);
11357       else
11358         return IntRange(std::max(NumPositive + 1, NumNegative),
11359                         false/*NonNegative*/);
11360     }
11361 
11362     if (const auto *EIT = dyn_cast<BitIntType>(T))
11363       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11364 
11365     const BuiltinType *BT = cast<BuiltinType>(T);
11366     assert(BT->isInteger());
11367 
11368     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11369   }
11370 
11371   /// Returns the "target" range of a canonical integral type, i.e.
11372   /// the range of values expressible in the type.
11373   ///
11374   /// This matches forValueOfCanonicalType except that enums have the
11375   /// full range of their type, not the range of their enumerators.
11376   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11377     assert(T->isCanonicalUnqualified());
11378 
11379     if (const VectorType *VT = dyn_cast<VectorType>(T))
11380       T = VT->getElementType().getTypePtr();
11381     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11382       T = CT->getElementType().getTypePtr();
11383     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11384       T = AT->getValueType().getTypePtr();
11385     if (const EnumType *ET = dyn_cast<EnumType>(T))
11386       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11387 
11388     if (const auto *EIT = dyn_cast<BitIntType>(T))
11389       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11390 
11391     const BuiltinType *BT = cast<BuiltinType>(T);
11392     assert(BT->isInteger());
11393 
11394     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11395   }
11396 
11397   /// Returns the supremum of two ranges: i.e. their conservative merge.
11398   static IntRange join(IntRange L, IntRange R) {
11399     bool Unsigned = L.NonNegative && R.NonNegative;
11400     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11401                     L.NonNegative && R.NonNegative);
11402   }
11403 
11404   /// Return the range of a bitwise-AND of the two ranges.
11405   static IntRange bit_and(IntRange L, IntRange R) {
11406     unsigned Bits = std::max(L.Width, R.Width);
11407     bool NonNegative = false;
11408     if (L.NonNegative) {
11409       Bits = std::min(Bits, L.Width);
11410       NonNegative = true;
11411     }
11412     if (R.NonNegative) {
11413       Bits = std::min(Bits, R.Width);
11414       NonNegative = true;
11415     }
11416     return IntRange(Bits, NonNegative);
11417   }
11418 
11419   /// Return the range of a sum of the two ranges.
11420   static IntRange sum(IntRange L, IntRange R) {
11421     bool Unsigned = L.NonNegative && R.NonNegative;
11422     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11423                     Unsigned);
11424   }
11425 
11426   /// Return the range of a difference of the two ranges.
11427   static IntRange difference(IntRange L, IntRange R) {
11428     // We need a 1-bit-wider range if:
11429     //   1) LHS can be negative: least value can be reduced.
11430     //   2) RHS can be negative: greatest value can be increased.
11431     bool CanWiden = !L.NonNegative || !R.NonNegative;
11432     bool Unsigned = L.NonNegative && R.Width == 0;
11433     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11434                         !Unsigned,
11435                     Unsigned);
11436   }
11437 
11438   /// Return the range of a product of the two ranges.
11439   static IntRange product(IntRange L, IntRange R) {
11440     // If both LHS and RHS can be negative, we can form
11441     //   -2^L * -2^R = 2^(L + R)
11442     // which requires L + R + 1 value bits to represent.
11443     bool CanWiden = !L.NonNegative && !R.NonNegative;
11444     bool Unsigned = L.NonNegative && R.NonNegative;
11445     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11446                     Unsigned);
11447   }
11448 
11449   /// Return the range of a remainder operation between the two ranges.
11450   static IntRange rem(IntRange L, IntRange R) {
11451     // The result of a remainder can't be larger than the result of
11452     // either side. The sign of the result is the sign of the LHS.
11453     bool Unsigned = L.NonNegative;
11454     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11455                     Unsigned);
11456   }
11457 };
11458 
11459 } // namespace
11460 
11461 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11462                               unsigned MaxWidth) {
11463   if (value.isSigned() && value.isNegative())
11464     return IntRange(value.getMinSignedBits(), false);
11465 
11466   if (value.getBitWidth() > MaxWidth)
11467     value = value.trunc(MaxWidth);
11468 
11469   // isNonNegative() just checks the sign bit without considering
11470   // signedness.
11471   return IntRange(value.getActiveBits(), true);
11472 }
11473 
11474 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11475                               unsigned MaxWidth) {
11476   if (result.isInt())
11477     return GetValueRange(C, result.getInt(), MaxWidth);
11478 
11479   if (result.isVector()) {
11480     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11481     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11482       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11483       R = IntRange::join(R, El);
11484     }
11485     return R;
11486   }
11487 
11488   if (result.isComplexInt()) {
11489     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11490     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11491     return IntRange::join(R, I);
11492   }
11493 
11494   // This can happen with lossless casts to intptr_t of "based" lvalues.
11495   // Assume it might use arbitrary bits.
11496   // FIXME: The only reason we need to pass the type in here is to get
11497   // the sign right on this one case.  It would be nice if APValue
11498   // preserved this.
11499   assert(result.isLValue() || result.isAddrLabelDiff());
11500   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11501 }
11502 
11503 static QualType GetExprType(const Expr *E) {
11504   QualType Ty = E->getType();
11505   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11506     Ty = AtomicRHS->getValueType();
11507   return Ty;
11508 }
11509 
11510 /// Pseudo-evaluate the given integer expression, estimating the
11511 /// range of values it might take.
11512 ///
11513 /// \param MaxWidth The width to which the value will be truncated.
11514 /// \param Approximate If \c true, return a likely range for the result: in
11515 ///        particular, assume that arithmetic on narrower types doesn't leave
11516 ///        those types. If \c false, return a range including all possible
11517 ///        result values.
11518 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11519                              bool InConstantContext, bool Approximate) {
11520   E = E->IgnoreParens();
11521 
11522   // Try a full evaluation first.
11523   Expr::EvalResult result;
11524   if (E->EvaluateAsRValue(result, C, InConstantContext))
11525     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11526 
11527   // I think we only want to look through implicit casts here; if the
11528   // user has an explicit widening cast, we should treat the value as
11529   // being of the new, wider type.
11530   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11531     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11532       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11533                           Approximate);
11534 
11535     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11536 
11537     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11538                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11539 
11540     // Assume that non-integer casts can span the full range of the type.
11541     if (!isIntegerCast)
11542       return OutputTypeRange;
11543 
11544     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11545                                      std::min(MaxWidth, OutputTypeRange.Width),
11546                                      InConstantContext, Approximate);
11547 
11548     // Bail out if the subexpr's range is as wide as the cast type.
11549     if (SubRange.Width >= OutputTypeRange.Width)
11550       return OutputTypeRange;
11551 
11552     // Otherwise, we take the smaller width, and we're non-negative if
11553     // either the output type or the subexpr is.
11554     return IntRange(SubRange.Width,
11555                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11556   }
11557 
11558   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11559     // If we can fold the condition, just take that operand.
11560     bool CondResult;
11561     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11562       return GetExprRange(C,
11563                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11564                           MaxWidth, InConstantContext, Approximate);
11565 
11566     // Otherwise, conservatively merge.
11567     // GetExprRange requires an integer expression, but a throw expression
11568     // results in a void type.
11569     Expr *E = CO->getTrueExpr();
11570     IntRange L = E->getType()->isVoidType()
11571                      ? IntRange{0, true}
11572                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11573     E = CO->getFalseExpr();
11574     IntRange R = E->getType()->isVoidType()
11575                      ? IntRange{0, true}
11576                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11577     return IntRange::join(L, R);
11578   }
11579 
11580   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11581     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11582 
11583     switch (BO->getOpcode()) {
11584     case BO_Cmp:
11585       llvm_unreachable("builtin <=> should have class type");
11586 
11587     // Boolean-valued operations are single-bit and positive.
11588     case BO_LAnd:
11589     case BO_LOr:
11590     case BO_LT:
11591     case BO_GT:
11592     case BO_LE:
11593     case BO_GE:
11594     case BO_EQ:
11595     case BO_NE:
11596       return IntRange::forBoolType();
11597 
11598     // The type of the assignments is the type of the LHS, so the RHS
11599     // is not necessarily the same type.
11600     case BO_MulAssign:
11601     case BO_DivAssign:
11602     case BO_RemAssign:
11603     case BO_AddAssign:
11604     case BO_SubAssign:
11605     case BO_XorAssign:
11606     case BO_OrAssign:
11607       // TODO: bitfields?
11608       return IntRange::forValueOfType(C, GetExprType(E));
11609 
11610     // Simple assignments just pass through the RHS, which will have
11611     // been coerced to the LHS type.
11612     case BO_Assign:
11613       // TODO: bitfields?
11614       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11615                           Approximate);
11616 
11617     // Operations with opaque sources are black-listed.
11618     case BO_PtrMemD:
11619     case BO_PtrMemI:
11620       return IntRange::forValueOfType(C, GetExprType(E));
11621 
11622     // Bitwise-and uses the *infinum* of the two source ranges.
11623     case BO_And:
11624     case BO_AndAssign:
11625       Combine = IntRange::bit_and;
11626       break;
11627 
11628     // Left shift gets black-listed based on a judgement call.
11629     case BO_Shl:
11630       // ...except that we want to treat '1 << (blah)' as logically
11631       // positive.  It's an important idiom.
11632       if (IntegerLiteral *I
11633             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11634         if (I->getValue() == 1) {
11635           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11636           return IntRange(R.Width, /*NonNegative*/ true);
11637         }
11638       }
11639       LLVM_FALLTHROUGH;
11640 
11641     case BO_ShlAssign:
11642       return IntRange::forValueOfType(C, GetExprType(E));
11643 
11644     // Right shift by a constant can narrow its left argument.
11645     case BO_Shr:
11646     case BO_ShrAssign: {
11647       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11648                                 Approximate);
11649 
11650       // If the shift amount is a positive constant, drop the width by
11651       // that much.
11652       if (Optional<llvm::APSInt> shift =
11653               BO->getRHS()->getIntegerConstantExpr(C)) {
11654         if (shift->isNonNegative()) {
11655           unsigned zext = shift->getZExtValue();
11656           if (zext >= L.Width)
11657             L.Width = (L.NonNegative ? 0 : 1);
11658           else
11659             L.Width -= zext;
11660         }
11661       }
11662 
11663       return L;
11664     }
11665 
11666     // Comma acts as its right operand.
11667     case BO_Comma:
11668       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11669                           Approximate);
11670 
11671     case BO_Add:
11672       if (!Approximate)
11673         Combine = IntRange::sum;
11674       break;
11675 
11676     case BO_Sub:
11677       if (BO->getLHS()->getType()->isPointerType())
11678         return IntRange::forValueOfType(C, GetExprType(E));
11679       if (!Approximate)
11680         Combine = IntRange::difference;
11681       break;
11682 
11683     case BO_Mul:
11684       if (!Approximate)
11685         Combine = IntRange::product;
11686       break;
11687 
11688     // The width of a division result is mostly determined by the size
11689     // of the LHS.
11690     case BO_Div: {
11691       // Don't 'pre-truncate' the operands.
11692       unsigned opWidth = C.getIntWidth(GetExprType(E));
11693       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11694                                 Approximate);
11695 
11696       // If the divisor is constant, use that.
11697       if (Optional<llvm::APSInt> divisor =
11698               BO->getRHS()->getIntegerConstantExpr(C)) {
11699         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11700         if (log2 >= L.Width)
11701           L.Width = (L.NonNegative ? 0 : 1);
11702         else
11703           L.Width = std::min(L.Width - log2, MaxWidth);
11704         return L;
11705       }
11706 
11707       // Otherwise, just use the LHS's width.
11708       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11709       // could be -1.
11710       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11711                                 Approximate);
11712       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11713     }
11714 
11715     case BO_Rem:
11716       Combine = IntRange::rem;
11717       break;
11718 
11719     // The default behavior is okay for these.
11720     case BO_Xor:
11721     case BO_Or:
11722       break;
11723     }
11724 
11725     // Combine the two ranges, but limit the result to the type in which we
11726     // performed the computation.
11727     QualType T = GetExprType(E);
11728     unsigned opWidth = C.getIntWidth(T);
11729     IntRange L =
11730         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11731     IntRange R =
11732         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11733     IntRange C = Combine(L, R);
11734     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11735     C.Width = std::min(C.Width, MaxWidth);
11736     return C;
11737   }
11738 
11739   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11740     switch (UO->getOpcode()) {
11741     // Boolean-valued operations are white-listed.
11742     case UO_LNot:
11743       return IntRange::forBoolType();
11744 
11745     // Operations with opaque sources are black-listed.
11746     case UO_Deref:
11747     case UO_AddrOf: // should be impossible
11748       return IntRange::forValueOfType(C, GetExprType(E));
11749 
11750     default:
11751       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11752                           Approximate);
11753     }
11754   }
11755 
11756   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11757     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11758                         Approximate);
11759 
11760   if (const auto *BitField = E->getSourceBitField())
11761     return IntRange(BitField->getBitWidthValue(C),
11762                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11763 
11764   return IntRange::forValueOfType(C, GetExprType(E));
11765 }
11766 
11767 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11768                              bool InConstantContext, bool Approximate) {
11769   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11770                       Approximate);
11771 }
11772 
11773 /// Checks whether the given value, which currently has the given
11774 /// source semantics, has the same value when coerced through the
11775 /// target semantics.
11776 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11777                                  const llvm::fltSemantics &Src,
11778                                  const llvm::fltSemantics &Tgt) {
11779   llvm::APFloat truncated = value;
11780 
11781   bool ignored;
11782   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11783   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11784 
11785   return truncated.bitwiseIsEqual(value);
11786 }
11787 
11788 /// Checks whether the given value, which currently has the given
11789 /// source semantics, has the same value when coerced through the
11790 /// target semantics.
11791 ///
11792 /// The value might be a vector of floats (or a complex number).
11793 static bool IsSameFloatAfterCast(const APValue &value,
11794                                  const llvm::fltSemantics &Src,
11795                                  const llvm::fltSemantics &Tgt) {
11796   if (value.isFloat())
11797     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11798 
11799   if (value.isVector()) {
11800     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11801       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11802         return false;
11803     return true;
11804   }
11805 
11806   assert(value.isComplexFloat());
11807   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11808           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11809 }
11810 
11811 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11812                                        bool IsListInit = false);
11813 
11814 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11815   // Suppress cases where we are comparing against an enum constant.
11816   if (const DeclRefExpr *DR =
11817       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11818     if (isa<EnumConstantDecl>(DR->getDecl()))
11819       return true;
11820 
11821   // Suppress cases where the value is expanded from a macro, unless that macro
11822   // is how a language represents a boolean literal. This is the case in both C
11823   // and Objective-C.
11824   SourceLocation BeginLoc = E->getBeginLoc();
11825   if (BeginLoc.isMacroID()) {
11826     StringRef MacroName = Lexer::getImmediateMacroName(
11827         BeginLoc, S.getSourceManager(), S.getLangOpts());
11828     return MacroName != "YES" && MacroName != "NO" &&
11829            MacroName != "true" && MacroName != "false";
11830   }
11831 
11832   return false;
11833 }
11834 
11835 static bool isKnownToHaveUnsignedValue(Expr *E) {
11836   return E->getType()->isIntegerType() &&
11837          (!E->getType()->isSignedIntegerType() ||
11838           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11839 }
11840 
11841 namespace {
11842 /// The promoted range of values of a type. In general this has the
11843 /// following structure:
11844 ///
11845 ///     |-----------| . . . |-----------|
11846 ///     ^           ^       ^           ^
11847 ///    Min       HoleMin  HoleMax      Max
11848 ///
11849 /// ... where there is only a hole if a signed type is promoted to unsigned
11850 /// (in which case Min and Max are the smallest and largest representable
11851 /// values).
11852 struct PromotedRange {
11853   // Min, or HoleMax if there is a hole.
11854   llvm::APSInt PromotedMin;
11855   // Max, or HoleMin if there is a hole.
11856   llvm::APSInt PromotedMax;
11857 
11858   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11859     if (R.Width == 0)
11860       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11861     else if (R.Width >= BitWidth && !Unsigned) {
11862       // Promotion made the type *narrower*. This happens when promoting
11863       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11864       // Treat all values of 'signed int' as being in range for now.
11865       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11866       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11867     } else {
11868       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11869                         .extOrTrunc(BitWidth);
11870       PromotedMin.setIsUnsigned(Unsigned);
11871 
11872       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11873                         .extOrTrunc(BitWidth);
11874       PromotedMax.setIsUnsigned(Unsigned);
11875     }
11876   }
11877 
11878   // Determine whether this range is contiguous (has no hole).
11879   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11880 
11881   // Where a constant value is within the range.
11882   enum ComparisonResult {
11883     LT = 0x1,
11884     LE = 0x2,
11885     GT = 0x4,
11886     GE = 0x8,
11887     EQ = 0x10,
11888     NE = 0x20,
11889     InRangeFlag = 0x40,
11890 
11891     Less = LE | LT | NE,
11892     Min = LE | InRangeFlag,
11893     InRange = InRangeFlag,
11894     Max = GE | InRangeFlag,
11895     Greater = GE | GT | NE,
11896 
11897     OnlyValue = LE | GE | EQ | InRangeFlag,
11898     InHole = NE
11899   };
11900 
11901   ComparisonResult compare(const llvm::APSInt &Value) const {
11902     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11903            Value.isUnsigned() == PromotedMin.isUnsigned());
11904     if (!isContiguous()) {
11905       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11906       if (Value.isMinValue()) return Min;
11907       if (Value.isMaxValue()) return Max;
11908       if (Value >= PromotedMin) return InRange;
11909       if (Value <= PromotedMax) return InRange;
11910       return InHole;
11911     }
11912 
11913     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11914     case -1: return Less;
11915     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11916     case 1:
11917       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11918       case -1: return InRange;
11919       case 0: return Max;
11920       case 1: return Greater;
11921       }
11922     }
11923 
11924     llvm_unreachable("impossible compare result");
11925   }
11926 
11927   static llvm::Optional<StringRef>
11928   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11929     if (Op == BO_Cmp) {
11930       ComparisonResult LTFlag = LT, GTFlag = GT;
11931       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11932 
11933       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11934       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11935       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11936       return llvm::None;
11937     }
11938 
11939     ComparisonResult TrueFlag, FalseFlag;
11940     if (Op == BO_EQ) {
11941       TrueFlag = EQ;
11942       FalseFlag = NE;
11943     } else if (Op == BO_NE) {
11944       TrueFlag = NE;
11945       FalseFlag = EQ;
11946     } else {
11947       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11948         TrueFlag = LT;
11949         FalseFlag = GE;
11950       } else {
11951         TrueFlag = GT;
11952         FalseFlag = LE;
11953       }
11954       if (Op == BO_GE || Op == BO_LE)
11955         std::swap(TrueFlag, FalseFlag);
11956     }
11957     if (R & TrueFlag)
11958       return StringRef("true");
11959     if (R & FalseFlag)
11960       return StringRef("false");
11961     return llvm::None;
11962   }
11963 };
11964 }
11965 
11966 static bool HasEnumType(Expr *E) {
11967   // Strip off implicit integral promotions.
11968   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11969     if (ICE->getCastKind() != CK_IntegralCast &&
11970         ICE->getCastKind() != CK_NoOp)
11971       break;
11972     E = ICE->getSubExpr();
11973   }
11974 
11975   return E->getType()->isEnumeralType();
11976 }
11977 
11978 static int classifyConstantValue(Expr *Constant) {
11979   // The values of this enumeration are used in the diagnostics
11980   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11981   enum ConstantValueKind {
11982     Miscellaneous = 0,
11983     LiteralTrue,
11984     LiteralFalse
11985   };
11986   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11987     return BL->getValue() ? ConstantValueKind::LiteralTrue
11988                           : ConstantValueKind::LiteralFalse;
11989   return ConstantValueKind::Miscellaneous;
11990 }
11991 
11992 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11993                                         Expr *Constant, Expr *Other,
11994                                         const llvm::APSInt &Value,
11995                                         bool RhsConstant) {
11996   if (S.inTemplateInstantiation())
11997     return false;
11998 
11999   Expr *OriginalOther = Other;
12000 
12001   Constant = Constant->IgnoreParenImpCasts();
12002   Other = Other->IgnoreParenImpCasts();
12003 
12004   // Suppress warnings on tautological comparisons between values of the same
12005   // enumeration type. There are only two ways we could warn on this:
12006   //  - If the constant is outside the range of representable values of
12007   //    the enumeration. In such a case, we should warn about the cast
12008   //    to enumeration type, not about the comparison.
12009   //  - If the constant is the maximum / minimum in-range value. For an
12010   //    enumeratin type, such comparisons can be meaningful and useful.
12011   if (Constant->getType()->isEnumeralType() &&
12012       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12013     return false;
12014 
12015   IntRange OtherValueRange = GetExprRange(
12016       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12017 
12018   QualType OtherT = Other->getType();
12019   if (const auto *AT = OtherT->getAs<AtomicType>())
12020     OtherT = AT->getValueType();
12021   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12022 
12023   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12024   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12025   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12026                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12027                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12028 
12029   // Whether we're treating Other as being a bool because of the form of
12030   // expression despite it having another type (typically 'int' in C).
12031   bool OtherIsBooleanDespiteType =
12032       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12033   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12034     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12035 
12036   // Check if all values in the range of possible values of this expression
12037   // lead to the same comparison outcome.
12038   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12039                                         Value.isUnsigned());
12040   auto Cmp = OtherPromotedValueRange.compare(Value);
12041   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12042   if (!Result)
12043     return false;
12044 
12045   // Also consider the range determined by the type alone. This allows us to
12046   // classify the warning under the proper diagnostic group.
12047   bool TautologicalTypeCompare = false;
12048   {
12049     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12050                                          Value.isUnsigned());
12051     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12052     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12053                                                        RhsConstant)) {
12054       TautologicalTypeCompare = true;
12055       Cmp = TypeCmp;
12056       Result = TypeResult;
12057     }
12058   }
12059 
12060   // Don't warn if the non-constant operand actually always evaluates to the
12061   // same value.
12062   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12063     return false;
12064 
12065   // Suppress the diagnostic for an in-range comparison if the constant comes
12066   // from a macro or enumerator. We don't want to diagnose
12067   //
12068   //   some_long_value <= INT_MAX
12069   //
12070   // when sizeof(int) == sizeof(long).
12071   bool InRange = Cmp & PromotedRange::InRangeFlag;
12072   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12073     return false;
12074 
12075   // A comparison of an unsigned bit-field against 0 is really a type problem,
12076   // even though at the type level the bit-field might promote to 'signed int'.
12077   if (Other->refersToBitField() && InRange && Value == 0 &&
12078       Other->getType()->isUnsignedIntegerOrEnumerationType())
12079     TautologicalTypeCompare = true;
12080 
12081   // If this is a comparison to an enum constant, include that
12082   // constant in the diagnostic.
12083   const EnumConstantDecl *ED = nullptr;
12084   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12085     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12086 
12087   // Should be enough for uint128 (39 decimal digits)
12088   SmallString<64> PrettySourceValue;
12089   llvm::raw_svector_ostream OS(PrettySourceValue);
12090   if (ED) {
12091     OS << '\'' << *ED << "' (" << Value << ")";
12092   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12093                Constant->IgnoreParenImpCasts())) {
12094     OS << (BL->getValue() ? "YES" : "NO");
12095   } else {
12096     OS << Value;
12097   }
12098 
12099   if (!TautologicalTypeCompare) {
12100     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12101         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12102         << E->getOpcodeStr() << OS.str() << *Result
12103         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12104     return true;
12105   }
12106 
12107   if (IsObjCSignedCharBool) {
12108     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12109                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12110                               << OS.str() << *Result);
12111     return true;
12112   }
12113 
12114   // FIXME: We use a somewhat different formatting for the in-range cases and
12115   // cases involving boolean values for historical reasons. We should pick a
12116   // consistent way of presenting these diagnostics.
12117   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12118 
12119     S.DiagRuntimeBehavior(
12120         E->getOperatorLoc(), E,
12121         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12122                          : diag::warn_tautological_bool_compare)
12123             << OS.str() << classifyConstantValue(Constant) << OtherT
12124             << OtherIsBooleanDespiteType << *Result
12125             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12126   } else {
12127     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12128     unsigned Diag =
12129         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12130             ? (HasEnumType(OriginalOther)
12131                    ? diag::warn_unsigned_enum_always_true_comparison
12132                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12133                               : diag::warn_unsigned_always_true_comparison)
12134             : diag::warn_tautological_constant_compare;
12135 
12136     S.Diag(E->getOperatorLoc(), Diag)
12137         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12138         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12139   }
12140 
12141   return true;
12142 }
12143 
12144 /// Analyze the operands of the given comparison.  Implements the
12145 /// fallback case from AnalyzeComparison.
12146 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12147   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12148   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12149 }
12150 
12151 /// Implements -Wsign-compare.
12152 ///
12153 /// \param E the binary operator to check for warnings
12154 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12155   // The type the comparison is being performed in.
12156   QualType T = E->getLHS()->getType();
12157 
12158   // Only analyze comparison operators where both sides have been converted to
12159   // the same type.
12160   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12161     return AnalyzeImpConvsInComparison(S, E);
12162 
12163   // Don't analyze value-dependent comparisons directly.
12164   if (E->isValueDependent())
12165     return AnalyzeImpConvsInComparison(S, E);
12166 
12167   Expr *LHS = E->getLHS();
12168   Expr *RHS = E->getRHS();
12169 
12170   if (T->isIntegralType(S.Context)) {
12171     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12172     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12173 
12174     // We don't care about expressions whose result is a constant.
12175     if (RHSValue && LHSValue)
12176       return AnalyzeImpConvsInComparison(S, E);
12177 
12178     // We only care about expressions where just one side is literal
12179     if ((bool)RHSValue ^ (bool)LHSValue) {
12180       // Is the constant on the RHS or LHS?
12181       const bool RhsConstant = (bool)RHSValue;
12182       Expr *Const = RhsConstant ? RHS : LHS;
12183       Expr *Other = RhsConstant ? LHS : RHS;
12184       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12185 
12186       // Check whether an integer constant comparison results in a value
12187       // of 'true' or 'false'.
12188       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12189         return AnalyzeImpConvsInComparison(S, E);
12190     }
12191   }
12192 
12193   if (!T->hasUnsignedIntegerRepresentation()) {
12194     // We don't do anything special if this isn't an unsigned integral
12195     // comparison:  we're only interested in integral comparisons, and
12196     // signed comparisons only happen in cases we don't care to warn about.
12197     return AnalyzeImpConvsInComparison(S, E);
12198   }
12199 
12200   LHS = LHS->IgnoreParenImpCasts();
12201   RHS = RHS->IgnoreParenImpCasts();
12202 
12203   if (!S.getLangOpts().CPlusPlus) {
12204     // Avoid warning about comparison of integers with different signs when
12205     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12206     // the type of `E`.
12207     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12208       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12209     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12210       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12211   }
12212 
12213   // Check to see if one of the (unmodified) operands is of different
12214   // signedness.
12215   Expr *signedOperand, *unsignedOperand;
12216   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12217     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12218            "unsigned comparison between two signed integer expressions?");
12219     signedOperand = LHS;
12220     unsignedOperand = RHS;
12221   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12222     signedOperand = RHS;
12223     unsignedOperand = LHS;
12224   } else {
12225     return AnalyzeImpConvsInComparison(S, E);
12226   }
12227 
12228   // Otherwise, calculate the effective range of the signed operand.
12229   IntRange signedRange = GetExprRange(
12230       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12231 
12232   // Go ahead and analyze implicit conversions in the operands.  Note
12233   // that we skip the implicit conversions on both sides.
12234   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12235   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12236 
12237   // If the signed range is non-negative, -Wsign-compare won't fire.
12238   if (signedRange.NonNegative)
12239     return;
12240 
12241   // For (in)equality comparisons, if the unsigned operand is a
12242   // constant which cannot collide with a overflowed signed operand,
12243   // then reinterpreting the signed operand as unsigned will not
12244   // change the result of the comparison.
12245   if (E->isEqualityOp()) {
12246     unsigned comparisonWidth = S.Context.getIntWidth(T);
12247     IntRange unsignedRange =
12248         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12249                      /*Approximate*/ true);
12250 
12251     // We should never be unable to prove that the unsigned operand is
12252     // non-negative.
12253     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12254 
12255     if (unsignedRange.Width < comparisonWidth)
12256       return;
12257   }
12258 
12259   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12260                         S.PDiag(diag::warn_mixed_sign_comparison)
12261                             << LHS->getType() << RHS->getType()
12262                             << LHS->getSourceRange() << RHS->getSourceRange());
12263 }
12264 
12265 /// Analyzes an attempt to assign the given value to a bitfield.
12266 ///
12267 /// Returns true if there was something fishy about the attempt.
12268 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12269                                       SourceLocation InitLoc) {
12270   assert(Bitfield->isBitField());
12271   if (Bitfield->isInvalidDecl())
12272     return false;
12273 
12274   // White-list bool bitfields.
12275   QualType BitfieldType = Bitfield->getType();
12276   if (BitfieldType->isBooleanType())
12277      return false;
12278 
12279   if (BitfieldType->isEnumeralType()) {
12280     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12281     // If the underlying enum type was not explicitly specified as an unsigned
12282     // type and the enum contain only positive values, MSVC++ will cause an
12283     // inconsistency by storing this as a signed type.
12284     if (S.getLangOpts().CPlusPlus11 &&
12285         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12286         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12287         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12288       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12289           << BitfieldEnumDecl;
12290     }
12291   }
12292 
12293   if (Bitfield->getType()->isBooleanType())
12294     return false;
12295 
12296   // Ignore value- or type-dependent expressions.
12297   if (Bitfield->getBitWidth()->isValueDependent() ||
12298       Bitfield->getBitWidth()->isTypeDependent() ||
12299       Init->isValueDependent() ||
12300       Init->isTypeDependent())
12301     return false;
12302 
12303   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12304   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12305 
12306   Expr::EvalResult Result;
12307   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12308                                    Expr::SE_AllowSideEffects)) {
12309     // The RHS is not constant.  If the RHS has an enum type, make sure the
12310     // bitfield is wide enough to hold all the values of the enum without
12311     // truncation.
12312     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12313       EnumDecl *ED = EnumTy->getDecl();
12314       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12315 
12316       // Enum types are implicitly signed on Windows, so check if there are any
12317       // negative enumerators to see if the enum was intended to be signed or
12318       // not.
12319       bool SignedEnum = ED->getNumNegativeBits() > 0;
12320 
12321       // Check for surprising sign changes when assigning enum values to a
12322       // bitfield of different signedness.  If the bitfield is signed and we
12323       // have exactly the right number of bits to store this unsigned enum,
12324       // suggest changing the enum to an unsigned type. This typically happens
12325       // on Windows where unfixed enums always use an underlying type of 'int'.
12326       unsigned DiagID = 0;
12327       if (SignedEnum && !SignedBitfield) {
12328         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12329       } else if (SignedBitfield && !SignedEnum &&
12330                  ED->getNumPositiveBits() == FieldWidth) {
12331         DiagID = diag::warn_signed_bitfield_enum_conversion;
12332       }
12333 
12334       if (DiagID) {
12335         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12336         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12337         SourceRange TypeRange =
12338             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12339         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12340             << SignedEnum << TypeRange;
12341       }
12342 
12343       // Compute the required bitwidth. If the enum has negative values, we need
12344       // one more bit than the normal number of positive bits to represent the
12345       // sign bit.
12346       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12347                                                   ED->getNumNegativeBits())
12348                                        : ED->getNumPositiveBits();
12349 
12350       // Check the bitwidth.
12351       if (BitsNeeded > FieldWidth) {
12352         Expr *WidthExpr = Bitfield->getBitWidth();
12353         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12354             << Bitfield << ED;
12355         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12356             << BitsNeeded << ED << WidthExpr->getSourceRange();
12357       }
12358     }
12359 
12360     return false;
12361   }
12362 
12363   llvm::APSInt Value = Result.Val.getInt();
12364 
12365   unsigned OriginalWidth = Value.getBitWidth();
12366 
12367   if (!Value.isSigned() || Value.isNegative())
12368     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12369       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12370         OriginalWidth = Value.getMinSignedBits();
12371 
12372   if (OriginalWidth <= FieldWidth)
12373     return false;
12374 
12375   // Compute the value which the bitfield will contain.
12376   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12377   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12378 
12379   // Check whether the stored value is equal to the original value.
12380   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12381   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12382     return false;
12383 
12384   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12385   // therefore don't strictly fit into a signed bitfield of width 1.
12386   if (FieldWidth == 1 && Value == 1)
12387     return false;
12388 
12389   std::string PrettyValue = toString(Value, 10);
12390   std::string PrettyTrunc = toString(TruncatedValue, 10);
12391 
12392   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12393     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12394     << Init->getSourceRange();
12395 
12396   return true;
12397 }
12398 
12399 /// Analyze the given simple or compound assignment for warning-worthy
12400 /// operations.
12401 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12402   // Just recurse on the LHS.
12403   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12404 
12405   // We want to recurse on the RHS as normal unless we're assigning to
12406   // a bitfield.
12407   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12408     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12409                                   E->getOperatorLoc())) {
12410       // Recurse, ignoring any implicit conversions on the RHS.
12411       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12412                                         E->getOperatorLoc());
12413     }
12414   }
12415 
12416   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12417 
12418   // Diagnose implicitly sequentially-consistent atomic assignment.
12419   if (E->getLHS()->getType()->isAtomicType())
12420     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12421 }
12422 
12423 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12424 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12425                             SourceLocation CContext, unsigned diag,
12426                             bool pruneControlFlow = false) {
12427   if (pruneControlFlow) {
12428     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12429                           S.PDiag(diag)
12430                               << SourceType << T << E->getSourceRange()
12431                               << SourceRange(CContext));
12432     return;
12433   }
12434   S.Diag(E->getExprLoc(), diag)
12435     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12436 }
12437 
12438 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12439 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12440                             SourceLocation CContext,
12441                             unsigned diag, bool pruneControlFlow = false) {
12442   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12443 }
12444 
12445 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12446   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12447       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12448 }
12449 
12450 static void adornObjCBoolConversionDiagWithTernaryFixit(
12451     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12452   Expr *Ignored = SourceExpr->IgnoreImplicit();
12453   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12454     Ignored = OVE->getSourceExpr();
12455   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12456                      isa<BinaryOperator>(Ignored) ||
12457                      isa<CXXOperatorCallExpr>(Ignored);
12458   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12459   if (NeedsParens)
12460     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12461             << FixItHint::CreateInsertion(EndLoc, ")");
12462   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12463 }
12464 
12465 /// Diagnose an implicit cast from a floating point value to an integer value.
12466 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12467                                     SourceLocation CContext) {
12468   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12469   const bool PruneWarnings = S.inTemplateInstantiation();
12470 
12471   Expr *InnerE = E->IgnoreParenImpCasts();
12472   // We also want to warn on, e.g., "int i = -1.234"
12473   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12474     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12475       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12476 
12477   const bool IsLiteral =
12478       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12479 
12480   llvm::APFloat Value(0.0);
12481   bool IsConstant =
12482     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12483   if (!IsConstant) {
12484     if (isObjCSignedCharBool(S, T)) {
12485       return adornObjCBoolConversionDiagWithTernaryFixit(
12486           S, E,
12487           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12488               << E->getType());
12489     }
12490 
12491     return DiagnoseImpCast(S, E, T, CContext,
12492                            diag::warn_impcast_float_integer, PruneWarnings);
12493   }
12494 
12495   bool isExact = false;
12496 
12497   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12498                             T->hasUnsignedIntegerRepresentation());
12499   llvm::APFloat::opStatus Result = Value.convertToInteger(
12500       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12501 
12502   // FIXME: Force the precision of the source value down so we don't print
12503   // digits which are usually useless (we don't really care here if we
12504   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12505   // would automatically print the shortest representation, but it's a bit
12506   // tricky to implement.
12507   SmallString<16> PrettySourceValue;
12508   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12509   precision = (precision * 59 + 195) / 196;
12510   Value.toString(PrettySourceValue, precision);
12511 
12512   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12513     return adornObjCBoolConversionDiagWithTernaryFixit(
12514         S, E,
12515         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12516             << PrettySourceValue);
12517   }
12518 
12519   if (Result == llvm::APFloat::opOK && isExact) {
12520     if (IsLiteral) return;
12521     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12522                            PruneWarnings);
12523   }
12524 
12525   // Conversion of a floating-point value to a non-bool integer where the
12526   // integral part cannot be represented by the integer type is undefined.
12527   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12528     return DiagnoseImpCast(
12529         S, E, T, CContext,
12530         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12531                   : diag::warn_impcast_float_to_integer_out_of_range,
12532         PruneWarnings);
12533 
12534   unsigned DiagID = 0;
12535   if (IsLiteral) {
12536     // Warn on floating point literal to integer.
12537     DiagID = diag::warn_impcast_literal_float_to_integer;
12538   } else if (IntegerValue == 0) {
12539     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12540       return DiagnoseImpCast(S, E, T, CContext,
12541                              diag::warn_impcast_float_integer, PruneWarnings);
12542     }
12543     // Warn on non-zero to zero conversion.
12544     DiagID = diag::warn_impcast_float_to_integer_zero;
12545   } else {
12546     if (IntegerValue.isUnsigned()) {
12547       if (!IntegerValue.isMaxValue()) {
12548         return DiagnoseImpCast(S, E, T, CContext,
12549                                diag::warn_impcast_float_integer, PruneWarnings);
12550       }
12551     } else {  // IntegerValue.isSigned()
12552       if (!IntegerValue.isMaxSignedValue() &&
12553           !IntegerValue.isMinSignedValue()) {
12554         return DiagnoseImpCast(S, E, T, CContext,
12555                                diag::warn_impcast_float_integer, PruneWarnings);
12556       }
12557     }
12558     // Warn on evaluatable floating point expression to integer conversion.
12559     DiagID = diag::warn_impcast_float_to_integer;
12560   }
12561 
12562   SmallString<16> PrettyTargetValue;
12563   if (IsBool)
12564     PrettyTargetValue = Value.isZero() ? "false" : "true";
12565   else
12566     IntegerValue.toString(PrettyTargetValue);
12567 
12568   if (PruneWarnings) {
12569     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12570                           S.PDiag(DiagID)
12571                               << E->getType() << T.getUnqualifiedType()
12572                               << PrettySourceValue << PrettyTargetValue
12573                               << E->getSourceRange() << SourceRange(CContext));
12574   } else {
12575     S.Diag(E->getExprLoc(), DiagID)
12576         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12577         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12578   }
12579 }
12580 
12581 /// Analyze the given compound assignment for the possible losing of
12582 /// floating-point precision.
12583 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12584   assert(isa<CompoundAssignOperator>(E) &&
12585          "Must be compound assignment operation");
12586   // Recurse on the LHS and RHS in here
12587   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12588   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12589 
12590   if (E->getLHS()->getType()->isAtomicType())
12591     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12592 
12593   // Now check the outermost expression
12594   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12595   const auto *RBT = cast<CompoundAssignOperator>(E)
12596                         ->getComputationResultType()
12597                         ->getAs<BuiltinType>();
12598 
12599   // The below checks assume source is floating point.
12600   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12601 
12602   // If source is floating point but target is an integer.
12603   if (ResultBT->isInteger())
12604     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12605                            E->getExprLoc(), diag::warn_impcast_float_integer);
12606 
12607   if (!ResultBT->isFloatingPoint())
12608     return;
12609 
12610   // If both source and target are floating points, warn about losing precision.
12611   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12612       QualType(ResultBT, 0), QualType(RBT, 0));
12613   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12614     // warn about dropping FP rank.
12615     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12616                     diag::warn_impcast_float_result_precision);
12617 }
12618 
12619 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12620                                       IntRange Range) {
12621   if (!Range.Width) return "0";
12622 
12623   llvm::APSInt ValueInRange = Value;
12624   ValueInRange.setIsSigned(!Range.NonNegative);
12625   ValueInRange = ValueInRange.trunc(Range.Width);
12626   return toString(ValueInRange, 10);
12627 }
12628 
12629 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12630   if (!isa<ImplicitCastExpr>(Ex))
12631     return false;
12632 
12633   Expr *InnerE = Ex->IgnoreParenImpCasts();
12634   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12635   const Type *Source =
12636     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12637   if (Target->isDependentType())
12638     return false;
12639 
12640   const BuiltinType *FloatCandidateBT =
12641     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12642   const Type *BoolCandidateType = ToBool ? Target : Source;
12643 
12644   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12645           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12646 }
12647 
12648 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12649                                              SourceLocation CC) {
12650   unsigned NumArgs = TheCall->getNumArgs();
12651   for (unsigned i = 0; i < NumArgs; ++i) {
12652     Expr *CurrA = TheCall->getArg(i);
12653     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12654       continue;
12655 
12656     bool IsSwapped = ((i > 0) &&
12657         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12658     IsSwapped |= ((i < (NumArgs - 1)) &&
12659         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12660     if (IsSwapped) {
12661       // Warn on this floating-point to bool conversion.
12662       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12663                       CurrA->getType(), CC,
12664                       diag::warn_impcast_floating_point_to_bool);
12665     }
12666   }
12667 }
12668 
12669 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12670                                    SourceLocation CC) {
12671   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12672                         E->getExprLoc()))
12673     return;
12674 
12675   // Don't warn on functions which have return type nullptr_t.
12676   if (isa<CallExpr>(E))
12677     return;
12678 
12679   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12680   const Expr::NullPointerConstantKind NullKind =
12681       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12682   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12683     return;
12684 
12685   // Return if target type is a safe conversion.
12686   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12687       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12688     return;
12689 
12690   SourceLocation Loc = E->getSourceRange().getBegin();
12691 
12692   // Venture through the macro stacks to get to the source of macro arguments.
12693   // The new location is a better location than the complete location that was
12694   // passed in.
12695   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12696   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12697 
12698   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12699   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12700     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12701         Loc, S.SourceMgr, S.getLangOpts());
12702     if (MacroName == "NULL")
12703       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12704   }
12705 
12706   // Only warn if the null and context location are in the same macro expansion.
12707   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12708     return;
12709 
12710   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12711       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12712       << FixItHint::CreateReplacement(Loc,
12713                                       S.getFixItZeroLiteralForType(T, Loc));
12714 }
12715 
12716 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12717                                   ObjCArrayLiteral *ArrayLiteral);
12718 
12719 static void
12720 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12721                            ObjCDictionaryLiteral *DictionaryLiteral);
12722 
12723 /// Check a single element within a collection literal against the
12724 /// target element type.
12725 static void checkObjCCollectionLiteralElement(Sema &S,
12726                                               QualType TargetElementType,
12727                                               Expr *Element,
12728                                               unsigned ElementKind) {
12729   // Skip a bitcast to 'id' or qualified 'id'.
12730   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12731     if (ICE->getCastKind() == CK_BitCast &&
12732         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12733       Element = ICE->getSubExpr();
12734   }
12735 
12736   QualType ElementType = Element->getType();
12737   ExprResult ElementResult(Element);
12738   if (ElementType->getAs<ObjCObjectPointerType>() &&
12739       S.CheckSingleAssignmentConstraints(TargetElementType,
12740                                          ElementResult,
12741                                          false, false)
12742         != Sema::Compatible) {
12743     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12744         << ElementType << ElementKind << TargetElementType
12745         << Element->getSourceRange();
12746   }
12747 
12748   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12749     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12750   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12751     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12752 }
12753 
12754 /// Check an Objective-C array literal being converted to the given
12755 /// target type.
12756 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12757                                   ObjCArrayLiteral *ArrayLiteral) {
12758   if (!S.NSArrayDecl)
12759     return;
12760 
12761   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12762   if (!TargetObjCPtr)
12763     return;
12764 
12765   if (TargetObjCPtr->isUnspecialized() ||
12766       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12767         != S.NSArrayDecl->getCanonicalDecl())
12768     return;
12769 
12770   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12771   if (TypeArgs.size() != 1)
12772     return;
12773 
12774   QualType TargetElementType = TypeArgs[0];
12775   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12776     checkObjCCollectionLiteralElement(S, TargetElementType,
12777                                       ArrayLiteral->getElement(I),
12778                                       0);
12779   }
12780 }
12781 
12782 /// Check an Objective-C dictionary literal being converted to the given
12783 /// target type.
12784 static void
12785 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12786                            ObjCDictionaryLiteral *DictionaryLiteral) {
12787   if (!S.NSDictionaryDecl)
12788     return;
12789 
12790   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12791   if (!TargetObjCPtr)
12792     return;
12793 
12794   if (TargetObjCPtr->isUnspecialized() ||
12795       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12796         != S.NSDictionaryDecl->getCanonicalDecl())
12797     return;
12798 
12799   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12800   if (TypeArgs.size() != 2)
12801     return;
12802 
12803   QualType TargetKeyType = TypeArgs[0];
12804   QualType TargetObjectType = TypeArgs[1];
12805   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12806     auto Element = DictionaryLiteral->getKeyValueElement(I);
12807     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12808     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12809   }
12810 }
12811 
12812 // Helper function to filter out cases for constant width constant conversion.
12813 // Don't warn on char array initialization or for non-decimal values.
12814 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12815                                           SourceLocation CC) {
12816   // If initializing from a constant, and the constant starts with '0',
12817   // then it is a binary, octal, or hexadecimal.  Allow these constants
12818   // to fill all the bits, even if there is a sign change.
12819   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12820     const char FirstLiteralCharacter =
12821         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12822     if (FirstLiteralCharacter == '0')
12823       return false;
12824   }
12825 
12826   // If the CC location points to a '{', and the type is char, then assume
12827   // assume it is an array initialization.
12828   if (CC.isValid() && T->isCharType()) {
12829     const char FirstContextCharacter =
12830         S.getSourceManager().getCharacterData(CC)[0];
12831     if (FirstContextCharacter == '{')
12832       return false;
12833   }
12834 
12835   return true;
12836 }
12837 
12838 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12839   const auto *IL = dyn_cast<IntegerLiteral>(E);
12840   if (!IL) {
12841     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12842       if (UO->getOpcode() == UO_Minus)
12843         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12844     }
12845   }
12846 
12847   return IL;
12848 }
12849 
12850 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12851   E = E->IgnoreParenImpCasts();
12852   SourceLocation ExprLoc = E->getExprLoc();
12853 
12854   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12855     BinaryOperator::Opcode Opc = BO->getOpcode();
12856     Expr::EvalResult Result;
12857     // Do not diagnose unsigned shifts.
12858     if (Opc == BO_Shl) {
12859       const auto *LHS = getIntegerLiteral(BO->getLHS());
12860       const auto *RHS = getIntegerLiteral(BO->getRHS());
12861       if (LHS && LHS->getValue() == 0)
12862         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12863       else if (!E->isValueDependent() && LHS && RHS &&
12864                RHS->getValue().isNonNegative() &&
12865                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12866         S.Diag(ExprLoc, diag::warn_left_shift_always)
12867             << (Result.Val.getInt() != 0);
12868       else if (E->getType()->isSignedIntegerType())
12869         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12870     }
12871   }
12872 
12873   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12874     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12875     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12876     if (!LHS || !RHS)
12877       return;
12878     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12879         (RHS->getValue() == 0 || RHS->getValue() == 1))
12880       // Do not diagnose common idioms.
12881       return;
12882     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12883       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12884   }
12885 }
12886 
12887 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12888                                     SourceLocation CC,
12889                                     bool *ICContext = nullptr,
12890                                     bool IsListInit = false) {
12891   if (E->isTypeDependent() || E->isValueDependent()) return;
12892 
12893   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12894   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12895   if (Source == Target) return;
12896   if (Target->isDependentType()) return;
12897 
12898   // If the conversion context location is invalid don't complain. We also
12899   // don't want to emit a warning if the issue occurs from the expansion of
12900   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12901   // delay this check as long as possible. Once we detect we are in that
12902   // scenario, we just return.
12903   if (CC.isInvalid())
12904     return;
12905 
12906   if (Source->isAtomicType())
12907     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12908 
12909   // Diagnose implicit casts to bool.
12910   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12911     if (isa<StringLiteral>(E))
12912       // Warn on string literal to bool.  Checks for string literals in logical
12913       // and expressions, for instance, assert(0 && "error here"), are
12914       // prevented by a check in AnalyzeImplicitConversions().
12915       return DiagnoseImpCast(S, E, T, CC,
12916                              diag::warn_impcast_string_literal_to_bool);
12917     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12918         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12919       // This covers the literal expressions that evaluate to Objective-C
12920       // objects.
12921       return DiagnoseImpCast(S, E, T, CC,
12922                              diag::warn_impcast_objective_c_literal_to_bool);
12923     }
12924     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12925       // Warn on pointer to bool conversion that is always true.
12926       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12927                                      SourceRange(CC));
12928     }
12929   }
12930 
12931   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12932   // is a typedef for signed char (macOS), then that constant value has to be 1
12933   // or 0.
12934   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12935     Expr::EvalResult Result;
12936     if (E->EvaluateAsInt(Result, S.getASTContext(),
12937                          Expr::SE_AllowSideEffects)) {
12938       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12939         adornObjCBoolConversionDiagWithTernaryFixit(
12940             S, E,
12941             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12942                 << toString(Result.Val.getInt(), 10));
12943       }
12944       return;
12945     }
12946   }
12947 
12948   // Check implicit casts from Objective-C collection literals to specialized
12949   // collection types, e.g., NSArray<NSString *> *.
12950   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12951     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12952   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12953     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12954 
12955   // Strip vector types.
12956   if (isa<VectorType>(Source)) {
12957     if (Target->isVLSTBuiltinType() &&
12958         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12959                                          QualType(Source, 0)) ||
12960          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12961                                             QualType(Source, 0))))
12962       return;
12963 
12964     if (!isa<VectorType>(Target)) {
12965       if (S.SourceMgr.isInSystemMacro(CC))
12966         return;
12967       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12968     }
12969 
12970     // If the vector cast is cast between two vectors of the same size, it is
12971     // a bitcast, not a conversion.
12972     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12973       return;
12974 
12975     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12976     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12977   }
12978   if (auto VecTy = dyn_cast<VectorType>(Target))
12979     Target = VecTy->getElementType().getTypePtr();
12980 
12981   // Strip complex types.
12982   if (isa<ComplexType>(Source)) {
12983     if (!isa<ComplexType>(Target)) {
12984       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12985         return;
12986 
12987       return DiagnoseImpCast(S, E, T, CC,
12988                              S.getLangOpts().CPlusPlus
12989                                  ? diag::err_impcast_complex_scalar
12990                                  : diag::warn_impcast_complex_scalar);
12991     }
12992 
12993     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12994     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12995   }
12996 
12997   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12998   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12999 
13000   // If the source is floating point...
13001   if (SourceBT && SourceBT->isFloatingPoint()) {
13002     // ...and the target is floating point...
13003     if (TargetBT && TargetBT->isFloatingPoint()) {
13004       // ...then warn if we're dropping FP rank.
13005 
13006       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13007           QualType(SourceBT, 0), QualType(TargetBT, 0));
13008       if (Order > 0) {
13009         // Don't warn about float constants that are precisely
13010         // representable in the target type.
13011         Expr::EvalResult result;
13012         if (E->EvaluateAsRValue(result, S.Context)) {
13013           // Value might be a float, a float vector, or a float complex.
13014           if (IsSameFloatAfterCast(result.Val,
13015                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13016                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13017             return;
13018         }
13019 
13020         if (S.SourceMgr.isInSystemMacro(CC))
13021           return;
13022 
13023         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13024       }
13025       // ... or possibly if we're increasing rank, too
13026       else if (Order < 0) {
13027         if (S.SourceMgr.isInSystemMacro(CC))
13028           return;
13029 
13030         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13031       }
13032       return;
13033     }
13034 
13035     // If the target is integral, always warn.
13036     if (TargetBT && TargetBT->isInteger()) {
13037       if (S.SourceMgr.isInSystemMacro(CC))
13038         return;
13039 
13040       DiagnoseFloatingImpCast(S, E, T, CC);
13041     }
13042 
13043     // Detect the case where a call result is converted from floating-point to
13044     // to bool, and the final argument to the call is converted from bool, to
13045     // discover this typo:
13046     //
13047     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13048     //
13049     // FIXME: This is an incredibly special case; is there some more general
13050     // way to detect this class of misplaced-parentheses bug?
13051     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13052       // Check last argument of function call to see if it is an
13053       // implicit cast from a type matching the type the result
13054       // is being cast to.
13055       CallExpr *CEx = cast<CallExpr>(E);
13056       if (unsigned NumArgs = CEx->getNumArgs()) {
13057         Expr *LastA = CEx->getArg(NumArgs - 1);
13058         Expr *InnerE = LastA->IgnoreParenImpCasts();
13059         if (isa<ImplicitCastExpr>(LastA) &&
13060             InnerE->getType()->isBooleanType()) {
13061           // Warn on this floating-point to bool conversion
13062           DiagnoseImpCast(S, E, T, CC,
13063                           diag::warn_impcast_floating_point_to_bool);
13064         }
13065       }
13066     }
13067     return;
13068   }
13069 
13070   // Valid casts involving fixed point types should be accounted for here.
13071   if (Source->isFixedPointType()) {
13072     if (Target->isUnsaturatedFixedPointType()) {
13073       Expr::EvalResult Result;
13074       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13075                                   S.isConstantEvaluated())) {
13076         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13077         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13078         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13079         if (Value > MaxVal || Value < MinVal) {
13080           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13081                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13082                                     << Value.toString() << T
13083                                     << E->getSourceRange()
13084                                     << clang::SourceRange(CC));
13085           return;
13086         }
13087       }
13088     } else if (Target->isIntegerType()) {
13089       Expr::EvalResult Result;
13090       if (!S.isConstantEvaluated() &&
13091           E->EvaluateAsFixedPoint(Result, S.Context,
13092                                   Expr::SE_AllowSideEffects)) {
13093         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13094 
13095         bool Overflowed;
13096         llvm::APSInt IntResult = FXResult.convertToInt(
13097             S.Context.getIntWidth(T),
13098             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13099 
13100         if (Overflowed) {
13101           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13102                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13103                                     << FXResult.toString() << T
13104                                     << E->getSourceRange()
13105                                     << clang::SourceRange(CC));
13106           return;
13107         }
13108       }
13109     }
13110   } else if (Target->isUnsaturatedFixedPointType()) {
13111     if (Source->isIntegerType()) {
13112       Expr::EvalResult Result;
13113       if (!S.isConstantEvaluated() &&
13114           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13115         llvm::APSInt Value = Result.Val.getInt();
13116 
13117         bool Overflowed;
13118         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13119             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13120 
13121         if (Overflowed) {
13122           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13123                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13124                                     << toString(Value, /*Radix=*/10) << T
13125                                     << E->getSourceRange()
13126                                     << clang::SourceRange(CC));
13127           return;
13128         }
13129       }
13130     }
13131   }
13132 
13133   // If we are casting an integer type to a floating point type without
13134   // initialization-list syntax, we might lose accuracy if the floating
13135   // point type has a narrower significand than the integer type.
13136   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13137       TargetBT->isFloatingType() && !IsListInit) {
13138     // Determine the number of precision bits in the source integer type.
13139     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13140                                         /*Approximate*/ true);
13141     unsigned int SourcePrecision = SourceRange.Width;
13142 
13143     // Determine the number of precision bits in the
13144     // target floating point type.
13145     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13146         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13147 
13148     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13149         SourcePrecision > TargetPrecision) {
13150 
13151       if (Optional<llvm::APSInt> SourceInt =
13152               E->getIntegerConstantExpr(S.Context)) {
13153         // If the source integer is a constant, convert it to the target
13154         // floating point type. Issue a warning if the value changes
13155         // during the whole conversion.
13156         llvm::APFloat TargetFloatValue(
13157             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13158         llvm::APFloat::opStatus ConversionStatus =
13159             TargetFloatValue.convertFromAPInt(
13160                 *SourceInt, SourceBT->isSignedInteger(),
13161                 llvm::APFloat::rmNearestTiesToEven);
13162 
13163         if (ConversionStatus != llvm::APFloat::opOK) {
13164           SmallString<32> PrettySourceValue;
13165           SourceInt->toString(PrettySourceValue, 10);
13166           SmallString<32> PrettyTargetValue;
13167           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13168 
13169           S.DiagRuntimeBehavior(
13170               E->getExprLoc(), E,
13171               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13172                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13173                   << E->getSourceRange() << clang::SourceRange(CC));
13174         }
13175       } else {
13176         // Otherwise, the implicit conversion may lose precision.
13177         DiagnoseImpCast(S, E, T, CC,
13178                         diag::warn_impcast_integer_float_precision);
13179       }
13180     }
13181   }
13182 
13183   DiagnoseNullConversion(S, E, T, CC);
13184 
13185   S.DiscardMisalignedMemberAddress(Target, E);
13186 
13187   if (Target->isBooleanType())
13188     DiagnoseIntInBoolContext(S, E);
13189 
13190   if (!Source->isIntegerType() || !Target->isIntegerType())
13191     return;
13192 
13193   // TODO: remove this early return once the false positives for constant->bool
13194   // in templates, macros, etc, are reduced or removed.
13195   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13196     return;
13197 
13198   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13199       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13200     return adornObjCBoolConversionDiagWithTernaryFixit(
13201         S, E,
13202         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13203             << E->getType());
13204   }
13205 
13206   IntRange SourceTypeRange =
13207       IntRange::forTargetOfCanonicalType(S.Context, Source);
13208   IntRange LikelySourceRange =
13209       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13210   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13211 
13212   if (LikelySourceRange.Width > TargetRange.Width) {
13213     // If the source is a constant, use a default-on diagnostic.
13214     // TODO: this should happen for bitfield stores, too.
13215     Expr::EvalResult Result;
13216     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13217                          S.isConstantEvaluated())) {
13218       llvm::APSInt Value(32);
13219       Value = Result.Val.getInt();
13220 
13221       if (S.SourceMgr.isInSystemMacro(CC))
13222         return;
13223 
13224       std::string PrettySourceValue = toString(Value, 10);
13225       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13226 
13227       S.DiagRuntimeBehavior(
13228           E->getExprLoc(), E,
13229           S.PDiag(diag::warn_impcast_integer_precision_constant)
13230               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13231               << E->getSourceRange() << SourceRange(CC));
13232       return;
13233     }
13234 
13235     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13236     if (S.SourceMgr.isInSystemMacro(CC))
13237       return;
13238 
13239     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13240       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13241                              /* pruneControlFlow */ true);
13242     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13243   }
13244 
13245   if (TargetRange.Width > SourceTypeRange.Width) {
13246     if (auto *UO = dyn_cast<UnaryOperator>(E))
13247       if (UO->getOpcode() == UO_Minus)
13248         if (Source->isUnsignedIntegerType()) {
13249           if (Target->isUnsignedIntegerType())
13250             return DiagnoseImpCast(S, E, T, CC,
13251                                    diag::warn_impcast_high_order_zero_bits);
13252           if (Target->isSignedIntegerType())
13253             return DiagnoseImpCast(S, E, T, CC,
13254                                    diag::warn_impcast_nonnegative_result);
13255         }
13256   }
13257 
13258   if (TargetRange.Width == LikelySourceRange.Width &&
13259       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13260       Source->isSignedIntegerType()) {
13261     // Warn when doing a signed to signed conversion, warn if the positive
13262     // source value is exactly the width of the target type, which will
13263     // cause a negative value to be stored.
13264 
13265     Expr::EvalResult Result;
13266     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13267         !S.SourceMgr.isInSystemMacro(CC)) {
13268       llvm::APSInt Value = Result.Val.getInt();
13269       if (isSameWidthConstantConversion(S, E, T, CC)) {
13270         std::string PrettySourceValue = toString(Value, 10);
13271         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13272 
13273         S.DiagRuntimeBehavior(
13274             E->getExprLoc(), E,
13275             S.PDiag(diag::warn_impcast_integer_precision_constant)
13276                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13277                 << E->getSourceRange() << SourceRange(CC));
13278         return;
13279       }
13280     }
13281 
13282     // Fall through for non-constants to give a sign conversion warning.
13283   }
13284 
13285   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13286       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13287        LikelySourceRange.Width == TargetRange.Width)) {
13288     if (S.SourceMgr.isInSystemMacro(CC))
13289       return;
13290 
13291     unsigned DiagID = diag::warn_impcast_integer_sign;
13292 
13293     // Traditionally, gcc has warned about this under -Wsign-compare.
13294     // We also want to warn about it in -Wconversion.
13295     // So if -Wconversion is off, use a completely identical diagnostic
13296     // in the sign-compare group.
13297     // The conditional-checking code will
13298     if (ICContext) {
13299       DiagID = diag::warn_impcast_integer_sign_conditional;
13300       *ICContext = true;
13301     }
13302 
13303     return DiagnoseImpCast(S, E, T, CC, DiagID);
13304   }
13305 
13306   // Diagnose conversions between different enumeration types.
13307   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13308   // type, to give us better diagnostics.
13309   QualType SourceType = E->getType();
13310   if (!S.getLangOpts().CPlusPlus) {
13311     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13312       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13313         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13314         SourceType = S.Context.getTypeDeclType(Enum);
13315         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13316       }
13317   }
13318 
13319   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13320     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13321       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13322           TargetEnum->getDecl()->hasNameForLinkage() &&
13323           SourceEnum != TargetEnum) {
13324         if (S.SourceMgr.isInSystemMacro(CC))
13325           return;
13326 
13327         return DiagnoseImpCast(S, E, SourceType, T, CC,
13328                                diag::warn_impcast_different_enum_types);
13329       }
13330 }
13331 
13332 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13333                                      SourceLocation CC, QualType T);
13334 
13335 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13336                                     SourceLocation CC, bool &ICContext) {
13337   E = E->IgnoreParenImpCasts();
13338 
13339   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13340     return CheckConditionalOperator(S, CO, CC, T);
13341 
13342   AnalyzeImplicitConversions(S, E, CC);
13343   if (E->getType() != T)
13344     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13345 }
13346 
13347 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13348                                      SourceLocation CC, QualType T) {
13349   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13350 
13351   Expr *TrueExpr = E->getTrueExpr();
13352   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13353     TrueExpr = BCO->getCommon();
13354 
13355   bool Suspicious = false;
13356   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13357   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13358 
13359   if (T->isBooleanType())
13360     DiagnoseIntInBoolContext(S, E);
13361 
13362   // If -Wconversion would have warned about either of the candidates
13363   // for a signedness conversion to the context type...
13364   if (!Suspicious) return;
13365 
13366   // ...but it's currently ignored...
13367   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13368     return;
13369 
13370   // ...then check whether it would have warned about either of the
13371   // candidates for a signedness conversion to the condition type.
13372   if (E->getType() == T) return;
13373 
13374   Suspicious = false;
13375   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13376                           E->getType(), CC, &Suspicious);
13377   if (!Suspicious)
13378     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13379                             E->getType(), CC, &Suspicious);
13380 }
13381 
13382 /// Check conversion of given expression to boolean.
13383 /// Input argument E is a logical expression.
13384 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13385   if (S.getLangOpts().Bool)
13386     return;
13387   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13388     return;
13389   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13390 }
13391 
13392 namespace {
13393 struct AnalyzeImplicitConversionsWorkItem {
13394   Expr *E;
13395   SourceLocation CC;
13396   bool IsListInit;
13397 };
13398 }
13399 
13400 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13401 /// that should be visited are added to WorkList.
13402 static void AnalyzeImplicitConversions(
13403     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13404     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13405   Expr *OrigE = Item.E;
13406   SourceLocation CC = Item.CC;
13407 
13408   QualType T = OrigE->getType();
13409   Expr *E = OrigE->IgnoreParenImpCasts();
13410 
13411   // Propagate whether we are in a C++ list initialization expression.
13412   // If so, we do not issue warnings for implicit int-float conversion
13413   // precision loss, because C++11 narrowing already handles it.
13414   bool IsListInit = Item.IsListInit ||
13415                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13416 
13417   if (E->isTypeDependent() || E->isValueDependent())
13418     return;
13419 
13420   Expr *SourceExpr = E;
13421   // Examine, but don't traverse into the source expression of an
13422   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13423   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13424   // evaluate it in the context of checking the specific conversion to T though.
13425   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13426     if (auto *Src = OVE->getSourceExpr())
13427       SourceExpr = Src;
13428 
13429   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13430     if (UO->getOpcode() == UO_Not &&
13431         UO->getSubExpr()->isKnownToHaveBooleanValue())
13432       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13433           << OrigE->getSourceRange() << T->isBooleanType()
13434           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13435 
13436   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13437     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13438         BO->getLHS()->isKnownToHaveBooleanValue() &&
13439         BO->getRHS()->isKnownToHaveBooleanValue() &&
13440         BO->getLHS()->HasSideEffects(S.Context) &&
13441         BO->getRHS()->HasSideEffects(S.Context)) {
13442       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13443           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13444           << FixItHint::CreateReplacement(
13445                  BO->getOperatorLoc(),
13446                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13447       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13448     }
13449 
13450   // For conditional operators, we analyze the arguments as if they
13451   // were being fed directly into the output.
13452   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13453     CheckConditionalOperator(S, CO, CC, T);
13454     return;
13455   }
13456 
13457   // Check implicit argument conversions for function calls.
13458   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13459     CheckImplicitArgumentConversions(S, Call, CC);
13460 
13461   // Go ahead and check any implicit conversions we might have skipped.
13462   // The non-canonical typecheck is just an optimization;
13463   // CheckImplicitConversion will filter out dead implicit conversions.
13464   if (SourceExpr->getType() != T)
13465     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13466 
13467   // Now continue drilling into this expression.
13468 
13469   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13470     // The bound subexpressions in a PseudoObjectExpr are not reachable
13471     // as transitive children.
13472     // FIXME: Use a more uniform representation for this.
13473     for (auto *SE : POE->semantics())
13474       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13475         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13476   }
13477 
13478   // Skip past explicit casts.
13479   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13480     E = CE->getSubExpr()->IgnoreParenImpCasts();
13481     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13482       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13483     WorkList.push_back({E, CC, IsListInit});
13484     return;
13485   }
13486 
13487   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13488     // Do a somewhat different check with comparison operators.
13489     if (BO->isComparisonOp())
13490       return AnalyzeComparison(S, BO);
13491 
13492     // And with simple assignments.
13493     if (BO->getOpcode() == BO_Assign)
13494       return AnalyzeAssignment(S, BO);
13495     // And with compound assignments.
13496     if (BO->isAssignmentOp())
13497       return AnalyzeCompoundAssignment(S, BO);
13498   }
13499 
13500   // These break the otherwise-useful invariant below.  Fortunately,
13501   // we don't really need to recurse into them, because any internal
13502   // expressions should have been analyzed already when they were
13503   // built into statements.
13504   if (isa<StmtExpr>(E)) return;
13505 
13506   // Don't descend into unevaluated contexts.
13507   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13508 
13509   // Now just recurse over the expression's children.
13510   CC = E->getExprLoc();
13511   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13512   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13513   for (Stmt *SubStmt : E->children()) {
13514     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13515     if (!ChildExpr)
13516       continue;
13517 
13518     if (IsLogicalAndOperator &&
13519         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13520       // Ignore checking string literals that are in logical and operators.
13521       // This is a common pattern for asserts.
13522       continue;
13523     WorkList.push_back({ChildExpr, CC, IsListInit});
13524   }
13525 
13526   if (BO && BO->isLogicalOp()) {
13527     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13528     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13529       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13530 
13531     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13532     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13533       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13534   }
13535 
13536   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13537     if (U->getOpcode() == UO_LNot) {
13538       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13539     } else if (U->getOpcode() != UO_AddrOf) {
13540       if (U->getSubExpr()->getType()->isAtomicType())
13541         S.Diag(U->getSubExpr()->getBeginLoc(),
13542                diag::warn_atomic_implicit_seq_cst);
13543     }
13544   }
13545 }
13546 
13547 /// AnalyzeImplicitConversions - Find and report any interesting
13548 /// implicit conversions in the given expression.  There are a couple
13549 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13550 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13551                                        bool IsListInit/*= false*/) {
13552   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13553   WorkList.push_back({OrigE, CC, IsListInit});
13554   while (!WorkList.empty())
13555     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13556 }
13557 
13558 /// Diagnose integer type and any valid implicit conversion to it.
13559 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13560   // Taking into account implicit conversions,
13561   // allow any integer.
13562   if (!E->getType()->isIntegerType()) {
13563     S.Diag(E->getBeginLoc(),
13564            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13565     return true;
13566   }
13567   // Potentially emit standard warnings for implicit conversions if enabled
13568   // using -Wconversion.
13569   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13570   return false;
13571 }
13572 
13573 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13574 // Returns true when emitting a warning about taking the address of a reference.
13575 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13576                               const PartialDiagnostic &PD) {
13577   E = E->IgnoreParenImpCasts();
13578 
13579   const FunctionDecl *FD = nullptr;
13580 
13581   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13582     if (!DRE->getDecl()->getType()->isReferenceType())
13583       return false;
13584   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13585     if (!M->getMemberDecl()->getType()->isReferenceType())
13586       return false;
13587   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13588     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13589       return false;
13590     FD = Call->getDirectCallee();
13591   } else {
13592     return false;
13593   }
13594 
13595   SemaRef.Diag(E->getExprLoc(), PD);
13596 
13597   // If possible, point to location of function.
13598   if (FD) {
13599     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13600   }
13601 
13602   return true;
13603 }
13604 
13605 // Returns true if the SourceLocation is expanded from any macro body.
13606 // Returns false if the SourceLocation is invalid, is from not in a macro
13607 // expansion, or is from expanded from a top-level macro argument.
13608 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13609   if (Loc.isInvalid())
13610     return false;
13611 
13612   while (Loc.isMacroID()) {
13613     if (SM.isMacroBodyExpansion(Loc))
13614       return true;
13615     Loc = SM.getImmediateMacroCallerLoc(Loc);
13616   }
13617 
13618   return false;
13619 }
13620 
13621 /// Diagnose pointers that are always non-null.
13622 /// \param E the expression containing the pointer
13623 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13624 /// compared to a null pointer
13625 /// \param IsEqual True when the comparison is equal to a null pointer
13626 /// \param Range Extra SourceRange to highlight in the diagnostic
13627 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13628                                         Expr::NullPointerConstantKind NullKind,
13629                                         bool IsEqual, SourceRange Range) {
13630   if (!E)
13631     return;
13632 
13633   // Don't warn inside macros.
13634   if (E->getExprLoc().isMacroID()) {
13635     const SourceManager &SM = getSourceManager();
13636     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13637         IsInAnyMacroBody(SM, Range.getBegin()))
13638       return;
13639   }
13640   E = E->IgnoreImpCasts();
13641 
13642   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13643 
13644   if (isa<CXXThisExpr>(E)) {
13645     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13646                                 : diag::warn_this_bool_conversion;
13647     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13648     return;
13649   }
13650 
13651   bool IsAddressOf = false;
13652 
13653   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13654     if (UO->getOpcode() != UO_AddrOf)
13655       return;
13656     IsAddressOf = true;
13657     E = UO->getSubExpr();
13658   }
13659 
13660   if (IsAddressOf) {
13661     unsigned DiagID = IsCompare
13662                           ? diag::warn_address_of_reference_null_compare
13663                           : diag::warn_address_of_reference_bool_conversion;
13664     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13665                                          << IsEqual;
13666     if (CheckForReference(*this, E, PD)) {
13667       return;
13668     }
13669   }
13670 
13671   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13672     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13673     std::string Str;
13674     llvm::raw_string_ostream S(Str);
13675     E->printPretty(S, nullptr, getPrintingPolicy());
13676     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13677                                 : diag::warn_cast_nonnull_to_bool;
13678     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13679       << E->getSourceRange() << Range << IsEqual;
13680     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13681   };
13682 
13683   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13684   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13685     if (auto *Callee = Call->getDirectCallee()) {
13686       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13687         ComplainAboutNonnullParamOrCall(A);
13688         return;
13689       }
13690     }
13691   }
13692 
13693   // Expect to find a single Decl.  Skip anything more complicated.
13694   ValueDecl *D = nullptr;
13695   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13696     D = R->getDecl();
13697   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13698     D = M->getMemberDecl();
13699   }
13700 
13701   // Weak Decls can be null.
13702   if (!D || D->isWeak())
13703     return;
13704 
13705   // Check for parameter decl with nonnull attribute
13706   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13707     if (getCurFunction() &&
13708         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13709       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13710         ComplainAboutNonnullParamOrCall(A);
13711         return;
13712       }
13713 
13714       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13715         // Skip function template not specialized yet.
13716         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13717           return;
13718         auto ParamIter = llvm::find(FD->parameters(), PV);
13719         assert(ParamIter != FD->param_end());
13720         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13721 
13722         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13723           if (!NonNull->args_size()) {
13724               ComplainAboutNonnullParamOrCall(NonNull);
13725               return;
13726           }
13727 
13728           for (const ParamIdx &ArgNo : NonNull->args()) {
13729             if (ArgNo.getASTIndex() == ParamNo) {
13730               ComplainAboutNonnullParamOrCall(NonNull);
13731               return;
13732             }
13733           }
13734         }
13735       }
13736     }
13737   }
13738 
13739   QualType T = D->getType();
13740   const bool IsArray = T->isArrayType();
13741   const bool IsFunction = T->isFunctionType();
13742 
13743   // Address of function is used to silence the function warning.
13744   if (IsAddressOf && IsFunction) {
13745     return;
13746   }
13747 
13748   // Found nothing.
13749   if (!IsAddressOf && !IsFunction && !IsArray)
13750     return;
13751 
13752   // Pretty print the expression for the diagnostic.
13753   std::string Str;
13754   llvm::raw_string_ostream S(Str);
13755   E->printPretty(S, nullptr, getPrintingPolicy());
13756 
13757   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13758                               : diag::warn_impcast_pointer_to_bool;
13759   enum {
13760     AddressOf,
13761     FunctionPointer,
13762     ArrayPointer
13763   } DiagType;
13764   if (IsAddressOf)
13765     DiagType = AddressOf;
13766   else if (IsFunction)
13767     DiagType = FunctionPointer;
13768   else if (IsArray)
13769     DiagType = ArrayPointer;
13770   else
13771     llvm_unreachable("Could not determine diagnostic.");
13772   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13773                                 << Range << IsEqual;
13774 
13775   if (!IsFunction)
13776     return;
13777 
13778   // Suggest '&' to silence the function warning.
13779   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13780       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13781 
13782   // Check to see if '()' fixit should be emitted.
13783   QualType ReturnType;
13784   UnresolvedSet<4> NonTemplateOverloads;
13785   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13786   if (ReturnType.isNull())
13787     return;
13788 
13789   if (IsCompare) {
13790     // There are two cases here.  If there is null constant, the only suggest
13791     // for a pointer return type.  If the null is 0, then suggest if the return
13792     // type is a pointer or an integer type.
13793     if (!ReturnType->isPointerType()) {
13794       if (NullKind == Expr::NPCK_ZeroExpression ||
13795           NullKind == Expr::NPCK_ZeroLiteral) {
13796         if (!ReturnType->isIntegerType())
13797           return;
13798       } else {
13799         return;
13800       }
13801     }
13802   } else { // !IsCompare
13803     // For function to bool, only suggest if the function pointer has bool
13804     // return type.
13805     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13806       return;
13807   }
13808   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13809       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13810 }
13811 
13812 /// Diagnoses "dangerous" implicit conversions within the given
13813 /// expression (which is a full expression).  Implements -Wconversion
13814 /// and -Wsign-compare.
13815 ///
13816 /// \param CC the "context" location of the implicit conversion, i.e.
13817 ///   the most location of the syntactic entity requiring the implicit
13818 ///   conversion
13819 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13820   // Don't diagnose in unevaluated contexts.
13821   if (isUnevaluatedContext())
13822     return;
13823 
13824   // Don't diagnose for value- or type-dependent expressions.
13825   if (E->isTypeDependent() || E->isValueDependent())
13826     return;
13827 
13828   // Check for array bounds violations in cases where the check isn't triggered
13829   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13830   // ArraySubscriptExpr is on the RHS of a variable initialization.
13831   CheckArrayAccess(E);
13832 
13833   // This is not the right CC for (e.g.) a variable initialization.
13834   AnalyzeImplicitConversions(*this, E, CC);
13835 }
13836 
13837 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13838 /// Input argument E is a logical expression.
13839 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13840   ::CheckBoolLikeConversion(*this, E, CC);
13841 }
13842 
13843 /// Diagnose when expression is an integer constant expression and its evaluation
13844 /// results in integer overflow
13845 void Sema::CheckForIntOverflow (Expr *E) {
13846   // Use a work list to deal with nested struct initializers.
13847   SmallVector<Expr *, 2> Exprs(1, E);
13848 
13849   do {
13850     Expr *OriginalE = Exprs.pop_back_val();
13851     Expr *E = OriginalE->IgnoreParenCasts();
13852 
13853     if (isa<BinaryOperator>(E)) {
13854       E->EvaluateForOverflow(Context);
13855       continue;
13856     }
13857 
13858     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13859       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13860     else if (isa<ObjCBoxedExpr>(OriginalE))
13861       E->EvaluateForOverflow(Context);
13862     else if (auto Call = dyn_cast<CallExpr>(E))
13863       Exprs.append(Call->arg_begin(), Call->arg_end());
13864     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13865       Exprs.append(Message->arg_begin(), Message->arg_end());
13866   } while (!Exprs.empty());
13867 }
13868 
13869 namespace {
13870 
13871 /// Visitor for expressions which looks for unsequenced operations on the
13872 /// same object.
13873 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13874   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13875 
13876   /// A tree of sequenced regions within an expression. Two regions are
13877   /// unsequenced if one is an ancestor or a descendent of the other. When we
13878   /// finish processing an expression with sequencing, such as a comma
13879   /// expression, we fold its tree nodes into its parent, since they are
13880   /// unsequenced with respect to nodes we will visit later.
13881   class SequenceTree {
13882     struct Value {
13883       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13884       unsigned Parent : 31;
13885       unsigned Merged : 1;
13886     };
13887     SmallVector<Value, 8> Values;
13888 
13889   public:
13890     /// A region within an expression which may be sequenced with respect
13891     /// to some other region.
13892     class Seq {
13893       friend class SequenceTree;
13894 
13895       unsigned Index;
13896 
13897       explicit Seq(unsigned N) : Index(N) {}
13898 
13899     public:
13900       Seq() : Index(0) {}
13901     };
13902 
13903     SequenceTree() { Values.push_back(Value(0)); }
13904     Seq root() const { return Seq(0); }
13905 
13906     /// Create a new sequence of operations, which is an unsequenced
13907     /// subset of \p Parent. This sequence of operations is sequenced with
13908     /// respect to other children of \p Parent.
13909     Seq allocate(Seq Parent) {
13910       Values.push_back(Value(Parent.Index));
13911       return Seq(Values.size() - 1);
13912     }
13913 
13914     /// Merge a sequence of operations into its parent.
13915     void merge(Seq S) {
13916       Values[S.Index].Merged = true;
13917     }
13918 
13919     /// Determine whether two operations are unsequenced. This operation
13920     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13921     /// should have been merged into its parent as appropriate.
13922     bool isUnsequenced(Seq Cur, Seq Old) {
13923       unsigned C = representative(Cur.Index);
13924       unsigned Target = representative(Old.Index);
13925       while (C >= Target) {
13926         if (C == Target)
13927           return true;
13928         C = Values[C].Parent;
13929       }
13930       return false;
13931     }
13932 
13933   private:
13934     /// Pick a representative for a sequence.
13935     unsigned representative(unsigned K) {
13936       if (Values[K].Merged)
13937         // Perform path compression as we go.
13938         return Values[K].Parent = representative(Values[K].Parent);
13939       return K;
13940     }
13941   };
13942 
13943   /// An object for which we can track unsequenced uses.
13944   using Object = const NamedDecl *;
13945 
13946   /// Different flavors of object usage which we track. We only track the
13947   /// least-sequenced usage of each kind.
13948   enum UsageKind {
13949     /// A read of an object. Multiple unsequenced reads are OK.
13950     UK_Use,
13951 
13952     /// A modification of an object which is sequenced before the value
13953     /// computation of the expression, such as ++n in C++.
13954     UK_ModAsValue,
13955 
13956     /// A modification of an object which is not sequenced before the value
13957     /// computation of the expression, such as n++.
13958     UK_ModAsSideEffect,
13959 
13960     UK_Count = UK_ModAsSideEffect + 1
13961   };
13962 
13963   /// Bundle together a sequencing region and the expression corresponding
13964   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13965   struct Usage {
13966     const Expr *UsageExpr;
13967     SequenceTree::Seq Seq;
13968 
13969     Usage() : UsageExpr(nullptr), Seq() {}
13970   };
13971 
13972   struct UsageInfo {
13973     Usage Uses[UK_Count];
13974 
13975     /// Have we issued a diagnostic for this object already?
13976     bool Diagnosed;
13977 
13978     UsageInfo() : Uses(), Diagnosed(false) {}
13979   };
13980   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13981 
13982   Sema &SemaRef;
13983 
13984   /// Sequenced regions within the expression.
13985   SequenceTree Tree;
13986 
13987   /// Declaration modifications and references which we have seen.
13988   UsageInfoMap UsageMap;
13989 
13990   /// The region we are currently within.
13991   SequenceTree::Seq Region;
13992 
13993   /// Filled in with declarations which were modified as a side-effect
13994   /// (that is, post-increment operations).
13995   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13996 
13997   /// Expressions to check later. We defer checking these to reduce
13998   /// stack usage.
13999   SmallVectorImpl<const Expr *> &WorkList;
14000 
14001   /// RAII object wrapping the visitation of a sequenced subexpression of an
14002   /// expression. At the end of this process, the side-effects of the evaluation
14003   /// become sequenced with respect to the value computation of the result, so
14004   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14005   /// UK_ModAsValue.
14006   struct SequencedSubexpression {
14007     SequencedSubexpression(SequenceChecker &Self)
14008       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14009       Self.ModAsSideEffect = &ModAsSideEffect;
14010     }
14011 
14012     ~SequencedSubexpression() {
14013       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14014         // Add a new usage with usage kind UK_ModAsValue, and then restore
14015         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14016         // the previous one was empty).
14017         UsageInfo &UI = Self.UsageMap[M.first];
14018         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14019         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14020         SideEffectUsage = M.second;
14021       }
14022       Self.ModAsSideEffect = OldModAsSideEffect;
14023     }
14024 
14025     SequenceChecker &Self;
14026     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14027     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14028   };
14029 
14030   /// RAII object wrapping the visitation of a subexpression which we might
14031   /// choose to evaluate as a constant. If any subexpression is evaluated and
14032   /// found to be non-constant, this allows us to suppress the evaluation of
14033   /// the outer expression.
14034   class EvaluationTracker {
14035   public:
14036     EvaluationTracker(SequenceChecker &Self)
14037         : Self(Self), Prev(Self.EvalTracker) {
14038       Self.EvalTracker = this;
14039     }
14040 
14041     ~EvaluationTracker() {
14042       Self.EvalTracker = Prev;
14043       if (Prev)
14044         Prev->EvalOK &= EvalOK;
14045     }
14046 
14047     bool evaluate(const Expr *E, bool &Result) {
14048       if (!EvalOK || E->isValueDependent())
14049         return false;
14050       EvalOK = E->EvaluateAsBooleanCondition(
14051           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14052       return EvalOK;
14053     }
14054 
14055   private:
14056     SequenceChecker &Self;
14057     EvaluationTracker *Prev;
14058     bool EvalOK = true;
14059   } *EvalTracker = nullptr;
14060 
14061   /// Find the object which is produced by the specified expression,
14062   /// if any.
14063   Object getObject(const Expr *E, bool Mod) const {
14064     E = E->IgnoreParenCasts();
14065     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14066       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14067         return getObject(UO->getSubExpr(), Mod);
14068     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14069       if (BO->getOpcode() == BO_Comma)
14070         return getObject(BO->getRHS(), Mod);
14071       if (Mod && BO->isAssignmentOp())
14072         return getObject(BO->getLHS(), Mod);
14073     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14074       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14075       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14076         return ME->getMemberDecl();
14077     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14078       // FIXME: If this is a reference, map through to its value.
14079       return DRE->getDecl();
14080     return nullptr;
14081   }
14082 
14083   /// Note that an object \p O was modified or used by an expression
14084   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14085   /// the object \p O as obtained via the \p UsageMap.
14086   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14087     // Get the old usage for the given object and usage kind.
14088     Usage &U = UI.Uses[UK];
14089     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14090       // If we have a modification as side effect and are in a sequenced
14091       // subexpression, save the old Usage so that we can restore it later
14092       // in SequencedSubexpression::~SequencedSubexpression.
14093       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14094         ModAsSideEffect->push_back(std::make_pair(O, U));
14095       // Then record the new usage with the current sequencing region.
14096       U.UsageExpr = UsageExpr;
14097       U.Seq = Region;
14098     }
14099   }
14100 
14101   /// Check whether a modification or use of an object \p O in an expression
14102   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14103   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14104   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14105   /// usage and false we are checking for a mod-use unsequenced usage.
14106   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14107                   UsageKind OtherKind, bool IsModMod) {
14108     if (UI.Diagnosed)
14109       return;
14110 
14111     const Usage &U = UI.Uses[OtherKind];
14112     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14113       return;
14114 
14115     const Expr *Mod = U.UsageExpr;
14116     const Expr *ModOrUse = UsageExpr;
14117     if (OtherKind == UK_Use)
14118       std::swap(Mod, ModOrUse);
14119 
14120     SemaRef.DiagRuntimeBehavior(
14121         Mod->getExprLoc(), {Mod, ModOrUse},
14122         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14123                                : diag::warn_unsequenced_mod_use)
14124             << O << SourceRange(ModOrUse->getExprLoc()));
14125     UI.Diagnosed = true;
14126   }
14127 
14128   // A note on note{Pre, Post}{Use, Mod}:
14129   //
14130   // (It helps to follow the algorithm with an expression such as
14131   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14132   //  operations before C++17 and both are well-defined in C++17).
14133   //
14134   // When visiting a node which uses/modify an object we first call notePreUse
14135   // or notePreMod before visiting its sub-expression(s). At this point the
14136   // children of the current node have not yet been visited and so the eventual
14137   // uses/modifications resulting from the children of the current node have not
14138   // been recorded yet.
14139   //
14140   // We then visit the children of the current node. After that notePostUse or
14141   // notePostMod is called. These will 1) detect an unsequenced modification
14142   // as side effect (as in "k++ + k") and 2) add a new usage with the
14143   // appropriate usage kind.
14144   //
14145   // We also have to be careful that some operation sequences modification as
14146   // side effect as well (for example: || or ,). To account for this we wrap
14147   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14148   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14149   // which record usages which are modifications as side effect, and then
14150   // downgrade them (or more accurately restore the previous usage which was a
14151   // modification as side effect) when exiting the scope of the sequenced
14152   // subexpression.
14153 
14154   void notePreUse(Object O, const Expr *UseExpr) {
14155     UsageInfo &UI = UsageMap[O];
14156     // Uses conflict with other modifications.
14157     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14158   }
14159 
14160   void notePostUse(Object O, const Expr *UseExpr) {
14161     UsageInfo &UI = UsageMap[O];
14162     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14163                /*IsModMod=*/false);
14164     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14165   }
14166 
14167   void notePreMod(Object O, const Expr *ModExpr) {
14168     UsageInfo &UI = UsageMap[O];
14169     // Modifications conflict with other modifications and with uses.
14170     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14171     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14172   }
14173 
14174   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14175     UsageInfo &UI = UsageMap[O];
14176     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14177                /*IsModMod=*/true);
14178     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14179   }
14180 
14181 public:
14182   SequenceChecker(Sema &S, const Expr *E,
14183                   SmallVectorImpl<const Expr *> &WorkList)
14184       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14185     Visit(E);
14186     // Silence a -Wunused-private-field since WorkList is now unused.
14187     // TODO: Evaluate if it can be used, and if not remove it.
14188     (void)this->WorkList;
14189   }
14190 
14191   void VisitStmt(const Stmt *S) {
14192     // Skip all statements which aren't expressions for now.
14193   }
14194 
14195   void VisitExpr(const Expr *E) {
14196     // By default, just recurse to evaluated subexpressions.
14197     Base::VisitStmt(E);
14198   }
14199 
14200   void VisitCastExpr(const CastExpr *E) {
14201     Object O = Object();
14202     if (E->getCastKind() == CK_LValueToRValue)
14203       O = getObject(E->getSubExpr(), false);
14204 
14205     if (O)
14206       notePreUse(O, E);
14207     VisitExpr(E);
14208     if (O)
14209       notePostUse(O, E);
14210   }
14211 
14212   void VisitSequencedExpressions(const Expr *SequencedBefore,
14213                                  const Expr *SequencedAfter) {
14214     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14215     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14216     SequenceTree::Seq OldRegion = Region;
14217 
14218     {
14219       SequencedSubexpression SeqBefore(*this);
14220       Region = BeforeRegion;
14221       Visit(SequencedBefore);
14222     }
14223 
14224     Region = AfterRegion;
14225     Visit(SequencedAfter);
14226 
14227     Region = OldRegion;
14228 
14229     Tree.merge(BeforeRegion);
14230     Tree.merge(AfterRegion);
14231   }
14232 
14233   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14234     // C++17 [expr.sub]p1:
14235     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14236     //   expression E1 is sequenced before the expression E2.
14237     if (SemaRef.getLangOpts().CPlusPlus17)
14238       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14239     else {
14240       Visit(ASE->getLHS());
14241       Visit(ASE->getRHS());
14242     }
14243   }
14244 
14245   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14246   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14247   void VisitBinPtrMem(const BinaryOperator *BO) {
14248     // C++17 [expr.mptr.oper]p4:
14249     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14250     //  the expression E1 is sequenced before the expression E2.
14251     if (SemaRef.getLangOpts().CPlusPlus17)
14252       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14253     else {
14254       Visit(BO->getLHS());
14255       Visit(BO->getRHS());
14256     }
14257   }
14258 
14259   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14260   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14261   void VisitBinShlShr(const BinaryOperator *BO) {
14262     // C++17 [expr.shift]p4:
14263     //  The expression E1 is sequenced before the expression E2.
14264     if (SemaRef.getLangOpts().CPlusPlus17)
14265       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14266     else {
14267       Visit(BO->getLHS());
14268       Visit(BO->getRHS());
14269     }
14270   }
14271 
14272   void VisitBinComma(const BinaryOperator *BO) {
14273     // C++11 [expr.comma]p1:
14274     //   Every value computation and side effect associated with the left
14275     //   expression is sequenced before every value computation and side
14276     //   effect associated with the right expression.
14277     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14278   }
14279 
14280   void VisitBinAssign(const BinaryOperator *BO) {
14281     SequenceTree::Seq RHSRegion;
14282     SequenceTree::Seq LHSRegion;
14283     if (SemaRef.getLangOpts().CPlusPlus17) {
14284       RHSRegion = Tree.allocate(Region);
14285       LHSRegion = Tree.allocate(Region);
14286     } else {
14287       RHSRegion = Region;
14288       LHSRegion = Region;
14289     }
14290     SequenceTree::Seq OldRegion = Region;
14291 
14292     // C++11 [expr.ass]p1:
14293     //  [...] the assignment is sequenced after the value computation
14294     //  of the right and left operands, [...]
14295     //
14296     // so check it before inspecting the operands and update the
14297     // map afterwards.
14298     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14299     if (O)
14300       notePreMod(O, BO);
14301 
14302     if (SemaRef.getLangOpts().CPlusPlus17) {
14303       // C++17 [expr.ass]p1:
14304       //  [...] The right operand is sequenced before the left operand. [...]
14305       {
14306         SequencedSubexpression SeqBefore(*this);
14307         Region = RHSRegion;
14308         Visit(BO->getRHS());
14309       }
14310 
14311       Region = LHSRegion;
14312       Visit(BO->getLHS());
14313 
14314       if (O && isa<CompoundAssignOperator>(BO))
14315         notePostUse(O, BO);
14316 
14317     } else {
14318       // C++11 does not specify any sequencing between the LHS and RHS.
14319       Region = LHSRegion;
14320       Visit(BO->getLHS());
14321 
14322       if (O && isa<CompoundAssignOperator>(BO))
14323         notePostUse(O, BO);
14324 
14325       Region = RHSRegion;
14326       Visit(BO->getRHS());
14327     }
14328 
14329     // C++11 [expr.ass]p1:
14330     //  the assignment is sequenced [...] before the value computation of the
14331     //  assignment expression.
14332     // C11 6.5.16/3 has no such rule.
14333     Region = OldRegion;
14334     if (O)
14335       notePostMod(O, BO,
14336                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14337                                                   : UK_ModAsSideEffect);
14338     if (SemaRef.getLangOpts().CPlusPlus17) {
14339       Tree.merge(RHSRegion);
14340       Tree.merge(LHSRegion);
14341     }
14342   }
14343 
14344   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14345     VisitBinAssign(CAO);
14346   }
14347 
14348   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14349   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14350   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14351     Object O = getObject(UO->getSubExpr(), true);
14352     if (!O)
14353       return VisitExpr(UO);
14354 
14355     notePreMod(O, UO);
14356     Visit(UO->getSubExpr());
14357     // C++11 [expr.pre.incr]p1:
14358     //   the expression ++x is equivalent to x+=1
14359     notePostMod(O, UO,
14360                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14361                                                 : UK_ModAsSideEffect);
14362   }
14363 
14364   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14365   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14366   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14367     Object O = getObject(UO->getSubExpr(), true);
14368     if (!O)
14369       return VisitExpr(UO);
14370 
14371     notePreMod(O, UO);
14372     Visit(UO->getSubExpr());
14373     notePostMod(O, UO, UK_ModAsSideEffect);
14374   }
14375 
14376   void VisitBinLOr(const BinaryOperator *BO) {
14377     // C++11 [expr.log.or]p2:
14378     //  If the second expression is evaluated, every value computation and
14379     //  side effect associated with the first expression is sequenced before
14380     //  every value computation and side effect associated with the
14381     //  second expression.
14382     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14383     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14384     SequenceTree::Seq OldRegion = Region;
14385 
14386     EvaluationTracker Eval(*this);
14387     {
14388       SequencedSubexpression Sequenced(*this);
14389       Region = LHSRegion;
14390       Visit(BO->getLHS());
14391     }
14392 
14393     // C++11 [expr.log.or]p1:
14394     //  [...] the second operand is not evaluated if the first operand
14395     //  evaluates to true.
14396     bool EvalResult = false;
14397     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14398     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14399     if (ShouldVisitRHS) {
14400       Region = RHSRegion;
14401       Visit(BO->getRHS());
14402     }
14403 
14404     Region = OldRegion;
14405     Tree.merge(LHSRegion);
14406     Tree.merge(RHSRegion);
14407   }
14408 
14409   void VisitBinLAnd(const BinaryOperator *BO) {
14410     // C++11 [expr.log.and]p2:
14411     //  If the second expression is evaluated, every value computation and
14412     //  side effect associated with the first expression is sequenced before
14413     //  every value computation and side effect associated with the
14414     //  second expression.
14415     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14416     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14417     SequenceTree::Seq OldRegion = Region;
14418 
14419     EvaluationTracker Eval(*this);
14420     {
14421       SequencedSubexpression Sequenced(*this);
14422       Region = LHSRegion;
14423       Visit(BO->getLHS());
14424     }
14425 
14426     // C++11 [expr.log.and]p1:
14427     //  [...] the second operand is not evaluated if the first operand is false.
14428     bool EvalResult = false;
14429     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14430     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14431     if (ShouldVisitRHS) {
14432       Region = RHSRegion;
14433       Visit(BO->getRHS());
14434     }
14435 
14436     Region = OldRegion;
14437     Tree.merge(LHSRegion);
14438     Tree.merge(RHSRegion);
14439   }
14440 
14441   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14442     // C++11 [expr.cond]p1:
14443     //  [...] Every value computation and side effect associated with the first
14444     //  expression is sequenced before every value computation and side effect
14445     //  associated with the second or third expression.
14446     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14447 
14448     // No sequencing is specified between the true and false expression.
14449     // However since exactly one of both is going to be evaluated we can
14450     // consider them to be sequenced. This is needed to avoid warning on
14451     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14452     // both the true and false expressions because we can't evaluate x.
14453     // This will still allow us to detect an expression like (pre C++17)
14454     // "(x ? y += 1 : y += 2) = y".
14455     //
14456     // We don't wrap the visitation of the true and false expression with
14457     // SequencedSubexpression because we don't want to downgrade modifications
14458     // as side effect in the true and false expressions after the visition
14459     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14460     // not warn between the two "y++", but we should warn between the "y++"
14461     // and the "y".
14462     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14463     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14464     SequenceTree::Seq OldRegion = Region;
14465 
14466     EvaluationTracker Eval(*this);
14467     {
14468       SequencedSubexpression Sequenced(*this);
14469       Region = ConditionRegion;
14470       Visit(CO->getCond());
14471     }
14472 
14473     // C++11 [expr.cond]p1:
14474     // [...] The first expression is contextually converted to bool (Clause 4).
14475     // It is evaluated and if it is true, the result of the conditional
14476     // expression is the value of the second expression, otherwise that of the
14477     // third expression. Only one of the second and third expressions is
14478     // evaluated. [...]
14479     bool EvalResult = false;
14480     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14481     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14482     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14483     if (ShouldVisitTrueExpr) {
14484       Region = TrueRegion;
14485       Visit(CO->getTrueExpr());
14486     }
14487     if (ShouldVisitFalseExpr) {
14488       Region = FalseRegion;
14489       Visit(CO->getFalseExpr());
14490     }
14491 
14492     Region = OldRegion;
14493     Tree.merge(ConditionRegion);
14494     Tree.merge(TrueRegion);
14495     Tree.merge(FalseRegion);
14496   }
14497 
14498   void VisitCallExpr(const CallExpr *CE) {
14499     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14500 
14501     if (CE->isUnevaluatedBuiltinCall(Context))
14502       return;
14503 
14504     // C++11 [intro.execution]p15:
14505     //   When calling a function [...], every value computation and side effect
14506     //   associated with any argument expression, or with the postfix expression
14507     //   designating the called function, is sequenced before execution of every
14508     //   expression or statement in the body of the function [and thus before
14509     //   the value computation of its result].
14510     SequencedSubexpression Sequenced(*this);
14511     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14512       // C++17 [expr.call]p5
14513       //   The postfix-expression is sequenced before each expression in the
14514       //   expression-list and any default argument. [...]
14515       SequenceTree::Seq CalleeRegion;
14516       SequenceTree::Seq OtherRegion;
14517       if (SemaRef.getLangOpts().CPlusPlus17) {
14518         CalleeRegion = Tree.allocate(Region);
14519         OtherRegion = Tree.allocate(Region);
14520       } else {
14521         CalleeRegion = Region;
14522         OtherRegion = Region;
14523       }
14524       SequenceTree::Seq OldRegion = Region;
14525 
14526       // Visit the callee expression first.
14527       Region = CalleeRegion;
14528       if (SemaRef.getLangOpts().CPlusPlus17) {
14529         SequencedSubexpression Sequenced(*this);
14530         Visit(CE->getCallee());
14531       } else {
14532         Visit(CE->getCallee());
14533       }
14534 
14535       // Then visit the argument expressions.
14536       Region = OtherRegion;
14537       for (const Expr *Argument : CE->arguments())
14538         Visit(Argument);
14539 
14540       Region = OldRegion;
14541       if (SemaRef.getLangOpts().CPlusPlus17) {
14542         Tree.merge(CalleeRegion);
14543         Tree.merge(OtherRegion);
14544       }
14545     });
14546   }
14547 
14548   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14549     // C++17 [over.match.oper]p2:
14550     //   [...] the operator notation is first transformed to the equivalent
14551     //   function-call notation as summarized in Table 12 (where @ denotes one
14552     //   of the operators covered in the specified subclause). However, the
14553     //   operands are sequenced in the order prescribed for the built-in
14554     //   operator (Clause 8).
14555     //
14556     // From the above only overloaded binary operators and overloaded call
14557     // operators have sequencing rules in C++17 that we need to handle
14558     // separately.
14559     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14560         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14561       return VisitCallExpr(CXXOCE);
14562 
14563     enum {
14564       NoSequencing,
14565       LHSBeforeRHS,
14566       RHSBeforeLHS,
14567       LHSBeforeRest
14568     } SequencingKind;
14569     switch (CXXOCE->getOperator()) {
14570     case OO_Equal:
14571     case OO_PlusEqual:
14572     case OO_MinusEqual:
14573     case OO_StarEqual:
14574     case OO_SlashEqual:
14575     case OO_PercentEqual:
14576     case OO_CaretEqual:
14577     case OO_AmpEqual:
14578     case OO_PipeEqual:
14579     case OO_LessLessEqual:
14580     case OO_GreaterGreaterEqual:
14581       SequencingKind = RHSBeforeLHS;
14582       break;
14583 
14584     case OO_LessLess:
14585     case OO_GreaterGreater:
14586     case OO_AmpAmp:
14587     case OO_PipePipe:
14588     case OO_Comma:
14589     case OO_ArrowStar:
14590     case OO_Subscript:
14591       SequencingKind = LHSBeforeRHS;
14592       break;
14593 
14594     case OO_Call:
14595       SequencingKind = LHSBeforeRest;
14596       break;
14597 
14598     default:
14599       SequencingKind = NoSequencing;
14600       break;
14601     }
14602 
14603     if (SequencingKind == NoSequencing)
14604       return VisitCallExpr(CXXOCE);
14605 
14606     // This is a call, so all subexpressions are sequenced before the result.
14607     SequencedSubexpression Sequenced(*this);
14608 
14609     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14610       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14611              "Should only get there with C++17 and above!");
14612       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14613              "Should only get there with an overloaded binary operator"
14614              " or an overloaded call operator!");
14615 
14616       if (SequencingKind == LHSBeforeRest) {
14617         assert(CXXOCE->getOperator() == OO_Call &&
14618                "We should only have an overloaded call operator here!");
14619 
14620         // This is very similar to VisitCallExpr, except that we only have the
14621         // C++17 case. The postfix-expression is the first argument of the
14622         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14623         // are in the following arguments.
14624         //
14625         // Note that we intentionally do not visit the callee expression since
14626         // it is just a decayed reference to a function.
14627         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14628         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14629         SequenceTree::Seq OldRegion = Region;
14630 
14631         assert(CXXOCE->getNumArgs() >= 1 &&
14632                "An overloaded call operator must have at least one argument"
14633                " for the postfix-expression!");
14634         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14635         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14636                                           CXXOCE->getNumArgs() - 1);
14637 
14638         // Visit the postfix-expression first.
14639         {
14640           Region = PostfixExprRegion;
14641           SequencedSubexpression Sequenced(*this);
14642           Visit(PostfixExpr);
14643         }
14644 
14645         // Then visit the argument expressions.
14646         Region = ArgsRegion;
14647         for (const Expr *Arg : Args)
14648           Visit(Arg);
14649 
14650         Region = OldRegion;
14651         Tree.merge(PostfixExprRegion);
14652         Tree.merge(ArgsRegion);
14653       } else {
14654         assert(CXXOCE->getNumArgs() == 2 &&
14655                "Should only have two arguments here!");
14656         assert((SequencingKind == LHSBeforeRHS ||
14657                 SequencingKind == RHSBeforeLHS) &&
14658                "Unexpected sequencing kind!");
14659 
14660         // We do not visit the callee expression since it is just a decayed
14661         // reference to a function.
14662         const Expr *E1 = CXXOCE->getArg(0);
14663         const Expr *E2 = CXXOCE->getArg(1);
14664         if (SequencingKind == RHSBeforeLHS)
14665           std::swap(E1, E2);
14666 
14667         return VisitSequencedExpressions(E1, E2);
14668       }
14669     });
14670   }
14671 
14672   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14673     // This is a call, so all subexpressions are sequenced before the result.
14674     SequencedSubexpression Sequenced(*this);
14675 
14676     if (!CCE->isListInitialization())
14677       return VisitExpr(CCE);
14678 
14679     // In C++11, list initializations are sequenced.
14680     SmallVector<SequenceTree::Seq, 32> Elts;
14681     SequenceTree::Seq Parent = Region;
14682     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14683                                               E = CCE->arg_end();
14684          I != E; ++I) {
14685       Region = Tree.allocate(Parent);
14686       Elts.push_back(Region);
14687       Visit(*I);
14688     }
14689 
14690     // Forget that the initializers are sequenced.
14691     Region = Parent;
14692     for (unsigned I = 0; I < Elts.size(); ++I)
14693       Tree.merge(Elts[I]);
14694   }
14695 
14696   void VisitInitListExpr(const InitListExpr *ILE) {
14697     if (!SemaRef.getLangOpts().CPlusPlus11)
14698       return VisitExpr(ILE);
14699 
14700     // In C++11, list initializations are sequenced.
14701     SmallVector<SequenceTree::Seq, 32> Elts;
14702     SequenceTree::Seq Parent = Region;
14703     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14704       const Expr *E = ILE->getInit(I);
14705       if (!E)
14706         continue;
14707       Region = Tree.allocate(Parent);
14708       Elts.push_back(Region);
14709       Visit(E);
14710     }
14711 
14712     // Forget that the initializers are sequenced.
14713     Region = Parent;
14714     for (unsigned I = 0; I < Elts.size(); ++I)
14715       Tree.merge(Elts[I]);
14716   }
14717 };
14718 
14719 } // namespace
14720 
14721 void Sema::CheckUnsequencedOperations(const Expr *E) {
14722   SmallVector<const Expr *, 8> WorkList;
14723   WorkList.push_back(E);
14724   while (!WorkList.empty()) {
14725     const Expr *Item = WorkList.pop_back_val();
14726     SequenceChecker(*this, Item, WorkList);
14727   }
14728 }
14729 
14730 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14731                               bool IsConstexpr) {
14732   llvm::SaveAndRestore<bool> ConstantContext(
14733       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14734   CheckImplicitConversions(E, CheckLoc);
14735   if (!E->isInstantiationDependent())
14736     CheckUnsequencedOperations(E);
14737   if (!IsConstexpr && !E->isValueDependent())
14738     CheckForIntOverflow(E);
14739   DiagnoseMisalignedMembers();
14740 }
14741 
14742 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14743                                        FieldDecl *BitField,
14744                                        Expr *Init) {
14745   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14746 }
14747 
14748 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14749                                          SourceLocation Loc) {
14750   if (!PType->isVariablyModifiedType())
14751     return;
14752   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14753     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14754     return;
14755   }
14756   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14757     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14758     return;
14759   }
14760   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14761     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14762     return;
14763   }
14764 
14765   const ArrayType *AT = S.Context.getAsArrayType(PType);
14766   if (!AT)
14767     return;
14768 
14769   if (AT->getSizeModifier() != ArrayType::Star) {
14770     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14771     return;
14772   }
14773 
14774   S.Diag(Loc, diag::err_array_star_in_function_definition);
14775 }
14776 
14777 /// CheckParmsForFunctionDef - Check that the parameters of the given
14778 /// function are appropriate for the definition of a function. This
14779 /// takes care of any checks that cannot be performed on the
14780 /// declaration itself, e.g., that the types of each of the function
14781 /// parameters are complete.
14782 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14783                                     bool CheckParameterNames) {
14784   bool HasInvalidParm = false;
14785   for (ParmVarDecl *Param : Parameters) {
14786     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14787     // function declarator that is part of a function definition of
14788     // that function shall not have incomplete type.
14789     //
14790     // This is also C++ [dcl.fct]p6.
14791     if (!Param->isInvalidDecl() &&
14792         RequireCompleteType(Param->getLocation(), Param->getType(),
14793                             diag::err_typecheck_decl_incomplete_type)) {
14794       Param->setInvalidDecl();
14795       HasInvalidParm = true;
14796     }
14797 
14798     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14799     // declaration of each parameter shall include an identifier.
14800     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14801         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14802       // Diagnose this as an extension in C17 and earlier.
14803       if (!getLangOpts().C2x)
14804         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14805     }
14806 
14807     // C99 6.7.5.3p12:
14808     //   If the function declarator is not part of a definition of that
14809     //   function, parameters may have incomplete type and may use the [*]
14810     //   notation in their sequences of declarator specifiers to specify
14811     //   variable length array types.
14812     QualType PType = Param->getOriginalType();
14813     // FIXME: This diagnostic should point the '[*]' if source-location
14814     // information is added for it.
14815     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14816 
14817     // If the parameter is a c++ class type and it has to be destructed in the
14818     // callee function, declare the destructor so that it can be called by the
14819     // callee function. Do not perform any direct access check on the dtor here.
14820     if (!Param->isInvalidDecl()) {
14821       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14822         if (!ClassDecl->isInvalidDecl() &&
14823             !ClassDecl->hasIrrelevantDestructor() &&
14824             !ClassDecl->isDependentContext() &&
14825             ClassDecl->isParamDestroyedInCallee()) {
14826           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14827           MarkFunctionReferenced(Param->getLocation(), Destructor);
14828           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14829         }
14830       }
14831     }
14832 
14833     // Parameters with the pass_object_size attribute only need to be marked
14834     // constant at function definitions. Because we lack information about
14835     // whether we're on a declaration or definition when we're instantiating the
14836     // attribute, we need to check for constness here.
14837     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14838       if (!Param->getType().isConstQualified())
14839         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14840             << Attr->getSpelling() << 1;
14841 
14842     // Check for parameter names shadowing fields from the class.
14843     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14844       // The owning context for the parameter should be the function, but we
14845       // want to see if this function's declaration context is a record.
14846       DeclContext *DC = Param->getDeclContext();
14847       if (DC && DC->isFunctionOrMethod()) {
14848         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14849           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14850                                      RD, /*DeclIsField*/ false);
14851       }
14852     }
14853   }
14854 
14855   return HasInvalidParm;
14856 }
14857 
14858 Optional<std::pair<CharUnits, CharUnits>>
14859 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14860 
14861 /// Compute the alignment and offset of the base class object given the
14862 /// derived-to-base cast expression and the alignment and offset of the derived
14863 /// class object.
14864 static std::pair<CharUnits, CharUnits>
14865 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14866                                    CharUnits BaseAlignment, CharUnits Offset,
14867                                    ASTContext &Ctx) {
14868   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14869        ++PathI) {
14870     const CXXBaseSpecifier *Base = *PathI;
14871     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14872     if (Base->isVirtual()) {
14873       // The complete object may have a lower alignment than the non-virtual
14874       // alignment of the base, in which case the base may be misaligned. Choose
14875       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14876       // conservative lower bound of the complete object alignment.
14877       CharUnits NonVirtualAlignment =
14878           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14879       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14880       Offset = CharUnits::Zero();
14881     } else {
14882       const ASTRecordLayout &RL =
14883           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14884       Offset += RL.getBaseClassOffset(BaseDecl);
14885     }
14886     DerivedType = Base->getType();
14887   }
14888 
14889   return std::make_pair(BaseAlignment, Offset);
14890 }
14891 
14892 /// Compute the alignment and offset of a binary additive operator.
14893 static Optional<std::pair<CharUnits, CharUnits>>
14894 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14895                                      bool IsSub, ASTContext &Ctx) {
14896   QualType PointeeType = PtrE->getType()->getPointeeType();
14897 
14898   if (!PointeeType->isConstantSizeType())
14899     return llvm::None;
14900 
14901   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14902 
14903   if (!P)
14904     return llvm::None;
14905 
14906   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14907   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14908     CharUnits Offset = EltSize * IdxRes->getExtValue();
14909     if (IsSub)
14910       Offset = -Offset;
14911     return std::make_pair(P->first, P->second + Offset);
14912   }
14913 
14914   // If the integer expression isn't a constant expression, compute the lower
14915   // bound of the alignment using the alignment and offset of the pointer
14916   // expression and the element size.
14917   return std::make_pair(
14918       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14919       CharUnits::Zero());
14920 }
14921 
14922 /// This helper function takes an lvalue expression and returns the alignment of
14923 /// a VarDecl and a constant offset from the VarDecl.
14924 Optional<std::pair<CharUnits, CharUnits>>
14925 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14926   E = E->IgnoreParens();
14927   switch (E->getStmtClass()) {
14928   default:
14929     break;
14930   case Stmt::CStyleCastExprClass:
14931   case Stmt::CXXStaticCastExprClass:
14932   case Stmt::ImplicitCastExprClass: {
14933     auto *CE = cast<CastExpr>(E);
14934     const Expr *From = CE->getSubExpr();
14935     switch (CE->getCastKind()) {
14936     default:
14937       break;
14938     case CK_NoOp:
14939       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14940     case CK_UncheckedDerivedToBase:
14941     case CK_DerivedToBase: {
14942       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14943       if (!P)
14944         break;
14945       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14946                                                 P->second, Ctx);
14947     }
14948     }
14949     break;
14950   }
14951   case Stmt::ArraySubscriptExprClass: {
14952     auto *ASE = cast<ArraySubscriptExpr>(E);
14953     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14954                                                 false, Ctx);
14955   }
14956   case Stmt::DeclRefExprClass: {
14957     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14958       // FIXME: If VD is captured by copy or is an escaping __block variable,
14959       // use the alignment of VD's type.
14960       if (!VD->getType()->isReferenceType())
14961         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14962       if (VD->hasInit())
14963         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14964     }
14965     break;
14966   }
14967   case Stmt::MemberExprClass: {
14968     auto *ME = cast<MemberExpr>(E);
14969     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14970     if (!FD || FD->getType()->isReferenceType() ||
14971         FD->getParent()->isInvalidDecl())
14972       break;
14973     Optional<std::pair<CharUnits, CharUnits>> P;
14974     if (ME->isArrow())
14975       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14976     else
14977       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14978     if (!P)
14979       break;
14980     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14981     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14982     return std::make_pair(P->first,
14983                           P->second + CharUnits::fromQuantity(Offset));
14984   }
14985   case Stmt::UnaryOperatorClass: {
14986     auto *UO = cast<UnaryOperator>(E);
14987     switch (UO->getOpcode()) {
14988     default:
14989       break;
14990     case UO_Deref:
14991       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14992     }
14993     break;
14994   }
14995   case Stmt::BinaryOperatorClass: {
14996     auto *BO = cast<BinaryOperator>(E);
14997     auto Opcode = BO->getOpcode();
14998     switch (Opcode) {
14999     default:
15000       break;
15001     case BO_Comma:
15002       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15003     }
15004     break;
15005   }
15006   }
15007   return llvm::None;
15008 }
15009 
15010 /// This helper function takes a pointer expression and returns the alignment of
15011 /// a VarDecl and a constant offset from the VarDecl.
15012 Optional<std::pair<CharUnits, CharUnits>>
15013 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15014   E = E->IgnoreParens();
15015   switch (E->getStmtClass()) {
15016   default:
15017     break;
15018   case Stmt::CStyleCastExprClass:
15019   case Stmt::CXXStaticCastExprClass:
15020   case Stmt::ImplicitCastExprClass: {
15021     auto *CE = cast<CastExpr>(E);
15022     const Expr *From = CE->getSubExpr();
15023     switch (CE->getCastKind()) {
15024     default:
15025       break;
15026     case CK_NoOp:
15027       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15028     case CK_ArrayToPointerDecay:
15029       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15030     case CK_UncheckedDerivedToBase:
15031     case CK_DerivedToBase: {
15032       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15033       if (!P)
15034         break;
15035       return getDerivedToBaseAlignmentAndOffset(
15036           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15037     }
15038     }
15039     break;
15040   }
15041   case Stmt::CXXThisExprClass: {
15042     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15043     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15044     return std::make_pair(Alignment, CharUnits::Zero());
15045   }
15046   case Stmt::UnaryOperatorClass: {
15047     auto *UO = cast<UnaryOperator>(E);
15048     if (UO->getOpcode() == UO_AddrOf)
15049       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15050     break;
15051   }
15052   case Stmt::BinaryOperatorClass: {
15053     auto *BO = cast<BinaryOperator>(E);
15054     auto Opcode = BO->getOpcode();
15055     switch (Opcode) {
15056     default:
15057       break;
15058     case BO_Add:
15059     case BO_Sub: {
15060       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15061       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15062         std::swap(LHS, RHS);
15063       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15064                                                   Ctx);
15065     }
15066     case BO_Comma:
15067       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15068     }
15069     break;
15070   }
15071   }
15072   return llvm::None;
15073 }
15074 
15075 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15076   // See if we can compute the alignment of a VarDecl and an offset from it.
15077   Optional<std::pair<CharUnits, CharUnits>> P =
15078       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15079 
15080   if (P)
15081     return P->first.alignmentAtOffset(P->second);
15082 
15083   // If that failed, return the type's alignment.
15084   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15085 }
15086 
15087 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15088 /// pointer cast increases the alignment requirements.
15089 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15090   // This is actually a lot of work to potentially be doing on every
15091   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15092   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15093     return;
15094 
15095   // Ignore dependent types.
15096   if (T->isDependentType() || Op->getType()->isDependentType())
15097     return;
15098 
15099   // Require that the destination be a pointer type.
15100   const PointerType *DestPtr = T->getAs<PointerType>();
15101   if (!DestPtr) return;
15102 
15103   // If the destination has alignment 1, we're done.
15104   QualType DestPointee = DestPtr->getPointeeType();
15105   if (DestPointee->isIncompleteType()) return;
15106   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15107   if (DestAlign.isOne()) return;
15108 
15109   // Require that the source be a pointer type.
15110   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15111   if (!SrcPtr) return;
15112   QualType SrcPointee = SrcPtr->getPointeeType();
15113 
15114   // Explicitly allow casts from cv void*.  We already implicitly
15115   // allowed casts to cv void*, since they have alignment 1.
15116   // Also allow casts involving incomplete types, which implicitly
15117   // includes 'void'.
15118   if (SrcPointee->isIncompleteType()) return;
15119 
15120   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15121 
15122   if (SrcAlign >= DestAlign) return;
15123 
15124   Diag(TRange.getBegin(), diag::warn_cast_align)
15125     << Op->getType() << T
15126     << static_cast<unsigned>(SrcAlign.getQuantity())
15127     << static_cast<unsigned>(DestAlign.getQuantity())
15128     << TRange << Op->getSourceRange();
15129 }
15130 
15131 /// Check whether this array fits the idiom of a size-one tail padded
15132 /// array member of a struct.
15133 ///
15134 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15135 /// commonly used to emulate flexible arrays in C89 code.
15136 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15137                                     const NamedDecl *ND) {
15138   if (Size != 1 || !ND) return false;
15139 
15140   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15141   if (!FD) return false;
15142 
15143   // Don't consider sizes resulting from macro expansions or template argument
15144   // substitution to form C89 tail-padded arrays.
15145 
15146   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15147   while (TInfo) {
15148     TypeLoc TL = TInfo->getTypeLoc();
15149     // Look through typedefs.
15150     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15151       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15152       TInfo = TDL->getTypeSourceInfo();
15153       continue;
15154     }
15155     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15156       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15157       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15158         return false;
15159     }
15160     break;
15161   }
15162 
15163   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15164   if (!RD) return false;
15165   if (RD->isUnion()) return false;
15166   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15167     if (!CRD->isStandardLayout()) return false;
15168   }
15169 
15170   // See if this is the last field decl in the record.
15171   const Decl *D = FD;
15172   while ((D = D->getNextDeclInContext()))
15173     if (isa<FieldDecl>(D))
15174       return false;
15175   return true;
15176 }
15177 
15178 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15179                             const ArraySubscriptExpr *ASE,
15180                             bool AllowOnePastEnd, bool IndexNegated) {
15181   // Already diagnosed by the constant evaluator.
15182   if (isConstantEvaluated())
15183     return;
15184 
15185   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15186   if (IndexExpr->isValueDependent())
15187     return;
15188 
15189   const Type *EffectiveType =
15190       BaseExpr->getType()->getPointeeOrArrayElementType();
15191   BaseExpr = BaseExpr->IgnoreParenCasts();
15192   const ConstantArrayType *ArrayTy =
15193       Context.getAsConstantArrayType(BaseExpr->getType());
15194 
15195   const Type *BaseType =
15196       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15197   bool IsUnboundedArray = (BaseType == nullptr);
15198   if (EffectiveType->isDependentType() ||
15199       (!IsUnboundedArray && BaseType->isDependentType()))
15200     return;
15201 
15202   Expr::EvalResult Result;
15203   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15204     return;
15205 
15206   llvm::APSInt index = Result.Val.getInt();
15207   if (IndexNegated) {
15208     index.setIsUnsigned(false);
15209     index = -index;
15210   }
15211 
15212   const NamedDecl *ND = nullptr;
15213   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15214     ND = DRE->getDecl();
15215   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15216     ND = ME->getMemberDecl();
15217 
15218   if (IsUnboundedArray) {
15219     if (index.isUnsigned() || !index.isNegative()) {
15220       const auto &ASTC = getASTContext();
15221       unsigned AddrBits =
15222           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15223               EffectiveType->getCanonicalTypeInternal()));
15224       if (index.getBitWidth() < AddrBits)
15225         index = index.zext(AddrBits);
15226       Optional<CharUnits> ElemCharUnits =
15227           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15228       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15229       // pointer) bounds-checking isn't meaningful.
15230       if (!ElemCharUnits)
15231         return;
15232       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15233       // If index has more active bits than address space, we already know
15234       // we have a bounds violation to warn about.  Otherwise, compute
15235       // address of (index + 1)th element, and warn about bounds violation
15236       // only if that address exceeds address space.
15237       if (index.getActiveBits() <= AddrBits) {
15238         bool Overflow;
15239         llvm::APInt Product(index);
15240         Product += 1;
15241         Product = Product.umul_ov(ElemBytes, Overflow);
15242         if (!Overflow && Product.getActiveBits() <= AddrBits)
15243           return;
15244       }
15245 
15246       // Need to compute max possible elements in address space, since that
15247       // is included in diag message.
15248       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15249       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15250       MaxElems += 1;
15251       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15252       MaxElems = MaxElems.udiv(ElemBytes);
15253 
15254       unsigned DiagID =
15255           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15256               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15257 
15258       // Diag message shows element size in bits and in "bytes" (platform-
15259       // dependent CharUnits)
15260       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15261                           PDiag(DiagID)
15262                               << toString(index, 10, true) << AddrBits
15263                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15264                               << toString(ElemBytes, 10, false)
15265                               << toString(MaxElems, 10, false)
15266                               << (unsigned)MaxElems.getLimitedValue(~0U)
15267                               << IndexExpr->getSourceRange());
15268 
15269       if (!ND) {
15270         // Try harder to find a NamedDecl to point at in the note.
15271         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15272           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15273         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15274           ND = DRE->getDecl();
15275         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15276           ND = ME->getMemberDecl();
15277       }
15278 
15279       if (ND)
15280         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15281                             PDiag(diag::note_array_declared_here) << ND);
15282     }
15283     return;
15284   }
15285 
15286   if (index.isUnsigned() || !index.isNegative()) {
15287     // It is possible that the type of the base expression after
15288     // IgnoreParenCasts is incomplete, even though the type of the base
15289     // expression before IgnoreParenCasts is complete (see PR39746 for an
15290     // example). In this case we have no information about whether the array
15291     // access exceeds the array bounds. However we can still diagnose an array
15292     // access which precedes the array bounds.
15293     if (BaseType->isIncompleteType())
15294       return;
15295 
15296     llvm::APInt size = ArrayTy->getSize();
15297     if (!size.isStrictlyPositive())
15298       return;
15299 
15300     if (BaseType != EffectiveType) {
15301       // Make sure we're comparing apples to apples when comparing index to size
15302       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15303       uint64_t array_typesize = Context.getTypeSize(BaseType);
15304       // Handle ptrarith_typesize being zero, such as when casting to void*
15305       if (!ptrarith_typesize) ptrarith_typesize = 1;
15306       if (ptrarith_typesize != array_typesize) {
15307         // There's a cast to a different size type involved
15308         uint64_t ratio = array_typesize / ptrarith_typesize;
15309         // TODO: Be smarter about handling cases where array_typesize is not a
15310         // multiple of ptrarith_typesize
15311         if (ptrarith_typesize * ratio == array_typesize)
15312           size *= llvm::APInt(size.getBitWidth(), ratio);
15313       }
15314     }
15315 
15316     if (size.getBitWidth() > index.getBitWidth())
15317       index = index.zext(size.getBitWidth());
15318     else if (size.getBitWidth() < index.getBitWidth())
15319       size = size.zext(index.getBitWidth());
15320 
15321     // For array subscripting the index must be less than size, but for pointer
15322     // arithmetic also allow the index (offset) to be equal to size since
15323     // computing the next address after the end of the array is legal and
15324     // commonly done e.g. in C++ iterators and range-based for loops.
15325     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15326       return;
15327 
15328     // Also don't warn for arrays of size 1 which are members of some
15329     // structure. These are often used to approximate flexible arrays in C89
15330     // code.
15331     if (IsTailPaddedMemberArray(*this, size, ND))
15332       return;
15333 
15334     // Suppress the warning if the subscript expression (as identified by the
15335     // ']' location) and the index expression are both from macro expansions
15336     // within a system header.
15337     if (ASE) {
15338       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15339           ASE->getRBracketLoc());
15340       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15341         SourceLocation IndexLoc =
15342             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15343         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15344           return;
15345       }
15346     }
15347 
15348     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15349                           : diag::warn_ptr_arith_exceeds_bounds;
15350 
15351     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15352                         PDiag(DiagID) << toString(index, 10, true)
15353                                       << toString(size, 10, true)
15354                                       << (unsigned)size.getLimitedValue(~0U)
15355                                       << IndexExpr->getSourceRange());
15356   } else {
15357     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15358     if (!ASE) {
15359       DiagID = diag::warn_ptr_arith_precedes_bounds;
15360       if (index.isNegative()) index = -index;
15361     }
15362 
15363     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15364                         PDiag(DiagID) << toString(index, 10, true)
15365                                       << IndexExpr->getSourceRange());
15366   }
15367 
15368   if (!ND) {
15369     // Try harder to find a NamedDecl to point at in the note.
15370     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15371       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15372     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15373       ND = DRE->getDecl();
15374     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15375       ND = ME->getMemberDecl();
15376   }
15377 
15378   if (ND)
15379     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15380                         PDiag(diag::note_array_declared_here) << ND);
15381 }
15382 
15383 void Sema::CheckArrayAccess(const Expr *expr) {
15384   int AllowOnePastEnd = 0;
15385   while (expr) {
15386     expr = expr->IgnoreParenImpCasts();
15387     switch (expr->getStmtClass()) {
15388       case Stmt::ArraySubscriptExprClass: {
15389         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15390         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15391                          AllowOnePastEnd > 0);
15392         expr = ASE->getBase();
15393         break;
15394       }
15395       case Stmt::MemberExprClass: {
15396         expr = cast<MemberExpr>(expr)->getBase();
15397         break;
15398       }
15399       case Stmt::OMPArraySectionExprClass: {
15400         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15401         if (ASE->getLowerBound())
15402           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15403                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15404         return;
15405       }
15406       case Stmt::UnaryOperatorClass: {
15407         // Only unwrap the * and & unary operators
15408         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15409         expr = UO->getSubExpr();
15410         switch (UO->getOpcode()) {
15411           case UO_AddrOf:
15412             AllowOnePastEnd++;
15413             break;
15414           case UO_Deref:
15415             AllowOnePastEnd--;
15416             break;
15417           default:
15418             return;
15419         }
15420         break;
15421       }
15422       case Stmt::ConditionalOperatorClass: {
15423         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15424         if (const Expr *lhs = cond->getLHS())
15425           CheckArrayAccess(lhs);
15426         if (const Expr *rhs = cond->getRHS())
15427           CheckArrayAccess(rhs);
15428         return;
15429       }
15430       case Stmt::CXXOperatorCallExprClass: {
15431         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15432         for (const auto *Arg : OCE->arguments())
15433           CheckArrayAccess(Arg);
15434         return;
15435       }
15436       default:
15437         return;
15438     }
15439   }
15440 }
15441 
15442 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15443 
15444 namespace {
15445 
15446 struct RetainCycleOwner {
15447   VarDecl *Variable = nullptr;
15448   SourceRange Range;
15449   SourceLocation Loc;
15450   bool Indirect = false;
15451 
15452   RetainCycleOwner() = default;
15453 
15454   void setLocsFrom(Expr *e) {
15455     Loc = e->getExprLoc();
15456     Range = e->getSourceRange();
15457   }
15458 };
15459 
15460 } // namespace
15461 
15462 /// Consider whether capturing the given variable can possibly lead to
15463 /// a retain cycle.
15464 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15465   // In ARC, it's captured strongly iff the variable has __strong
15466   // lifetime.  In MRR, it's captured strongly if the variable is
15467   // __block and has an appropriate type.
15468   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15469     return false;
15470 
15471   owner.Variable = var;
15472   if (ref)
15473     owner.setLocsFrom(ref);
15474   return true;
15475 }
15476 
15477 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15478   while (true) {
15479     e = e->IgnoreParens();
15480     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15481       switch (cast->getCastKind()) {
15482       case CK_BitCast:
15483       case CK_LValueBitCast:
15484       case CK_LValueToRValue:
15485       case CK_ARCReclaimReturnedObject:
15486         e = cast->getSubExpr();
15487         continue;
15488 
15489       default:
15490         return false;
15491       }
15492     }
15493 
15494     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15495       ObjCIvarDecl *ivar = ref->getDecl();
15496       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15497         return false;
15498 
15499       // Try to find a retain cycle in the base.
15500       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15501         return false;
15502 
15503       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15504       owner.Indirect = true;
15505       return true;
15506     }
15507 
15508     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15509       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15510       if (!var) return false;
15511       return considerVariable(var, ref, owner);
15512     }
15513 
15514     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15515       if (member->isArrow()) return false;
15516 
15517       // Don't count this as an indirect ownership.
15518       e = member->getBase();
15519       continue;
15520     }
15521 
15522     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15523       // Only pay attention to pseudo-objects on property references.
15524       ObjCPropertyRefExpr *pre
15525         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15526                                               ->IgnoreParens());
15527       if (!pre) return false;
15528       if (pre->isImplicitProperty()) return false;
15529       ObjCPropertyDecl *property = pre->getExplicitProperty();
15530       if (!property->isRetaining() &&
15531           !(property->getPropertyIvarDecl() &&
15532             property->getPropertyIvarDecl()->getType()
15533               .getObjCLifetime() == Qualifiers::OCL_Strong))
15534           return false;
15535 
15536       owner.Indirect = true;
15537       if (pre->isSuperReceiver()) {
15538         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15539         if (!owner.Variable)
15540           return false;
15541         owner.Loc = pre->getLocation();
15542         owner.Range = pre->getSourceRange();
15543         return true;
15544       }
15545       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15546                               ->getSourceExpr());
15547       continue;
15548     }
15549 
15550     // Array ivars?
15551 
15552     return false;
15553   }
15554 }
15555 
15556 namespace {
15557 
15558   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15559     ASTContext &Context;
15560     VarDecl *Variable;
15561     Expr *Capturer = nullptr;
15562     bool VarWillBeReased = false;
15563 
15564     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15565         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15566           Context(Context), Variable(variable) {}
15567 
15568     void VisitDeclRefExpr(DeclRefExpr *ref) {
15569       if (ref->getDecl() == Variable && !Capturer)
15570         Capturer = ref;
15571     }
15572 
15573     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15574       if (Capturer) return;
15575       Visit(ref->getBase());
15576       if (Capturer && ref->isFreeIvar())
15577         Capturer = ref;
15578     }
15579 
15580     void VisitBlockExpr(BlockExpr *block) {
15581       // Look inside nested blocks
15582       if (block->getBlockDecl()->capturesVariable(Variable))
15583         Visit(block->getBlockDecl()->getBody());
15584     }
15585 
15586     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15587       if (Capturer) return;
15588       if (OVE->getSourceExpr())
15589         Visit(OVE->getSourceExpr());
15590     }
15591 
15592     void VisitBinaryOperator(BinaryOperator *BinOp) {
15593       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15594         return;
15595       Expr *LHS = BinOp->getLHS();
15596       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15597         if (DRE->getDecl() != Variable)
15598           return;
15599         if (Expr *RHS = BinOp->getRHS()) {
15600           RHS = RHS->IgnoreParenCasts();
15601           Optional<llvm::APSInt> Value;
15602           VarWillBeReased =
15603               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15604                *Value == 0);
15605         }
15606       }
15607     }
15608   };
15609 
15610 } // namespace
15611 
15612 /// Check whether the given argument is a block which captures a
15613 /// variable.
15614 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15615   assert(owner.Variable && owner.Loc.isValid());
15616 
15617   e = e->IgnoreParenCasts();
15618 
15619   // Look through [^{...} copy] and Block_copy(^{...}).
15620   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15621     Selector Cmd = ME->getSelector();
15622     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15623       e = ME->getInstanceReceiver();
15624       if (!e)
15625         return nullptr;
15626       e = e->IgnoreParenCasts();
15627     }
15628   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15629     if (CE->getNumArgs() == 1) {
15630       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15631       if (Fn) {
15632         const IdentifierInfo *FnI = Fn->getIdentifier();
15633         if (FnI && FnI->isStr("_Block_copy")) {
15634           e = CE->getArg(0)->IgnoreParenCasts();
15635         }
15636       }
15637     }
15638   }
15639 
15640   BlockExpr *block = dyn_cast<BlockExpr>(e);
15641   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15642     return nullptr;
15643 
15644   FindCaptureVisitor visitor(S.Context, owner.Variable);
15645   visitor.Visit(block->getBlockDecl()->getBody());
15646   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15647 }
15648 
15649 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15650                                 RetainCycleOwner &owner) {
15651   assert(capturer);
15652   assert(owner.Variable && owner.Loc.isValid());
15653 
15654   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15655     << owner.Variable << capturer->getSourceRange();
15656   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15657     << owner.Indirect << owner.Range;
15658 }
15659 
15660 /// Check for a keyword selector that starts with the word 'add' or
15661 /// 'set'.
15662 static bool isSetterLikeSelector(Selector sel) {
15663   if (sel.isUnarySelector()) return false;
15664 
15665   StringRef str = sel.getNameForSlot(0);
15666   while (!str.empty() && str.front() == '_') str = str.substr(1);
15667   if (str.startswith("set"))
15668     str = str.substr(3);
15669   else if (str.startswith("add")) {
15670     // Specially allow 'addOperationWithBlock:'.
15671     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15672       return false;
15673     str = str.substr(3);
15674   }
15675   else
15676     return false;
15677 
15678   if (str.empty()) return true;
15679   return !isLowercase(str.front());
15680 }
15681 
15682 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15683                                                     ObjCMessageExpr *Message) {
15684   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15685                                                 Message->getReceiverInterface(),
15686                                                 NSAPI::ClassId_NSMutableArray);
15687   if (!IsMutableArray) {
15688     return None;
15689   }
15690 
15691   Selector Sel = Message->getSelector();
15692 
15693   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15694     S.NSAPIObj->getNSArrayMethodKind(Sel);
15695   if (!MKOpt) {
15696     return None;
15697   }
15698 
15699   NSAPI::NSArrayMethodKind MK = *MKOpt;
15700 
15701   switch (MK) {
15702     case NSAPI::NSMutableArr_addObject:
15703     case NSAPI::NSMutableArr_insertObjectAtIndex:
15704     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15705       return 0;
15706     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15707       return 1;
15708 
15709     default:
15710       return None;
15711   }
15712 
15713   return None;
15714 }
15715 
15716 static
15717 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15718                                                   ObjCMessageExpr *Message) {
15719   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15720                                             Message->getReceiverInterface(),
15721                                             NSAPI::ClassId_NSMutableDictionary);
15722   if (!IsMutableDictionary) {
15723     return None;
15724   }
15725 
15726   Selector Sel = Message->getSelector();
15727 
15728   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15729     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15730   if (!MKOpt) {
15731     return None;
15732   }
15733 
15734   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15735 
15736   switch (MK) {
15737     case NSAPI::NSMutableDict_setObjectForKey:
15738     case NSAPI::NSMutableDict_setValueForKey:
15739     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15740       return 0;
15741 
15742     default:
15743       return None;
15744   }
15745 
15746   return None;
15747 }
15748 
15749 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15750   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15751                                                 Message->getReceiverInterface(),
15752                                                 NSAPI::ClassId_NSMutableSet);
15753 
15754   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15755                                             Message->getReceiverInterface(),
15756                                             NSAPI::ClassId_NSMutableOrderedSet);
15757   if (!IsMutableSet && !IsMutableOrderedSet) {
15758     return None;
15759   }
15760 
15761   Selector Sel = Message->getSelector();
15762 
15763   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15764   if (!MKOpt) {
15765     return None;
15766   }
15767 
15768   NSAPI::NSSetMethodKind MK = *MKOpt;
15769 
15770   switch (MK) {
15771     case NSAPI::NSMutableSet_addObject:
15772     case NSAPI::NSOrderedSet_setObjectAtIndex:
15773     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15774     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15775       return 0;
15776     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15777       return 1;
15778   }
15779 
15780   return None;
15781 }
15782 
15783 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15784   if (!Message->isInstanceMessage()) {
15785     return;
15786   }
15787 
15788   Optional<int> ArgOpt;
15789 
15790   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15791       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15792       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15793     return;
15794   }
15795 
15796   int ArgIndex = *ArgOpt;
15797 
15798   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15799   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15800     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15801   }
15802 
15803   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15804     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15805       if (ArgRE->isObjCSelfExpr()) {
15806         Diag(Message->getSourceRange().getBegin(),
15807              diag::warn_objc_circular_container)
15808           << ArgRE->getDecl() << StringRef("'super'");
15809       }
15810     }
15811   } else {
15812     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15813 
15814     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15815       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15816     }
15817 
15818     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15819       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15820         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15821           ValueDecl *Decl = ReceiverRE->getDecl();
15822           Diag(Message->getSourceRange().getBegin(),
15823                diag::warn_objc_circular_container)
15824             << Decl << Decl;
15825           if (!ArgRE->isObjCSelfExpr()) {
15826             Diag(Decl->getLocation(),
15827                  diag::note_objc_circular_container_declared_here)
15828               << Decl;
15829           }
15830         }
15831       }
15832     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15833       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15834         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15835           ObjCIvarDecl *Decl = IvarRE->getDecl();
15836           Diag(Message->getSourceRange().getBegin(),
15837                diag::warn_objc_circular_container)
15838             << Decl << Decl;
15839           Diag(Decl->getLocation(),
15840                diag::note_objc_circular_container_declared_here)
15841             << Decl;
15842         }
15843       }
15844     }
15845   }
15846 }
15847 
15848 /// Check a message send to see if it's likely to cause a retain cycle.
15849 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15850   // Only check instance methods whose selector looks like a setter.
15851   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15852     return;
15853 
15854   // Try to find a variable that the receiver is strongly owned by.
15855   RetainCycleOwner owner;
15856   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15857     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15858       return;
15859   } else {
15860     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15861     owner.Variable = getCurMethodDecl()->getSelfDecl();
15862     owner.Loc = msg->getSuperLoc();
15863     owner.Range = msg->getSuperLoc();
15864   }
15865 
15866   // Check whether the receiver is captured by any of the arguments.
15867   const ObjCMethodDecl *MD = msg->getMethodDecl();
15868   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15869     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15870       // noescape blocks should not be retained by the method.
15871       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15872         continue;
15873       return diagnoseRetainCycle(*this, capturer, owner);
15874     }
15875   }
15876 }
15877 
15878 /// Check a property assign to see if it's likely to cause a retain cycle.
15879 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15880   RetainCycleOwner owner;
15881   if (!findRetainCycleOwner(*this, receiver, owner))
15882     return;
15883 
15884   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15885     diagnoseRetainCycle(*this, capturer, owner);
15886 }
15887 
15888 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15889   RetainCycleOwner Owner;
15890   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15891     return;
15892 
15893   // Because we don't have an expression for the variable, we have to set the
15894   // location explicitly here.
15895   Owner.Loc = Var->getLocation();
15896   Owner.Range = Var->getSourceRange();
15897 
15898   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15899     diagnoseRetainCycle(*this, Capturer, Owner);
15900 }
15901 
15902 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15903                                      Expr *RHS, bool isProperty) {
15904   // Check if RHS is an Objective-C object literal, which also can get
15905   // immediately zapped in a weak reference.  Note that we explicitly
15906   // allow ObjCStringLiterals, since those are designed to never really die.
15907   RHS = RHS->IgnoreParenImpCasts();
15908 
15909   // This enum needs to match with the 'select' in
15910   // warn_objc_arc_literal_assign (off-by-1).
15911   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15912   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15913     return false;
15914 
15915   S.Diag(Loc, diag::warn_arc_literal_assign)
15916     << (unsigned) Kind
15917     << (isProperty ? 0 : 1)
15918     << RHS->getSourceRange();
15919 
15920   return true;
15921 }
15922 
15923 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15924                                     Qualifiers::ObjCLifetime LT,
15925                                     Expr *RHS, bool isProperty) {
15926   // Strip off any implicit cast added to get to the one ARC-specific.
15927   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15928     if (cast->getCastKind() == CK_ARCConsumeObject) {
15929       S.Diag(Loc, diag::warn_arc_retained_assign)
15930         << (LT == Qualifiers::OCL_ExplicitNone)
15931         << (isProperty ? 0 : 1)
15932         << RHS->getSourceRange();
15933       return true;
15934     }
15935     RHS = cast->getSubExpr();
15936   }
15937 
15938   if (LT == Qualifiers::OCL_Weak &&
15939       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15940     return true;
15941 
15942   return false;
15943 }
15944 
15945 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15946                               QualType LHS, Expr *RHS) {
15947   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15948 
15949   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15950     return false;
15951 
15952   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15953     return true;
15954 
15955   return false;
15956 }
15957 
15958 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15959                               Expr *LHS, Expr *RHS) {
15960   QualType LHSType;
15961   // PropertyRef on LHS type need be directly obtained from
15962   // its declaration as it has a PseudoType.
15963   ObjCPropertyRefExpr *PRE
15964     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15965   if (PRE && !PRE->isImplicitProperty()) {
15966     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15967     if (PD)
15968       LHSType = PD->getType();
15969   }
15970 
15971   if (LHSType.isNull())
15972     LHSType = LHS->getType();
15973 
15974   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15975 
15976   if (LT == Qualifiers::OCL_Weak) {
15977     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15978       getCurFunction()->markSafeWeakUse(LHS);
15979   }
15980 
15981   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15982     return;
15983 
15984   // FIXME. Check for other life times.
15985   if (LT != Qualifiers::OCL_None)
15986     return;
15987 
15988   if (PRE) {
15989     if (PRE->isImplicitProperty())
15990       return;
15991     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15992     if (!PD)
15993       return;
15994 
15995     unsigned Attributes = PD->getPropertyAttributes();
15996     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15997       // when 'assign' attribute was not explicitly specified
15998       // by user, ignore it and rely on property type itself
15999       // for lifetime info.
16000       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16001       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16002           LHSType->isObjCRetainableType())
16003         return;
16004 
16005       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16006         if (cast->getCastKind() == CK_ARCConsumeObject) {
16007           Diag(Loc, diag::warn_arc_retained_property_assign)
16008           << RHS->getSourceRange();
16009           return;
16010         }
16011         RHS = cast->getSubExpr();
16012       }
16013     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16014       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16015         return;
16016     }
16017   }
16018 }
16019 
16020 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16021 
16022 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16023                                         SourceLocation StmtLoc,
16024                                         const NullStmt *Body) {
16025   // Do not warn if the body is a macro that expands to nothing, e.g:
16026   //
16027   // #define CALL(x)
16028   // if (condition)
16029   //   CALL(0);
16030   if (Body->hasLeadingEmptyMacro())
16031     return false;
16032 
16033   // Get line numbers of statement and body.
16034   bool StmtLineInvalid;
16035   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16036                                                       &StmtLineInvalid);
16037   if (StmtLineInvalid)
16038     return false;
16039 
16040   bool BodyLineInvalid;
16041   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16042                                                       &BodyLineInvalid);
16043   if (BodyLineInvalid)
16044     return false;
16045 
16046   // Warn if null statement and body are on the same line.
16047   if (StmtLine != BodyLine)
16048     return false;
16049 
16050   return true;
16051 }
16052 
16053 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16054                                  const Stmt *Body,
16055                                  unsigned DiagID) {
16056   // Since this is a syntactic check, don't emit diagnostic for template
16057   // instantiations, this just adds noise.
16058   if (CurrentInstantiationScope)
16059     return;
16060 
16061   // The body should be a null statement.
16062   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16063   if (!NBody)
16064     return;
16065 
16066   // Do the usual checks.
16067   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16068     return;
16069 
16070   Diag(NBody->getSemiLoc(), DiagID);
16071   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16072 }
16073 
16074 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16075                                  const Stmt *PossibleBody) {
16076   assert(!CurrentInstantiationScope); // Ensured by caller
16077 
16078   SourceLocation StmtLoc;
16079   const Stmt *Body;
16080   unsigned DiagID;
16081   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16082     StmtLoc = FS->getRParenLoc();
16083     Body = FS->getBody();
16084     DiagID = diag::warn_empty_for_body;
16085   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16086     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16087     Body = WS->getBody();
16088     DiagID = diag::warn_empty_while_body;
16089   } else
16090     return; // Neither `for' nor `while'.
16091 
16092   // The body should be a null statement.
16093   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16094   if (!NBody)
16095     return;
16096 
16097   // Skip expensive checks if diagnostic is disabled.
16098   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16099     return;
16100 
16101   // Do the usual checks.
16102   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16103     return;
16104 
16105   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16106   // noise level low, emit diagnostics only if for/while is followed by a
16107   // CompoundStmt, e.g.:
16108   //    for (int i = 0; i < n; i++);
16109   //    {
16110   //      a(i);
16111   //    }
16112   // or if for/while is followed by a statement with more indentation
16113   // than for/while itself:
16114   //    for (int i = 0; i < n; i++);
16115   //      a(i);
16116   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16117   if (!ProbableTypo) {
16118     bool BodyColInvalid;
16119     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16120         PossibleBody->getBeginLoc(), &BodyColInvalid);
16121     if (BodyColInvalid)
16122       return;
16123 
16124     bool StmtColInvalid;
16125     unsigned StmtCol =
16126         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16127     if (StmtColInvalid)
16128       return;
16129 
16130     if (BodyCol > StmtCol)
16131       ProbableTypo = true;
16132   }
16133 
16134   if (ProbableTypo) {
16135     Diag(NBody->getSemiLoc(), DiagID);
16136     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16137   }
16138 }
16139 
16140 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16141 
16142 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16143 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16144                              SourceLocation OpLoc) {
16145   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16146     return;
16147 
16148   if (inTemplateInstantiation())
16149     return;
16150 
16151   // Strip parens and casts away.
16152   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16153   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16154 
16155   // Check for a call expression
16156   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16157   if (!CE || CE->getNumArgs() != 1)
16158     return;
16159 
16160   // Check for a call to std::move
16161   if (!CE->isCallToStdMove())
16162     return;
16163 
16164   // Get argument from std::move
16165   RHSExpr = CE->getArg(0);
16166 
16167   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16168   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16169 
16170   // Two DeclRefExpr's, check that the decls are the same.
16171   if (LHSDeclRef && RHSDeclRef) {
16172     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16173       return;
16174     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16175         RHSDeclRef->getDecl()->getCanonicalDecl())
16176       return;
16177 
16178     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16179                                         << LHSExpr->getSourceRange()
16180                                         << RHSExpr->getSourceRange();
16181     return;
16182   }
16183 
16184   // Member variables require a different approach to check for self moves.
16185   // MemberExpr's are the same if every nested MemberExpr refers to the same
16186   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16187   // the base Expr's are CXXThisExpr's.
16188   const Expr *LHSBase = LHSExpr;
16189   const Expr *RHSBase = RHSExpr;
16190   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16191   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16192   if (!LHSME || !RHSME)
16193     return;
16194 
16195   while (LHSME && RHSME) {
16196     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16197         RHSME->getMemberDecl()->getCanonicalDecl())
16198       return;
16199 
16200     LHSBase = LHSME->getBase();
16201     RHSBase = RHSME->getBase();
16202     LHSME = dyn_cast<MemberExpr>(LHSBase);
16203     RHSME = dyn_cast<MemberExpr>(RHSBase);
16204   }
16205 
16206   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16207   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16208   if (LHSDeclRef && RHSDeclRef) {
16209     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16210       return;
16211     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16212         RHSDeclRef->getDecl()->getCanonicalDecl())
16213       return;
16214 
16215     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16216                                         << LHSExpr->getSourceRange()
16217                                         << RHSExpr->getSourceRange();
16218     return;
16219   }
16220 
16221   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16222     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16223                                         << LHSExpr->getSourceRange()
16224                                         << RHSExpr->getSourceRange();
16225 }
16226 
16227 //===--- Layout compatibility ----------------------------------------------//
16228 
16229 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16230 
16231 /// Check if two enumeration types are layout-compatible.
16232 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16233   // C++11 [dcl.enum] p8:
16234   // Two enumeration types are layout-compatible if they have the same
16235   // underlying type.
16236   return ED1->isComplete() && ED2->isComplete() &&
16237          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16238 }
16239 
16240 /// Check if two fields are layout-compatible.
16241 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16242                                FieldDecl *Field2) {
16243   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16244     return false;
16245 
16246   if (Field1->isBitField() != Field2->isBitField())
16247     return false;
16248 
16249   if (Field1->isBitField()) {
16250     // Make sure that the bit-fields are the same length.
16251     unsigned Bits1 = Field1->getBitWidthValue(C);
16252     unsigned Bits2 = Field2->getBitWidthValue(C);
16253 
16254     if (Bits1 != Bits2)
16255       return false;
16256   }
16257 
16258   return true;
16259 }
16260 
16261 /// Check if two standard-layout structs are layout-compatible.
16262 /// (C++11 [class.mem] p17)
16263 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16264                                      RecordDecl *RD2) {
16265   // If both records are C++ classes, check that base classes match.
16266   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16267     // If one of records is a CXXRecordDecl we are in C++ mode,
16268     // thus the other one is a CXXRecordDecl, too.
16269     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16270     // Check number of base classes.
16271     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16272       return false;
16273 
16274     // Check the base classes.
16275     for (CXXRecordDecl::base_class_const_iterator
16276                Base1 = D1CXX->bases_begin(),
16277            BaseEnd1 = D1CXX->bases_end(),
16278               Base2 = D2CXX->bases_begin();
16279          Base1 != BaseEnd1;
16280          ++Base1, ++Base2) {
16281       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16282         return false;
16283     }
16284   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16285     // If only RD2 is a C++ class, it should have zero base classes.
16286     if (D2CXX->getNumBases() > 0)
16287       return false;
16288   }
16289 
16290   // Check the fields.
16291   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16292                              Field2End = RD2->field_end(),
16293                              Field1 = RD1->field_begin(),
16294                              Field1End = RD1->field_end();
16295   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16296     if (!isLayoutCompatible(C, *Field1, *Field2))
16297       return false;
16298   }
16299   if (Field1 != Field1End || Field2 != Field2End)
16300     return false;
16301 
16302   return true;
16303 }
16304 
16305 /// Check if two standard-layout unions are layout-compatible.
16306 /// (C++11 [class.mem] p18)
16307 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16308                                     RecordDecl *RD2) {
16309   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16310   for (auto *Field2 : RD2->fields())
16311     UnmatchedFields.insert(Field2);
16312 
16313   for (auto *Field1 : RD1->fields()) {
16314     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16315         I = UnmatchedFields.begin(),
16316         E = UnmatchedFields.end();
16317 
16318     for ( ; I != E; ++I) {
16319       if (isLayoutCompatible(C, Field1, *I)) {
16320         bool Result = UnmatchedFields.erase(*I);
16321         (void) Result;
16322         assert(Result);
16323         break;
16324       }
16325     }
16326     if (I == E)
16327       return false;
16328   }
16329 
16330   return UnmatchedFields.empty();
16331 }
16332 
16333 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16334                                RecordDecl *RD2) {
16335   if (RD1->isUnion() != RD2->isUnion())
16336     return false;
16337 
16338   if (RD1->isUnion())
16339     return isLayoutCompatibleUnion(C, RD1, RD2);
16340   else
16341     return isLayoutCompatibleStruct(C, RD1, RD2);
16342 }
16343 
16344 /// Check if two types are layout-compatible in C++11 sense.
16345 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16346   if (T1.isNull() || T2.isNull())
16347     return false;
16348 
16349   // C++11 [basic.types] p11:
16350   // If two types T1 and T2 are the same type, then T1 and T2 are
16351   // layout-compatible types.
16352   if (C.hasSameType(T1, T2))
16353     return true;
16354 
16355   T1 = T1.getCanonicalType().getUnqualifiedType();
16356   T2 = T2.getCanonicalType().getUnqualifiedType();
16357 
16358   const Type::TypeClass TC1 = T1->getTypeClass();
16359   const Type::TypeClass TC2 = T2->getTypeClass();
16360 
16361   if (TC1 != TC2)
16362     return false;
16363 
16364   if (TC1 == Type::Enum) {
16365     return isLayoutCompatible(C,
16366                               cast<EnumType>(T1)->getDecl(),
16367                               cast<EnumType>(T2)->getDecl());
16368   } else if (TC1 == Type::Record) {
16369     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16370       return false;
16371 
16372     return isLayoutCompatible(C,
16373                               cast<RecordType>(T1)->getDecl(),
16374                               cast<RecordType>(T2)->getDecl());
16375   }
16376 
16377   return false;
16378 }
16379 
16380 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16381 
16382 /// Given a type tag expression find the type tag itself.
16383 ///
16384 /// \param TypeExpr Type tag expression, as it appears in user's code.
16385 ///
16386 /// \param VD Declaration of an identifier that appears in a type tag.
16387 ///
16388 /// \param MagicValue Type tag magic value.
16389 ///
16390 /// \param isConstantEvaluated whether the evalaution should be performed in
16391 
16392 /// constant context.
16393 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16394                             const ValueDecl **VD, uint64_t *MagicValue,
16395                             bool isConstantEvaluated) {
16396   while(true) {
16397     if (!TypeExpr)
16398       return false;
16399 
16400     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16401 
16402     switch (TypeExpr->getStmtClass()) {
16403     case Stmt::UnaryOperatorClass: {
16404       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16405       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16406         TypeExpr = UO->getSubExpr();
16407         continue;
16408       }
16409       return false;
16410     }
16411 
16412     case Stmt::DeclRefExprClass: {
16413       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16414       *VD = DRE->getDecl();
16415       return true;
16416     }
16417 
16418     case Stmt::IntegerLiteralClass: {
16419       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16420       llvm::APInt MagicValueAPInt = IL->getValue();
16421       if (MagicValueAPInt.getActiveBits() <= 64) {
16422         *MagicValue = MagicValueAPInt.getZExtValue();
16423         return true;
16424       } else
16425         return false;
16426     }
16427 
16428     case Stmt::BinaryConditionalOperatorClass:
16429     case Stmt::ConditionalOperatorClass: {
16430       const AbstractConditionalOperator *ACO =
16431           cast<AbstractConditionalOperator>(TypeExpr);
16432       bool Result;
16433       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16434                                                      isConstantEvaluated)) {
16435         if (Result)
16436           TypeExpr = ACO->getTrueExpr();
16437         else
16438           TypeExpr = ACO->getFalseExpr();
16439         continue;
16440       }
16441       return false;
16442     }
16443 
16444     case Stmt::BinaryOperatorClass: {
16445       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16446       if (BO->getOpcode() == BO_Comma) {
16447         TypeExpr = BO->getRHS();
16448         continue;
16449       }
16450       return false;
16451     }
16452 
16453     default:
16454       return false;
16455     }
16456   }
16457 }
16458 
16459 /// Retrieve the C type corresponding to type tag TypeExpr.
16460 ///
16461 /// \param TypeExpr Expression that specifies a type tag.
16462 ///
16463 /// \param MagicValues Registered magic values.
16464 ///
16465 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16466 ///        kind.
16467 ///
16468 /// \param TypeInfo Information about the corresponding C type.
16469 ///
16470 /// \param isConstantEvaluated whether the evalaution should be performed in
16471 /// constant context.
16472 ///
16473 /// \returns true if the corresponding C type was found.
16474 static bool GetMatchingCType(
16475     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16476     const ASTContext &Ctx,
16477     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16478         *MagicValues,
16479     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16480     bool isConstantEvaluated) {
16481   FoundWrongKind = false;
16482 
16483   // Variable declaration that has type_tag_for_datatype attribute.
16484   const ValueDecl *VD = nullptr;
16485 
16486   uint64_t MagicValue;
16487 
16488   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16489     return false;
16490 
16491   if (VD) {
16492     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16493       if (I->getArgumentKind() != ArgumentKind) {
16494         FoundWrongKind = true;
16495         return false;
16496       }
16497       TypeInfo.Type = I->getMatchingCType();
16498       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16499       TypeInfo.MustBeNull = I->getMustBeNull();
16500       return true;
16501     }
16502     return false;
16503   }
16504 
16505   if (!MagicValues)
16506     return false;
16507 
16508   llvm::DenseMap<Sema::TypeTagMagicValue,
16509                  Sema::TypeTagData>::const_iterator I =
16510       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16511   if (I == MagicValues->end())
16512     return false;
16513 
16514   TypeInfo = I->second;
16515   return true;
16516 }
16517 
16518 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16519                                       uint64_t MagicValue, QualType Type,
16520                                       bool LayoutCompatible,
16521                                       bool MustBeNull) {
16522   if (!TypeTagForDatatypeMagicValues)
16523     TypeTagForDatatypeMagicValues.reset(
16524         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16525 
16526   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16527   (*TypeTagForDatatypeMagicValues)[Magic] =
16528       TypeTagData(Type, LayoutCompatible, MustBeNull);
16529 }
16530 
16531 static bool IsSameCharType(QualType T1, QualType T2) {
16532   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16533   if (!BT1)
16534     return false;
16535 
16536   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16537   if (!BT2)
16538     return false;
16539 
16540   BuiltinType::Kind T1Kind = BT1->getKind();
16541   BuiltinType::Kind T2Kind = BT2->getKind();
16542 
16543   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16544          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16545          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16546          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16547 }
16548 
16549 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16550                                     const ArrayRef<const Expr *> ExprArgs,
16551                                     SourceLocation CallSiteLoc) {
16552   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16553   bool IsPointerAttr = Attr->getIsPointer();
16554 
16555   // Retrieve the argument representing the 'type_tag'.
16556   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16557   if (TypeTagIdxAST >= ExprArgs.size()) {
16558     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16559         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16560     return;
16561   }
16562   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16563   bool FoundWrongKind;
16564   TypeTagData TypeInfo;
16565   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16566                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16567                         TypeInfo, isConstantEvaluated())) {
16568     if (FoundWrongKind)
16569       Diag(TypeTagExpr->getExprLoc(),
16570            diag::warn_type_tag_for_datatype_wrong_kind)
16571         << TypeTagExpr->getSourceRange();
16572     return;
16573   }
16574 
16575   // Retrieve the argument representing the 'arg_idx'.
16576   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16577   if (ArgumentIdxAST >= ExprArgs.size()) {
16578     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16579         << 1 << Attr->getArgumentIdx().getSourceIndex();
16580     return;
16581   }
16582   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16583   if (IsPointerAttr) {
16584     // Skip implicit cast of pointer to `void *' (as a function argument).
16585     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16586       if (ICE->getType()->isVoidPointerType() &&
16587           ICE->getCastKind() == CK_BitCast)
16588         ArgumentExpr = ICE->getSubExpr();
16589   }
16590   QualType ArgumentType = ArgumentExpr->getType();
16591 
16592   // Passing a `void*' pointer shouldn't trigger a warning.
16593   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16594     return;
16595 
16596   if (TypeInfo.MustBeNull) {
16597     // Type tag with matching void type requires a null pointer.
16598     if (!ArgumentExpr->isNullPointerConstant(Context,
16599                                              Expr::NPC_ValueDependentIsNotNull)) {
16600       Diag(ArgumentExpr->getExprLoc(),
16601            diag::warn_type_safety_null_pointer_required)
16602           << ArgumentKind->getName()
16603           << ArgumentExpr->getSourceRange()
16604           << TypeTagExpr->getSourceRange();
16605     }
16606     return;
16607   }
16608 
16609   QualType RequiredType = TypeInfo.Type;
16610   if (IsPointerAttr)
16611     RequiredType = Context.getPointerType(RequiredType);
16612 
16613   bool mismatch = false;
16614   if (!TypeInfo.LayoutCompatible) {
16615     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16616 
16617     // C++11 [basic.fundamental] p1:
16618     // Plain char, signed char, and unsigned char are three distinct types.
16619     //
16620     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16621     // char' depending on the current char signedness mode.
16622     if (mismatch)
16623       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16624                                            RequiredType->getPointeeType())) ||
16625           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16626         mismatch = false;
16627   } else
16628     if (IsPointerAttr)
16629       mismatch = !isLayoutCompatible(Context,
16630                                      ArgumentType->getPointeeType(),
16631                                      RequiredType->getPointeeType());
16632     else
16633       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16634 
16635   if (mismatch)
16636     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16637         << ArgumentType << ArgumentKind
16638         << TypeInfo.LayoutCompatible << RequiredType
16639         << ArgumentExpr->getSourceRange()
16640         << TypeTagExpr->getSourceRange();
16641 }
16642 
16643 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16644                                          CharUnits Alignment) {
16645   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16646 }
16647 
16648 void Sema::DiagnoseMisalignedMembers() {
16649   for (MisalignedMember &m : MisalignedMembers) {
16650     const NamedDecl *ND = m.RD;
16651     if (ND->getName().empty()) {
16652       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16653         ND = TD;
16654     }
16655     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16656         << m.MD << ND << m.E->getSourceRange();
16657   }
16658   MisalignedMembers.clear();
16659 }
16660 
16661 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16662   E = E->IgnoreParens();
16663   if (!T->isPointerType() && !T->isIntegerType())
16664     return;
16665   if (isa<UnaryOperator>(E) &&
16666       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16667     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16668     if (isa<MemberExpr>(Op)) {
16669       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16670       if (MA != MisalignedMembers.end() &&
16671           (T->isIntegerType() ||
16672            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16673                                    Context.getTypeAlignInChars(
16674                                        T->getPointeeType()) <= MA->Alignment))))
16675         MisalignedMembers.erase(MA);
16676     }
16677   }
16678 }
16679 
16680 void Sema::RefersToMemberWithReducedAlignment(
16681     Expr *E,
16682     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16683         Action) {
16684   const auto *ME = dyn_cast<MemberExpr>(E);
16685   if (!ME)
16686     return;
16687 
16688   // No need to check expressions with an __unaligned-qualified type.
16689   if (E->getType().getQualifiers().hasUnaligned())
16690     return;
16691 
16692   // For a chain of MemberExpr like "a.b.c.d" this list
16693   // will keep FieldDecl's like [d, c, b].
16694   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16695   const MemberExpr *TopME = nullptr;
16696   bool AnyIsPacked = false;
16697   do {
16698     QualType BaseType = ME->getBase()->getType();
16699     if (BaseType->isDependentType())
16700       return;
16701     if (ME->isArrow())
16702       BaseType = BaseType->getPointeeType();
16703     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16704     if (RD->isInvalidDecl())
16705       return;
16706 
16707     ValueDecl *MD = ME->getMemberDecl();
16708     auto *FD = dyn_cast<FieldDecl>(MD);
16709     // We do not care about non-data members.
16710     if (!FD || FD->isInvalidDecl())
16711       return;
16712 
16713     AnyIsPacked =
16714         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16715     ReverseMemberChain.push_back(FD);
16716 
16717     TopME = ME;
16718     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16719   } while (ME);
16720   assert(TopME && "We did not compute a topmost MemberExpr!");
16721 
16722   // Not the scope of this diagnostic.
16723   if (!AnyIsPacked)
16724     return;
16725 
16726   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16727   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16728   // TODO: The innermost base of the member expression may be too complicated.
16729   // For now, just disregard these cases. This is left for future
16730   // improvement.
16731   if (!DRE && !isa<CXXThisExpr>(TopBase))
16732       return;
16733 
16734   // Alignment expected by the whole expression.
16735   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16736 
16737   // No need to do anything else with this case.
16738   if (ExpectedAlignment.isOne())
16739     return;
16740 
16741   // Synthesize offset of the whole access.
16742   CharUnits Offset;
16743   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16744     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16745 
16746   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16747   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16748       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16749 
16750   // The base expression of the innermost MemberExpr may give
16751   // stronger guarantees than the class containing the member.
16752   if (DRE && !TopME->isArrow()) {
16753     const ValueDecl *VD = DRE->getDecl();
16754     if (!VD->getType()->isReferenceType())
16755       CompleteObjectAlignment =
16756           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16757   }
16758 
16759   // Check if the synthesized offset fulfills the alignment.
16760   if (Offset % ExpectedAlignment != 0 ||
16761       // It may fulfill the offset it but the effective alignment may still be
16762       // lower than the expected expression alignment.
16763       CompleteObjectAlignment < ExpectedAlignment) {
16764     // If this happens, we want to determine a sensible culprit of this.
16765     // Intuitively, watching the chain of member expressions from right to
16766     // left, we start with the required alignment (as required by the field
16767     // type) but some packed attribute in that chain has reduced the alignment.
16768     // It may happen that another packed structure increases it again. But if
16769     // we are here such increase has not been enough. So pointing the first
16770     // FieldDecl that either is packed or else its RecordDecl is,
16771     // seems reasonable.
16772     FieldDecl *FD = nullptr;
16773     CharUnits Alignment;
16774     for (FieldDecl *FDI : ReverseMemberChain) {
16775       if (FDI->hasAttr<PackedAttr>() ||
16776           FDI->getParent()->hasAttr<PackedAttr>()) {
16777         FD = FDI;
16778         Alignment = std::min(
16779             Context.getTypeAlignInChars(FD->getType()),
16780             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16781         break;
16782       }
16783     }
16784     assert(FD && "We did not find a packed FieldDecl!");
16785     Action(E, FD->getParent(), FD, Alignment);
16786   }
16787 }
16788 
16789 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16790   using namespace std::placeholders;
16791 
16792   RefersToMemberWithReducedAlignment(
16793       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16794                      _2, _3, _4));
16795 }
16796 
16797 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16798 // not a valid type, emit an error message and return true. Otherwise return
16799 // false.
16800 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16801                                         QualType Ty) {
16802   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16803     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16804         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16805     return true;
16806   }
16807   return false;
16808 }
16809 
16810 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16811   if (checkArgCount(*this, TheCall, 1))
16812     return true;
16813 
16814   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16815   if (A.isInvalid())
16816     return true;
16817 
16818   TheCall->setArg(0, A.get());
16819   QualType TyA = A.get()->getType();
16820 
16821   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16822     return true;
16823 
16824   TheCall->setType(TyA);
16825   return false;
16826 }
16827 
16828 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16829   if (checkArgCount(*this, TheCall, 2))
16830     return true;
16831 
16832   ExprResult A = TheCall->getArg(0);
16833   ExprResult B = TheCall->getArg(1);
16834   // Do standard promotions between the two arguments, returning their common
16835   // type.
16836   QualType Res =
16837       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16838   if (A.isInvalid() || B.isInvalid())
16839     return true;
16840 
16841   QualType TyA = A.get()->getType();
16842   QualType TyB = B.get()->getType();
16843 
16844   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16845     return Diag(A.get()->getBeginLoc(),
16846                 diag::err_typecheck_call_different_arg_types)
16847            << TyA << TyB;
16848 
16849   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16850     return true;
16851 
16852   TheCall->setArg(0, A.get());
16853   TheCall->setArg(1, B.get());
16854   TheCall->setType(Res);
16855   return false;
16856 }
16857 
16858 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) {
16859   if (checkArgCount(*this, TheCall, 1))
16860     return true;
16861 
16862   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16863   if (A.isInvalid())
16864     return true;
16865 
16866   TheCall->setArg(0, A.get());
16867   const VectorType *TyA = A.get()->getType()->getAs<VectorType>();
16868   if (!TyA) {
16869     SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16870     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16871            << 1 << /* vector ty*/ 4 << A.get()->getType();
16872   }
16873 
16874   TheCall->setType(TyA->getElementType());
16875   return false;
16876 }
16877 
16878 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16879                                             ExprResult CallResult) {
16880   if (checkArgCount(*this, TheCall, 1))
16881     return ExprError();
16882 
16883   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16884   if (MatrixArg.isInvalid())
16885     return MatrixArg;
16886   Expr *Matrix = MatrixArg.get();
16887 
16888   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16889   if (!MType) {
16890     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16891         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16892     return ExprError();
16893   }
16894 
16895   // Create returned matrix type by swapping rows and columns of the argument
16896   // matrix type.
16897   QualType ResultType = Context.getConstantMatrixType(
16898       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16899 
16900   // Change the return type to the type of the returned matrix.
16901   TheCall->setType(ResultType);
16902 
16903   // Update call argument to use the possibly converted matrix argument.
16904   TheCall->setArg(0, Matrix);
16905   return CallResult;
16906 }
16907 
16908 // Get and verify the matrix dimensions.
16909 static llvm::Optional<unsigned>
16910 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16911   SourceLocation ErrorPos;
16912   Optional<llvm::APSInt> Value =
16913       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16914   if (!Value) {
16915     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16916         << Name;
16917     return {};
16918   }
16919   uint64_t Dim = Value->getZExtValue();
16920   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16921     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16922         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16923     return {};
16924   }
16925   return Dim;
16926 }
16927 
16928 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16929                                                   ExprResult CallResult) {
16930   if (!getLangOpts().MatrixTypes) {
16931     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16932     return ExprError();
16933   }
16934 
16935   if (checkArgCount(*this, TheCall, 4))
16936     return ExprError();
16937 
16938   unsigned PtrArgIdx = 0;
16939   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16940   Expr *RowsExpr = TheCall->getArg(1);
16941   Expr *ColumnsExpr = TheCall->getArg(2);
16942   Expr *StrideExpr = TheCall->getArg(3);
16943 
16944   bool ArgError = false;
16945 
16946   // Check pointer argument.
16947   {
16948     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16949     if (PtrConv.isInvalid())
16950       return PtrConv;
16951     PtrExpr = PtrConv.get();
16952     TheCall->setArg(0, PtrExpr);
16953     if (PtrExpr->isTypeDependent()) {
16954       TheCall->setType(Context.DependentTy);
16955       return TheCall;
16956     }
16957   }
16958 
16959   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16960   QualType ElementTy;
16961   if (!PtrTy) {
16962     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16963         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16964     ArgError = true;
16965   } else {
16966     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16967 
16968     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16969       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16970           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
16971           << PtrExpr->getType();
16972       ArgError = true;
16973     }
16974   }
16975 
16976   // Apply default Lvalue conversions and convert the expression to size_t.
16977   auto ApplyArgumentConversions = [this](Expr *E) {
16978     ExprResult Conv = DefaultLvalueConversion(E);
16979     if (Conv.isInvalid())
16980       return Conv;
16981 
16982     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16983   };
16984 
16985   // Apply conversion to row and column expressions.
16986   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16987   if (!RowsConv.isInvalid()) {
16988     RowsExpr = RowsConv.get();
16989     TheCall->setArg(1, RowsExpr);
16990   } else
16991     RowsExpr = nullptr;
16992 
16993   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16994   if (!ColumnsConv.isInvalid()) {
16995     ColumnsExpr = ColumnsConv.get();
16996     TheCall->setArg(2, ColumnsExpr);
16997   } else
16998     ColumnsExpr = nullptr;
16999 
17000   // If any any part of the result matrix type is still pending, just use
17001   // Context.DependentTy, until all parts are resolved.
17002   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17003       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17004     TheCall->setType(Context.DependentTy);
17005     return CallResult;
17006   }
17007 
17008   // Check row and column dimensions.
17009   llvm::Optional<unsigned> MaybeRows;
17010   if (RowsExpr)
17011     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17012 
17013   llvm::Optional<unsigned> MaybeColumns;
17014   if (ColumnsExpr)
17015     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17016 
17017   // Check stride argument.
17018   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17019   if (StrideConv.isInvalid())
17020     return ExprError();
17021   StrideExpr = StrideConv.get();
17022   TheCall->setArg(3, StrideExpr);
17023 
17024   if (MaybeRows) {
17025     if (Optional<llvm::APSInt> Value =
17026             StrideExpr->getIntegerConstantExpr(Context)) {
17027       uint64_t Stride = Value->getZExtValue();
17028       if (Stride < *MaybeRows) {
17029         Diag(StrideExpr->getBeginLoc(),
17030              diag::err_builtin_matrix_stride_too_small);
17031         ArgError = true;
17032       }
17033     }
17034   }
17035 
17036   if (ArgError || !MaybeRows || !MaybeColumns)
17037     return ExprError();
17038 
17039   TheCall->setType(
17040       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17041   return CallResult;
17042 }
17043 
17044 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17045                                                    ExprResult CallResult) {
17046   if (checkArgCount(*this, TheCall, 3))
17047     return ExprError();
17048 
17049   unsigned PtrArgIdx = 1;
17050   Expr *MatrixExpr = TheCall->getArg(0);
17051   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17052   Expr *StrideExpr = TheCall->getArg(2);
17053 
17054   bool ArgError = false;
17055 
17056   {
17057     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17058     if (MatrixConv.isInvalid())
17059       return MatrixConv;
17060     MatrixExpr = MatrixConv.get();
17061     TheCall->setArg(0, MatrixExpr);
17062   }
17063   if (MatrixExpr->isTypeDependent()) {
17064     TheCall->setType(Context.DependentTy);
17065     return TheCall;
17066   }
17067 
17068   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17069   if (!MatrixTy) {
17070     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17071         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17072     ArgError = true;
17073   }
17074 
17075   {
17076     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17077     if (PtrConv.isInvalid())
17078       return PtrConv;
17079     PtrExpr = PtrConv.get();
17080     TheCall->setArg(1, PtrExpr);
17081     if (PtrExpr->isTypeDependent()) {
17082       TheCall->setType(Context.DependentTy);
17083       return TheCall;
17084     }
17085   }
17086 
17087   // Check pointer argument.
17088   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17089   if (!PtrTy) {
17090     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17091         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17092     ArgError = true;
17093   } else {
17094     QualType ElementTy = PtrTy->getPointeeType();
17095     if (ElementTy.isConstQualified()) {
17096       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17097       ArgError = true;
17098     }
17099     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17100     if (MatrixTy &&
17101         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17102       Diag(PtrExpr->getBeginLoc(),
17103            diag::err_builtin_matrix_pointer_arg_mismatch)
17104           << ElementTy << MatrixTy->getElementType();
17105       ArgError = true;
17106     }
17107   }
17108 
17109   // Apply default Lvalue conversions and convert the stride expression to
17110   // size_t.
17111   {
17112     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17113     if (StrideConv.isInvalid())
17114       return StrideConv;
17115 
17116     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17117     if (StrideConv.isInvalid())
17118       return StrideConv;
17119     StrideExpr = StrideConv.get();
17120     TheCall->setArg(2, StrideExpr);
17121   }
17122 
17123   // Check stride argument.
17124   if (MatrixTy) {
17125     if (Optional<llvm::APSInt> Value =
17126             StrideExpr->getIntegerConstantExpr(Context)) {
17127       uint64_t Stride = Value->getZExtValue();
17128       if (Stride < MatrixTy->getNumRows()) {
17129         Diag(StrideExpr->getBeginLoc(),
17130              diag::err_builtin_matrix_stride_too_small);
17131         ArgError = true;
17132       }
17133     }
17134   }
17135 
17136   if (ArgError)
17137     return ExprError();
17138 
17139   return CallResult;
17140 }
17141 
17142 /// \brief Enforce the bounds of a TCB
17143 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17144 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17145 /// and enforce_tcb_leaf attributes.
17146 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17147                                const FunctionDecl *Callee) {
17148   const FunctionDecl *Caller = getCurFunctionDecl();
17149 
17150   // Calls to builtins are not enforced.
17151   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17152       Callee->getBuiltinID() != 0)
17153     return;
17154 
17155   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17156   // all TCBs the callee is a part of.
17157   llvm::StringSet<> CalleeTCBs;
17158   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17159            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17160   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17161            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17162 
17163   // Go through the TCBs the caller is a part of and emit warnings if Caller
17164   // is in a TCB that the Callee is not.
17165   for_each(
17166       Caller->specific_attrs<EnforceTCBAttr>(),
17167       [&](const auto *A) {
17168         StringRef CallerTCB = A->getTCBName();
17169         if (CalleeTCBs.count(CallerTCB) == 0) {
17170           this->Diag(TheCall->getExprLoc(),
17171                      diag::warn_tcb_enforcement_violation) << Callee
17172                                                            << CallerTCB;
17173         }
17174       });
17175 }
17176