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 ExtIntType args larger than 128 bits to mul function until
329   // 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->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_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 EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << toString(ObjectSize, /*Radix=*/10)
776                           << toString(UsedSize.getValue(), /*Radix=*/10));
777 }
778 
779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844     return true;
845   }
846   return false;
847 }
848 
849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850   if (checkArgCount(S, TheCall, 2))
851     return true;
852 
853   if (checkOpenCLSubgroupExt(S, TheCall))
854     return true;
855 
856   // First argument is an ndrange_t type.
857   Expr *NDRangeArg = TheCall->getArg(0);
858   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860         << TheCall->getDirectCallee() << "'ndrange_t'";
861     return true;
862   }
863 
864   Expr *BlockArg = TheCall->getArg(1);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874 /// get_kernel_work_group_size
875 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877   if (checkArgCount(S, TheCall, 1))
878     return true;
879 
880   Expr *BlockArg = TheCall->getArg(0);
881   if (!isBlockPointer(BlockArg)) {
882     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883         << TheCall->getDirectCallee() << "block";
884     return true;
885   }
886   return checkOpenCLBlockArgs(S, BlockArg);
887 }
888 
889 /// Diagnose integer type and any valid implicit conversion to it.
890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891                                       const QualType &IntType);
892 
893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894                                             unsigned Start, unsigned End) {
895   bool IllegalParams = false;
896   for (unsigned I = Start; I <= End; ++I)
897     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898                                               S.Context.getSizeType());
899   return IllegalParams;
900 }
901 
902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903 /// 'local void*' parameter of passed block.
904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905                                            Expr *BlockArg,
906                                            unsigned NumNonVarArgs) {
907   const BlockPointerType *BPT =
908       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909   unsigned NumBlockParams =
910       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911   unsigned TotalNumArgs = TheCall->getNumArgs();
912 
913   // For each argument passed to the block, a corresponding uint needs to
914   // be passed to describe the size of the local memory.
915   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916     S.Diag(TheCall->getBeginLoc(),
917            diag::err_opencl_enqueue_kernel_local_size_args);
918     return true;
919   }
920 
921   // Check that the sizes of the local memory are specified by integers.
922   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923                                          TotalNumArgs - 1);
924 }
925 
926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927 /// overload formats specified in Table 6.13.17.1.
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    void (^block)(void))
932 /// int enqueue_kernel(queue_t queue,
933 ///                    kernel_enqueue_flags_t flags,
934 ///                    const ndrange_t ndrange,
935 ///                    uint num_events_in_wait_list,
936 ///                    clk_event_t *event_wait_list,
937 ///                    clk_event_t *event_ret,
938 ///                    void (^block)(void))
939 /// int enqueue_kernel(queue_t queue,
940 ///                    kernel_enqueue_flags_t flags,
941 ///                    const ndrange_t ndrange,
942 ///                    void (^block)(local void*, ...),
943 ///                    uint size0, ...)
944 /// int enqueue_kernel(queue_t queue,
945 ///                    kernel_enqueue_flags_t flags,
946 ///                    const ndrange_t ndrange,
947 ///                    uint num_events_in_wait_list,
948 ///                    clk_event_t *event_wait_list,
949 ///                    clk_event_t *event_ret,
950 ///                    void (^block)(local void*, ...),
951 ///                    uint size0, ...)
952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953   unsigned NumArgs = TheCall->getNumArgs();
954 
955   if (NumArgs < 4) {
956     S.Diag(TheCall->getBeginLoc(),
957            diag::err_typecheck_call_too_few_args_at_least)
958         << 0 << 4 << NumArgs;
959     return true;
960   }
961 
962   Expr *Arg0 = TheCall->getArg(0);
963   Expr *Arg1 = TheCall->getArg(1);
964   Expr *Arg2 = TheCall->getArg(2);
965   Expr *Arg3 = TheCall->getArg(3);
966 
967   // First argument always needs to be a queue_t type.
968   if (!Arg0->getType()->isQueueT()) {
969     S.Diag(TheCall->getArg(0)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972     return true;
973   }
974 
975   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976   if (!Arg1->getType()->isIntegerType()) {
977     S.Diag(TheCall->getArg(1)->getBeginLoc(),
978            diag::err_opencl_builtin_expected_type)
979         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980     return true;
981   }
982 
983   // Third argument is always an ndrange_t type.
984   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985     S.Diag(TheCall->getArg(2)->getBeginLoc(),
986            diag::err_opencl_builtin_expected_type)
987         << TheCall->getDirectCallee() << "'ndrange_t'";
988     return true;
989   }
990 
991   // With four arguments, there is only one form that the function could be
992   // called in: no events and no variable arguments.
993   if (NumArgs == 4) {
994     // check that the last argument is the right block type.
995     if (!isBlockPointer(Arg3)) {
996       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997           << TheCall->getDirectCallee() << "block";
998       return true;
999     }
1000     // we have a block type, check the prototype
1001     const BlockPointerType *BPT =
1002         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004       S.Diag(Arg3->getBeginLoc(),
1005              diag::err_opencl_enqueue_kernel_blocks_no_args);
1006       return true;
1007     }
1008     return false;
1009   }
1010   // we can have block + varargs.
1011   if (isBlockPointer(Arg3))
1012     return (checkOpenCLBlockArgs(S, Arg3) ||
1013             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014   // last two cases with either exactly 7 args or 7 args and varargs.
1015   if (NumArgs >= 7) {
1016     // check common block argument.
1017     Expr *Arg6 = TheCall->getArg(6);
1018     if (!isBlockPointer(Arg6)) {
1019       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020           << TheCall->getDirectCallee() << "block";
1021       return true;
1022     }
1023     if (checkOpenCLBlockArgs(S, Arg6))
1024       return true;
1025 
1026     // Forth argument has to be any integer type.
1027     if (!Arg3->getType()->isIntegerType()) {
1028       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029              diag::err_opencl_builtin_expected_type)
1030           << TheCall->getDirectCallee() << "integer";
1031       return true;
1032     }
1033     // check remaining common arguments.
1034     Expr *Arg4 = TheCall->getArg(4);
1035     Expr *Arg5 = TheCall->getArg(5);
1036 
1037     // Fifth argument is always passed as a pointer to clk_event_t.
1038     if (!Arg4->isNullPointerConstant(S.Context,
1039                                      Expr::NPC_ValueDependentIsNotNull) &&
1040         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042              diag::err_opencl_builtin_expected_type)
1043           << TheCall->getDirectCallee()
1044           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045       return true;
1046     }
1047 
1048     // Sixth argument is always passed as a pointer to clk_event_t.
1049     if (!Arg5->isNullPointerConstant(S.Context,
1050                                      Expr::NPC_ValueDependentIsNotNull) &&
1051         !(Arg5->getType()->isPointerType() &&
1052           Arg5->getType()->getPointeeType()->isClkEventT())) {
1053       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054              diag::err_opencl_builtin_expected_type)
1055           << TheCall->getDirectCallee()
1056           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057       return true;
1058     }
1059 
1060     if (NumArgs == 7)
1061       return false;
1062 
1063     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064   }
1065 
1066   // None of the specific case has been detected, give generic error
1067   S.Diag(TheCall->getBeginLoc(),
1068          diag::err_opencl_enqueue_kernel_incorrect_args);
1069   return true;
1070 }
1071 
1072 /// Returns OpenCL access qual.
1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074     return D->getAttr<OpenCLAccessAttr>();
1075 }
1076 
1077 /// Returns true if pipe element type is different from the pointer.
1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079   const Expr *Arg0 = Call->getArg(0);
1080   // First argument type should always be pipe.
1081   if (!Arg0->getType()->isPipeType()) {
1082     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083         << Call->getDirectCallee() << Arg0->getSourceRange();
1084     return true;
1085   }
1086   OpenCLAccessAttr *AccessQual =
1087       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088   // Validates the access qualifier is compatible with the call.
1089   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090   // read_only and write_only, and assumed to be read_only if no qualifier is
1091   // specified.
1092   switch (Call->getDirectCallee()->getBuiltinID()) {
1093   case Builtin::BIread_pipe:
1094   case Builtin::BIreserve_read_pipe:
1095   case Builtin::BIcommit_read_pipe:
1096   case Builtin::BIwork_group_reserve_read_pipe:
1097   case Builtin::BIsub_group_reserve_read_pipe:
1098   case Builtin::BIwork_group_commit_read_pipe:
1099   case Builtin::BIsub_group_commit_read_pipe:
1100     if (!(!AccessQual || AccessQual->isReadOnly())) {
1101       S.Diag(Arg0->getBeginLoc(),
1102              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103           << "read_only" << Arg0->getSourceRange();
1104       return true;
1105     }
1106     break;
1107   case Builtin::BIwrite_pipe:
1108   case Builtin::BIreserve_write_pipe:
1109   case Builtin::BIcommit_write_pipe:
1110   case Builtin::BIwork_group_reserve_write_pipe:
1111   case Builtin::BIsub_group_reserve_write_pipe:
1112   case Builtin::BIwork_group_commit_write_pipe:
1113   case Builtin::BIsub_group_commit_write_pipe:
1114     if (!(AccessQual && AccessQual->isWriteOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "write_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   default:
1122     break;
1123   }
1124   return false;
1125 }
1126 
1127 /// Returns true if pipe element type is different from the pointer.
1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129   const Expr *Arg0 = Call->getArg(0);
1130   const Expr *ArgIdx = Call->getArg(Idx);
1131   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132   const QualType EltTy = PipeTy->getElementType();
1133   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134   // The Idx argument should be a pointer and the type of the pointer and
1135   // the type of pipe element should also be the same.
1136   if (!ArgTy ||
1137       !S.Context.hasSameType(
1138           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141         << ArgIdx->getType() << ArgIdx->getSourceRange();
1142     return true;
1143   }
1144   return false;
1145 }
1146 
1147 // Performs semantic analysis for the read/write_pipe call.
1148 // \param S Reference to the semantic analyzer.
1149 // \param Call A pointer to the builtin call.
1150 // \return True if a semantic error has been found, false otherwise.
1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153   // functions have two forms.
1154   switch (Call->getNumArgs()) {
1155   case 2:
1156     if (checkOpenCLPipeArg(S, Call))
1157       return true;
1158     // The call with 2 arguments should be
1159     // read/write_pipe(pipe T, T*).
1160     // Check packet type T.
1161     if (checkOpenCLPipePacketType(S, Call, 1))
1162       return true;
1163     break;
1164 
1165   case 4: {
1166     if (checkOpenCLPipeArg(S, Call))
1167       return true;
1168     // The call with 4 arguments should be
1169     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170     // Check reserve_id_t.
1171     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175       return true;
1176     }
1177 
1178     // Check the index.
1179     const Expr *Arg2 = Call->getArg(2);
1180     if (!Arg2->getType()->isIntegerType() &&
1181         !Arg2->getType()->isUnsignedIntegerType()) {
1182       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184           << Arg2->getType() << Arg2->getSourceRange();
1185       return true;
1186     }
1187 
1188     // Check packet type T.
1189     if (checkOpenCLPipePacketType(S, Call, 3))
1190       return true;
1191   } break;
1192   default:
1193     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194         << Call->getDirectCallee() << Call->getSourceRange();
1195     return true;
1196   }
1197 
1198   return false;
1199 }
1200 
1201 // Performs a semantic analysis on the {work_group_/sub_group_
1202 //        /_}reserve_{read/write}_pipe
1203 // \param S Reference to the semantic analyzer.
1204 // \param Call The call to the builtin function to be analyzed.
1205 // \return True if a semantic error was found, false otherwise.
1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207   if (checkArgCount(S, Call, 2))
1208     return true;
1209 
1210   if (checkOpenCLPipeArg(S, Call))
1211     return true;
1212 
1213   // Check the reserve size.
1214   if (!Call->getArg(1)->getType()->isIntegerType() &&
1215       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219     return true;
1220   }
1221 
1222   // Since return type of reserve_read/write_pipe built-in function is
1223   // reserve_id_t, which is not defined in the builtin def file , we used int
1224   // as return type and need to override the return type of these functions.
1225   Call->setType(S.Context.OCLReserveIDTy);
1226 
1227   return false;
1228 }
1229 
1230 // Performs a semantic analysis on {work_group_/sub_group_
1231 //        /_}commit_{read/write}_pipe
1232 // \param S Reference to the semantic analyzer.
1233 // \param Call The call to the builtin function to be analyzed.
1234 // \return True if a semantic error was found, false otherwise.
1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236   if (checkArgCount(S, Call, 2))
1237     return true;
1238 
1239   if (checkOpenCLPipeArg(S, Call))
1240     return true;
1241 
1242   // Check reserve_id_t.
1243   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247     return true;
1248   }
1249 
1250   return false;
1251 }
1252 
1253 // Performs a semantic analysis on the call to built-in Pipe
1254 //        Query Functions.
1255 // \param S Reference to the semantic analyzer.
1256 // \param Call The call to the builtin function to be analyzed.
1257 // \return True if a semantic error was found, false otherwise.
1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259   if (checkArgCount(S, Call, 1))
1260     return true;
1261 
1262   if (!Call->getArg(0)->getType()->isPipeType()) {
1263     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265     return true;
1266   }
1267 
1268   return false;
1269 }
1270 
1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272 // Performs semantic analysis for the to_global/local/private call.
1273 // \param S Reference to the semantic analyzer.
1274 // \param BuiltinID ID of the builtin function.
1275 // \param Call A pointer to the builtin call.
1276 // \return True if a semantic error has been found, false otherwise.
1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278                                     CallExpr *Call) {
1279   if (checkArgCount(S, Call, 1))
1280     return true;
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppcle:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   case llvm::Triple::riscv32:
1434   case llvm::Triple::riscv64:
1435     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436   }
1437 }
1438 
1439 ExprResult
1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441                                CallExpr *TheCall) {
1442   ExprResult TheCallResult(TheCall);
1443 
1444   // Find out if any arguments are required to be integer constant expressions.
1445   unsigned ICEArguments = 0;
1446   ASTContext::GetBuiltinTypeError Error;
1447   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448   if (Error != ASTContext::GE_None)
1449     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1450 
1451   // If any arguments are required to be ICE's, check and diagnose.
1452   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453     // Skip arguments not required to be ICE's.
1454     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455 
1456     llvm::APSInt Result;
1457     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458       return true;
1459     ICEArguments &= ~(1 << ArgNo);
1460   }
1461 
1462   switch (BuiltinID) {
1463   case Builtin::BI__builtin___CFStringMakeConstantString:
1464     assert(TheCall->getNumArgs() == 1 &&
1465            "Wrong # arguments to builtin CFStringMakeConstantString");
1466     if (CheckObjCString(TheCall->getArg(0)))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_ms_va_start:
1470   case Builtin::BI__builtin_stdarg_start:
1471   case Builtin::BI__builtin_va_start:
1472     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BI__va_start: {
1476     switch (Context.getTargetInfo().getTriple().getArch()) {
1477     case llvm::Triple::aarch64:
1478     case llvm::Triple::arm:
1479     case llvm::Triple::thumb:
1480       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481         return ExprError();
1482       break;
1483     default:
1484       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485         return ExprError();
1486       break;
1487     }
1488     break;
1489   }
1490 
1491   // The acquire, release, and no fence variants are ARM and AArch64 only.
1492   case Builtin::BI_interlockedbittestandset_acq:
1493   case Builtin::BI_interlockedbittestandset_rel:
1494   case Builtin::BI_interlockedbittestandset_nf:
1495   case Builtin::BI_interlockedbittestandreset_acq:
1496   case Builtin::BI_interlockedbittestandreset_rel:
1497   case Builtin::BI_interlockedbittestandreset_nf:
1498     if (CheckBuiltinTargetSupport(
1499             *this, BuiltinID, TheCall,
1500             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501       return ExprError();
1502     break;
1503 
1504   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505   case Builtin::BI_bittest64:
1506   case Builtin::BI_bittestandcomplement64:
1507   case Builtin::BI_bittestandreset64:
1508   case Builtin::BI_bittestandset64:
1509   case Builtin::BI_interlockedbittestandreset64:
1510   case Builtin::BI_interlockedbittestandset64:
1511     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1513                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1514       return ExprError();
1515     break;
1516 
1517   case Builtin::BI__builtin_isgreater:
1518   case Builtin::BI__builtin_isgreaterequal:
1519   case Builtin::BI__builtin_isless:
1520   case Builtin::BI__builtin_islessequal:
1521   case Builtin::BI__builtin_islessgreater:
1522   case Builtin::BI__builtin_isunordered:
1523     if (SemaBuiltinUnorderedCompare(TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_fpclassify:
1527     if (SemaBuiltinFPClassification(TheCall, 6))
1528       return ExprError();
1529     break;
1530   case Builtin::BI__builtin_isfinite:
1531   case Builtin::BI__builtin_isinf:
1532   case Builtin::BI__builtin_isinf_sign:
1533   case Builtin::BI__builtin_isnan:
1534   case Builtin::BI__builtin_isnormal:
1535   case Builtin::BI__builtin_signbit:
1536   case Builtin::BI__builtin_signbitf:
1537   case Builtin::BI__builtin_signbitl:
1538     if (SemaBuiltinFPClassification(TheCall, 1))
1539       return ExprError();
1540     break;
1541   case Builtin::BI__builtin_shufflevector:
1542     return SemaBuiltinShuffleVector(TheCall);
1543     // TheCall will be freed by the smart pointer here, but that's fine, since
1544     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545   case Builtin::BI__builtin_prefetch:
1546     if (SemaBuiltinPrefetch(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_alloca_with_align:
1550     if (SemaBuiltinAllocaWithAlign(TheCall))
1551       return ExprError();
1552     LLVM_FALLTHROUGH;
1553   case Builtin::BI__builtin_alloca:
1554     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555         << TheCall->getDirectCallee();
1556     break;
1557   case Builtin::BI__assume:
1558   case Builtin::BI__builtin_assume:
1559     if (SemaBuiltinAssume(TheCall))
1560       return ExprError();
1561     break;
1562   case Builtin::BI__builtin_assume_aligned:
1563     if (SemaBuiltinAssumeAligned(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_dynamic_object_size:
1567   case Builtin::BI__builtin_object_size:
1568     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1569       return ExprError();
1570     break;
1571   case Builtin::BI__builtin_longjmp:
1572     if (SemaBuiltinLongjmp(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_setjmp:
1576     if (SemaBuiltinSetjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_classify_type:
1580     if (checkArgCount(*this, TheCall, 1)) return true;
1581     TheCall->setType(Context.IntTy);
1582     break;
1583   case Builtin::BI__builtin_complex:
1584     if (SemaBuiltinComplex(TheCall))
1585       return ExprError();
1586     break;
1587   case Builtin::BI__builtin_constant_p: {
1588     if (checkArgCount(*this, TheCall, 1)) return true;
1589     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1590     if (Arg.isInvalid()) return true;
1591     TheCall->setArg(0, Arg.get());
1592     TheCall->setType(Context.IntTy);
1593     break;
1594   }
1595   case Builtin::BI__builtin_launder:
1596     return SemaBuiltinLaunder(*this, TheCall);
1597   case Builtin::BI__sync_fetch_and_add:
1598   case Builtin::BI__sync_fetch_and_add_1:
1599   case Builtin::BI__sync_fetch_and_add_2:
1600   case Builtin::BI__sync_fetch_and_add_4:
1601   case Builtin::BI__sync_fetch_and_add_8:
1602   case Builtin::BI__sync_fetch_and_add_16:
1603   case Builtin::BI__sync_fetch_and_sub:
1604   case Builtin::BI__sync_fetch_and_sub_1:
1605   case Builtin::BI__sync_fetch_and_sub_2:
1606   case Builtin::BI__sync_fetch_and_sub_4:
1607   case Builtin::BI__sync_fetch_and_sub_8:
1608   case Builtin::BI__sync_fetch_and_sub_16:
1609   case Builtin::BI__sync_fetch_and_or:
1610   case Builtin::BI__sync_fetch_and_or_1:
1611   case Builtin::BI__sync_fetch_and_or_2:
1612   case Builtin::BI__sync_fetch_and_or_4:
1613   case Builtin::BI__sync_fetch_and_or_8:
1614   case Builtin::BI__sync_fetch_and_or_16:
1615   case Builtin::BI__sync_fetch_and_and:
1616   case Builtin::BI__sync_fetch_and_and_1:
1617   case Builtin::BI__sync_fetch_and_and_2:
1618   case Builtin::BI__sync_fetch_and_and_4:
1619   case Builtin::BI__sync_fetch_and_and_8:
1620   case Builtin::BI__sync_fetch_and_and_16:
1621   case Builtin::BI__sync_fetch_and_xor:
1622   case Builtin::BI__sync_fetch_and_xor_1:
1623   case Builtin::BI__sync_fetch_and_xor_2:
1624   case Builtin::BI__sync_fetch_and_xor_4:
1625   case Builtin::BI__sync_fetch_and_xor_8:
1626   case Builtin::BI__sync_fetch_and_xor_16:
1627   case Builtin::BI__sync_fetch_and_nand:
1628   case Builtin::BI__sync_fetch_and_nand_1:
1629   case Builtin::BI__sync_fetch_and_nand_2:
1630   case Builtin::BI__sync_fetch_and_nand_4:
1631   case Builtin::BI__sync_fetch_and_nand_8:
1632   case Builtin::BI__sync_fetch_and_nand_16:
1633   case Builtin::BI__sync_add_and_fetch:
1634   case Builtin::BI__sync_add_and_fetch_1:
1635   case Builtin::BI__sync_add_and_fetch_2:
1636   case Builtin::BI__sync_add_and_fetch_4:
1637   case Builtin::BI__sync_add_and_fetch_8:
1638   case Builtin::BI__sync_add_and_fetch_16:
1639   case Builtin::BI__sync_sub_and_fetch:
1640   case Builtin::BI__sync_sub_and_fetch_1:
1641   case Builtin::BI__sync_sub_and_fetch_2:
1642   case Builtin::BI__sync_sub_and_fetch_4:
1643   case Builtin::BI__sync_sub_and_fetch_8:
1644   case Builtin::BI__sync_sub_and_fetch_16:
1645   case Builtin::BI__sync_and_and_fetch:
1646   case Builtin::BI__sync_and_and_fetch_1:
1647   case Builtin::BI__sync_and_and_fetch_2:
1648   case Builtin::BI__sync_and_and_fetch_4:
1649   case Builtin::BI__sync_and_and_fetch_8:
1650   case Builtin::BI__sync_and_and_fetch_16:
1651   case Builtin::BI__sync_or_and_fetch:
1652   case Builtin::BI__sync_or_and_fetch_1:
1653   case Builtin::BI__sync_or_and_fetch_2:
1654   case Builtin::BI__sync_or_and_fetch_4:
1655   case Builtin::BI__sync_or_and_fetch_8:
1656   case Builtin::BI__sync_or_and_fetch_16:
1657   case Builtin::BI__sync_xor_and_fetch:
1658   case Builtin::BI__sync_xor_and_fetch_1:
1659   case Builtin::BI__sync_xor_and_fetch_2:
1660   case Builtin::BI__sync_xor_and_fetch_4:
1661   case Builtin::BI__sync_xor_and_fetch_8:
1662   case Builtin::BI__sync_xor_and_fetch_16:
1663   case Builtin::BI__sync_nand_and_fetch:
1664   case Builtin::BI__sync_nand_and_fetch_1:
1665   case Builtin::BI__sync_nand_and_fetch_2:
1666   case Builtin::BI__sync_nand_and_fetch_4:
1667   case Builtin::BI__sync_nand_and_fetch_8:
1668   case Builtin::BI__sync_nand_and_fetch_16:
1669   case Builtin::BI__sync_val_compare_and_swap:
1670   case Builtin::BI__sync_val_compare_and_swap_1:
1671   case Builtin::BI__sync_val_compare_and_swap_2:
1672   case Builtin::BI__sync_val_compare_and_swap_4:
1673   case Builtin::BI__sync_val_compare_and_swap_8:
1674   case Builtin::BI__sync_val_compare_and_swap_16:
1675   case Builtin::BI__sync_bool_compare_and_swap:
1676   case Builtin::BI__sync_bool_compare_and_swap_1:
1677   case Builtin::BI__sync_bool_compare_and_swap_2:
1678   case Builtin::BI__sync_bool_compare_and_swap_4:
1679   case Builtin::BI__sync_bool_compare_and_swap_8:
1680   case Builtin::BI__sync_bool_compare_and_swap_16:
1681   case Builtin::BI__sync_lock_test_and_set:
1682   case Builtin::BI__sync_lock_test_and_set_1:
1683   case Builtin::BI__sync_lock_test_and_set_2:
1684   case Builtin::BI__sync_lock_test_and_set_4:
1685   case Builtin::BI__sync_lock_test_and_set_8:
1686   case Builtin::BI__sync_lock_test_and_set_16:
1687   case Builtin::BI__sync_lock_release:
1688   case Builtin::BI__sync_lock_release_1:
1689   case Builtin::BI__sync_lock_release_2:
1690   case Builtin::BI__sync_lock_release_4:
1691   case Builtin::BI__sync_lock_release_8:
1692   case Builtin::BI__sync_lock_release_16:
1693   case Builtin::BI__sync_swap:
1694   case Builtin::BI__sync_swap_1:
1695   case Builtin::BI__sync_swap_2:
1696   case Builtin::BI__sync_swap_4:
1697   case Builtin::BI__sync_swap_8:
1698   case Builtin::BI__sync_swap_16:
1699     return SemaBuiltinAtomicOverloaded(TheCallResult);
1700   case Builtin::BI__sync_synchronize:
1701     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1702         << TheCall->getCallee()->getSourceRange();
1703     break;
1704   case Builtin::BI__builtin_nontemporal_load:
1705   case Builtin::BI__builtin_nontemporal_store:
1706     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1707   case Builtin::BI__builtin_memcpy_inline: {
1708     clang::Expr *SizeOp = TheCall->getArg(2);
1709     // We warn about copying to or from `nullptr` pointers when `size` is
1710     // greater than 0. When `size` is value dependent we cannot evaluate its
1711     // value so we bail out.
1712     if (SizeOp->isValueDependent())
1713       break;
1714     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1715       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1716       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1717     }
1718     break;
1719   }
1720 #define BUILTIN(ID, TYPE, ATTRS)
1721 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1722   case Builtin::BI##ID: \
1723     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1724 #include "clang/Basic/Builtins.def"
1725   case Builtin::BI__annotation:
1726     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1727       return ExprError();
1728     break;
1729   case Builtin::BI__builtin_annotation:
1730     if (SemaBuiltinAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_addressof:
1734     if (SemaBuiltinAddressof(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_is_aligned:
1738   case Builtin::BI__builtin_align_up:
1739   case Builtin::BI__builtin_align_down:
1740     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1741       return ExprError();
1742     break;
1743   case Builtin::BI__builtin_add_overflow:
1744   case Builtin::BI__builtin_sub_overflow:
1745   case Builtin::BI__builtin_mul_overflow:
1746     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1747       return ExprError();
1748     break;
1749   case Builtin::BI__builtin_operator_new:
1750   case Builtin::BI__builtin_operator_delete: {
1751     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1752     ExprResult Res =
1753         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1754     if (Res.isInvalid())
1755       CorrectDelayedTyposInExpr(TheCallResult.get());
1756     return Res;
1757   }
1758   case Builtin::BI__builtin_dump_struct: {
1759     // We first want to ensure we are called with 2 arguments
1760     if (checkArgCount(*this, TheCall, 2))
1761       return ExprError();
1762     // Ensure that the first argument is of type 'struct XX *'
1763     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1764     const QualType PtrArgType = PtrArg->getType();
1765     if (!PtrArgType->isPointerType() ||
1766         !PtrArgType->getPointeeType()->isRecordType()) {
1767       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1768           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1769           << "structure pointer";
1770       return ExprError();
1771     }
1772 
1773     // Ensure that the second argument is of type 'FunctionType'
1774     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1775     const QualType FnPtrArgType = FnPtrArg->getType();
1776     if (!FnPtrArgType->isPointerType()) {
1777       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1778           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1779           << FnPtrArgType << "'int (*)(const char *, ...)'";
1780       return ExprError();
1781     }
1782 
1783     const auto *FuncType =
1784         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1785 
1786     if (!FuncType) {
1787       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1788           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1789           << FnPtrArgType << "'int (*)(const char *, ...)'";
1790       return ExprError();
1791     }
1792 
1793     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1794       if (!FT->getNumParams()) {
1795         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1797             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1798         return ExprError();
1799       }
1800       QualType PT = FT->getParamType(0);
1801       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1802           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1803           !PT->getPointeeType().isConstQualified()) {
1804         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1805             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1806             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1807         return ExprError();
1808       }
1809     }
1810 
1811     TheCall->setType(Context.IntTy);
1812     break;
1813   }
1814   case Builtin::BI__builtin_expect_with_probability: {
1815     // We first want to ensure we are called with 3 arguments
1816     if (checkArgCount(*this, TheCall, 3))
1817       return ExprError();
1818     // then check probability is constant float in range [0.0, 1.0]
1819     const Expr *ProbArg = TheCall->getArg(2);
1820     SmallVector<PartialDiagnosticAt, 8> Notes;
1821     Expr::EvalResult Eval;
1822     Eval.Diag = &Notes;
1823     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1824         !Eval.Val.isFloat()) {
1825       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1826           << ProbArg->getSourceRange();
1827       for (const PartialDiagnosticAt &PDiag : Notes)
1828         Diag(PDiag.first, PDiag.second);
1829       return ExprError();
1830     }
1831     llvm::APFloat Probability = Eval.Val.getFloat();
1832     bool LoseInfo = false;
1833     Probability.convert(llvm::APFloat::IEEEdouble(),
1834                         llvm::RoundingMode::Dynamic, &LoseInfo);
1835     if (!(Probability >= llvm::APFloat(0.0) &&
1836           Probability <= llvm::APFloat(1.0))) {
1837       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1838           << ProbArg->getSourceRange();
1839       return ExprError();
1840     }
1841     break;
1842   }
1843   case Builtin::BI__builtin_preserve_access_index:
1844     if (SemaBuiltinPreserveAI(*this, TheCall))
1845       return ExprError();
1846     break;
1847   case Builtin::BI__builtin_call_with_static_chain:
1848     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__exception_code:
1852   case Builtin::BI_exception_code:
1853     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1854                                  diag::err_seh___except_block))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__exception_info:
1858   case Builtin::BI_exception_info:
1859     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1860                                  diag::err_seh___except_filter))
1861       return ExprError();
1862     break;
1863   case Builtin::BI__GetExceptionInfo:
1864     if (checkArgCount(*this, TheCall, 1))
1865       return ExprError();
1866 
1867     if (CheckCXXThrowOperand(
1868             TheCall->getBeginLoc(),
1869             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1870             TheCall))
1871       return ExprError();
1872 
1873     TheCall->setType(Context.VoidPtrTy);
1874     break;
1875   // OpenCL v2.0, s6.13.16 - Pipe functions
1876   case Builtin::BIread_pipe:
1877   case Builtin::BIwrite_pipe:
1878     // Since those two functions are declared with var args, we need a semantic
1879     // check for the argument.
1880     if (SemaBuiltinRWPipe(*this, TheCall))
1881       return ExprError();
1882     break;
1883   case Builtin::BIreserve_read_pipe:
1884   case Builtin::BIreserve_write_pipe:
1885   case Builtin::BIwork_group_reserve_read_pipe:
1886   case Builtin::BIwork_group_reserve_write_pipe:
1887     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1888       return ExprError();
1889     break;
1890   case Builtin::BIsub_group_reserve_read_pipe:
1891   case Builtin::BIsub_group_reserve_write_pipe:
1892     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1893         SemaBuiltinReserveRWPipe(*this, TheCall))
1894       return ExprError();
1895     break;
1896   case Builtin::BIcommit_read_pipe:
1897   case Builtin::BIcommit_write_pipe:
1898   case Builtin::BIwork_group_commit_read_pipe:
1899   case Builtin::BIwork_group_commit_write_pipe:
1900     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1901       return ExprError();
1902     break;
1903   case Builtin::BIsub_group_commit_read_pipe:
1904   case Builtin::BIsub_group_commit_write_pipe:
1905     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1906         SemaBuiltinCommitRWPipe(*this, TheCall))
1907       return ExprError();
1908     break;
1909   case Builtin::BIget_pipe_num_packets:
1910   case Builtin::BIget_pipe_max_packets:
1911     if (SemaBuiltinPipePackets(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIto_global:
1915   case Builtin::BIto_local:
1916   case Builtin::BIto_private:
1917     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1918       return ExprError();
1919     break;
1920   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1921   case Builtin::BIenqueue_kernel:
1922     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1923       return ExprError();
1924     break;
1925   case Builtin::BIget_kernel_work_group_size:
1926   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1927     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1928       return ExprError();
1929     break;
1930   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1931   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1932     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1933       return ExprError();
1934     break;
1935   case Builtin::BI__builtin_os_log_format:
1936     Cleanup.setExprNeedsCleanups(true);
1937     LLVM_FALLTHROUGH;
1938   case Builtin::BI__builtin_os_log_format_buffer_size:
1939     if (SemaBuiltinOSLogFormat(TheCall))
1940       return ExprError();
1941     break;
1942   case Builtin::BI__builtin_frame_address:
1943   case Builtin::BI__builtin_return_address: {
1944     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1945       return ExprError();
1946 
1947     // -Wframe-address warning if non-zero passed to builtin
1948     // return/frame address.
1949     Expr::EvalResult Result;
1950     if (!TheCall->getArg(0)->isValueDependent() &&
1951         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1952         Result.Val.getInt() != 0)
1953       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1954           << ((BuiltinID == Builtin::BI__builtin_return_address)
1955                   ? "__builtin_return_address"
1956                   : "__builtin_frame_address")
1957           << TheCall->getSourceRange();
1958     break;
1959   }
1960 
1961   case Builtin::BI__builtin_matrix_transpose:
1962     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1963 
1964   case Builtin::BI__builtin_matrix_column_major_load:
1965     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1966 
1967   case Builtin::BI__builtin_matrix_column_major_store:
1968     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1969 
1970   case Builtin::BI__builtin_get_device_side_mangled_name: {
1971     auto Check = [](CallExpr *TheCall) {
1972       if (TheCall->getNumArgs() != 1)
1973         return false;
1974       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1975       if (!DRE)
1976         return false;
1977       auto *D = DRE->getDecl();
1978       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1979         return false;
1980       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1981              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1982     };
1983     if (!Check(TheCall)) {
1984       Diag(TheCall->getBeginLoc(),
1985            diag::err_hip_invalid_args_builtin_mangled_name);
1986       return ExprError();
1987     }
1988   }
1989   }
1990 
1991   // Since the target specific builtins for each arch overlap, only check those
1992   // of the arch we are compiling for.
1993   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1994     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1995       assert(Context.getAuxTargetInfo() &&
1996              "Aux Target Builtin, but not an aux target?");
1997 
1998       if (CheckTSBuiltinFunctionCall(
1999               *Context.getAuxTargetInfo(),
2000               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2001         return ExprError();
2002     } else {
2003       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2004                                      TheCall))
2005         return ExprError();
2006     }
2007   }
2008 
2009   return TheCallResult;
2010 }
2011 
2012 // Get the valid immediate range for the specified NEON type code.
2013 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2014   NeonTypeFlags Type(t);
2015   int IsQuad = ForceQuad ? true : Type.isQuad();
2016   switch (Type.getEltType()) {
2017   case NeonTypeFlags::Int8:
2018   case NeonTypeFlags::Poly8:
2019     return shift ? 7 : (8 << IsQuad) - 1;
2020   case NeonTypeFlags::Int16:
2021   case NeonTypeFlags::Poly16:
2022     return shift ? 15 : (4 << IsQuad) - 1;
2023   case NeonTypeFlags::Int32:
2024     return shift ? 31 : (2 << IsQuad) - 1;
2025   case NeonTypeFlags::Int64:
2026   case NeonTypeFlags::Poly64:
2027     return shift ? 63 : (1 << IsQuad) - 1;
2028   case NeonTypeFlags::Poly128:
2029     return shift ? 127 : (1 << IsQuad) - 1;
2030   case NeonTypeFlags::Float16:
2031     assert(!shift && "cannot shift float types!");
2032     return (4 << IsQuad) - 1;
2033   case NeonTypeFlags::Float32:
2034     assert(!shift && "cannot shift float types!");
2035     return (2 << IsQuad) - 1;
2036   case NeonTypeFlags::Float64:
2037     assert(!shift && "cannot shift float types!");
2038     return (1 << IsQuad) - 1;
2039   case NeonTypeFlags::BFloat16:
2040     assert(!shift && "cannot shift float types!");
2041     return (4 << IsQuad) - 1;
2042   }
2043   llvm_unreachable("Invalid NeonTypeFlag!");
2044 }
2045 
2046 /// getNeonEltType - Return the QualType corresponding to the elements of
2047 /// the vector type specified by the NeonTypeFlags.  This is used to check
2048 /// the pointer arguments for Neon load/store intrinsics.
2049 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2050                                bool IsPolyUnsigned, bool IsInt64Long) {
2051   switch (Flags.getEltType()) {
2052   case NeonTypeFlags::Int8:
2053     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2054   case NeonTypeFlags::Int16:
2055     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2056   case NeonTypeFlags::Int32:
2057     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2058   case NeonTypeFlags::Int64:
2059     if (IsInt64Long)
2060       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2061     else
2062       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2063                                 : Context.LongLongTy;
2064   case NeonTypeFlags::Poly8:
2065     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2066   case NeonTypeFlags::Poly16:
2067     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2068   case NeonTypeFlags::Poly64:
2069     if (IsInt64Long)
2070       return Context.UnsignedLongTy;
2071     else
2072       return Context.UnsignedLongLongTy;
2073   case NeonTypeFlags::Poly128:
2074     break;
2075   case NeonTypeFlags::Float16:
2076     return Context.HalfTy;
2077   case NeonTypeFlags::Float32:
2078     return Context.FloatTy;
2079   case NeonTypeFlags::Float64:
2080     return Context.DoubleTy;
2081   case NeonTypeFlags::BFloat16:
2082     return Context.BFloat16Ty;
2083   }
2084   llvm_unreachable("Invalid NeonTypeFlag!");
2085 }
2086 
2087 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2088   // Range check SVE intrinsics that take immediate values.
2089   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2090 
2091   switch (BuiltinID) {
2092   default:
2093     return false;
2094 #define GET_SVE_IMMEDIATE_CHECK
2095 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2096 #undef GET_SVE_IMMEDIATE_CHECK
2097   }
2098 
2099   // Perform all the immediate checks for this builtin call.
2100   bool HasError = false;
2101   for (auto &I : ImmChecks) {
2102     int ArgNum, CheckTy, ElementSizeInBits;
2103     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2104 
2105     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2106 
2107     // Function that checks whether the operand (ArgNum) is an immediate
2108     // that is one of the predefined values.
2109     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2110                                    int ErrDiag) -> bool {
2111       // We can't check the value of a dependent argument.
2112       Expr *Arg = TheCall->getArg(ArgNum);
2113       if (Arg->isTypeDependent() || Arg->isValueDependent())
2114         return false;
2115 
2116       // Check constant-ness first.
2117       llvm::APSInt Imm;
2118       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2119         return true;
2120 
2121       if (!CheckImm(Imm.getSExtValue()))
2122         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2123       return false;
2124     };
2125 
2126     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2127     case SVETypeFlags::ImmCheck0_31:
2128       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2129         HasError = true;
2130       break;
2131     case SVETypeFlags::ImmCheck0_13:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck1_16:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck0_7:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheckExtract:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2145                                       (2048 / ElementSizeInBits) - 1))
2146         HasError = true;
2147       break;
2148     case SVETypeFlags::ImmCheckShiftRight:
2149       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRightNarrow:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2154                                       ElementSizeInBits / 2))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheckShiftLeft:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2159                                       ElementSizeInBits - 1))
2160         HasError = true;
2161       break;
2162     case SVETypeFlags::ImmCheckLaneIndex:
2163       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2164                                       (128 / (1 * ElementSizeInBits)) - 1))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2169                                       (128 / (2 * ElementSizeInBits)) - 1))
2170         HasError = true;
2171       break;
2172     case SVETypeFlags::ImmCheckLaneIndexDot:
2173       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2174                                       (128 / (4 * ElementSizeInBits)) - 1))
2175         HasError = true;
2176       break;
2177     case SVETypeFlags::ImmCheckComplexRot90_270:
2178       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2179                               diag::err_rotation_argument_to_cadd))
2180         HasError = true;
2181       break;
2182     case SVETypeFlags::ImmCheckComplexRotAll90:
2183       if (CheckImmediateInSet(
2184               [](int64_t V) {
2185                 return V == 0 || V == 90 || V == 180 || V == 270;
2186               },
2187               diag::err_rotation_argument_to_cmla))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheck0_1:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_2:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_3:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2200         HasError = true;
2201       break;
2202     }
2203   }
2204 
2205   return HasError;
2206 }
2207 
2208 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2209                                         unsigned BuiltinID, CallExpr *TheCall) {
2210   llvm::APSInt Result;
2211   uint64_t mask = 0;
2212   unsigned TV = 0;
2213   int PtrArgNum = -1;
2214   bool HasConstPtr = false;
2215   switch (BuiltinID) {
2216 #define GET_NEON_OVERLOAD_CHECK
2217 #include "clang/Basic/arm_neon.inc"
2218 #include "clang/Basic/arm_fp16.inc"
2219 #undef GET_NEON_OVERLOAD_CHECK
2220   }
2221 
2222   // For NEON intrinsics which are overloaded on vector element type, validate
2223   // the immediate which specifies which variant to emit.
2224   unsigned ImmArg = TheCall->getNumArgs()-1;
2225   if (mask) {
2226     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2227       return true;
2228 
2229     TV = Result.getLimitedValue(64);
2230     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2231       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2232              << TheCall->getArg(ImmArg)->getSourceRange();
2233   }
2234 
2235   if (PtrArgNum >= 0) {
2236     // Check that pointer arguments have the specified type.
2237     Expr *Arg = TheCall->getArg(PtrArgNum);
2238     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2239       Arg = ICE->getSubExpr();
2240     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2241     QualType RHSTy = RHS.get()->getType();
2242 
2243     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2244     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2245                           Arch == llvm::Triple::aarch64_32 ||
2246                           Arch == llvm::Triple::aarch64_be;
2247     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2248     QualType EltTy =
2249         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2250     if (HasConstPtr)
2251       EltTy = EltTy.withConst();
2252     QualType LHSTy = Context.getPointerType(EltTy);
2253     AssignConvertType ConvTy;
2254     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2255     if (RHS.isInvalid())
2256       return true;
2257     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2258                                  RHS.get(), AA_Assigning))
2259       return true;
2260   }
2261 
2262   // For NEON intrinsics which take an immediate value as part of the
2263   // instruction, range check them here.
2264   unsigned i = 0, l = 0, u = 0;
2265   switch (BuiltinID) {
2266   default:
2267     return false;
2268   #define GET_NEON_IMMEDIATE_CHECK
2269   #include "clang/Basic/arm_neon.inc"
2270   #include "clang/Basic/arm_fp16.inc"
2271   #undef GET_NEON_IMMEDIATE_CHECK
2272   }
2273 
2274   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2275 }
2276 
2277 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2278   switch (BuiltinID) {
2279   default:
2280     return false;
2281   #include "clang/Basic/arm_mve_builtin_sema.inc"
2282   }
2283 }
2284 
2285 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2286                                        CallExpr *TheCall) {
2287   bool Err = false;
2288   switch (BuiltinID) {
2289   default:
2290     return false;
2291 #include "clang/Basic/arm_cde_builtin_sema.inc"
2292   }
2293 
2294   if (Err)
2295     return true;
2296 
2297   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2298 }
2299 
2300 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2301                                         const Expr *CoprocArg, bool WantCDE) {
2302   if (isConstantEvaluated())
2303     return false;
2304 
2305   // We can't check the value of a dependent argument.
2306   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2307     return false;
2308 
2309   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2310   int64_t CoprocNo = CoprocNoAP.getExtValue();
2311   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2312 
2313   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2314   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2315 
2316   if (IsCDECoproc != WantCDE)
2317     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2318            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2319 
2320   return false;
2321 }
2322 
2323 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2324                                         unsigned MaxWidth) {
2325   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2326           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2327           BuiltinID == ARM::BI__builtin_arm_strex ||
2328           BuiltinID == ARM::BI__builtin_arm_stlex ||
2329           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2330           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2331           BuiltinID == AArch64::BI__builtin_arm_strex ||
2332           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2333          "unexpected ARM builtin");
2334   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2335                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2336                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2337                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2338 
2339   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2340 
2341   // Ensure that we have the proper number of arguments.
2342   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2343     return true;
2344 
2345   // Inspect the pointer argument of the atomic builtin.  This should always be
2346   // a pointer type, whose element is an integral scalar or pointer type.
2347   // Because it is a pointer type, we don't have to worry about any implicit
2348   // casts here.
2349   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2350   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2351   if (PointerArgRes.isInvalid())
2352     return true;
2353   PointerArg = PointerArgRes.get();
2354 
2355   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2356   if (!pointerType) {
2357     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2358         << PointerArg->getType() << PointerArg->getSourceRange();
2359     return true;
2360   }
2361 
2362   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2363   // task is to insert the appropriate casts into the AST. First work out just
2364   // what the appropriate type is.
2365   QualType ValType = pointerType->getPointeeType();
2366   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2367   if (IsLdrex)
2368     AddrType.addConst();
2369 
2370   // Issue a warning if the cast is dodgy.
2371   CastKind CastNeeded = CK_NoOp;
2372   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2373     CastNeeded = CK_BitCast;
2374     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2375         << PointerArg->getType() << Context.getPointerType(AddrType)
2376         << AA_Passing << PointerArg->getSourceRange();
2377   }
2378 
2379   // Finally, do the cast and replace the argument with the corrected version.
2380   AddrType = Context.getPointerType(AddrType);
2381   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2382   if (PointerArgRes.isInvalid())
2383     return true;
2384   PointerArg = PointerArgRes.get();
2385 
2386   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2387 
2388   // In general, we allow ints, floats and pointers to be loaded and stored.
2389   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2390       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2391     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2392         << PointerArg->getType() << PointerArg->getSourceRange();
2393     return true;
2394   }
2395 
2396   // But ARM doesn't have instructions to deal with 128-bit versions.
2397   if (Context.getTypeSize(ValType) > MaxWidth) {
2398     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2399     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2400         << PointerArg->getType() << PointerArg->getSourceRange();
2401     return true;
2402   }
2403 
2404   switch (ValType.getObjCLifetime()) {
2405   case Qualifiers::OCL_None:
2406   case Qualifiers::OCL_ExplicitNone:
2407     // okay
2408     break;
2409 
2410   case Qualifiers::OCL_Weak:
2411   case Qualifiers::OCL_Strong:
2412   case Qualifiers::OCL_Autoreleasing:
2413     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2414         << ValType << PointerArg->getSourceRange();
2415     return true;
2416   }
2417 
2418   if (IsLdrex) {
2419     TheCall->setType(ValType);
2420     return false;
2421   }
2422 
2423   // Initialize the argument to be stored.
2424   ExprResult ValArg = TheCall->getArg(0);
2425   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2426       Context, ValType, /*consume*/ false);
2427   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2428   if (ValArg.isInvalid())
2429     return true;
2430   TheCall->setArg(0, ValArg.get());
2431 
2432   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2433   // but the custom checker bypasses all default analysis.
2434   TheCall->setType(Context.IntTy);
2435   return false;
2436 }
2437 
2438 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2439                                        CallExpr *TheCall) {
2440   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2441       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2442       BuiltinID == ARM::BI__builtin_arm_strex ||
2443       BuiltinID == ARM::BI__builtin_arm_stlex) {
2444     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2445   }
2446 
2447   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2448     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2449       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2450   }
2451 
2452   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2453       BuiltinID == ARM::BI__builtin_arm_wsr64)
2454     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2457       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2458       BuiltinID == ARM::BI__builtin_arm_wsr ||
2459       BuiltinID == ARM::BI__builtin_arm_wsrp)
2460     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2461 
2462   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2463     return true;
2464   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2465     return true;
2466   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468 
2469   // For intrinsics which take an immediate value as part of the instruction,
2470   // range check them here.
2471   // FIXME: VFP Intrinsics should error if VFP not present.
2472   switch (BuiltinID) {
2473   default: return false;
2474   case ARM::BI__builtin_arm_ssat:
2475     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2476   case ARM::BI__builtin_arm_usat:
2477     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2478   case ARM::BI__builtin_arm_ssat16:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2480   case ARM::BI__builtin_arm_usat16:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2482   case ARM::BI__builtin_arm_vcvtr_f:
2483   case ARM::BI__builtin_arm_vcvtr_d:
2484     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2485   case ARM::BI__builtin_arm_dmb:
2486   case ARM::BI__builtin_arm_dsb:
2487   case ARM::BI__builtin_arm_isb:
2488   case ARM::BI__builtin_arm_dbg:
2489     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2490   case ARM::BI__builtin_arm_cdp:
2491   case ARM::BI__builtin_arm_cdp2:
2492   case ARM::BI__builtin_arm_mcr:
2493   case ARM::BI__builtin_arm_mcr2:
2494   case ARM::BI__builtin_arm_mrc:
2495   case ARM::BI__builtin_arm_mrc2:
2496   case ARM::BI__builtin_arm_mcrr:
2497   case ARM::BI__builtin_arm_mcrr2:
2498   case ARM::BI__builtin_arm_mrrc:
2499   case ARM::BI__builtin_arm_mrrc2:
2500   case ARM::BI__builtin_arm_ldc:
2501   case ARM::BI__builtin_arm_ldcl:
2502   case ARM::BI__builtin_arm_ldc2:
2503   case ARM::BI__builtin_arm_ldc2l:
2504   case ARM::BI__builtin_arm_stc:
2505   case ARM::BI__builtin_arm_stcl:
2506   case ARM::BI__builtin_arm_stc2:
2507   case ARM::BI__builtin_arm_stc2l:
2508     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2509            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2510                                         /*WantCDE*/ false);
2511   }
2512 }
2513 
2514 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2515                                            unsigned BuiltinID,
2516                                            CallExpr *TheCall) {
2517   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2518       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2519       BuiltinID == AArch64::BI__builtin_arm_strex ||
2520       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2521     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2522   }
2523 
2524   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2525     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2526       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2527       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2528       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2529   }
2530 
2531   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2532       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2533     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2534 
2535   // Memory Tagging Extensions (MTE) Intrinsics
2536   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2537       BuiltinID == AArch64::BI__builtin_arm_addg ||
2538       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2539       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2540       BuiltinID == AArch64::BI__builtin_arm_stg ||
2541       BuiltinID == AArch64::BI__builtin_arm_subp) {
2542     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2543   }
2544 
2545   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2546       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2547       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2548       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2549     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2550 
2551   // Only check the valid encoding range. Any constant in this range would be
2552   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2553   // an exception for incorrect registers. This matches MSVC behavior.
2554   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2555       BuiltinID == AArch64::BI_WriteStatusReg)
2556     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2557 
2558   if (BuiltinID == AArch64::BI__getReg)
2559     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2560 
2561   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2562     return true;
2563 
2564   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2565     return true;
2566 
2567   // For intrinsics which take an immediate value as part of the instruction,
2568   // range check them here.
2569   unsigned i = 0, l = 0, u = 0;
2570   switch (BuiltinID) {
2571   default: return false;
2572   case AArch64::BI__builtin_arm_dmb:
2573   case AArch64::BI__builtin_arm_dsb:
2574   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2575   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2576   }
2577 
2578   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2579 }
2580 
2581 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2582   if (Arg->getType()->getAsPlaceholderType())
2583     return false;
2584 
2585   // The first argument needs to be a record field access.
2586   // If it is an array element access, we delay decision
2587   // to BPF backend to check whether the access is a
2588   // field access or not.
2589   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2590           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2591           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2592 }
2593 
2594 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2595                             QualType VectorTy, QualType EltTy) {
2596   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2597   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2598     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2599         << Call->getSourceRange() << VectorEltTy << EltTy;
2600     return false;
2601   }
2602   return true;
2603 }
2604 
2605 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2606   QualType ArgType = Arg->getType();
2607   if (ArgType->getAsPlaceholderType())
2608     return false;
2609 
2610   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2611   // format:
2612   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2613   //   2. <type> var;
2614   //      __builtin_preserve_type_info(var, flag);
2615   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2616       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2617     return false;
2618 
2619   // Typedef type.
2620   if (ArgType->getAs<TypedefType>())
2621     return true;
2622 
2623   // Record type or Enum type.
2624   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2625   if (const auto *RT = Ty->getAs<RecordType>()) {
2626     if (!RT->getDecl()->getDeclName().isEmpty())
2627       return true;
2628   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2629     if (!ET->getDecl()->getDeclName().isEmpty())
2630       return true;
2631   }
2632 
2633   return false;
2634 }
2635 
2636 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2637   QualType ArgType = Arg->getType();
2638   if (ArgType->getAsPlaceholderType())
2639     return false;
2640 
2641   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2642   // format:
2643   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2644   //                                 flag);
2645   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2646   if (!UO)
2647     return false;
2648 
2649   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2650   if (!CE)
2651     return false;
2652   if (CE->getCastKind() != CK_IntegralToPointer &&
2653       CE->getCastKind() != CK_NullToPointer)
2654     return false;
2655 
2656   // The integer must be from an EnumConstantDecl.
2657   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2658   if (!DR)
2659     return false;
2660 
2661   const EnumConstantDecl *Enumerator =
2662       dyn_cast<EnumConstantDecl>(DR->getDecl());
2663   if (!Enumerator)
2664     return false;
2665 
2666   // The type must be EnumType.
2667   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2668   const auto *ET = Ty->getAs<EnumType>();
2669   if (!ET)
2670     return false;
2671 
2672   // The enum value must be supported.
2673   for (auto *EDI : ET->getDecl()->enumerators()) {
2674     if (EDI == Enumerator)
2675       return true;
2676   }
2677 
2678   return false;
2679 }
2680 
2681 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2682                                        CallExpr *TheCall) {
2683   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2684           BuiltinID == BPF::BI__builtin_btf_type_id ||
2685           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2686           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2687          "unexpected BPF builtin");
2688 
2689   if (checkArgCount(*this, TheCall, 2))
2690     return true;
2691 
2692   // The second argument needs to be a constant int
2693   Expr *Arg = TheCall->getArg(1);
2694   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2695   diag::kind kind;
2696   if (!Value) {
2697     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2698       kind = diag::err_preserve_field_info_not_const;
2699     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2700       kind = diag::err_btf_type_id_not_const;
2701     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2702       kind = diag::err_preserve_type_info_not_const;
2703     else
2704       kind = diag::err_preserve_enum_value_not_const;
2705     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2706     return true;
2707   }
2708 
2709   // The first argument
2710   Arg = TheCall->getArg(0);
2711   bool InvalidArg = false;
2712   bool ReturnUnsignedInt = true;
2713   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2714     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2715       InvalidArg = true;
2716       kind = diag::err_preserve_field_info_not_field;
2717     }
2718   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2719     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2720       InvalidArg = true;
2721       kind = diag::err_preserve_type_info_invalid;
2722     }
2723   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2724     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2725       InvalidArg = true;
2726       kind = diag::err_preserve_enum_value_invalid;
2727     }
2728     ReturnUnsignedInt = false;
2729   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2730     ReturnUnsignedInt = false;
2731   }
2732 
2733   if (InvalidArg) {
2734     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2735     return true;
2736   }
2737 
2738   if (ReturnUnsignedInt)
2739     TheCall->setType(Context.UnsignedIntTy);
2740   else
2741     TheCall->setType(Context.UnsignedLongTy);
2742   return false;
2743 }
2744 
2745 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2746   struct ArgInfo {
2747     uint8_t OpNum;
2748     bool IsSigned;
2749     uint8_t BitWidth;
2750     uint8_t Align;
2751   };
2752   struct BuiltinInfo {
2753     unsigned BuiltinID;
2754     ArgInfo Infos[2];
2755   };
2756 
2757   static BuiltinInfo Infos[] = {
2758     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2759     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2760     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2761     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2762     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2763     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2764     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2765     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2766     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2767     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2768     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2769 
2770     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2773     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2781 
2782     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2834                                                       {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2842                                                       {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2849                                                        { 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2851                                                        { 2, false, 6,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2853                                                        { 3, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2855                                                        { 3, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2872                                                       {{ 2, false, 4,  0 },
2873                                                        { 3, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2875                                                       {{ 2, false, 4,  0 },
2876                                                        { 3, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2878                                                       {{ 2, false, 4,  0 },
2879                                                        { 3, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2881                                                       {{ 2, false, 4,  0 },
2882                                                        { 3, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2894                                                        { 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2896                                                        { 2, false, 6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2906                                                       {{ 1, false, 4,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2909                                                       {{ 1, false, 4,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2930                                                       {{ 3, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2935                                                       {{ 3, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2940                                                       {{ 3, false, 1,  0 }} },
2941   };
2942 
2943   // Use a dynamically initialized static to sort the table exactly once on
2944   // first run.
2945   static const bool SortOnce =
2946       (llvm::sort(Infos,
2947                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2948                    return LHS.BuiltinID < RHS.BuiltinID;
2949                  }),
2950        true);
2951   (void)SortOnce;
2952 
2953   const BuiltinInfo *F = llvm::partition_point(
2954       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2955   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2956     return false;
2957 
2958   bool Error = false;
2959 
2960   for (const ArgInfo &A : F->Infos) {
2961     // Ignore empty ArgInfo elements.
2962     if (A.BitWidth == 0)
2963       continue;
2964 
2965     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2966     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2967     if (!A.Align) {
2968       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2969     } else {
2970       unsigned M = 1 << A.Align;
2971       Min *= M;
2972       Max *= M;
2973       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2974                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2975     }
2976   }
2977   return Error;
2978 }
2979 
2980 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2981                                            CallExpr *TheCall) {
2982   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2983 }
2984 
2985 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2986                                         unsigned BuiltinID, CallExpr *TheCall) {
2987   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2988          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2989 }
2990 
2991 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2992                                CallExpr *TheCall) {
2993 
2994   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2995       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2996     if (!TI.hasFeature("dsp"))
2997       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2998   }
2999 
3000   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3001       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3002     if (!TI.hasFeature("dspr2"))
3003       return Diag(TheCall->getBeginLoc(),
3004                   diag::err_mips_builtin_requires_dspr2);
3005   }
3006 
3007   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3008       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3009     if (!TI.hasFeature("msa"))
3010       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3011   }
3012 
3013   return false;
3014 }
3015 
3016 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3017 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3018 // ordering for DSP is unspecified. MSA is ordered by the data format used
3019 // by the underlying instruction i.e., df/m, df/n and then by size.
3020 //
3021 // FIXME: The size tests here should instead be tablegen'd along with the
3022 //        definitions from include/clang/Basic/BuiltinsMips.def.
3023 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3024 //        be too.
3025 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3026   unsigned i = 0, l = 0, u = 0, m = 0;
3027   switch (BuiltinID) {
3028   default: return false;
3029   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3030   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3031   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3032   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3033   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3034   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3035   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3036   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3037   // df/m field.
3038   // These intrinsics take an unsigned 3 bit immediate.
3039   case Mips::BI__builtin_msa_bclri_b:
3040   case Mips::BI__builtin_msa_bnegi_b:
3041   case Mips::BI__builtin_msa_bseti_b:
3042   case Mips::BI__builtin_msa_sat_s_b:
3043   case Mips::BI__builtin_msa_sat_u_b:
3044   case Mips::BI__builtin_msa_slli_b:
3045   case Mips::BI__builtin_msa_srai_b:
3046   case Mips::BI__builtin_msa_srari_b:
3047   case Mips::BI__builtin_msa_srli_b:
3048   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3049   case Mips::BI__builtin_msa_binsli_b:
3050   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3051   // These intrinsics take an unsigned 4 bit immediate.
3052   case Mips::BI__builtin_msa_bclri_h:
3053   case Mips::BI__builtin_msa_bnegi_h:
3054   case Mips::BI__builtin_msa_bseti_h:
3055   case Mips::BI__builtin_msa_sat_s_h:
3056   case Mips::BI__builtin_msa_sat_u_h:
3057   case Mips::BI__builtin_msa_slli_h:
3058   case Mips::BI__builtin_msa_srai_h:
3059   case Mips::BI__builtin_msa_srari_h:
3060   case Mips::BI__builtin_msa_srli_h:
3061   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3062   case Mips::BI__builtin_msa_binsli_h:
3063   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3064   // These intrinsics take an unsigned 5 bit immediate.
3065   // The first block of intrinsics actually have an unsigned 5 bit field,
3066   // not a df/n field.
3067   case Mips::BI__builtin_msa_cfcmsa:
3068   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3069   case Mips::BI__builtin_msa_clei_u_b:
3070   case Mips::BI__builtin_msa_clei_u_h:
3071   case Mips::BI__builtin_msa_clei_u_w:
3072   case Mips::BI__builtin_msa_clei_u_d:
3073   case Mips::BI__builtin_msa_clti_u_b:
3074   case Mips::BI__builtin_msa_clti_u_h:
3075   case Mips::BI__builtin_msa_clti_u_w:
3076   case Mips::BI__builtin_msa_clti_u_d:
3077   case Mips::BI__builtin_msa_maxi_u_b:
3078   case Mips::BI__builtin_msa_maxi_u_h:
3079   case Mips::BI__builtin_msa_maxi_u_w:
3080   case Mips::BI__builtin_msa_maxi_u_d:
3081   case Mips::BI__builtin_msa_mini_u_b:
3082   case Mips::BI__builtin_msa_mini_u_h:
3083   case Mips::BI__builtin_msa_mini_u_w:
3084   case Mips::BI__builtin_msa_mini_u_d:
3085   case Mips::BI__builtin_msa_addvi_b:
3086   case Mips::BI__builtin_msa_addvi_h:
3087   case Mips::BI__builtin_msa_addvi_w:
3088   case Mips::BI__builtin_msa_addvi_d:
3089   case Mips::BI__builtin_msa_bclri_w:
3090   case Mips::BI__builtin_msa_bnegi_w:
3091   case Mips::BI__builtin_msa_bseti_w:
3092   case Mips::BI__builtin_msa_sat_s_w:
3093   case Mips::BI__builtin_msa_sat_u_w:
3094   case Mips::BI__builtin_msa_slli_w:
3095   case Mips::BI__builtin_msa_srai_w:
3096   case Mips::BI__builtin_msa_srari_w:
3097   case Mips::BI__builtin_msa_srli_w:
3098   case Mips::BI__builtin_msa_srlri_w:
3099   case Mips::BI__builtin_msa_subvi_b:
3100   case Mips::BI__builtin_msa_subvi_h:
3101   case Mips::BI__builtin_msa_subvi_w:
3102   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3103   case Mips::BI__builtin_msa_binsli_w:
3104   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3105   // These intrinsics take an unsigned 6 bit immediate.
3106   case Mips::BI__builtin_msa_bclri_d:
3107   case Mips::BI__builtin_msa_bnegi_d:
3108   case Mips::BI__builtin_msa_bseti_d:
3109   case Mips::BI__builtin_msa_sat_s_d:
3110   case Mips::BI__builtin_msa_sat_u_d:
3111   case Mips::BI__builtin_msa_slli_d:
3112   case Mips::BI__builtin_msa_srai_d:
3113   case Mips::BI__builtin_msa_srari_d:
3114   case Mips::BI__builtin_msa_srli_d:
3115   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3116   case Mips::BI__builtin_msa_binsli_d:
3117   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3118   // These intrinsics take a signed 5 bit immediate.
3119   case Mips::BI__builtin_msa_ceqi_b:
3120   case Mips::BI__builtin_msa_ceqi_h:
3121   case Mips::BI__builtin_msa_ceqi_w:
3122   case Mips::BI__builtin_msa_ceqi_d:
3123   case Mips::BI__builtin_msa_clti_s_b:
3124   case Mips::BI__builtin_msa_clti_s_h:
3125   case Mips::BI__builtin_msa_clti_s_w:
3126   case Mips::BI__builtin_msa_clti_s_d:
3127   case Mips::BI__builtin_msa_clei_s_b:
3128   case Mips::BI__builtin_msa_clei_s_h:
3129   case Mips::BI__builtin_msa_clei_s_w:
3130   case Mips::BI__builtin_msa_clei_s_d:
3131   case Mips::BI__builtin_msa_maxi_s_b:
3132   case Mips::BI__builtin_msa_maxi_s_h:
3133   case Mips::BI__builtin_msa_maxi_s_w:
3134   case Mips::BI__builtin_msa_maxi_s_d:
3135   case Mips::BI__builtin_msa_mini_s_b:
3136   case Mips::BI__builtin_msa_mini_s_h:
3137   case Mips::BI__builtin_msa_mini_s_w:
3138   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3139   // These intrinsics take an unsigned 8 bit immediate.
3140   case Mips::BI__builtin_msa_andi_b:
3141   case Mips::BI__builtin_msa_nori_b:
3142   case Mips::BI__builtin_msa_ori_b:
3143   case Mips::BI__builtin_msa_shf_b:
3144   case Mips::BI__builtin_msa_shf_h:
3145   case Mips::BI__builtin_msa_shf_w:
3146   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3147   case Mips::BI__builtin_msa_bseli_b:
3148   case Mips::BI__builtin_msa_bmnzi_b:
3149   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3150   // df/n format
3151   // These intrinsics take an unsigned 4 bit immediate.
3152   case Mips::BI__builtin_msa_copy_s_b:
3153   case Mips::BI__builtin_msa_copy_u_b:
3154   case Mips::BI__builtin_msa_insve_b:
3155   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3156   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3157   // These intrinsics take an unsigned 3 bit immediate.
3158   case Mips::BI__builtin_msa_copy_s_h:
3159   case Mips::BI__builtin_msa_copy_u_h:
3160   case Mips::BI__builtin_msa_insve_h:
3161   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3162   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3163   // These intrinsics take an unsigned 2 bit immediate.
3164   case Mips::BI__builtin_msa_copy_s_w:
3165   case Mips::BI__builtin_msa_copy_u_w:
3166   case Mips::BI__builtin_msa_insve_w:
3167   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3168   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3169   // These intrinsics take an unsigned 1 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_d:
3171   case Mips::BI__builtin_msa_copy_u_d:
3172   case Mips::BI__builtin_msa_insve_d:
3173   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3174   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3175   // Memory offsets and immediate loads.
3176   // These intrinsics take a signed 10 bit immediate.
3177   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3178   case Mips::BI__builtin_msa_ldi_h:
3179   case Mips::BI__builtin_msa_ldi_w:
3180   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3181   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3182   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3183   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3184   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3185   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3186   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3187   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3188   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3189   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3190   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3191   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3192   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3193   }
3194 
3195   if (!m)
3196     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3197 
3198   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3199          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3200 }
3201 
3202 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3203 /// advancing the pointer over the consumed characters. The decoded type is
3204 /// returned. If the decoded type represents a constant integer with a
3205 /// constraint on its value then Mask is set to that value. The type descriptors
3206 /// used in Str are specific to PPC MMA builtins and are documented in the file
3207 /// defining the PPC builtins.
3208 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3209                                         unsigned &Mask) {
3210   bool RequireICE = false;
3211   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3212   switch (*Str++) {
3213   case 'V':
3214     return Context.getVectorType(Context.UnsignedCharTy, 16,
3215                                  VectorType::VectorKind::AltiVecVector);
3216   case 'i': {
3217     char *End;
3218     unsigned size = strtoul(Str, &End, 10);
3219     assert(End != Str && "Missing constant parameter constraint");
3220     Str = End;
3221     Mask = size;
3222     return Context.IntTy;
3223   }
3224   case 'W': {
3225     char *End;
3226     unsigned size = strtoul(Str, &End, 10);
3227     assert(End != Str && "Missing PowerPC MMA type size");
3228     Str = End;
3229     QualType Type;
3230     switch (size) {
3231   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3232     case size: Type = Context.Id##Ty; break;
3233   #include "clang/Basic/PPCTypes.def"
3234     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3235     }
3236     bool CheckVectorArgs = false;
3237     while (!CheckVectorArgs) {
3238       switch (*Str++) {
3239       case '*':
3240         Type = Context.getPointerType(Type);
3241         break;
3242       case 'C':
3243         Type = Type.withConst();
3244         break;
3245       default:
3246         CheckVectorArgs = true;
3247         --Str;
3248         break;
3249       }
3250     }
3251     return Type;
3252   }
3253   default:
3254     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3255   }
3256 }
3257 
3258 static bool isPPC_64Builtin(unsigned BuiltinID) {
3259   // These builtins only work on PPC 64bit targets.
3260   switch (BuiltinID) {
3261   case PPC::BI__builtin_divde:
3262   case PPC::BI__builtin_divdeu:
3263   case PPC::BI__builtin_bpermd:
3264     return true;
3265   }
3266   return false;
3267 }
3268 
3269 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3270                              StringRef FeatureToCheck, unsigned DiagID) {
3271   if (!S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3272     return S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3273   return false;
3274 }
3275 
3276 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3277                                        CallExpr *TheCall) {
3278   unsigned i = 0, l = 0, u = 0;
3279   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3280 
3281   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3282     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3283            << TheCall->getSourceRange();
3284 
3285   switch (BuiltinID) {
3286   default: return false;
3287   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3288   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3289     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3290            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3291   case PPC::BI__builtin_altivec_dss:
3292     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3293   case PPC::BI__builtin_tbegin:
3294   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3295   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3296   case PPC::BI__builtin_tabortwc:
3297   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3298   case PPC::BI__builtin_tabortwci:
3299   case PPC::BI__builtin_tabortdci:
3300     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3301            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3302   case PPC::BI__builtin_altivec_dst:
3303   case PPC::BI__builtin_altivec_dstt:
3304   case PPC::BI__builtin_altivec_dstst:
3305   case PPC::BI__builtin_altivec_dststt:
3306     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3307   case PPC::BI__builtin_vsx_xxpermdi:
3308   case PPC::BI__builtin_vsx_xxsldwi:
3309     return SemaBuiltinVSX(TheCall);
3310   case PPC::BI__builtin_divwe:
3311   case PPC::BI__builtin_divweu:
3312   case PPC::BI__builtin_divde:
3313   case PPC::BI__builtin_divdeu:
3314     return SemaFeatureCheck(*this, TheCall, "extdiv",
3315                             diag::err_ppc_builtin_only_on_pwr7);
3316   case PPC::BI__builtin_bpermd:
3317     return SemaFeatureCheck(*this, TheCall, "bpermd",
3318                             diag::err_ppc_builtin_only_on_pwr7);
3319   case PPC::BI__builtin_unpack_vector_int128:
3320     return SemaFeatureCheck(*this, TheCall, "vsx",
3321                             diag::err_ppc_builtin_only_on_pwr7) ||
3322            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3323   case PPC::BI__builtin_pack_vector_int128:
3324     return SemaFeatureCheck(*this, TheCall, "vsx",
3325                             diag::err_ppc_builtin_only_on_pwr7);
3326   case PPC::BI__builtin_altivec_vgnb:
3327      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3328   case PPC::BI__builtin_altivec_vec_replace_elt:
3329   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3330     QualType VecTy = TheCall->getArg(0)->getType();
3331     QualType EltTy = TheCall->getArg(1)->getType();
3332     unsigned Width = Context.getIntWidth(EltTy);
3333     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3334            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3335   }
3336   case PPC::BI__builtin_vsx_xxeval:
3337      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3338   case PPC::BI__builtin_altivec_vsldbi:
3339      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3340   case PPC::BI__builtin_altivec_vsrdbi:
3341      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3342   case PPC::BI__builtin_vsx_xxpermx:
3343      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3344 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3345   case PPC::BI__builtin_##Name: \
3346     return SemaBuiltinPPCMMACall(TheCall, Types);
3347 #include "clang/Basic/BuiltinsPPC.def"
3348   }
3349   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3350 }
3351 
3352 // Check if the given type is a non-pointer PPC MMA type. This function is used
3353 // in Sema to prevent invalid uses of restricted PPC MMA types.
3354 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3355   if (Type->isPointerType() || Type->isArrayType())
3356     return false;
3357 
3358   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3359 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3360   if (false
3361 #include "clang/Basic/PPCTypes.def"
3362      ) {
3363     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3364     return true;
3365   }
3366   return false;
3367 }
3368 
3369 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3370                                           CallExpr *TheCall) {
3371   // position of memory order and scope arguments in the builtin
3372   unsigned OrderIndex, ScopeIndex;
3373   switch (BuiltinID) {
3374   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3375   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3376   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3377   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3378     OrderIndex = 2;
3379     ScopeIndex = 3;
3380     break;
3381   case AMDGPU::BI__builtin_amdgcn_fence:
3382     OrderIndex = 0;
3383     ScopeIndex = 1;
3384     break;
3385   default:
3386     return false;
3387   }
3388 
3389   ExprResult Arg = TheCall->getArg(OrderIndex);
3390   auto ArgExpr = Arg.get();
3391   Expr::EvalResult ArgResult;
3392 
3393   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3394     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3395            << ArgExpr->getType();
3396   auto Ord = ArgResult.Val.getInt().getZExtValue();
3397 
3398   // Check valididty of memory ordering as per C11 / C++11's memody model.
3399   // Only fence needs check. Atomic dec/inc allow all memory orders.
3400   if (!llvm::isValidAtomicOrderingCABI(Ord))
3401     return Diag(ArgExpr->getBeginLoc(),
3402                 diag::warn_atomic_op_has_invalid_memory_order)
3403            << ArgExpr->getSourceRange();
3404   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3405   case llvm::AtomicOrderingCABI::relaxed:
3406   case llvm::AtomicOrderingCABI::consume:
3407     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3408       return Diag(ArgExpr->getBeginLoc(),
3409                   diag::warn_atomic_op_has_invalid_memory_order)
3410              << ArgExpr->getSourceRange();
3411     break;
3412   case llvm::AtomicOrderingCABI::acquire:
3413   case llvm::AtomicOrderingCABI::release:
3414   case llvm::AtomicOrderingCABI::acq_rel:
3415   case llvm::AtomicOrderingCABI::seq_cst:
3416     break;
3417   }
3418 
3419   Arg = TheCall->getArg(ScopeIndex);
3420   ArgExpr = Arg.get();
3421   Expr::EvalResult ArgResult1;
3422   // Check that sync scope is a constant literal
3423   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3424     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3425            << ArgExpr->getType();
3426 
3427   return false;
3428 }
3429 
3430 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3431   llvm::APSInt Result;
3432 
3433   // We can't check the value of a dependent argument.
3434   Expr *Arg = TheCall->getArg(ArgNum);
3435   if (Arg->isTypeDependent() || Arg->isValueDependent())
3436     return false;
3437 
3438   // Check constant-ness first.
3439   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3440     return true;
3441 
3442   int64_t Val = Result.getSExtValue();
3443   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3444     return false;
3445 
3446   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3447          << Arg->getSourceRange();
3448 }
3449 
3450 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3451                                          unsigned BuiltinID,
3452                                          CallExpr *TheCall) {
3453   // CodeGenFunction can also detect this, but this gives a better error
3454   // message.
3455   bool FeatureMissing = false;
3456   SmallVector<StringRef> ReqFeatures;
3457   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3458   Features.split(ReqFeatures, ',');
3459 
3460   // Check if each required feature is included
3461   for (StringRef F : ReqFeatures) {
3462     if (TI.hasFeature(F))
3463       continue;
3464 
3465     // If the feature is 64bit, alter the string so it will print better in
3466     // the diagnostic.
3467     if (F == "64bit")
3468       F = "RV64";
3469 
3470     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3471     F.consume_front("experimental-");
3472     std::string FeatureStr = F.str();
3473     FeatureStr[0] = std::toupper(FeatureStr[0]);
3474 
3475     // Error message
3476     FeatureMissing = true;
3477     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3478         << TheCall->getSourceRange() << StringRef(FeatureStr);
3479   }
3480 
3481   if (FeatureMissing)
3482     return true;
3483 
3484   switch (BuiltinID) {
3485   case RISCV::BI__builtin_rvv_vsetvli:
3486     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3487            CheckRISCVLMUL(TheCall, 2);
3488   case RISCV::BI__builtin_rvv_vsetvlimax:
3489     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3490            CheckRISCVLMUL(TheCall, 1);
3491   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3492   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3493   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3494   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3495   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3496   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3497   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3498   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3499   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3500   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3501   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3502   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3503   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3504   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3505   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3506   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3507   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3508   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3509   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3510   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3511   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3512   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3513   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3514   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3515   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3516   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3517   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3518   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3519   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3520   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3521     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3522   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3523   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3524   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3525   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3526   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3527   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3528   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3529   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3530   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3531   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3532   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3533   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3534   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3535   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3536   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3537   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3538   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3539   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3540   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3541   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3542     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3543   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3544   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3545   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3546   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3547   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3548   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3549   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3550   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3551   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3552   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3553     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3554   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3555   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3556   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3557   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3558   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3559   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3560   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3561   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3562   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3563   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3564   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3565   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3566   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3567   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3568   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3569   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3570   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3571   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3572   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3573   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3574   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3575   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3576   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3577   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3578   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3579   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3580   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3581   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3582   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3583   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3584     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3585   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3586   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3587   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3588   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3589   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3590   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3591   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3592   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3593   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3594   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3595   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3596   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3597   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3598   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3599   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3600   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3601   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3602   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3603   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3604   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3605     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3606   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3607   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3608   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3609   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3610   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3611   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3612   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3613   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3614   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3615   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3616     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3617   }
3618 
3619   return false;
3620 }
3621 
3622 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3623                                            CallExpr *TheCall) {
3624   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3625     Expr *Arg = TheCall->getArg(0);
3626     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3627       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3628         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3629                << Arg->getSourceRange();
3630   }
3631 
3632   // For intrinsics which take an immediate value as part of the instruction,
3633   // range check them here.
3634   unsigned i = 0, l = 0, u = 0;
3635   switch (BuiltinID) {
3636   default: return false;
3637   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3638   case SystemZ::BI__builtin_s390_verimb:
3639   case SystemZ::BI__builtin_s390_verimh:
3640   case SystemZ::BI__builtin_s390_verimf:
3641   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3642   case SystemZ::BI__builtin_s390_vfaeb:
3643   case SystemZ::BI__builtin_s390_vfaeh:
3644   case SystemZ::BI__builtin_s390_vfaef:
3645   case SystemZ::BI__builtin_s390_vfaebs:
3646   case SystemZ::BI__builtin_s390_vfaehs:
3647   case SystemZ::BI__builtin_s390_vfaefs:
3648   case SystemZ::BI__builtin_s390_vfaezb:
3649   case SystemZ::BI__builtin_s390_vfaezh:
3650   case SystemZ::BI__builtin_s390_vfaezf:
3651   case SystemZ::BI__builtin_s390_vfaezbs:
3652   case SystemZ::BI__builtin_s390_vfaezhs:
3653   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3654   case SystemZ::BI__builtin_s390_vfisb:
3655   case SystemZ::BI__builtin_s390_vfidb:
3656     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3657            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3658   case SystemZ::BI__builtin_s390_vftcisb:
3659   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3660   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3661   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3662   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3663   case SystemZ::BI__builtin_s390_vstrcb:
3664   case SystemZ::BI__builtin_s390_vstrch:
3665   case SystemZ::BI__builtin_s390_vstrcf:
3666   case SystemZ::BI__builtin_s390_vstrczb:
3667   case SystemZ::BI__builtin_s390_vstrczh:
3668   case SystemZ::BI__builtin_s390_vstrczf:
3669   case SystemZ::BI__builtin_s390_vstrcbs:
3670   case SystemZ::BI__builtin_s390_vstrchs:
3671   case SystemZ::BI__builtin_s390_vstrcfs:
3672   case SystemZ::BI__builtin_s390_vstrczbs:
3673   case SystemZ::BI__builtin_s390_vstrczhs:
3674   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3675   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3676   case SystemZ::BI__builtin_s390_vfminsb:
3677   case SystemZ::BI__builtin_s390_vfmaxsb:
3678   case SystemZ::BI__builtin_s390_vfmindb:
3679   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3680   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3681   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3682   }
3683   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3684 }
3685 
3686 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3687 /// This checks that the target supports __builtin_cpu_supports and
3688 /// that the string argument is constant and valid.
3689 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3690                                    CallExpr *TheCall) {
3691   Expr *Arg = TheCall->getArg(0);
3692 
3693   // Check if the argument is a string literal.
3694   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3695     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3696            << Arg->getSourceRange();
3697 
3698   // Check the contents of the string.
3699   StringRef Feature =
3700       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3701   if (!TI.validateCpuSupports(Feature))
3702     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3703            << Arg->getSourceRange();
3704   return false;
3705 }
3706 
3707 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3708 /// This checks that the target supports __builtin_cpu_is and
3709 /// that the string argument is constant and valid.
3710 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3711   Expr *Arg = TheCall->getArg(0);
3712 
3713   // Check if the argument is a string literal.
3714   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3715     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3716            << Arg->getSourceRange();
3717 
3718   // Check the contents of the string.
3719   StringRef Feature =
3720       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3721   if (!TI.validateCpuIs(Feature))
3722     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3723            << Arg->getSourceRange();
3724   return false;
3725 }
3726 
3727 // Check if the rounding mode is legal.
3728 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3729   // Indicates if this instruction has rounding control or just SAE.
3730   bool HasRC = false;
3731 
3732   unsigned ArgNum = 0;
3733   switch (BuiltinID) {
3734   default:
3735     return false;
3736   case X86::BI__builtin_ia32_vcvttsd2si32:
3737   case X86::BI__builtin_ia32_vcvttsd2si64:
3738   case X86::BI__builtin_ia32_vcvttsd2usi32:
3739   case X86::BI__builtin_ia32_vcvttsd2usi64:
3740   case X86::BI__builtin_ia32_vcvttss2si32:
3741   case X86::BI__builtin_ia32_vcvttss2si64:
3742   case X86::BI__builtin_ia32_vcvttss2usi32:
3743   case X86::BI__builtin_ia32_vcvttss2usi64:
3744     ArgNum = 1;
3745     break;
3746   case X86::BI__builtin_ia32_maxpd512:
3747   case X86::BI__builtin_ia32_maxps512:
3748   case X86::BI__builtin_ia32_minpd512:
3749   case X86::BI__builtin_ia32_minps512:
3750     ArgNum = 2;
3751     break;
3752   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3753   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3754   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3755   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3756   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3757   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3758   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3759   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3760   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3761   case X86::BI__builtin_ia32_exp2pd_mask:
3762   case X86::BI__builtin_ia32_exp2ps_mask:
3763   case X86::BI__builtin_ia32_getexppd512_mask:
3764   case X86::BI__builtin_ia32_getexpps512_mask:
3765   case X86::BI__builtin_ia32_rcp28pd_mask:
3766   case X86::BI__builtin_ia32_rcp28ps_mask:
3767   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3768   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3769   case X86::BI__builtin_ia32_vcomisd:
3770   case X86::BI__builtin_ia32_vcomiss:
3771   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3772     ArgNum = 3;
3773     break;
3774   case X86::BI__builtin_ia32_cmppd512_mask:
3775   case X86::BI__builtin_ia32_cmpps512_mask:
3776   case X86::BI__builtin_ia32_cmpsd_mask:
3777   case X86::BI__builtin_ia32_cmpss_mask:
3778   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3779   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3780   case X86::BI__builtin_ia32_getexpss128_round_mask:
3781   case X86::BI__builtin_ia32_getmantpd512_mask:
3782   case X86::BI__builtin_ia32_getmantps512_mask:
3783   case X86::BI__builtin_ia32_maxsd_round_mask:
3784   case X86::BI__builtin_ia32_maxss_round_mask:
3785   case X86::BI__builtin_ia32_minsd_round_mask:
3786   case X86::BI__builtin_ia32_minss_round_mask:
3787   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3788   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3789   case X86::BI__builtin_ia32_reducepd512_mask:
3790   case X86::BI__builtin_ia32_reduceps512_mask:
3791   case X86::BI__builtin_ia32_rndscalepd_mask:
3792   case X86::BI__builtin_ia32_rndscaleps_mask:
3793   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3794   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3795     ArgNum = 4;
3796     break;
3797   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3798   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3799   case X86::BI__builtin_ia32_fixupimmps512_mask:
3800   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3801   case X86::BI__builtin_ia32_fixupimmsd_mask:
3802   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3803   case X86::BI__builtin_ia32_fixupimmss_mask:
3804   case X86::BI__builtin_ia32_fixupimmss_maskz:
3805   case X86::BI__builtin_ia32_getmantsd_round_mask:
3806   case X86::BI__builtin_ia32_getmantss_round_mask:
3807   case X86::BI__builtin_ia32_rangepd512_mask:
3808   case X86::BI__builtin_ia32_rangeps512_mask:
3809   case X86::BI__builtin_ia32_rangesd128_round_mask:
3810   case X86::BI__builtin_ia32_rangess128_round_mask:
3811   case X86::BI__builtin_ia32_reducesd_mask:
3812   case X86::BI__builtin_ia32_reducess_mask:
3813   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3814   case X86::BI__builtin_ia32_rndscaless_round_mask:
3815     ArgNum = 5;
3816     break;
3817   case X86::BI__builtin_ia32_vcvtsd2si64:
3818   case X86::BI__builtin_ia32_vcvtsd2si32:
3819   case X86::BI__builtin_ia32_vcvtsd2usi32:
3820   case X86::BI__builtin_ia32_vcvtsd2usi64:
3821   case X86::BI__builtin_ia32_vcvtss2si32:
3822   case X86::BI__builtin_ia32_vcvtss2si64:
3823   case X86::BI__builtin_ia32_vcvtss2usi32:
3824   case X86::BI__builtin_ia32_vcvtss2usi64:
3825   case X86::BI__builtin_ia32_sqrtpd512:
3826   case X86::BI__builtin_ia32_sqrtps512:
3827     ArgNum = 1;
3828     HasRC = true;
3829     break;
3830   case X86::BI__builtin_ia32_addpd512:
3831   case X86::BI__builtin_ia32_addps512:
3832   case X86::BI__builtin_ia32_divpd512:
3833   case X86::BI__builtin_ia32_divps512:
3834   case X86::BI__builtin_ia32_mulpd512:
3835   case X86::BI__builtin_ia32_mulps512:
3836   case X86::BI__builtin_ia32_subpd512:
3837   case X86::BI__builtin_ia32_subps512:
3838   case X86::BI__builtin_ia32_cvtsi2sd64:
3839   case X86::BI__builtin_ia32_cvtsi2ss32:
3840   case X86::BI__builtin_ia32_cvtsi2ss64:
3841   case X86::BI__builtin_ia32_cvtusi2sd64:
3842   case X86::BI__builtin_ia32_cvtusi2ss32:
3843   case X86::BI__builtin_ia32_cvtusi2ss64:
3844     ArgNum = 2;
3845     HasRC = true;
3846     break;
3847   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3848   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3849   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3850   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3851   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3852   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3853   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3854   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3855   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3856   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3857   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3858   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3859   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3860   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3861   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3862     ArgNum = 3;
3863     HasRC = true;
3864     break;
3865   case X86::BI__builtin_ia32_addss_round_mask:
3866   case X86::BI__builtin_ia32_addsd_round_mask:
3867   case X86::BI__builtin_ia32_divss_round_mask:
3868   case X86::BI__builtin_ia32_divsd_round_mask:
3869   case X86::BI__builtin_ia32_mulss_round_mask:
3870   case X86::BI__builtin_ia32_mulsd_round_mask:
3871   case X86::BI__builtin_ia32_subss_round_mask:
3872   case X86::BI__builtin_ia32_subsd_round_mask:
3873   case X86::BI__builtin_ia32_scalefpd512_mask:
3874   case X86::BI__builtin_ia32_scalefps512_mask:
3875   case X86::BI__builtin_ia32_scalefsd_round_mask:
3876   case X86::BI__builtin_ia32_scalefss_round_mask:
3877   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3878   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3879   case X86::BI__builtin_ia32_sqrtss_round_mask:
3880   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3881   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3882   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3883   case X86::BI__builtin_ia32_vfmaddss3_mask:
3884   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3885   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3886   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3887   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3888   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3889   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3890   case X86::BI__builtin_ia32_vfmaddps512_mask:
3891   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3892   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3893   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3894   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3895   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3896   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3897   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3898   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3899   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3900   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3901   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3902     ArgNum = 4;
3903     HasRC = true;
3904     break;
3905   }
3906 
3907   llvm::APSInt Result;
3908 
3909   // We can't check the value of a dependent argument.
3910   Expr *Arg = TheCall->getArg(ArgNum);
3911   if (Arg->isTypeDependent() || Arg->isValueDependent())
3912     return false;
3913 
3914   // Check constant-ness first.
3915   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3916     return true;
3917 
3918   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3919   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3920   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3921   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3922   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3923       Result == 8/*ROUND_NO_EXC*/ ||
3924       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3925       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3926     return false;
3927 
3928   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3929          << Arg->getSourceRange();
3930 }
3931 
3932 // Check if the gather/scatter scale is legal.
3933 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3934                                              CallExpr *TheCall) {
3935   unsigned ArgNum = 0;
3936   switch (BuiltinID) {
3937   default:
3938     return false;
3939   case X86::BI__builtin_ia32_gatherpfdpd:
3940   case X86::BI__builtin_ia32_gatherpfdps:
3941   case X86::BI__builtin_ia32_gatherpfqpd:
3942   case X86::BI__builtin_ia32_gatherpfqps:
3943   case X86::BI__builtin_ia32_scatterpfdpd:
3944   case X86::BI__builtin_ia32_scatterpfdps:
3945   case X86::BI__builtin_ia32_scatterpfqpd:
3946   case X86::BI__builtin_ia32_scatterpfqps:
3947     ArgNum = 3;
3948     break;
3949   case X86::BI__builtin_ia32_gatherd_pd:
3950   case X86::BI__builtin_ia32_gatherd_pd256:
3951   case X86::BI__builtin_ia32_gatherq_pd:
3952   case X86::BI__builtin_ia32_gatherq_pd256:
3953   case X86::BI__builtin_ia32_gatherd_ps:
3954   case X86::BI__builtin_ia32_gatherd_ps256:
3955   case X86::BI__builtin_ia32_gatherq_ps:
3956   case X86::BI__builtin_ia32_gatherq_ps256:
3957   case X86::BI__builtin_ia32_gatherd_q:
3958   case X86::BI__builtin_ia32_gatherd_q256:
3959   case X86::BI__builtin_ia32_gatherq_q:
3960   case X86::BI__builtin_ia32_gatherq_q256:
3961   case X86::BI__builtin_ia32_gatherd_d:
3962   case X86::BI__builtin_ia32_gatherd_d256:
3963   case X86::BI__builtin_ia32_gatherq_d:
3964   case X86::BI__builtin_ia32_gatherq_d256:
3965   case X86::BI__builtin_ia32_gather3div2df:
3966   case X86::BI__builtin_ia32_gather3div2di:
3967   case X86::BI__builtin_ia32_gather3div4df:
3968   case X86::BI__builtin_ia32_gather3div4di:
3969   case X86::BI__builtin_ia32_gather3div4sf:
3970   case X86::BI__builtin_ia32_gather3div4si:
3971   case X86::BI__builtin_ia32_gather3div8sf:
3972   case X86::BI__builtin_ia32_gather3div8si:
3973   case X86::BI__builtin_ia32_gather3siv2df:
3974   case X86::BI__builtin_ia32_gather3siv2di:
3975   case X86::BI__builtin_ia32_gather3siv4df:
3976   case X86::BI__builtin_ia32_gather3siv4di:
3977   case X86::BI__builtin_ia32_gather3siv4sf:
3978   case X86::BI__builtin_ia32_gather3siv4si:
3979   case X86::BI__builtin_ia32_gather3siv8sf:
3980   case X86::BI__builtin_ia32_gather3siv8si:
3981   case X86::BI__builtin_ia32_gathersiv8df:
3982   case X86::BI__builtin_ia32_gathersiv16sf:
3983   case X86::BI__builtin_ia32_gatherdiv8df:
3984   case X86::BI__builtin_ia32_gatherdiv16sf:
3985   case X86::BI__builtin_ia32_gathersiv8di:
3986   case X86::BI__builtin_ia32_gathersiv16si:
3987   case X86::BI__builtin_ia32_gatherdiv8di:
3988   case X86::BI__builtin_ia32_gatherdiv16si:
3989   case X86::BI__builtin_ia32_scatterdiv2df:
3990   case X86::BI__builtin_ia32_scatterdiv2di:
3991   case X86::BI__builtin_ia32_scatterdiv4df:
3992   case X86::BI__builtin_ia32_scatterdiv4di:
3993   case X86::BI__builtin_ia32_scatterdiv4sf:
3994   case X86::BI__builtin_ia32_scatterdiv4si:
3995   case X86::BI__builtin_ia32_scatterdiv8sf:
3996   case X86::BI__builtin_ia32_scatterdiv8si:
3997   case X86::BI__builtin_ia32_scattersiv2df:
3998   case X86::BI__builtin_ia32_scattersiv2di:
3999   case X86::BI__builtin_ia32_scattersiv4df:
4000   case X86::BI__builtin_ia32_scattersiv4di:
4001   case X86::BI__builtin_ia32_scattersiv4sf:
4002   case X86::BI__builtin_ia32_scattersiv4si:
4003   case X86::BI__builtin_ia32_scattersiv8sf:
4004   case X86::BI__builtin_ia32_scattersiv8si:
4005   case X86::BI__builtin_ia32_scattersiv8df:
4006   case X86::BI__builtin_ia32_scattersiv16sf:
4007   case X86::BI__builtin_ia32_scatterdiv8df:
4008   case X86::BI__builtin_ia32_scatterdiv16sf:
4009   case X86::BI__builtin_ia32_scattersiv8di:
4010   case X86::BI__builtin_ia32_scattersiv16si:
4011   case X86::BI__builtin_ia32_scatterdiv8di:
4012   case X86::BI__builtin_ia32_scatterdiv16si:
4013     ArgNum = 4;
4014     break;
4015   }
4016 
4017   llvm::APSInt Result;
4018 
4019   // We can't check the value of a dependent argument.
4020   Expr *Arg = TheCall->getArg(ArgNum);
4021   if (Arg->isTypeDependent() || Arg->isValueDependent())
4022     return false;
4023 
4024   // Check constant-ness first.
4025   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4026     return true;
4027 
4028   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4029     return false;
4030 
4031   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4032          << Arg->getSourceRange();
4033 }
4034 
4035 enum { TileRegLow = 0, TileRegHigh = 7 };
4036 
4037 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4038                                              ArrayRef<int> ArgNums) {
4039   for (int ArgNum : ArgNums) {
4040     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4041       return true;
4042   }
4043   return false;
4044 }
4045 
4046 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4047                                         ArrayRef<int> ArgNums) {
4048   // Because the max number of tile register is TileRegHigh + 1, so here we use
4049   // each bit to represent the usage of them in bitset.
4050   std::bitset<TileRegHigh + 1> ArgValues;
4051   for (int ArgNum : ArgNums) {
4052     Expr *Arg = TheCall->getArg(ArgNum);
4053     if (Arg->isTypeDependent() || Arg->isValueDependent())
4054       continue;
4055 
4056     llvm::APSInt Result;
4057     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4058       return true;
4059     int ArgExtValue = Result.getExtValue();
4060     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4061            "Incorrect tile register num.");
4062     if (ArgValues.test(ArgExtValue))
4063       return Diag(TheCall->getBeginLoc(),
4064                   diag::err_x86_builtin_tile_arg_duplicate)
4065              << TheCall->getArg(ArgNum)->getSourceRange();
4066     ArgValues.set(ArgExtValue);
4067   }
4068   return false;
4069 }
4070 
4071 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4072                                                 ArrayRef<int> ArgNums) {
4073   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4074          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4075 }
4076 
4077 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4078   switch (BuiltinID) {
4079   default:
4080     return false;
4081   case X86::BI__builtin_ia32_tileloadd64:
4082   case X86::BI__builtin_ia32_tileloaddt164:
4083   case X86::BI__builtin_ia32_tilestored64:
4084   case X86::BI__builtin_ia32_tilezero:
4085     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4086   case X86::BI__builtin_ia32_tdpbssd:
4087   case X86::BI__builtin_ia32_tdpbsud:
4088   case X86::BI__builtin_ia32_tdpbusd:
4089   case X86::BI__builtin_ia32_tdpbuud:
4090   case X86::BI__builtin_ia32_tdpbf16ps:
4091     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4092   }
4093 }
4094 static bool isX86_32Builtin(unsigned BuiltinID) {
4095   // These builtins only work on x86-32 targets.
4096   switch (BuiltinID) {
4097   case X86::BI__builtin_ia32_readeflags_u32:
4098   case X86::BI__builtin_ia32_writeeflags_u32:
4099     return true;
4100   }
4101 
4102   return false;
4103 }
4104 
4105 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4106                                        CallExpr *TheCall) {
4107   if (BuiltinID == X86::BI__builtin_cpu_supports)
4108     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4109 
4110   if (BuiltinID == X86::BI__builtin_cpu_is)
4111     return SemaBuiltinCpuIs(*this, TI, TheCall);
4112 
4113   // Check for 32-bit only builtins on a 64-bit target.
4114   const llvm::Triple &TT = TI.getTriple();
4115   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4116     return Diag(TheCall->getCallee()->getBeginLoc(),
4117                 diag::err_32_bit_builtin_64_bit_tgt);
4118 
4119   // If the intrinsic has rounding or SAE make sure its valid.
4120   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4121     return true;
4122 
4123   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4124   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4125     return true;
4126 
4127   // If the intrinsic has a tile arguments, make sure they are valid.
4128   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4129     return true;
4130 
4131   // For intrinsics which take an immediate value as part of the instruction,
4132   // range check them here.
4133   int i = 0, l = 0, u = 0;
4134   switch (BuiltinID) {
4135   default:
4136     return false;
4137   case X86::BI__builtin_ia32_vec_ext_v2si:
4138   case X86::BI__builtin_ia32_vec_ext_v2di:
4139   case X86::BI__builtin_ia32_vextractf128_pd256:
4140   case X86::BI__builtin_ia32_vextractf128_ps256:
4141   case X86::BI__builtin_ia32_vextractf128_si256:
4142   case X86::BI__builtin_ia32_extract128i256:
4143   case X86::BI__builtin_ia32_extractf64x4_mask:
4144   case X86::BI__builtin_ia32_extracti64x4_mask:
4145   case X86::BI__builtin_ia32_extractf32x8_mask:
4146   case X86::BI__builtin_ia32_extracti32x8_mask:
4147   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4148   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4149   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4150   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4151     i = 1; l = 0; u = 1;
4152     break;
4153   case X86::BI__builtin_ia32_vec_set_v2di:
4154   case X86::BI__builtin_ia32_vinsertf128_pd256:
4155   case X86::BI__builtin_ia32_vinsertf128_ps256:
4156   case X86::BI__builtin_ia32_vinsertf128_si256:
4157   case X86::BI__builtin_ia32_insert128i256:
4158   case X86::BI__builtin_ia32_insertf32x8:
4159   case X86::BI__builtin_ia32_inserti32x8:
4160   case X86::BI__builtin_ia32_insertf64x4:
4161   case X86::BI__builtin_ia32_inserti64x4:
4162   case X86::BI__builtin_ia32_insertf64x2_256:
4163   case X86::BI__builtin_ia32_inserti64x2_256:
4164   case X86::BI__builtin_ia32_insertf32x4_256:
4165   case X86::BI__builtin_ia32_inserti32x4_256:
4166     i = 2; l = 0; u = 1;
4167     break;
4168   case X86::BI__builtin_ia32_vpermilpd:
4169   case X86::BI__builtin_ia32_vec_ext_v4hi:
4170   case X86::BI__builtin_ia32_vec_ext_v4si:
4171   case X86::BI__builtin_ia32_vec_ext_v4sf:
4172   case X86::BI__builtin_ia32_vec_ext_v4di:
4173   case X86::BI__builtin_ia32_extractf32x4_mask:
4174   case X86::BI__builtin_ia32_extracti32x4_mask:
4175   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4176   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4177     i = 1; l = 0; u = 3;
4178     break;
4179   case X86::BI_mm_prefetch:
4180   case X86::BI__builtin_ia32_vec_ext_v8hi:
4181   case X86::BI__builtin_ia32_vec_ext_v8si:
4182     i = 1; l = 0; u = 7;
4183     break;
4184   case X86::BI__builtin_ia32_sha1rnds4:
4185   case X86::BI__builtin_ia32_blendpd:
4186   case X86::BI__builtin_ia32_shufpd:
4187   case X86::BI__builtin_ia32_vec_set_v4hi:
4188   case X86::BI__builtin_ia32_vec_set_v4si:
4189   case X86::BI__builtin_ia32_vec_set_v4di:
4190   case X86::BI__builtin_ia32_shuf_f32x4_256:
4191   case X86::BI__builtin_ia32_shuf_f64x2_256:
4192   case X86::BI__builtin_ia32_shuf_i32x4_256:
4193   case X86::BI__builtin_ia32_shuf_i64x2_256:
4194   case X86::BI__builtin_ia32_insertf64x2_512:
4195   case X86::BI__builtin_ia32_inserti64x2_512:
4196   case X86::BI__builtin_ia32_insertf32x4:
4197   case X86::BI__builtin_ia32_inserti32x4:
4198     i = 2; l = 0; u = 3;
4199     break;
4200   case X86::BI__builtin_ia32_vpermil2pd:
4201   case X86::BI__builtin_ia32_vpermil2pd256:
4202   case X86::BI__builtin_ia32_vpermil2ps:
4203   case X86::BI__builtin_ia32_vpermil2ps256:
4204     i = 3; l = 0; u = 3;
4205     break;
4206   case X86::BI__builtin_ia32_cmpb128_mask:
4207   case X86::BI__builtin_ia32_cmpw128_mask:
4208   case X86::BI__builtin_ia32_cmpd128_mask:
4209   case X86::BI__builtin_ia32_cmpq128_mask:
4210   case X86::BI__builtin_ia32_cmpb256_mask:
4211   case X86::BI__builtin_ia32_cmpw256_mask:
4212   case X86::BI__builtin_ia32_cmpd256_mask:
4213   case X86::BI__builtin_ia32_cmpq256_mask:
4214   case X86::BI__builtin_ia32_cmpb512_mask:
4215   case X86::BI__builtin_ia32_cmpw512_mask:
4216   case X86::BI__builtin_ia32_cmpd512_mask:
4217   case X86::BI__builtin_ia32_cmpq512_mask:
4218   case X86::BI__builtin_ia32_ucmpb128_mask:
4219   case X86::BI__builtin_ia32_ucmpw128_mask:
4220   case X86::BI__builtin_ia32_ucmpd128_mask:
4221   case X86::BI__builtin_ia32_ucmpq128_mask:
4222   case X86::BI__builtin_ia32_ucmpb256_mask:
4223   case X86::BI__builtin_ia32_ucmpw256_mask:
4224   case X86::BI__builtin_ia32_ucmpd256_mask:
4225   case X86::BI__builtin_ia32_ucmpq256_mask:
4226   case X86::BI__builtin_ia32_ucmpb512_mask:
4227   case X86::BI__builtin_ia32_ucmpw512_mask:
4228   case X86::BI__builtin_ia32_ucmpd512_mask:
4229   case X86::BI__builtin_ia32_ucmpq512_mask:
4230   case X86::BI__builtin_ia32_vpcomub:
4231   case X86::BI__builtin_ia32_vpcomuw:
4232   case X86::BI__builtin_ia32_vpcomud:
4233   case X86::BI__builtin_ia32_vpcomuq:
4234   case X86::BI__builtin_ia32_vpcomb:
4235   case X86::BI__builtin_ia32_vpcomw:
4236   case X86::BI__builtin_ia32_vpcomd:
4237   case X86::BI__builtin_ia32_vpcomq:
4238   case X86::BI__builtin_ia32_vec_set_v8hi:
4239   case X86::BI__builtin_ia32_vec_set_v8si:
4240     i = 2; l = 0; u = 7;
4241     break;
4242   case X86::BI__builtin_ia32_vpermilpd256:
4243   case X86::BI__builtin_ia32_roundps:
4244   case X86::BI__builtin_ia32_roundpd:
4245   case X86::BI__builtin_ia32_roundps256:
4246   case X86::BI__builtin_ia32_roundpd256:
4247   case X86::BI__builtin_ia32_getmantpd128_mask:
4248   case X86::BI__builtin_ia32_getmantpd256_mask:
4249   case X86::BI__builtin_ia32_getmantps128_mask:
4250   case X86::BI__builtin_ia32_getmantps256_mask:
4251   case X86::BI__builtin_ia32_getmantpd512_mask:
4252   case X86::BI__builtin_ia32_getmantps512_mask:
4253   case X86::BI__builtin_ia32_vec_ext_v16qi:
4254   case X86::BI__builtin_ia32_vec_ext_v16hi:
4255     i = 1; l = 0; u = 15;
4256     break;
4257   case X86::BI__builtin_ia32_pblendd128:
4258   case X86::BI__builtin_ia32_blendps:
4259   case X86::BI__builtin_ia32_blendpd256:
4260   case X86::BI__builtin_ia32_shufpd256:
4261   case X86::BI__builtin_ia32_roundss:
4262   case X86::BI__builtin_ia32_roundsd:
4263   case X86::BI__builtin_ia32_rangepd128_mask:
4264   case X86::BI__builtin_ia32_rangepd256_mask:
4265   case X86::BI__builtin_ia32_rangepd512_mask:
4266   case X86::BI__builtin_ia32_rangeps128_mask:
4267   case X86::BI__builtin_ia32_rangeps256_mask:
4268   case X86::BI__builtin_ia32_rangeps512_mask:
4269   case X86::BI__builtin_ia32_getmantsd_round_mask:
4270   case X86::BI__builtin_ia32_getmantss_round_mask:
4271   case X86::BI__builtin_ia32_vec_set_v16qi:
4272   case X86::BI__builtin_ia32_vec_set_v16hi:
4273     i = 2; l = 0; u = 15;
4274     break;
4275   case X86::BI__builtin_ia32_vec_ext_v32qi:
4276     i = 1; l = 0; u = 31;
4277     break;
4278   case X86::BI__builtin_ia32_cmpps:
4279   case X86::BI__builtin_ia32_cmpss:
4280   case X86::BI__builtin_ia32_cmppd:
4281   case X86::BI__builtin_ia32_cmpsd:
4282   case X86::BI__builtin_ia32_cmpps256:
4283   case X86::BI__builtin_ia32_cmppd256:
4284   case X86::BI__builtin_ia32_cmpps128_mask:
4285   case X86::BI__builtin_ia32_cmppd128_mask:
4286   case X86::BI__builtin_ia32_cmpps256_mask:
4287   case X86::BI__builtin_ia32_cmppd256_mask:
4288   case X86::BI__builtin_ia32_cmpps512_mask:
4289   case X86::BI__builtin_ia32_cmppd512_mask:
4290   case X86::BI__builtin_ia32_cmpsd_mask:
4291   case X86::BI__builtin_ia32_cmpss_mask:
4292   case X86::BI__builtin_ia32_vec_set_v32qi:
4293     i = 2; l = 0; u = 31;
4294     break;
4295   case X86::BI__builtin_ia32_permdf256:
4296   case X86::BI__builtin_ia32_permdi256:
4297   case X86::BI__builtin_ia32_permdf512:
4298   case X86::BI__builtin_ia32_permdi512:
4299   case X86::BI__builtin_ia32_vpermilps:
4300   case X86::BI__builtin_ia32_vpermilps256:
4301   case X86::BI__builtin_ia32_vpermilpd512:
4302   case X86::BI__builtin_ia32_vpermilps512:
4303   case X86::BI__builtin_ia32_pshufd:
4304   case X86::BI__builtin_ia32_pshufd256:
4305   case X86::BI__builtin_ia32_pshufd512:
4306   case X86::BI__builtin_ia32_pshufhw:
4307   case X86::BI__builtin_ia32_pshufhw256:
4308   case X86::BI__builtin_ia32_pshufhw512:
4309   case X86::BI__builtin_ia32_pshuflw:
4310   case X86::BI__builtin_ia32_pshuflw256:
4311   case X86::BI__builtin_ia32_pshuflw512:
4312   case X86::BI__builtin_ia32_vcvtps2ph:
4313   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4314   case X86::BI__builtin_ia32_vcvtps2ph256:
4315   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4316   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4317   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4318   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4319   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4320   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4321   case X86::BI__builtin_ia32_rndscaleps_mask:
4322   case X86::BI__builtin_ia32_rndscalepd_mask:
4323   case X86::BI__builtin_ia32_reducepd128_mask:
4324   case X86::BI__builtin_ia32_reducepd256_mask:
4325   case X86::BI__builtin_ia32_reducepd512_mask:
4326   case X86::BI__builtin_ia32_reduceps128_mask:
4327   case X86::BI__builtin_ia32_reduceps256_mask:
4328   case X86::BI__builtin_ia32_reduceps512_mask:
4329   case X86::BI__builtin_ia32_prold512:
4330   case X86::BI__builtin_ia32_prolq512:
4331   case X86::BI__builtin_ia32_prold128:
4332   case X86::BI__builtin_ia32_prold256:
4333   case X86::BI__builtin_ia32_prolq128:
4334   case X86::BI__builtin_ia32_prolq256:
4335   case X86::BI__builtin_ia32_prord512:
4336   case X86::BI__builtin_ia32_prorq512:
4337   case X86::BI__builtin_ia32_prord128:
4338   case X86::BI__builtin_ia32_prord256:
4339   case X86::BI__builtin_ia32_prorq128:
4340   case X86::BI__builtin_ia32_prorq256:
4341   case X86::BI__builtin_ia32_fpclasspd128_mask:
4342   case X86::BI__builtin_ia32_fpclasspd256_mask:
4343   case X86::BI__builtin_ia32_fpclassps128_mask:
4344   case X86::BI__builtin_ia32_fpclassps256_mask:
4345   case X86::BI__builtin_ia32_fpclassps512_mask:
4346   case X86::BI__builtin_ia32_fpclasspd512_mask:
4347   case X86::BI__builtin_ia32_fpclasssd_mask:
4348   case X86::BI__builtin_ia32_fpclassss_mask:
4349   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4350   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4351   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4352   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4353   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4354   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4355   case X86::BI__builtin_ia32_kshiftliqi:
4356   case X86::BI__builtin_ia32_kshiftlihi:
4357   case X86::BI__builtin_ia32_kshiftlisi:
4358   case X86::BI__builtin_ia32_kshiftlidi:
4359   case X86::BI__builtin_ia32_kshiftriqi:
4360   case X86::BI__builtin_ia32_kshiftrihi:
4361   case X86::BI__builtin_ia32_kshiftrisi:
4362   case X86::BI__builtin_ia32_kshiftridi:
4363     i = 1; l = 0; u = 255;
4364     break;
4365   case X86::BI__builtin_ia32_vperm2f128_pd256:
4366   case X86::BI__builtin_ia32_vperm2f128_ps256:
4367   case X86::BI__builtin_ia32_vperm2f128_si256:
4368   case X86::BI__builtin_ia32_permti256:
4369   case X86::BI__builtin_ia32_pblendw128:
4370   case X86::BI__builtin_ia32_pblendw256:
4371   case X86::BI__builtin_ia32_blendps256:
4372   case X86::BI__builtin_ia32_pblendd256:
4373   case X86::BI__builtin_ia32_palignr128:
4374   case X86::BI__builtin_ia32_palignr256:
4375   case X86::BI__builtin_ia32_palignr512:
4376   case X86::BI__builtin_ia32_alignq512:
4377   case X86::BI__builtin_ia32_alignd512:
4378   case X86::BI__builtin_ia32_alignd128:
4379   case X86::BI__builtin_ia32_alignd256:
4380   case X86::BI__builtin_ia32_alignq128:
4381   case X86::BI__builtin_ia32_alignq256:
4382   case X86::BI__builtin_ia32_vcomisd:
4383   case X86::BI__builtin_ia32_vcomiss:
4384   case X86::BI__builtin_ia32_shuf_f32x4:
4385   case X86::BI__builtin_ia32_shuf_f64x2:
4386   case X86::BI__builtin_ia32_shuf_i32x4:
4387   case X86::BI__builtin_ia32_shuf_i64x2:
4388   case X86::BI__builtin_ia32_shufpd512:
4389   case X86::BI__builtin_ia32_shufps:
4390   case X86::BI__builtin_ia32_shufps256:
4391   case X86::BI__builtin_ia32_shufps512:
4392   case X86::BI__builtin_ia32_dbpsadbw128:
4393   case X86::BI__builtin_ia32_dbpsadbw256:
4394   case X86::BI__builtin_ia32_dbpsadbw512:
4395   case X86::BI__builtin_ia32_vpshldd128:
4396   case X86::BI__builtin_ia32_vpshldd256:
4397   case X86::BI__builtin_ia32_vpshldd512:
4398   case X86::BI__builtin_ia32_vpshldq128:
4399   case X86::BI__builtin_ia32_vpshldq256:
4400   case X86::BI__builtin_ia32_vpshldq512:
4401   case X86::BI__builtin_ia32_vpshldw128:
4402   case X86::BI__builtin_ia32_vpshldw256:
4403   case X86::BI__builtin_ia32_vpshldw512:
4404   case X86::BI__builtin_ia32_vpshrdd128:
4405   case X86::BI__builtin_ia32_vpshrdd256:
4406   case X86::BI__builtin_ia32_vpshrdd512:
4407   case X86::BI__builtin_ia32_vpshrdq128:
4408   case X86::BI__builtin_ia32_vpshrdq256:
4409   case X86::BI__builtin_ia32_vpshrdq512:
4410   case X86::BI__builtin_ia32_vpshrdw128:
4411   case X86::BI__builtin_ia32_vpshrdw256:
4412   case X86::BI__builtin_ia32_vpshrdw512:
4413     i = 2; l = 0; u = 255;
4414     break;
4415   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4416   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4417   case X86::BI__builtin_ia32_fixupimmps512_mask:
4418   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4419   case X86::BI__builtin_ia32_fixupimmsd_mask:
4420   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4421   case X86::BI__builtin_ia32_fixupimmss_mask:
4422   case X86::BI__builtin_ia32_fixupimmss_maskz:
4423   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4424   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4425   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4426   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4427   case X86::BI__builtin_ia32_fixupimmps128_mask:
4428   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4429   case X86::BI__builtin_ia32_fixupimmps256_mask:
4430   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4431   case X86::BI__builtin_ia32_pternlogd512_mask:
4432   case X86::BI__builtin_ia32_pternlogd512_maskz:
4433   case X86::BI__builtin_ia32_pternlogq512_mask:
4434   case X86::BI__builtin_ia32_pternlogq512_maskz:
4435   case X86::BI__builtin_ia32_pternlogd128_mask:
4436   case X86::BI__builtin_ia32_pternlogd128_maskz:
4437   case X86::BI__builtin_ia32_pternlogd256_mask:
4438   case X86::BI__builtin_ia32_pternlogd256_maskz:
4439   case X86::BI__builtin_ia32_pternlogq128_mask:
4440   case X86::BI__builtin_ia32_pternlogq128_maskz:
4441   case X86::BI__builtin_ia32_pternlogq256_mask:
4442   case X86::BI__builtin_ia32_pternlogq256_maskz:
4443     i = 3; l = 0; u = 255;
4444     break;
4445   case X86::BI__builtin_ia32_gatherpfdpd:
4446   case X86::BI__builtin_ia32_gatherpfdps:
4447   case X86::BI__builtin_ia32_gatherpfqpd:
4448   case X86::BI__builtin_ia32_gatherpfqps:
4449   case X86::BI__builtin_ia32_scatterpfdpd:
4450   case X86::BI__builtin_ia32_scatterpfdps:
4451   case X86::BI__builtin_ia32_scatterpfqpd:
4452   case X86::BI__builtin_ia32_scatterpfqps:
4453     i = 4; l = 2; u = 3;
4454     break;
4455   case X86::BI__builtin_ia32_reducesd_mask:
4456   case X86::BI__builtin_ia32_reducess_mask:
4457   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4458   case X86::BI__builtin_ia32_rndscaless_round_mask:
4459     i = 4; l = 0; u = 255;
4460     break;
4461   }
4462 
4463   // Note that we don't force a hard error on the range check here, allowing
4464   // template-generated or macro-generated dead code to potentially have out-of-
4465   // range values. These need to code generate, but don't need to necessarily
4466   // make any sense. We use a warning that defaults to an error.
4467   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4468 }
4469 
4470 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4471 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4472 /// Returns true when the format fits the function and the FormatStringInfo has
4473 /// been populated.
4474 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4475                                FormatStringInfo *FSI) {
4476   FSI->HasVAListArg = Format->getFirstArg() == 0;
4477   FSI->FormatIdx = Format->getFormatIdx() - 1;
4478   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4479 
4480   // The way the format attribute works in GCC, the implicit this argument
4481   // of member functions is counted. However, it doesn't appear in our own
4482   // lists, so decrement format_idx in that case.
4483   if (IsCXXMember) {
4484     if(FSI->FormatIdx == 0)
4485       return false;
4486     --FSI->FormatIdx;
4487     if (FSI->FirstDataArg != 0)
4488       --FSI->FirstDataArg;
4489   }
4490   return true;
4491 }
4492 
4493 /// Checks if a the given expression evaluates to null.
4494 ///
4495 /// Returns true if the value evaluates to null.
4496 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4497   // If the expression has non-null type, it doesn't evaluate to null.
4498   if (auto nullability
4499         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4500     if (*nullability == NullabilityKind::NonNull)
4501       return false;
4502   }
4503 
4504   // As a special case, transparent unions initialized with zero are
4505   // considered null for the purposes of the nonnull attribute.
4506   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4507     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4508       if (const CompoundLiteralExpr *CLE =
4509           dyn_cast<CompoundLiteralExpr>(Expr))
4510         if (const InitListExpr *ILE =
4511             dyn_cast<InitListExpr>(CLE->getInitializer()))
4512           Expr = ILE->getInit(0);
4513   }
4514 
4515   bool Result;
4516   return (!Expr->isValueDependent() &&
4517           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4518           !Result);
4519 }
4520 
4521 static void CheckNonNullArgument(Sema &S,
4522                                  const Expr *ArgExpr,
4523                                  SourceLocation CallSiteLoc) {
4524   if (CheckNonNullExpr(S, ArgExpr))
4525     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4526                           S.PDiag(diag::warn_null_arg)
4527                               << ArgExpr->getSourceRange());
4528 }
4529 
4530 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4531   FormatStringInfo FSI;
4532   if ((GetFormatStringType(Format) == FST_NSString) &&
4533       getFormatStringInfo(Format, false, &FSI)) {
4534     Idx = FSI.FormatIdx;
4535     return true;
4536   }
4537   return false;
4538 }
4539 
4540 /// Diagnose use of %s directive in an NSString which is being passed
4541 /// as formatting string to formatting method.
4542 static void
4543 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4544                                         const NamedDecl *FDecl,
4545                                         Expr **Args,
4546                                         unsigned NumArgs) {
4547   unsigned Idx = 0;
4548   bool Format = false;
4549   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4550   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4551     Idx = 2;
4552     Format = true;
4553   }
4554   else
4555     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4556       if (S.GetFormatNSStringIdx(I, Idx)) {
4557         Format = true;
4558         break;
4559       }
4560     }
4561   if (!Format || NumArgs <= Idx)
4562     return;
4563   const Expr *FormatExpr = Args[Idx];
4564   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4565     FormatExpr = CSCE->getSubExpr();
4566   const StringLiteral *FormatString;
4567   if (const ObjCStringLiteral *OSL =
4568       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4569     FormatString = OSL->getString();
4570   else
4571     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4572   if (!FormatString)
4573     return;
4574   if (S.FormatStringHasSArg(FormatString)) {
4575     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4576       << "%s" << 1 << 1;
4577     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4578       << FDecl->getDeclName();
4579   }
4580 }
4581 
4582 /// Determine whether the given type has a non-null nullability annotation.
4583 static bool isNonNullType(ASTContext &ctx, QualType type) {
4584   if (auto nullability = type->getNullability(ctx))
4585     return *nullability == NullabilityKind::NonNull;
4586 
4587   return false;
4588 }
4589 
4590 static void CheckNonNullArguments(Sema &S,
4591                                   const NamedDecl *FDecl,
4592                                   const FunctionProtoType *Proto,
4593                                   ArrayRef<const Expr *> Args,
4594                                   SourceLocation CallSiteLoc) {
4595   assert((FDecl || Proto) && "Need a function declaration or prototype");
4596 
4597   // Already checked by by constant evaluator.
4598   if (S.isConstantEvaluated())
4599     return;
4600   // Check the attributes attached to the method/function itself.
4601   llvm::SmallBitVector NonNullArgs;
4602   if (FDecl) {
4603     // Handle the nonnull attribute on the function/method declaration itself.
4604     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4605       if (!NonNull->args_size()) {
4606         // Easy case: all pointer arguments are nonnull.
4607         for (const auto *Arg : Args)
4608           if (S.isValidPointerAttrType(Arg->getType()))
4609             CheckNonNullArgument(S, Arg, CallSiteLoc);
4610         return;
4611       }
4612 
4613       for (const ParamIdx &Idx : NonNull->args()) {
4614         unsigned IdxAST = Idx.getASTIndex();
4615         if (IdxAST >= Args.size())
4616           continue;
4617         if (NonNullArgs.empty())
4618           NonNullArgs.resize(Args.size());
4619         NonNullArgs.set(IdxAST);
4620       }
4621     }
4622   }
4623 
4624   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4625     // Handle the nonnull attribute on the parameters of the
4626     // function/method.
4627     ArrayRef<ParmVarDecl*> parms;
4628     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4629       parms = FD->parameters();
4630     else
4631       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4632 
4633     unsigned ParamIndex = 0;
4634     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4635          I != E; ++I, ++ParamIndex) {
4636       const ParmVarDecl *PVD = *I;
4637       if (PVD->hasAttr<NonNullAttr>() ||
4638           isNonNullType(S.Context, PVD->getType())) {
4639         if (NonNullArgs.empty())
4640           NonNullArgs.resize(Args.size());
4641 
4642         NonNullArgs.set(ParamIndex);
4643       }
4644     }
4645   } else {
4646     // If we have a non-function, non-method declaration but no
4647     // function prototype, try to dig out the function prototype.
4648     if (!Proto) {
4649       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4650         QualType type = VD->getType().getNonReferenceType();
4651         if (auto pointerType = type->getAs<PointerType>())
4652           type = pointerType->getPointeeType();
4653         else if (auto blockType = type->getAs<BlockPointerType>())
4654           type = blockType->getPointeeType();
4655         // FIXME: data member pointers?
4656 
4657         // Dig out the function prototype, if there is one.
4658         Proto = type->getAs<FunctionProtoType>();
4659       }
4660     }
4661 
4662     // Fill in non-null argument information from the nullability
4663     // information on the parameter types (if we have them).
4664     if (Proto) {
4665       unsigned Index = 0;
4666       for (auto paramType : Proto->getParamTypes()) {
4667         if (isNonNullType(S.Context, paramType)) {
4668           if (NonNullArgs.empty())
4669             NonNullArgs.resize(Args.size());
4670 
4671           NonNullArgs.set(Index);
4672         }
4673 
4674         ++Index;
4675       }
4676     }
4677   }
4678 
4679   // Check for non-null arguments.
4680   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4681        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4682     if (NonNullArgs[ArgIndex])
4683       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4684   }
4685 }
4686 
4687 /// Warn if a pointer or reference argument passed to a function points to an
4688 /// object that is less aligned than the parameter. This can happen when
4689 /// creating a typedef with a lower alignment than the original type and then
4690 /// calling functions defined in terms of the original type.
4691 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4692                              StringRef ParamName, QualType ArgTy,
4693                              QualType ParamTy) {
4694 
4695   // If a function accepts a pointer or reference type
4696   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4697     return;
4698 
4699   // If the parameter is a pointer type, get the pointee type for the
4700   // argument too. If the parameter is a reference type, don't try to get
4701   // the pointee type for the argument.
4702   if (ParamTy->isPointerType())
4703     ArgTy = ArgTy->getPointeeType();
4704 
4705   // Remove reference or pointer
4706   ParamTy = ParamTy->getPointeeType();
4707 
4708   // Find expected alignment, and the actual alignment of the passed object.
4709   // getTypeAlignInChars requires complete types
4710   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4711       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4712       ArgTy->isUndeducedType())
4713     return;
4714 
4715   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4716   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4717 
4718   // If the argument is less aligned than the parameter, there is a
4719   // potential alignment issue.
4720   if (ArgAlign < ParamAlign)
4721     Diag(Loc, diag::warn_param_mismatched_alignment)
4722         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4723         << ParamName << FDecl;
4724 }
4725 
4726 /// Handles the checks for format strings, non-POD arguments to vararg
4727 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4728 /// attributes.
4729 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4730                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4731                      bool IsMemberFunction, SourceLocation Loc,
4732                      SourceRange Range, VariadicCallType CallType) {
4733   // FIXME: We should check as much as we can in the template definition.
4734   if (CurContext->isDependentContext())
4735     return;
4736 
4737   // Printf and scanf checking.
4738   llvm::SmallBitVector CheckedVarArgs;
4739   if (FDecl) {
4740     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4741       // Only create vector if there are format attributes.
4742       CheckedVarArgs.resize(Args.size());
4743 
4744       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4745                            CheckedVarArgs);
4746     }
4747   }
4748 
4749   // Refuse POD arguments that weren't caught by the format string
4750   // checks above.
4751   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4752   if (CallType != VariadicDoesNotApply &&
4753       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4754     unsigned NumParams = Proto ? Proto->getNumParams()
4755                        : FDecl && isa<FunctionDecl>(FDecl)
4756                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4757                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4758                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4759                        : 0;
4760 
4761     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4762       // Args[ArgIdx] can be null in malformed code.
4763       if (const Expr *Arg = Args[ArgIdx]) {
4764         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4765           checkVariadicArgument(Arg, CallType);
4766       }
4767     }
4768   }
4769 
4770   if (FDecl || Proto) {
4771     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4772 
4773     // Type safety checking.
4774     if (FDecl) {
4775       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4776         CheckArgumentWithTypeTag(I, Args, Loc);
4777     }
4778   }
4779 
4780   // Check that passed arguments match the alignment of original arguments.
4781   // Try to get the missing prototype from the declaration.
4782   if (!Proto && FDecl) {
4783     const auto *FT = FDecl->getFunctionType();
4784     if (isa_and_nonnull<FunctionProtoType>(FT))
4785       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4786   }
4787   if (Proto) {
4788     // For variadic functions, we may have more args than parameters.
4789     // For some K&R functions, we may have less args than parameters.
4790     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4791     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4792       // Args[ArgIdx] can be null in malformed code.
4793       if (const Expr *Arg = Args[ArgIdx]) {
4794         if (Arg->containsErrors())
4795           continue;
4796 
4797         QualType ParamTy = Proto->getParamType(ArgIdx);
4798         QualType ArgTy = Arg->getType();
4799         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4800                           ArgTy, ParamTy);
4801       }
4802     }
4803   }
4804 
4805   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4806     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4807     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4808     if (!Arg->isValueDependent()) {
4809       Expr::EvalResult Align;
4810       if (Arg->EvaluateAsInt(Align, Context)) {
4811         const llvm::APSInt &I = Align.Val.getInt();
4812         if (!I.isPowerOf2())
4813           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4814               << Arg->getSourceRange();
4815 
4816         if (I > Sema::MaximumAlignment)
4817           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4818               << Arg->getSourceRange() << Sema::MaximumAlignment;
4819       }
4820     }
4821   }
4822 
4823   if (FD)
4824     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4825 }
4826 
4827 /// CheckConstructorCall - Check a constructor call for correctness and safety
4828 /// properties not enforced by the C type system.
4829 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4830                                 ArrayRef<const Expr *> Args,
4831                                 const FunctionProtoType *Proto,
4832                                 SourceLocation Loc) {
4833   VariadicCallType CallType =
4834       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4835 
4836   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4837   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4838                     Context.getPointerType(Ctor->getThisObjectType()));
4839 
4840   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4841             Loc, SourceRange(), CallType);
4842 }
4843 
4844 /// CheckFunctionCall - Check a direct function call for various correctness
4845 /// and safety properties not strictly enforced by the C type system.
4846 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4847                              const FunctionProtoType *Proto) {
4848   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4849                               isa<CXXMethodDecl>(FDecl);
4850   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4851                           IsMemberOperatorCall;
4852   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4853                                                   TheCall->getCallee());
4854   Expr** Args = TheCall->getArgs();
4855   unsigned NumArgs = TheCall->getNumArgs();
4856 
4857   Expr *ImplicitThis = nullptr;
4858   if (IsMemberOperatorCall) {
4859     // If this is a call to a member operator, hide the first argument
4860     // from checkCall.
4861     // FIXME: Our choice of AST representation here is less than ideal.
4862     ImplicitThis = Args[0];
4863     ++Args;
4864     --NumArgs;
4865   } else if (IsMemberFunction)
4866     ImplicitThis =
4867         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4868 
4869   if (ImplicitThis) {
4870     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4871     // used.
4872     QualType ThisType = ImplicitThis->getType();
4873     if (!ThisType->isPointerType()) {
4874       assert(!ThisType->isReferenceType());
4875       ThisType = Context.getPointerType(ThisType);
4876     }
4877 
4878     QualType ThisTypeFromDecl =
4879         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4880 
4881     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4882                       ThisTypeFromDecl);
4883   }
4884 
4885   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4886             IsMemberFunction, TheCall->getRParenLoc(),
4887             TheCall->getCallee()->getSourceRange(), CallType);
4888 
4889   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4890   // None of the checks below are needed for functions that don't have
4891   // simple names (e.g., C++ conversion functions).
4892   if (!FnInfo)
4893     return false;
4894 
4895   CheckTCBEnforcement(TheCall, FDecl);
4896 
4897   CheckAbsoluteValueFunction(TheCall, FDecl);
4898   CheckMaxUnsignedZero(TheCall, FDecl);
4899 
4900   if (getLangOpts().ObjC)
4901     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4902 
4903   unsigned CMId = FDecl->getMemoryFunctionKind();
4904 
4905   // Handle memory setting and copying functions.
4906   switch (CMId) {
4907   case 0:
4908     return false;
4909   case Builtin::BIstrlcpy: // fallthrough
4910   case Builtin::BIstrlcat:
4911     CheckStrlcpycatArguments(TheCall, FnInfo);
4912     break;
4913   case Builtin::BIstrncat:
4914     CheckStrncatArguments(TheCall, FnInfo);
4915     break;
4916   case Builtin::BIfree:
4917     CheckFreeArguments(TheCall);
4918     break;
4919   default:
4920     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4921   }
4922 
4923   return false;
4924 }
4925 
4926 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4927                                ArrayRef<const Expr *> Args) {
4928   VariadicCallType CallType =
4929       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4930 
4931   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4932             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4933             CallType);
4934 
4935   return false;
4936 }
4937 
4938 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4939                             const FunctionProtoType *Proto) {
4940   QualType Ty;
4941   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4942     Ty = V->getType().getNonReferenceType();
4943   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4944     Ty = F->getType().getNonReferenceType();
4945   else
4946     return false;
4947 
4948   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4949       !Ty->isFunctionProtoType())
4950     return false;
4951 
4952   VariadicCallType CallType;
4953   if (!Proto || !Proto->isVariadic()) {
4954     CallType = VariadicDoesNotApply;
4955   } else if (Ty->isBlockPointerType()) {
4956     CallType = VariadicBlock;
4957   } else { // Ty->isFunctionPointerType()
4958     CallType = VariadicFunction;
4959   }
4960 
4961   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4962             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4963             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4964             TheCall->getCallee()->getSourceRange(), CallType);
4965 
4966   return false;
4967 }
4968 
4969 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4970 /// such as function pointers returned from functions.
4971 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4972   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4973                                                   TheCall->getCallee());
4974   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4975             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4976             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4977             TheCall->getCallee()->getSourceRange(), CallType);
4978 
4979   return false;
4980 }
4981 
4982 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4983   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4984     return false;
4985 
4986   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4987   switch (Op) {
4988   case AtomicExpr::AO__c11_atomic_init:
4989   case AtomicExpr::AO__opencl_atomic_init:
4990     llvm_unreachable("There is no ordering argument for an init");
4991 
4992   case AtomicExpr::AO__c11_atomic_load:
4993   case AtomicExpr::AO__opencl_atomic_load:
4994   case AtomicExpr::AO__atomic_load_n:
4995   case AtomicExpr::AO__atomic_load:
4996     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4997            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4998 
4999   case AtomicExpr::AO__c11_atomic_store:
5000   case AtomicExpr::AO__opencl_atomic_store:
5001   case AtomicExpr::AO__atomic_store:
5002   case AtomicExpr::AO__atomic_store_n:
5003     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5004            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5005            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5006 
5007   default:
5008     return true;
5009   }
5010 }
5011 
5012 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5013                                          AtomicExpr::AtomicOp Op) {
5014   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5015   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5016   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5017   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5018                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5019                          Op);
5020 }
5021 
5022 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5023                                  SourceLocation RParenLoc, MultiExprArg Args,
5024                                  AtomicExpr::AtomicOp Op,
5025                                  AtomicArgumentOrder ArgOrder) {
5026   // All the non-OpenCL operations take one of the following forms.
5027   // The OpenCL operations take the __c11 forms with one extra argument for
5028   // synchronization scope.
5029   enum {
5030     // C    __c11_atomic_init(A *, C)
5031     Init,
5032 
5033     // C    __c11_atomic_load(A *, int)
5034     Load,
5035 
5036     // void __atomic_load(A *, CP, int)
5037     LoadCopy,
5038 
5039     // void __atomic_store(A *, CP, int)
5040     Copy,
5041 
5042     // C    __c11_atomic_add(A *, M, int)
5043     Arithmetic,
5044 
5045     // C    __atomic_exchange_n(A *, CP, int)
5046     Xchg,
5047 
5048     // void __atomic_exchange(A *, C *, CP, int)
5049     GNUXchg,
5050 
5051     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5052     C11CmpXchg,
5053 
5054     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5055     GNUCmpXchg
5056   } Form = Init;
5057 
5058   const unsigned NumForm = GNUCmpXchg + 1;
5059   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5060   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5061   // where:
5062   //   C is an appropriate type,
5063   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5064   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5065   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5066   //   the int parameters are for orderings.
5067 
5068   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5069       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5070       "need to update code for modified forms");
5071   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5072                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5073                         AtomicExpr::AO__atomic_load,
5074                 "need to update code for modified C11 atomics");
5075   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5076                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5077   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5078                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5079                IsOpenCL;
5080   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5081              Op == AtomicExpr::AO__atomic_store_n ||
5082              Op == AtomicExpr::AO__atomic_exchange_n ||
5083              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5084   bool IsAddSub = false;
5085 
5086   switch (Op) {
5087   case AtomicExpr::AO__c11_atomic_init:
5088   case AtomicExpr::AO__opencl_atomic_init:
5089     Form = Init;
5090     break;
5091 
5092   case AtomicExpr::AO__c11_atomic_load:
5093   case AtomicExpr::AO__opencl_atomic_load:
5094   case AtomicExpr::AO__atomic_load_n:
5095     Form = Load;
5096     break;
5097 
5098   case AtomicExpr::AO__atomic_load:
5099     Form = LoadCopy;
5100     break;
5101 
5102   case AtomicExpr::AO__c11_atomic_store:
5103   case AtomicExpr::AO__opencl_atomic_store:
5104   case AtomicExpr::AO__atomic_store:
5105   case AtomicExpr::AO__atomic_store_n:
5106     Form = Copy;
5107     break;
5108 
5109   case AtomicExpr::AO__c11_atomic_fetch_add:
5110   case AtomicExpr::AO__c11_atomic_fetch_sub:
5111   case AtomicExpr::AO__opencl_atomic_fetch_add:
5112   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5113   case AtomicExpr::AO__atomic_fetch_add:
5114   case AtomicExpr::AO__atomic_fetch_sub:
5115   case AtomicExpr::AO__atomic_add_fetch:
5116   case AtomicExpr::AO__atomic_sub_fetch:
5117     IsAddSub = true;
5118     Form = Arithmetic;
5119     break;
5120   case AtomicExpr::AO__c11_atomic_fetch_and:
5121   case AtomicExpr::AO__c11_atomic_fetch_or:
5122   case AtomicExpr::AO__c11_atomic_fetch_xor:
5123   case AtomicExpr::AO__opencl_atomic_fetch_and:
5124   case AtomicExpr::AO__opencl_atomic_fetch_or:
5125   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5126   case AtomicExpr::AO__atomic_fetch_and:
5127   case AtomicExpr::AO__atomic_fetch_or:
5128   case AtomicExpr::AO__atomic_fetch_xor:
5129   case AtomicExpr::AO__atomic_fetch_nand:
5130   case AtomicExpr::AO__atomic_and_fetch:
5131   case AtomicExpr::AO__atomic_or_fetch:
5132   case AtomicExpr::AO__atomic_xor_fetch:
5133   case AtomicExpr::AO__atomic_nand_fetch:
5134     Form = Arithmetic;
5135     break;
5136   case AtomicExpr::AO__c11_atomic_fetch_min:
5137   case AtomicExpr::AO__c11_atomic_fetch_max:
5138   case AtomicExpr::AO__opencl_atomic_fetch_min:
5139   case AtomicExpr::AO__opencl_atomic_fetch_max:
5140   case AtomicExpr::AO__atomic_min_fetch:
5141   case AtomicExpr::AO__atomic_max_fetch:
5142   case AtomicExpr::AO__atomic_fetch_min:
5143   case AtomicExpr::AO__atomic_fetch_max:
5144     Form = Arithmetic;
5145     break;
5146 
5147   case AtomicExpr::AO__c11_atomic_exchange:
5148   case AtomicExpr::AO__opencl_atomic_exchange:
5149   case AtomicExpr::AO__atomic_exchange_n:
5150     Form = Xchg;
5151     break;
5152 
5153   case AtomicExpr::AO__atomic_exchange:
5154     Form = GNUXchg;
5155     break;
5156 
5157   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5158   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5159   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5160   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5161     Form = C11CmpXchg;
5162     break;
5163 
5164   case AtomicExpr::AO__atomic_compare_exchange:
5165   case AtomicExpr::AO__atomic_compare_exchange_n:
5166     Form = GNUCmpXchg;
5167     break;
5168   }
5169 
5170   unsigned AdjustedNumArgs = NumArgs[Form];
5171   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5172     ++AdjustedNumArgs;
5173   // Check we have the right number of arguments.
5174   if (Args.size() < AdjustedNumArgs) {
5175     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5176         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5177         << ExprRange;
5178     return ExprError();
5179   } else if (Args.size() > AdjustedNumArgs) {
5180     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5181          diag::err_typecheck_call_too_many_args)
5182         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5183         << ExprRange;
5184     return ExprError();
5185   }
5186 
5187   // Inspect the first argument of the atomic operation.
5188   Expr *Ptr = Args[0];
5189   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5190   if (ConvertedPtr.isInvalid())
5191     return ExprError();
5192 
5193   Ptr = ConvertedPtr.get();
5194   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5195   if (!pointerType) {
5196     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5197         << Ptr->getType() << Ptr->getSourceRange();
5198     return ExprError();
5199   }
5200 
5201   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5202   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5203   QualType ValType = AtomTy; // 'C'
5204   if (IsC11) {
5205     if (!AtomTy->isAtomicType()) {
5206       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5207           << Ptr->getType() << Ptr->getSourceRange();
5208       return ExprError();
5209     }
5210     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5211         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5212       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5213           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5214           << Ptr->getSourceRange();
5215       return ExprError();
5216     }
5217     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5218   } else if (Form != Load && Form != LoadCopy) {
5219     if (ValType.isConstQualified()) {
5220       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5221           << Ptr->getType() << Ptr->getSourceRange();
5222       return ExprError();
5223     }
5224   }
5225 
5226   // For an arithmetic operation, the implied arithmetic must be well-formed.
5227   if (Form == Arithmetic) {
5228     // gcc does not enforce these rules for GNU atomics, but we do so for
5229     // sanity.
5230     auto IsAllowedValueType = [&](QualType ValType) {
5231       if (ValType->isIntegerType())
5232         return true;
5233       if (ValType->isPointerType())
5234         return true;
5235       if (!ValType->isFloatingType())
5236         return false;
5237       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5238       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5239           &Context.getTargetInfo().getLongDoubleFormat() ==
5240               &llvm::APFloat::x87DoubleExtended())
5241         return false;
5242       return true;
5243     };
5244     if (IsAddSub && !IsAllowedValueType(ValType)) {
5245       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5246           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5247       return ExprError();
5248     }
5249     if (!IsAddSub && !ValType->isIntegerType()) {
5250       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5251           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5252       return ExprError();
5253     }
5254     if (IsC11 && ValType->isPointerType() &&
5255         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5256                             diag::err_incomplete_type)) {
5257       return ExprError();
5258     }
5259   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5260     // For __atomic_*_n operations, the value type must be a scalar integral or
5261     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5262     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5263         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5264     return ExprError();
5265   }
5266 
5267   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5268       !AtomTy->isScalarType()) {
5269     // For GNU atomics, require a trivially-copyable type. This is not part of
5270     // the GNU atomics specification, but we enforce it for sanity.
5271     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5272         << Ptr->getType() << Ptr->getSourceRange();
5273     return ExprError();
5274   }
5275 
5276   switch (ValType.getObjCLifetime()) {
5277   case Qualifiers::OCL_None:
5278   case Qualifiers::OCL_ExplicitNone:
5279     // okay
5280     break;
5281 
5282   case Qualifiers::OCL_Weak:
5283   case Qualifiers::OCL_Strong:
5284   case Qualifiers::OCL_Autoreleasing:
5285     // FIXME: Can this happen? By this point, ValType should be known
5286     // to be trivially copyable.
5287     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5288         << ValType << Ptr->getSourceRange();
5289     return ExprError();
5290   }
5291 
5292   // All atomic operations have an overload which takes a pointer to a volatile
5293   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5294   // into the result or the other operands. Similarly atomic_load takes a
5295   // pointer to a const 'A'.
5296   ValType.removeLocalVolatile();
5297   ValType.removeLocalConst();
5298   QualType ResultType = ValType;
5299   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5300       Form == Init)
5301     ResultType = Context.VoidTy;
5302   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5303     ResultType = Context.BoolTy;
5304 
5305   // The type of a parameter passed 'by value'. In the GNU atomics, such
5306   // arguments are actually passed as pointers.
5307   QualType ByValType = ValType; // 'CP'
5308   bool IsPassedByAddress = false;
5309   if (!IsC11 && !IsN) {
5310     ByValType = Ptr->getType();
5311     IsPassedByAddress = true;
5312   }
5313 
5314   SmallVector<Expr *, 5> APIOrderedArgs;
5315   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5316     APIOrderedArgs.push_back(Args[0]);
5317     switch (Form) {
5318     case Init:
5319     case Load:
5320       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5321       break;
5322     case LoadCopy:
5323     case Copy:
5324     case Arithmetic:
5325     case Xchg:
5326       APIOrderedArgs.push_back(Args[2]); // Val1
5327       APIOrderedArgs.push_back(Args[1]); // Order
5328       break;
5329     case GNUXchg:
5330       APIOrderedArgs.push_back(Args[2]); // Val1
5331       APIOrderedArgs.push_back(Args[3]); // Val2
5332       APIOrderedArgs.push_back(Args[1]); // Order
5333       break;
5334     case C11CmpXchg:
5335       APIOrderedArgs.push_back(Args[2]); // Val1
5336       APIOrderedArgs.push_back(Args[4]); // Val2
5337       APIOrderedArgs.push_back(Args[1]); // Order
5338       APIOrderedArgs.push_back(Args[3]); // OrderFail
5339       break;
5340     case GNUCmpXchg:
5341       APIOrderedArgs.push_back(Args[2]); // Val1
5342       APIOrderedArgs.push_back(Args[4]); // Val2
5343       APIOrderedArgs.push_back(Args[5]); // Weak
5344       APIOrderedArgs.push_back(Args[1]); // Order
5345       APIOrderedArgs.push_back(Args[3]); // OrderFail
5346       break;
5347     }
5348   } else
5349     APIOrderedArgs.append(Args.begin(), Args.end());
5350 
5351   // The first argument's non-CV pointer type is used to deduce the type of
5352   // subsequent arguments, except for:
5353   //  - weak flag (always converted to bool)
5354   //  - memory order (always converted to int)
5355   //  - scope  (always converted to int)
5356   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5357     QualType Ty;
5358     if (i < NumVals[Form] + 1) {
5359       switch (i) {
5360       case 0:
5361         // The first argument is always a pointer. It has a fixed type.
5362         // It is always dereferenced, a nullptr is undefined.
5363         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5364         // Nothing else to do: we already know all we want about this pointer.
5365         continue;
5366       case 1:
5367         // The second argument is the non-atomic operand. For arithmetic, this
5368         // is always passed by value, and for a compare_exchange it is always
5369         // passed by address. For the rest, GNU uses by-address and C11 uses
5370         // by-value.
5371         assert(Form != Load);
5372         if (Form == Arithmetic && ValType->isPointerType())
5373           Ty = Context.getPointerDiffType();
5374         else if (Form == Init || Form == Arithmetic)
5375           Ty = ValType;
5376         else if (Form == Copy || Form == Xchg) {
5377           if (IsPassedByAddress) {
5378             // The value pointer is always dereferenced, a nullptr is undefined.
5379             CheckNonNullArgument(*this, APIOrderedArgs[i],
5380                                  ExprRange.getBegin());
5381           }
5382           Ty = ByValType;
5383         } else {
5384           Expr *ValArg = APIOrderedArgs[i];
5385           // The value pointer is always dereferenced, a nullptr is undefined.
5386           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5387           LangAS AS = LangAS::Default;
5388           // Keep address space of non-atomic pointer type.
5389           if (const PointerType *PtrTy =
5390                   ValArg->getType()->getAs<PointerType>()) {
5391             AS = PtrTy->getPointeeType().getAddressSpace();
5392           }
5393           Ty = Context.getPointerType(
5394               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5395         }
5396         break;
5397       case 2:
5398         // The third argument to compare_exchange / GNU exchange is the desired
5399         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5400         if (IsPassedByAddress)
5401           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5402         Ty = ByValType;
5403         break;
5404       case 3:
5405         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5406         Ty = Context.BoolTy;
5407         break;
5408       }
5409     } else {
5410       // The order(s) and scope are always converted to int.
5411       Ty = Context.IntTy;
5412     }
5413 
5414     InitializedEntity Entity =
5415         InitializedEntity::InitializeParameter(Context, Ty, false);
5416     ExprResult Arg = APIOrderedArgs[i];
5417     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5418     if (Arg.isInvalid())
5419       return true;
5420     APIOrderedArgs[i] = Arg.get();
5421   }
5422 
5423   // Permute the arguments into a 'consistent' order.
5424   SmallVector<Expr*, 5> SubExprs;
5425   SubExprs.push_back(Ptr);
5426   switch (Form) {
5427   case Init:
5428     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5429     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5430     break;
5431   case Load:
5432     SubExprs.push_back(APIOrderedArgs[1]); // Order
5433     break;
5434   case LoadCopy:
5435   case Copy:
5436   case Arithmetic:
5437   case Xchg:
5438     SubExprs.push_back(APIOrderedArgs[2]); // Order
5439     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5440     break;
5441   case GNUXchg:
5442     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5443     SubExprs.push_back(APIOrderedArgs[3]); // Order
5444     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5445     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5446     break;
5447   case C11CmpXchg:
5448     SubExprs.push_back(APIOrderedArgs[3]); // Order
5449     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5450     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5451     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5452     break;
5453   case GNUCmpXchg:
5454     SubExprs.push_back(APIOrderedArgs[4]); // Order
5455     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5456     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5457     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5458     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5459     break;
5460   }
5461 
5462   if (SubExprs.size() >= 2 && Form != Init) {
5463     if (Optional<llvm::APSInt> Result =
5464             SubExprs[1]->getIntegerConstantExpr(Context))
5465       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5466         Diag(SubExprs[1]->getBeginLoc(),
5467              diag::warn_atomic_op_has_invalid_memory_order)
5468             << SubExprs[1]->getSourceRange();
5469   }
5470 
5471   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5472     auto *Scope = Args[Args.size() - 1];
5473     if (Optional<llvm::APSInt> Result =
5474             Scope->getIntegerConstantExpr(Context)) {
5475       if (!ScopeModel->isValid(Result->getZExtValue()))
5476         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5477             << Scope->getSourceRange();
5478     }
5479     SubExprs.push_back(Scope);
5480   }
5481 
5482   AtomicExpr *AE = new (Context)
5483       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5484 
5485   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5486        Op == AtomicExpr::AO__c11_atomic_store ||
5487        Op == AtomicExpr::AO__opencl_atomic_load ||
5488        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5489       Context.AtomicUsesUnsupportedLibcall(AE))
5490     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5491         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5492              Op == AtomicExpr::AO__opencl_atomic_load)
5493                 ? 0
5494                 : 1);
5495 
5496   if (ValType->isExtIntType()) {
5497     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5498     return ExprError();
5499   }
5500 
5501   return AE;
5502 }
5503 
5504 /// checkBuiltinArgument - Given a call to a builtin function, perform
5505 /// normal type-checking on the given argument, updating the call in
5506 /// place.  This is useful when a builtin function requires custom
5507 /// type-checking for some of its arguments but not necessarily all of
5508 /// them.
5509 ///
5510 /// Returns true on error.
5511 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5512   FunctionDecl *Fn = E->getDirectCallee();
5513   assert(Fn && "builtin call without direct callee!");
5514 
5515   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5516   InitializedEntity Entity =
5517     InitializedEntity::InitializeParameter(S.Context, Param);
5518 
5519   ExprResult Arg = E->getArg(0);
5520   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5521   if (Arg.isInvalid())
5522     return true;
5523 
5524   E->setArg(ArgIndex, Arg.get());
5525   return false;
5526 }
5527 
5528 /// We have a call to a function like __sync_fetch_and_add, which is an
5529 /// overloaded function based on the pointer type of its first argument.
5530 /// The main BuildCallExpr routines have already promoted the types of
5531 /// arguments because all of these calls are prototyped as void(...).
5532 ///
5533 /// This function goes through and does final semantic checking for these
5534 /// builtins, as well as generating any warnings.
5535 ExprResult
5536 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5537   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5538   Expr *Callee = TheCall->getCallee();
5539   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5540   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5541 
5542   // Ensure that we have at least one argument to do type inference from.
5543   if (TheCall->getNumArgs() < 1) {
5544     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5545         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5546     return ExprError();
5547   }
5548 
5549   // Inspect the first argument of the atomic builtin.  This should always be
5550   // a pointer type, whose element is an integral scalar or pointer type.
5551   // Because it is a pointer type, we don't have to worry about any implicit
5552   // casts here.
5553   // FIXME: We don't allow floating point scalars as input.
5554   Expr *FirstArg = TheCall->getArg(0);
5555   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5556   if (FirstArgResult.isInvalid())
5557     return ExprError();
5558   FirstArg = FirstArgResult.get();
5559   TheCall->setArg(0, FirstArg);
5560 
5561   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5562   if (!pointerType) {
5563     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5564         << FirstArg->getType() << FirstArg->getSourceRange();
5565     return ExprError();
5566   }
5567 
5568   QualType ValType = pointerType->getPointeeType();
5569   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5570       !ValType->isBlockPointerType()) {
5571     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5572         << FirstArg->getType() << FirstArg->getSourceRange();
5573     return ExprError();
5574   }
5575 
5576   if (ValType.isConstQualified()) {
5577     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5578         << FirstArg->getType() << FirstArg->getSourceRange();
5579     return ExprError();
5580   }
5581 
5582   switch (ValType.getObjCLifetime()) {
5583   case Qualifiers::OCL_None:
5584   case Qualifiers::OCL_ExplicitNone:
5585     // okay
5586     break;
5587 
5588   case Qualifiers::OCL_Weak:
5589   case Qualifiers::OCL_Strong:
5590   case Qualifiers::OCL_Autoreleasing:
5591     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5592         << ValType << FirstArg->getSourceRange();
5593     return ExprError();
5594   }
5595 
5596   // Strip any qualifiers off ValType.
5597   ValType = ValType.getUnqualifiedType();
5598 
5599   // The majority of builtins return a value, but a few have special return
5600   // types, so allow them to override appropriately below.
5601   QualType ResultType = ValType;
5602 
5603   // We need to figure out which concrete builtin this maps onto.  For example,
5604   // __sync_fetch_and_add with a 2 byte object turns into
5605   // __sync_fetch_and_add_2.
5606 #define BUILTIN_ROW(x) \
5607   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5608     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5609 
5610   static const unsigned BuiltinIndices[][5] = {
5611     BUILTIN_ROW(__sync_fetch_and_add),
5612     BUILTIN_ROW(__sync_fetch_and_sub),
5613     BUILTIN_ROW(__sync_fetch_and_or),
5614     BUILTIN_ROW(__sync_fetch_and_and),
5615     BUILTIN_ROW(__sync_fetch_and_xor),
5616     BUILTIN_ROW(__sync_fetch_and_nand),
5617 
5618     BUILTIN_ROW(__sync_add_and_fetch),
5619     BUILTIN_ROW(__sync_sub_and_fetch),
5620     BUILTIN_ROW(__sync_and_and_fetch),
5621     BUILTIN_ROW(__sync_or_and_fetch),
5622     BUILTIN_ROW(__sync_xor_and_fetch),
5623     BUILTIN_ROW(__sync_nand_and_fetch),
5624 
5625     BUILTIN_ROW(__sync_val_compare_and_swap),
5626     BUILTIN_ROW(__sync_bool_compare_and_swap),
5627     BUILTIN_ROW(__sync_lock_test_and_set),
5628     BUILTIN_ROW(__sync_lock_release),
5629     BUILTIN_ROW(__sync_swap)
5630   };
5631 #undef BUILTIN_ROW
5632 
5633   // Determine the index of the size.
5634   unsigned SizeIndex;
5635   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5636   case 1: SizeIndex = 0; break;
5637   case 2: SizeIndex = 1; break;
5638   case 4: SizeIndex = 2; break;
5639   case 8: SizeIndex = 3; break;
5640   case 16: SizeIndex = 4; break;
5641   default:
5642     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5643         << FirstArg->getType() << FirstArg->getSourceRange();
5644     return ExprError();
5645   }
5646 
5647   // Each of these builtins has one pointer argument, followed by some number of
5648   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5649   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5650   // as the number of fixed args.
5651   unsigned BuiltinID = FDecl->getBuiltinID();
5652   unsigned BuiltinIndex, NumFixed = 1;
5653   bool WarnAboutSemanticsChange = false;
5654   switch (BuiltinID) {
5655   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5656   case Builtin::BI__sync_fetch_and_add:
5657   case Builtin::BI__sync_fetch_and_add_1:
5658   case Builtin::BI__sync_fetch_and_add_2:
5659   case Builtin::BI__sync_fetch_and_add_4:
5660   case Builtin::BI__sync_fetch_and_add_8:
5661   case Builtin::BI__sync_fetch_and_add_16:
5662     BuiltinIndex = 0;
5663     break;
5664 
5665   case Builtin::BI__sync_fetch_and_sub:
5666   case Builtin::BI__sync_fetch_and_sub_1:
5667   case Builtin::BI__sync_fetch_and_sub_2:
5668   case Builtin::BI__sync_fetch_and_sub_4:
5669   case Builtin::BI__sync_fetch_and_sub_8:
5670   case Builtin::BI__sync_fetch_and_sub_16:
5671     BuiltinIndex = 1;
5672     break;
5673 
5674   case Builtin::BI__sync_fetch_and_or:
5675   case Builtin::BI__sync_fetch_and_or_1:
5676   case Builtin::BI__sync_fetch_and_or_2:
5677   case Builtin::BI__sync_fetch_and_or_4:
5678   case Builtin::BI__sync_fetch_and_or_8:
5679   case Builtin::BI__sync_fetch_and_or_16:
5680     BuiltinIndex = 2;
5681     break;
5682 
5683   case Builtin::BI__sync_fetch_and_and:
5684   case Builtin::BI__sync_fetch_and_and_1:
5685   case Builtin::BI__sync_fetch_and_and_2:
5686   case Builtin::BI__sync_fetch_and_and_4:
5687   case Builtin::BI__sync_fetch_and_and_8:
5688   case Builtin::BI__sync_fetch_and_and_16:
5689     BuiltinIndex = 3;
5690     break;
5691 
5692   case Builtin::BI__sync_fetch_and_xor:
5693   case Builtin::BI__sync_fetch_and_xor_1:
5694   case Builtin::BI__sync_fetch_and_xor_2:
5695   case Builtin::BI__sync_fetch_and_xor_4:
5696   case Builtin::BI__sync_fetch_and_xor_8:
5697   case Builtin::BI__sync_fetch_and_xor_16:
5698     BuiltinIndex = 4;
5699     break;
5700 
5701   case Builtin::BI__sync_fetch_and_nand:
5702   case Builtin::BI__sync_fetch_and_nand_1:
5703   case Builtin::BI__sync_fetch_and_nand_2:
5704   case Builtin::BI__sync_fetch_and_nand_4:
5705   case Builtin::BI__sync_fetch_and_nand_8:
5706   case Builtin::BI__sync_fetch_and_nand_16:
5707     BuiltinIndex = 5;
5708     WarnAboutSemanticsChange = true;
5709     break;
5710 
5711   case Builtin::BI__sync_add_and_fetch:
5712   case Builtin::BI__sync_add_and_fetch_1:
5713   case Builtin::BI__sync_add_and_fetch_2:
5714   case Builtin::BI__sync_add_and_fetch_4:
5715   case Builtin::BI__sync_add_and_fetch_8:
5716   case Builtin::BI__sync_add_and_fetch_16:
5717     BuiltinIndex = 6;
5718     break;
5719 
5720   case Builtin::BI__sync_sub_and_fetch:
5721   case Builtin::BI__sync_sub_and_fetch_1:
5722   case Builtin::BI__sync_sub_and_fetch_2:
5723   case Builtin::BI__sync_sub_and_fetch_4:
5724   case Builtin::BI__sync_sub_and_fetch_8:
5725   case Builtin::BI__sync_sub_and_fetch_16:
5726     BuiltinIndex = 7;
5727     break;
5728 
5729   case Builtin::BI__sync_and_and_fetch:
5730   case Builtin::BI__sync_and_and_fetch_1:
5731   case Builtin::BI__sync_and_and_fetch_2:
5732   case Builtin::BI__sync_and_and_fetch_4:
5733   case Builtin::BI__sync_and_and_fetch_8:
5734   case Builtin::BI__sync_and_and_fetch_16:
5735     BuiltinIndex = 8;
5736     break;
5737 
5738   case Builtin::BI__sync_or_and_fetch:
5739   case Builtin::BI__sync_or_and_fetch_1:
5740   case Builtin::BI__sync_or_and_fetch_2:
5741   case Builtin::BI__sync_or_and_fetch_4:
5742   case Builtin::BI__sync_or_and_fetch_8:
5743   case Builtin::BI__sync_or_and_fetch_16:
5744     BuiltinIndex = 9;
5745     break;
5746 
5747   case Builtin::BI__sync_xor_and_fetch:
5748   case Builtin::BI__sync_xor_and_fetch_1:
5749   case Builtin::BI__sync_xor_and_fetch_2:
5750   case Builtin::BI__sync_xor_and_fetch_4:
5751   case Builtin::BI__sync_xor_and_fetch_8:
5752   case Builtin::BI__sync_xor_and_fetch_16:
5753     BuiltinIndex = 10;
5754     break;
5755 
5756   case Builtin::BI__sync_nand_and_fetch:
5757   case Builtin::BI__sync_nand_and_fetch_1:
5758   case Builtin::BI__sync_nand_and_fetch_2:
5759   case Builtin::BI__sync_nand_and_fetch_4:
5760   case Builtin::BI__sync_nand_and_fetch_8:
5761   case Builtin::BI__sync_nand_and_fetch_16:
5762     BuiltinIndex = 11;
5763     WarnAboutSemanticsChange = true;
5764     break;
5765 
5766   case Builtin::BI__sync_val_compare_and_swap:
5767   case Builtin::BI__sync_val_compare_and_swap_1:
5768   case Builtin::BI__sync_val_compare_and_swap_2:
5769   case Builtin::BI__sync_val_compare_and_swap_4:
5770   case Builtin::BI__sync_val_compare_and_swap_8:
5771   case Builtin::BI__sync_val_compare_and_swap_16:
5772     BuiltinIndex = 12;
5773     NumFixed = 2;
5774     break;
5775 
5776   case Builtin::BI__sync_bool_compare_and_swap:
5777   case Builtin::BI__sync_bool_compare_and_swap_1:
5778   case Builtin::BI__sync_bool_compare_and_swap_2:
5779   case Builtin::BI__sync_bool_compare_and_swap_4:
5780   case Builtin::BI__sync_bool_compare_and_swap_8:
5781   case Builtin::BI__sync_bool_compare_and_swap_16:
5782     BuiltinIndex = 13;
5783     NumFixed = 2;
5784     ResultType = Context.BoolTy;
5785     break;
5786 
5787   case Builtin::BI__sync_lock_test_and_set:
5788   case Builtin::BI__sync_lock_test_and_set_1:
5789   case Builtin::BI__sync_lock_test_and_set_2:
5790   case Builtin::BI__sync_lock_test_and_set_4:
5791   case Builtin::BI__sync_lock_test_and_set_8:
5792   case Builtin::BI__sync_lock_test_and_set_16:
5793     BuiltinIndex = 14;
5794     break;
5795 
5796   case Builtin::BI__sync_lock_release:
5797   case Builtin::BI__sync_lock_release_1:
5798   case Builtin::BI__sync_lock_release_2:
5799   case Builtin::BI__sync_lock_release_4:
5800   case Builtin::BI__sync_lock_release_8:
5801   case Builtin::BI__sync_lock_release_16:
5802     BuiltinIndex = 15;
5803     NumFixed = 0;
5804     ResultType = Context.VoidTy;
5805     break;
5806 
5807   case Builtin::BI__sync_swap:
5808   case Builtin::BI__sync_swap_1:
5809   case Builtin::BI__sync_swap_2:
5810   case Builtin::BI__sync_swap_4:
5811   case Builtin::BI__sync_swap_8:
5812   case Builtin::BI__sync_swap_16:
5813     BuiltinIndex = 16;
5814     break;
5815   }
5816 
5817   // Now that we know how many fixed arguments we expect, first check that we
5818   // have at least that many.
5819   if (TheCall->getNumArgs() < 1+NumFixed) {
5820     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5821         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5822         << Callee->getSourceRange();
5823     return ExprError();
5824   }
5825 
5826   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5827       << Callee->getSourceRange();
5828 
5829   if (WarnAboutSemanticsChange) {
5830     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5831         << Callee->getSourceRange();
5832   }
5833 
5834   // Get the decl for the concrete builtin from this, we can tell what the
5835   // concrete integer type we should convert to is.
5836   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5837   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5838   FunctionDecl *NewBuiltinDecl;
5839   if (NewBuiltinID == BuiltinID)
5840     NewBuiltinDecl = FDecl;
5841   else {
5842     // Perform builtin lookup to avoid redeclaring it.
5843     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5844     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5845     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5846     assert(Res.getFoundDecl());
5847     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5848     if (!NewBuiltinDecl)
5849       return ExprError();
5850   }
5851 
5852   // The first argument --- the pointer --- has a fixed type; we
5853   // deduce the types of the rest of the arguments accordingly.  Walk
5854   // the remaining arguments, converting them to the deduced value type.
5855   for (unsigned i = 0; i != NumFixed; ++i) {
5856     ExprResult Arg = TheCall->getArg(i+1);
5857 
5858     // GCC does an implicit conversion to the pointer or integer ValType.  This
5859     // can fail in some cases (1i -> int**), check for this error case now.
5860     // Initialize the argument.
5861     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5862                                                    ValType, /*consume*/ false);
5863     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5864     if (Arg.isInvalid())
5865       return ExprError();
5866 
5867     // Okay, we have something that *can* be converted to the right type.  Check
5868     // to see if there is a potentially weird extension going on here.  This can
5869     // happen when you do an atomic operation on something like an char* and
5870     // pass in 42.  The 42 gets converted to char.  This is even more strange
5871     // for things like 45.123 -> char, etc.
5872     // FIXME: Do this check.
5873     TheCall->setArg(i+1, Arg.get());
5874   }
5875 
5876   // Create a new DeclRefExpr to refer to the new decl.
5877   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5878       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5879       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5880       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5881 
5882   // Set the callee in the CallExpr.
5883   // FIXME: This loses syntactic information.
5884   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5885   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5886                                               CK_BuiltinFnToFnPtr);
5887   TheCall->setCallee(PromotedCall.get());
5888 
5889   // Change the result type of the call to match the original value type. This
5890   // is arbitrary, but the codegen for these builtins ins design to handle it
5891   // gracefully.
5892   TheCall->setType(ResultType);
5893 
5894   // Prohibit use of _ExtInt with atomic builtins.
5895   // The arguments would have already been converted to the first argument's
5896   // type, so only need to check the first argument.
5897   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5898   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5899     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5900     return ExprError();
5901   }
5902 
5903   return TheCallResult;
5904 }
5905 
5906 /// SemaBuiltinNontemporalOverloaded - We have a call to
5907 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5908 /// overloaded function based on the pointer type of its last argument.
5909 ///
5910 /// This function goes through and does final semantic checking for these
5911 /// builtins.
5912 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5913   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5914   DeclRefExpr *DRE =
5915       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5916   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5917   unsigned BuiltinID = FDecl->getBuiltinID();
5918   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5919           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5920          "Unexpected nontemporal load/store builtin!");
5921   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5922   unsigned numArgs = isStore ? 2 : 1;
5923 
5924   // Ensure that we have the proper number of arguments.
5925   if (checkArgCount(*this, TheCall, numArgs))
5926     return ExprError();
5927 
5928   // Inspect the last argument of the nontemporal builtin.  This should always
5929   // be a pointer type, from which we imply the type of the memory access.
5930   // Because it is a pointer type, we don't have to worry about any implicit
5931   // casts here.
5932   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5933   ExprResult PointerArgResult =
5934       DefaultFunctionArrayLvalueConversion(PointerArg);
5935 
5936   if (PointerArgResult.isInvalid())
5937     return ExprError();
5938   PointerArg = PointerArgResult.get();
5939   TheCall->setArg(numArgs - 1, PointerArg);
5940 
5941   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5942   if (!pointerType) {
5943     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5944         << PointerArg->getType() << PointerArg->getSourceRange();
5945     return ExprError();
5946   }
5947 
5948   QualType ValType = pointerType->getPointeeType();
5949 
5950   // Strip any qualifiers off ValType.
5951   ValType = ValType.getUnqualifiedType();
5952   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5953       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5954       !ValType->isVectorType()) {
5955     Diag(DRE->getBeginLoc(),
5956          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5957         << PointerArg->getType() << PointerArg->getSourceRange();
5958     return ExprError();
5959   }
5960 
5961   if (!isStore) {
5962     TheCall->setType(ValType);
5963     return TheCallResult;
5964   }
5965 
5966   ExprResult ValArg = TheCall->getArg(0);
5967   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5968       Context, ValType, /*consume*/ false);
5969   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5970   if (ValArg.isInvalid())
5971     return ExprError();
5972 
5973   TheCall->setArg(0, ValArg.get());
5974   TheCall->setType(Context.VoidTy);
5975   return TheCallResult;
5976 }
5977 
5978 /// CheckObjCString - Checks that the argument to the builtin
5979 /// CFString constructor is correct
5980 /// Note: It might also make sense to do the UTF-16 conversion here (would
5981 /// simplify the backend).
5982 bool Sema::CheckObjCString(Expr *Arg) {
5983   Arg = Arg->IgnoreParenCasts();
5984   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5985 
5986   if (!Literal || !Literal->isAscii()) {
5987     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5988         << Arg->getSourceRange();
5989     return true;
5990   }
5991 
5992   if (Literal->containsNonAsciiOrNull()) {
5993     StringRef String = Literal->getString();
5994     unsigned NumBytes = String.size();
5995     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5996     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5997     llvm::UTF16 *ToPtr = &ToBuf[0];
5998 
5999     llvm::ConversionResult Result =
6000         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6001                                  ToPtr + NumBytes, llvm::strictConversion);
6002     // Check for conversion failure.
6003     if (Result != llvm::conversionOK)
6004       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6005           << Arg->getSourceRange();
6006   }
6007   return false;
6008 }
6009 
6010 /// CheckObjCString - Checks that the format string argument to the os_log()
6011 /// and os_trace() functions is correct, and converts it to const char *.
6012 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6013   Arg = Arg->IgnoreParenCasts();
6014   auto *Literal = dyn_cast<StringLiteral>(Arg);
6015   if (!Literal) {
6016     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6017       Literal = ObjcLiteral->getString();
6018     }
6019   }
6020 
6021   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6022     return ExprError(
6023         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6024         << Arg->getSourceRange());
6025   }
6026 
6027   ExprResult Result(Literal);
6028   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6029   InitializedEntity Entity =
6030       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6031   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6032   return Result;
6033 }
6034 
6035 /// Check that the user is calling the appropriate va_start builtin for the
6036 /// target and calling convention.
6037 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6038   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6039   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6040   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6041                     TT.getArch() == llvm::Triple::aarch64_32);
6042   bool IsWindows = TT.isOSWindows();
6043   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6044   if (IsX64 || IsAArch64) {
6045     CallingConv CC = CC_C;
6046     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6047       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6048     if (IsMSVAStart) {
6049       // Don't allow this in System V ABI functions.
6050       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6051         return S.Diag(Fn->getBeginLoc(),
6052                       diag::err_ms_va_start_used_in_sysv_function);
6053     } else {
6054       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6055       // On x64 Windows, don't allow this in System V ABI functions.
6056       // (Yes, that means there's no corresponding way to support variadic
6057       // System V ABI functions on Windows.)
6058       if ((IsWindows && CC == CC_X86_64SysV) ||
6059           (!IsWindows && CC == CC_Win64))
6060         return S.Diag(Fn->getBeginLoc(),
6061                       diag::err_va_start_used_in_wrong_abi_function)
6062                << !IsWindows;
6063     }
6064     return false;
6065   }
6066 
6067   if (IsMSVAStart)
6068     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6069   return false;
6070 }
6071 
6072 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6073                                              ParmVarDecl **LastParam = nullptr) {
6074   // Determine whether the current function, block, or obj-c method is variadic
6075   // and get its parameter list.
6076   bool IsVariadic = false;
6077   ArrayRef<ParmVarDecl *> Params;
6078   DeclContext *Caller = S.CurContext;
6079   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6080     IsVariadic = Block->isVariadic();
6081     Params = Block->parameters();
6082   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6083     IsVariadic = FD->isVariadic();
6084     Params = FD->parameters();
6085   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6086     IsVariadic = MD->isVariadic();
6087     // FIXME: This isn't correct for methods (results in bogus warning).
6088     Params = MD->parameters();
6089   } else if (isa<CapturedDecl>(Caller)) {
6090     // We don't support va_start in a CapturedDecl.
6091     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6092     return true;
6093   } else {
6094     // This must be some other declcontext that parses exprs.
6095     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6096     return true;
6097   }
6098 
6099   if (!IsVariadic) {
6100     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6101     return true;
6102   }
6103 
6104   if (LastParam)
6105     *LastParam = Params.empty() ? nullptr : Params.back();
6106 
6107   return false;
6108 }
6109 
6110 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6111 /// for validity.  Emit an error and return true on failure; return false
6112 /// on success.
6113 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6114   Expr *Fn = TheCall->getCallee();
6115 
6116   if (checkVAStartABI(*this, BuiltinID, Fn))
6117     return true;
6118 
6119   if (checkArgCount(*this, TheCall, 2))
6120     return true;
6121 
6122   // Type-check the first argument normally.
6123   if (checkBuiltinArgument(*this, TheCall, 0))
6124     return true;
6125 
6126   // Check that the current function is variadic, and get its last parameter.
6127   ParmVarDecl *LastParam;
6128   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6129     return true;
6130 
6131   // Verify that the second argument to the builtin is the last argument of the
6132   // current function or method.
6133   bool SecondArgIsLastNamedArgument = false;
6134   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6135 
6136   // These are valid if SecondArgIsLastNamedArgument is false after the next
6137   // block.
6138   QualType Type;
6139   SourceLocation ParamLoc;
6140   bool IsCRegister = false;
6141 
6142   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6143     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6144       SecondArgIsLastNamedArgument = PV == LastParam;
6145 
6146       Type = PV->getType();
6147       ParamLoc = PV->getLocation();
6148       IsCRegister =
6149           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6150     }
6151   }
6152 
6153   if (!SecondArgIsLastNamedArgument)
6154     Diag(TheCall->getArg(1)->getBeginLoc(),
6155          diag::warn_second_arg_of_va_start_not_last_named_param);
6156   else if (IsCRegister || Type->isReferenceType() ||
6157            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6158              // Promotable integers are UB, but enumerations need a bit of
6159              // extra checking to see what their promotable type actually is.
6160              if (!Type->isPromotableIntegerType())
6161                return false;
6162              if (!Type->isEnumeralType())
6163                return true;
6164              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6165              return !(ED &&
6166                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6167            }()) {
6168     unsigned Reason = 0;
6169     if (Type->isReferenceType())  Reason = 1;
6170     else if (IsCRegister)         Reason = 2;
6171     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6172     Diag(ParamLoc, diag::note_parameter_type) << Type;
6173   }
6174 
6175   TheCall->setType(Context.VoidTy);
6176   return false;
6177 }
6178 
6179 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6180   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6181   //                 const char *named_addr);
6182 
6183   Expr *Func = Call->getCallee();
6184 
6185   if (Call->getNumArgs() < 3)
6186     return Diag(Call->getEndLoc(),
6187                 diag::err_typecheck_call_too_few_args_at_least)
6188            << 0 /*function call*/ << 3 << Call->getNumArgs();
6189 
6190   // Type-check the first argument normally.
6191   if (checkBuiltinArgument(*this, Call, 0))
6192     return true;
6193 
6194   // Check that the current function is variadic.
6195   if (checkVAStartIsInVariadicFunction(*this, Func))
6196     return true;
6197 
6198   // __va_start on Windows does not validate the parameter qualifiers
6199 
6200   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6201   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6202 
6203   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6204   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6205 
6206   const QualType &ConstCharPtrTy =
6207       Context.getPointerType(Context.CharTy.withConst());
6208   if (!Arg1Ty->isPointerType() ||
6209       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6210     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6211         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6212         << 0                                      /* qualifier difference */
6213         << 3                                      /* parameter mismatch */
6214         << 2 << Arg1->getType() << ConstCharPtrTy;
6215 
6216   const QualType SizeTy = Context.getSizeType();
6217   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6218     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6219         << Arg2->getType() << SizeTy << 1 /* different class */
6220         << 0                              /* qualifier difference */
6221         << 3                              /* parameter mismatch */
6222         << 3 << Arg2->getType() << SizeTy;
6223 
6224   return false;
6225 }
6226 
6227 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6228 /// friends.  This is declared to take (...), so we have to check everything.
6229 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6230   if (checkArgCount(*this, TheCall, 2))
6231     return true;
6232 
6233   ExprResult OrigArg0 = TheCall->getArg(0);
6234   ExprResult OrigArg1 = TheCall->getArg(1);
6235 
6236   // Do standard promotions between the two arguments, returning their common
6237   // type.
6238   QualType Res = UsualArithmeticConversions(
6239       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6240   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6241     return true;
6242 
6243   // Make sure any conversions are pushed back into the call; this is
6244   // type safe since unordered compare builtins are declared as "_Bool
6245   // foo(...)".
6246   TheCall->setArg(0, OrigArg0.get());
6247   TheCall->setArg(1, OrigArg1.get());
6248 
6249   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6250     return false;
6251 
6252   // If the common type isn't a real floating type, then the arguments were
6253   // invalid for this operation.
6254   if (Res.isNull() || !Res->isRealFloatingType())
6255     return Diag(OrigArg0.get()->getBeginLoc(),
6256                 diag::err_typecheck_call_invalid_ordered_compare)
6257            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6258            << SourceRange(OrigArg0.get()->getBeginLoc(),
6259                           OrigArg1.get()->getEndLoc());
6260 
6261   return false;
6262 }
6263 
6264 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6265 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6266 /// to check everything. We expect the last argument to be a floating point
6267 /// value.
6268 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6269   if (checkArgCount(*this, TheCall, NumArgs))
6270     return true;
6271 
6272   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6273   // on all preceding parameters just being int.  Try all of those.
6274   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6275     Expr *Arg = TheCall->getArg(i);
6276 
6277     if (Arg->isTypeDependent())
6278       return false;
6279 
6280     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6281 
6282     if (Res.isInvalid())
6283       return true;
6284     TheCall->setArg(i, Res.get());
6285   }
6286 
6287   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6288 
6289   if (OrigArg->isTypeDependent())
6290     return false;
6291 
6292   // Usual Unary Conversions will convert half to float, which we want for
6293   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6294   // type how it is, but do normal L->Rvalue conversions.
6295   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6296     OrigArg = UsualUnaryConversions(OrigArg).get();
6297   else
6298     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6299   TheCall->setArg(NumArgs - 1, OrigArg);
6300 
6301   // This operation requires a non-_Complex floating-point number.
6302   if (!OrigArg->getType()->isRealFloatingType())
6303     return Diag(OrigArg->getBeginLoc(),
6304                 diag::err_typecheck_call_invalid_unary_fp)
6305            << OrigArg->getType() << OrigArg->getSourceRange();
6306 
6307   return false;
6308 }
6309 
6310 /// Perform semantic analysis for a call to __builtin_complex.
6311 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6312   if (checkArgCount(*this, TheCall, 2))
6313     return true;
6314 
6315   bool Dependent = false;
6316   for (unsigned I = 0; I != 2; ++I) {
6317     Expr *Arg = TheCall->getArg(I);
6318     QualType T = Arg->getType();
6319     if (T->isDependentType()) {
6320       Dependent = true;
6321       continue;
6322     }
6323 
6324     // Despite supporting _Complex int, GCC requires a real floating point type
6325     // for the operands of __builtin_complex.
6326     if (!T->isRealFloatingType()) {
6327       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6328              << Arg->getType() << Arg->getSourceRange();
6329     }
6330 
6331     ExprResult Converted = DefaultLvalueConversion(Arg);
6332     if (Converted.isInvalid())
6333       return true;
6334     TheCall->setArg(I, Converted.get());
6335   }
6336 
6337   if (Dependent) {
6338     TheCall->setType(Context.DependentTy);
6339     return false;
6340   }
6341 
6342   Expr *Real = TheCall->getArg(0);
6343   Expr *Imag = TheCall->getArg(1);
6344   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6345     return Diag(Real->getBeginLoc(),
6346                 diag::err_typecheck_call_different_arg_types)
6347            << Real->getType() << Imag->getType()
6348            << Real->getSourceRange() << Imag->getSourceRange();
6349   }
6350 
6351   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6352   // don't allow this builtin to form those types either.
6353   // FIXME: Should we allow these types?
6354   if (Real->getType()->isFloat16Type())
6355     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6356            << "_Float16";
6357   if (Real->getType()->isHalfType())
6358     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6359            << "half";
6360 
6361   TheCall->setType(Context.getComplexType(Real->getType()));
6362   return false;
6363 }
6364 
6365 // Customized Sema Checking for VSX builtins that have the following signature:
6366 // vector [...] builtinName(vector [...], vector [...], const int);
6367 // Which takes the same type of vectors (any legal vector type) for the first
6368 // two arguments and takes compile time constant for the third argument.
6369 // Example builtins are :
6370 // vector double vec_xxpermdi(vector double, vector double, int);
6371 // vector short vec_xxsldwi(vector short, vector short, int);
6372 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6373   unsigned ExpectedNumArgs = 3;
6374   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6375     return true;
6376 
6377   // Check the third argument is a compile time constant
6378   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6379     return Diag(TheCall->getBeginLoc(),
6380                 diag::err_vsx_builtin_nonconstant_argument)
6381            << 3 /* argument index */ << TheCall->getDirectCallee()
6382            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6383                           TheCall->getArg(2)->getEndLoc());
6384 
6385   QualType Arg1Ty = TheCall->getArg(0)->getType();
6386   QualType Arg2Ty = TheCall->getArg(1)->getType();
6387 
6388   // Check the type of argument 1 and argument 2 are vectors.
6389   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6390   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6391       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6392     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6393            << TheCall->getDirectCallee()
6394            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6395                           TheCall->getArg(1)->getEndLoc());
6396   }
6397 
6398   // Check the first two arguments are the same type.
6399   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6400     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6401            << TheCall->getDirectCallee()
6402            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6403                           TheCall->getArg(1)->getEndLoc());
6404   }
6405 
6406   // When default clang type checking is turned off and the customized type
6407   // checking is used, the returning type of the function must be explicitly
6408   // set. Otherwise it is _Bool by default.
6409   TheCall->setType(Arg1Ty);
6410 
6411   return false;
6412 }
6413 
6414 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6415 // This is declared to take (...), so we have to check everything.
6416 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6417   if (TheCall->getNumArgs() < 2)
6418     return ExprError(Diag(TheCall->getEndLoc(),
6419                           diag::err_typecheck_call_too_few_args_at_least)
6420                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6421                      << TheCall->getSourceRange());
6422 
6423   // Determine which of the following types of shufflevector we're checking:
6424   // 1) unary, vector mask: (lhs, mask)
6425   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6426   QualType resType = TheCall->getArg(0)->getType();
6427   unsigned numElements = 0;
6428 
6429   if (!TheCall->getArg(0)->isTypeDependent() &&
6430       !TheCall->getArg(1)->isTypeDependent()) {
6431     QualType LHSType = TheCall->getArg(0)->getType();
6432     QualType RHSType = TheCall->getArg(1)->getType();
6433 
6434     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6435       return ExprError(
6436           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6437           << TheCall->getDirectCallee()
6438           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6439                          TheCall->getArg(1)->getEndLoc()));
6440 
6441     numElements = LHSType->castAs<VectorType>()->getNumElements();
6442     unsigned numResElements = TheCall->getNumArgs() - 2;
6443 
6444     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6445     // with mask.  If so, verify that RHS is an integer vector type with the
6446     // same number of elts as lhs.
6447     if (TheCall->getNumArgs() == 2) {
6448       if (!RHSType->hasIntegerRepresentation() ||
6449           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6450         return ExprError(Diag(TheCall->getBeginLoc(),
6451                               diag::err_vec_builtin_incompatible_vector)
6452                          << TheCall->getDirectCallee()
6453                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6454                                         TheCall->getArg(1)->getEndLoc()));
6455     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6456       return ExprError(Diag(TheCall->getBeginLoc(),
6457                             diag::err_vec_builtin_incompatible_vector)
6458                        << TheCall->getDirectCallee()
6459                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6460                                       TheCall->getArg(1)->getEndLoc()));
6461     } else if (numElements != numResElements) {
6462       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6463       resType = Context.getVectorType(eltType, numResElements,
6464                                       VectorType::GenericVector);
6465     }
6466   }
6467 
6468   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6469     if (TheCall->getArg(i)->isTypeDependent() ||
6470         TheCall->getArg(i)->isValueDependent())
6471       continue;
6472 
6473     Optional<llvm::APSInt> Result;
6474     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6475       return ExprError(Diag(TheCall->getBeginLoc(),
6476                             diag::err_shufflevector_nonconstant_argument)
6477                        << TheCall->getArg(i)->getSourceRange());
6478 
6479     // Allow -1 which will be translated to undef in the IR.
6480     if (Result->isSigned() && Result->isAllOnesValue())
6481       continue;
6482 
6483     if (Result->getActiveBits() > 64 ||
6484         Result->getZExtValue() >= numElements * 2)
6485       return ExprError(Diag(TheCall->getBeginLoc(),
6486                             diag::err_shufflevector_argument_too_large)
6487                        << TheCall->getArg(i)->getSourceRange());
6488   }
6489 
6490   SmallVector<Expr*, 32> exprs;
6491 
6492   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6493     exprs.push_back(TheCall->getArg(i));
6494     TheCall->setArg(i, nullptr);
6495   }
6496 
6497   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6498                                          TheCall->getCallee()->getBeginLoc(),
6499                                          TheCall->getRParenLoc());
6500 }
6501 
6502 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6503 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6504                                        SourceLocation BuiltinLoc,
6505                                        SourceLocation RParenLoc) {
6506   ExprValueKind VK = VK_PRValue;
6507   ExprObjectKind OK = OK_Ordinary;
6508   QualType DstTy = TInfo->getType();
6509   QualType SrcTy = E->getType();
6510 
6511   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6512     return ExprError(Diag(BuiltinLoc,
6513                           diag::err_convertvector_non_vector)
6514                      << E->getSourceRange());
6515   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6516     return ExprError(Diag(BuiltinLoc,
6517                           diag::err_convertvector_non_vector_type));
6518 
6519   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6520     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6521     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6522     if (SrcElts != DstElts)
6523       return ExprError(Diag(BuiltinLoc,
6524                             diag::err_convertvector_incompatible_vector)
6525                        << E->getSourceRange());
6526   }
6527 
6528   return new (Context)
6529       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6530 }
6531 
6532 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6533 // This is declared to take (const void*, ...) and can take two
6534 // optional constant int args.
6535 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6536   unsigned NumArgs = TheCall->getNumArgs();
6537 
6538   if (NumArgs > 3)
6539     return Diag(TheCall->getEndLoc(),
6540                 diag::err_typecheck_call_too_many_args_at_most)
6541            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6542 
6543   // Argument 0 is checked for us and the remaining arguments must be
6544   // constant integers.
6545   for (unsigned i = 1; i != NumArgs; ++i)
6546     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6547       return true;
6548 
6549   return false;
6550 }
6551 
6552 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6553 // __assume does not evaluate its arguments, and should warn if its argument
6554 // has side effects.
6555 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6556   Expr *Arg = TheCall->getArg(0);
6557   if (Arg->isInstantiationDependent()) return false;
6558 
6559   if (Arg->HasSideEffects(Context))
6560     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6561         << Arg->getSourceRange()
6562         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6563 
6564   return false;
6565 }
6566 
6567 /// Handle __builtin_alloca_with_align. This is declared
6568 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6569 /// than 8.
6570 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6571   // The alignment must be a constant integer.
6572   Expr *Arg = TheCall->getArg(1);
6573 
6574   // We can't check the value of a dependent argument.
6575   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6576     if (const auto *UE =
6577             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6578       if (UE->getKind() == UETT_AlignOf ||
6579           UE->getKind() == UETT_PreferredAlignOf)
6580         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6581             << Arg->getSourceRange();
6582 
6583     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6584 
6585     if (!Result.isPowerOf2())
6586       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6587              << Arg->getSourceRange();
6588 
6589     if (Result < Context.getCharWidth())
6590       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6591              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6592 
6593     if (Result > std::numeric_limits<int32_t>::max())
6594       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6595              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6596   }
6597 
6598   return false;
6599 }
6600 
6601 /// Handle __builtin_assume_aligned. This is declared
6602 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6603 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6604   unsigned NumArgs = TheCall->getNumArgs();
6605 
6606   if (NumArgs > 3)
6607     return Diag(TheCall->getEndLoc(),
6608                 diag::err_typecheck_call_too_many_args_at_most)
6609            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6610 
6611   // The alignment must be a constant integer.
6612   Expr *Arg = TheCall->getArg(1);
6613 
6614   // We can't check the value of a dependent argument.
6615   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6616     llvm::APSInt Result;
6617     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6618       return true;
6619 
6620     if (!Result.isPowerOf2())
6621       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6622              << Arg->getSourceRange();
6623 
6624     if (Result > Sema::MaximumAlignment)
6625       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6626           << Arg->getSourceRange() << Sema::MaximumAlignment;
6627   }
6628 
6629   if (NumArgs > 2) {
6630     ExprResult Arg(TheCall->getArg(2));
6631     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6632       Context.getSizeType(), false);
6633     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6634     if (Arg.isInvalid()) return true;
6635     TheCall->setArg(2, Arg.get());
6636   }
6637 
6638   return false;
6639 }
6640 
6641 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6642   unsigned BuiltinID =
6643       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6644   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6645 
6646   unsigned NumArgs = TheCall->getNumArgs();
6647   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6648   if (NumArgs < NumRequiredArgs) {
6649     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6650            << 0 /* function call */ << NumRequiredArgs << NumArgs
6651            << TheCall->getSourceRange();
6652   }
6653   if (NumArgs >= NumRequiredArgs + 0x100) {
6654     return Diag(TheCall->getEndLoc(),
6655                 diag::err_typecheck_call_too_many_args_at_most)
6656            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6657            << TheCall->getSourceRange();
6658   }
6659   unsigned i = 0;
6660 
6661   // For formatting call, check buffer arg.
6662   if (!IsSizeCall) {
6663     ExprResult Arg(TheCall->getArg(i));
6664     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6665         Context, Context.VoidPtrTy, false);
6666     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6667     if (Arg.isInvalid())
6668       return true;
6669     TheCall->setArg(i, Arg.get());
6670     i++;
6671   }
6672 
6673   // Check string literal arg.
6674   unsigned FormatIdx = i;
6675   {
6676     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6677     if (Arg.isInvalid())
6678       return true;
6679     TheCall->setArg(i, Arg.get());
6680     i++;
6681   }
6682 
6683   // Make sure variadic args are scalar.
6684   unsigned FirstDataArg = i;
6685   while (i < NumArgs) {
6686     ExprResult Arg = DefaultVariadicArgumentPromotion(
6687         TheCall->getArg(i), VariadicFunction, nullptr);
6688     if (Arg.isInvalid())
6689       return true;
6690     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6691     if (ArgSize.getQuantity() >= 0x100) {
6692       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6693              << i << (int)ArgSize.getQuantity() << 0xff
6694              << TheCall->getSourceRange();
6695     }
6696     TheCall->setArg(i, Arg.get());
6697     i++;
6698   }
6699 
6700   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6701   // call to avoid duplicate diagnostics.
6702   if (!IsSizeCall) {
6703     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6704     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6705     bool Success = CheckFormatArguments(
6706         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6707         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6708         CheckedVarArgs);
6709     if (!Success)
6710       return true;
6711   }
6712 
6713   if (IsSizeCall) {
6714     TheCall->setType(Context.getSizeType());
6715   } else {
6716     TheCall->setType(Context.VoidPtrTy);
6717   }
6718   return false;
6719 }
6720 
6721 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6722 /// TheCall is a constant expression.
6723 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6724                                   llvm::APSInt &Result) {
6725   Expr *Arg = TheCall->getArg(ArgNum);
6726   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6727   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6728 
6729   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6730 
6731   Optional<llvm::APSInt> R;
6732   if (!(R = Arg->getIntegerConstantExpr(Context)))
6733     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6734            << FDecl->getDeclName() << Arg->getSourceRange();
6735   Result = *R;
6736   return false;
6737 }
6738 
6739 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6740 /// TheCall is a constant expression in the range [Low, High].
6741 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6742                                        int Low, int High, bool RangeIsError) {
6743   if (isConstantEvaluated())
6744     return false;
6745   llvm::APSInt Result;
6746 
6747   // We can't check the value of a dependent argument.
6748   Expr *Arg = TheCall->getArg(ArgNum);
6749   if (Arg->isTypeDependent() || Arg->isValueDependent())
6750     return false;
6751 
6752   // Check constant-ness first.
6753   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6754     return true;
6755 
6756   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6757     if (RangeIsError)
6758       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6759              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6760     else
6761       // Defer the warning until we know if the code will be emitted so that
6762       // dead code can ignore this.
6763       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6764                           PDiag(diag::warn_argument_invalid_range)
6765                               << toString(Result, 10) << Low << High
6766                               << Arg->getSourceRange());
6767   }
6768 
6769   return false;
6770 }
6771 
6772 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6773 /// TheCall is a constant expression is a multiple of Num..
6774 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6775                                           unsigned Num) {
6776   llvm::APSInt Result;
6777 
6778   // We can't check the value of a dependent argument.
6779   Expr *Arg = TheCall->getArg(ArgNum);
6780   if (Arg->isTypeDependent() || Arg->isValueDependent())
6781     return false;
6782 
6783   // Check constant-ness first.
6784   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6785     return true;
6786 
6787   if (Result.getSExtValue() % Num != 0)
6788     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6789            << Num << Arg->getSourceRange();
6790 
6791   return false;
6792 }
6793 
6794 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6795 /// constant expression representing a power of 2.
6796 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6797   llvm::APSInt Result;
6798 
6799   // We can't check the value of a dependent argument.
6800   Expr *Arg = TheCall->getArg(ArgNum);
6801   if (Arg->isTypeDependent() || Arg->isValueDependent())
6802     return false;
6803 
6804   // Check constant-ness first.
6805   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6806     return true;
6807 
6808   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6809   // and only if x is a power of 2.
6810   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6811     return false;
6812 
6813   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6814          << Arg->getSourceRange();
6815 }
6816 
6817 static bool IsShiftedByte(llvm::APSInt Value) {
6818   if (Value.isNegative())
6819     return false;
6820 
6821   // Check if it's a shifted byte, by shifting it down
6822   while (true) {
6823     // If the value fits in the bottom byte, the check passes.
6824     if (Value < 0x100)
6825       return true;
6826 
6827     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6828     // fails.
6829     if ((Value & 0xFF) != 0)
6830       return false;
6831 
6832     // If the bottom 8 bits are all 0, but something above that is nonzero,
6833     // then shifting the value right by 8 bits won't affect whether it's a
6834     // shifted byte or not. So do that, and go round again.
6835     Value >>= 8;
6836   }
6837 }
6838 
6839 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6840 /// a constant expression representing an arbitrary byte value shifted left by
6841 /// a multiple of 8 bits.
6842 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6843                                              unsigned ArgBits) {
6844   llvm::APSInt Result;
6845 
6846   // We can't check the value of a dependent argument.
6847   Expr *Arg = TheCall->getArg(ArgNum);
6848   if (Arg->isTypeDependent() || Arg->isValueDependent())
6849     return false;
6850 
6851   // Check constant-ness first.
6852   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6853     return true;
6854 
6855   // Truncate to the given size.
6856   Result = Result.getLoBits(ArgBits);
6857   Result.setIsUnsigned(true);
6858 
6859   if (IsShiftedByte(Result))
6860     return false;
6861 
6862   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6863          << Arg->getSourceRange();
6864 }
6865 
6866 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6867 /// TheCall is a constant expression representing either a shifted byte value,
6868 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6869 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6870 /// Arm MVE intrinsics.
6871 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6872                                                    int ArgNum,
6873                                                    unsigned ArgBits) {
6874   llvm::APSInt Result;
6875 
6876   // We can't check the value of a dependent argument.
6877   Expr *Arg = TheCall->getArg(ArgNum);
6878   if (Arg->isTypeDependent() || Arg->isValueDependent())
6879     return false;
6880 
6881   // Check constant-ness first.
6882   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6883     return true;
6884 
6885   // Truncate to the given size.
6886   Result = Result.getLoBits(ArgBits);
6887   Result.setIsUnsigned(true);
6888 
6889   // Check to see if it's in either of the required forms.
6890   if (IsShiftedByte(Result) ||
6891       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6892     return false;
6893 
6894   return Diag(TheCall->getBeginLoc(),
6895               diag::err_argument_not_shifted_byte_or_xxff)
6896          << Arg->getSourceRange();
6897 }
6898 
6899 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6900 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6901   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6902     if (checkArgCount(*this, TheCall, 2))
6903       return true;
6904     Expr *Arg0 = TheCall->getArg(0);
6905     Expr *Arg1 = TheCall->getArg(1);
6906 
6907     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6908     if (FirstArg.isInvalid())
6909       return true;
6910     QualType FirstArgType = FirstArg.get()->getType();
6911     if (!FirstArgType->isAnyPointerType())
6912       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6913                << "first" << FirstArgType << Arg0->getSourceRange();
6914     TheCall->setArg(0, FirstArg.get());
6915 
6916     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6917     if (SecArg.isInvalid())
6918       return true;
6919     QualType SecArgType = SecArg.get()->getType();
6920     if (!SecArgType->isIntegerType())
6921       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6922                << "second" << SecArgType << Arg1->getSourceRange();
6923 
6924     // Derive the return type from the pointer argument.
6925     TheCall->setType(FirstArgType);
6926     return false;
6927   }
6928 
6929   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6930     if (checkArgCount(*this, TheCall, 2))
6931       return true;
6932 
6933     Expr *Arg0 = TheCall->getArg(0);
6934     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6935     if (FirstArg.isInvalid())
6936       return true;
6937     QualType FirstArgType = FirstArg.get()->getType();
6938     if (!FirstArgType->isAnyPointerType())
6939       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6940                << "first" << FirstArgType << Arg0->getSourceRange();
6941     TheCall->setArg(0, FirstArg.get());
6942 
6943     // Derive the return type from the pointer argument.
6944     TheCall->setType(FirstArgType);
6945 
6946     // Second arg must be an constant in range [0,15]
6947     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6948   }
6949 
6950   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6951     if (checkArgCount(*this, TheCall, 2))
6952       return true;
6953     Expr *Arg0 = TheCall->getArg(0);
6954     Expr *Arg1 = TheCall->getArg(1);
6955 
6956     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6957     if (FirstArg.isInvalid())
6958       return true;
6959     QualType FirstArgType = FirstArg.get()->getType();
6960     if (!FirstArgType->isAnyPointerType())
6961       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6962                << "first" << FirstArgType << Arg0->getSourceRange();
6963 
6964     QualType SecArgType = Arg1->getType();
6965     if (!SecArgType->isIntegerType())
6966       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6967                << "second" << SecArgType << Arg1->getSourceRange();
6968     TheCall->setType(Context.IntTy);
6969     return false;
6970   }
6971 
6972   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6973       BuiltinID == AArch64::BI__builtin_arm_stg) {
6974     if (checkArgCount(*this, TheCall, 1))
6975       return true;
6976     Expr *Arg0 = TheCall->getArg(0);
6977     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6978     if (FirstArg.isInvalid())
6979       return true;
6980 
6981     QualType FirstArgType = FirstArg.get()->getType();
6982     if (!FirstArgType->isAnyPointerType())
6983       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6984                << "first" << FirstArgType << Arg0->getSourceRange();
6985     TheCall->setArg(0, FirstArg.get());
6986 
6987     // Derive the return type from the pointer argument.
6988     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6989       TheCall->setType(FirstArgType);
6990     return false;
6991   }
6992 
6993   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6994     Expr *ArgA = TheCall->getArg(0);
6995     Expr *ArgB = TheCall->getArg(1);
6996 
6997     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6998     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6999 
7000     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7001       return true;
7002 
7003     QualType ArgTypeA = ArgExprA.get()->getType();
7004     QualType ArgTypeB = ArgExprB.get()->getType();
7005 
7006     auto isNull = [&] (Expr *E) -> bool {
7007       return E->isNullPointerConstant(
7008                         Context, Expr::NPC_ValueDependentIsNotNull); };
7009 
7010     // argument should be either a pointer or null
7011     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7012       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7013         << "first" << ArgTypeA << ArgA->getSourceRange();
7014 
7015     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7016       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7017         << "second" << ArgTypeB << ArgB->getSourceRange();
7018 
7019     // Ensure Pointee types are compatible
7020     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7021         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7022       QualType pointeeA = ArgTypeA->getPointeeType();
7023       QualType pointeeB = ArgTypeB->getPointeeType();
7024       if (!Context.typesAreCompatible(
7025              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7026              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7027         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7028           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7029           << ArgB->getSourceRange();
7030       }
7031     }
7032 
7033     // at least one argument should be pointer type
7034     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7035       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7036         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7037 
7038     if (isNull(ArgA)) // adopt type of the other pointer
7039       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7040 
7041     if (isNull(ArgB))
7042       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7043 
7044     TheCall->setArg(0, ArgExprA.get());
7045     TheCall->setArg(1, ArgExprB.get());
7046     TheCall->setType(Context.LongLongTy);
7047     return false;
7048   }
7049   assert(false && "Unhandled ARM MTE intrinsic");
7050   return true;
7051 }
7052 
7053 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7054 /// TheCall is an ARM/AArch64 special register string literal.
7055 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7056                                     int ArgNum, unsigned ExpectedFieldNum,
7057                                     bool AllowName) {
7058   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7059                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7060                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7061                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7062                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7063                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7064   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7065                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7066                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7067                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7068                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7069                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7070   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7071 
7072   // We can't check the value of a dependent argument.
7073   Expr *Arg = TheCall->getArg(ArgNum);
7074   if (Arg->isTypeDependent() || Arg->isValueDependent())
7075     return false;
7076 
7077   // Check if the argument is a string literal.
7078   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7079     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7080            << Arg->getSourceRange();
7081 
7082   // Check the type of special register given.
7083   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7084   SmallVector<StringRef, 6> Fields;
7085   Reg.split(Fields, ":");
7086 
7087   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7088     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7089            << Arg->getSourceRange();
7090 
7091   // If the string is the name of a register then we cannot check that it is
7092   // valid here but if the string is of one the forms described in ACLE then we
7093   // can check that the supplied fields are integers and within the valid
7094   // ranges.
7095   if (Fields.size() > 1) {
7096     bool FiveFields = Fields.size() == 5;
7097 
7098     bool ValidString = true;
7099     if (IsARMBuiltin) {
7100       ValidString &= Fields[0].startswith_insensitive("cp") ||
7101                      Fields[0].startswith_insensitive("p");
7102       if (ValidString)
7103         Fields[0] = Fields[0].drop_front(
7104             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7105 
7106       ValidString &= Fields[2].startswith_insensitive("c");
7107       if (ValidString)
7108         Fields[2] = Fields[2].drop_front(1);
7109 
7110       if (FiveFields) {
7111         ValidString &= Fields[3].startswith_insensitive("c");
7112         if (ValidString)
7113           Fields[3] = Fields[3].drop_front(1);
7114       }
7115     }
7116 
7117     SmallVector<int, 5> Ranges;
7118     if (FiveFields)
7119       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7120     else
7121       Ranges.append({15, 7, 15});
7122 
7123     for (unsigned i=0; i<Fields.size(); ++i) {
7124       int IntField;
7125       ValidString &= !Fields[i].getAsInteger(10, IntField);
7126       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7127     }
7128 
7129     if (!ValidString)
7130       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7131              << Arg->getSourceRange();
7132   } else if (IsAArch64Builtin && Fields.size() == 1) {
7133     // If the register name is one of those that appear in the condition below
7134     // and the special register builtin being used is one of the write builtins,
7135     // then we require that the argument provided for writing to the register
7136     // is an integer constant expression. This is because it will be lowered to
7137     // an MSR (immediate) instruction, so we need to know the immediate at
7138     // compile time.
7139     if (TheCall->getNumArgs() != 2)
7140       return false;
7141 
7142     std::string RegLower = Reg.lower();
7143     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7144         RegLower != "pan" && RegLower != "uao")
7145       return false;
7146 
7147     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7148   }
7149 
7150   return false;
7151 }
7152 
7153 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7154 /// Emit an error and return true on failure; return false on success.
7155 /// TypeStr is a string containing the type descriptor of the value returned by
7156 /// the builtin and the descriptors of the expected type of the arguments.
7157 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7158 
7159   assert((TypeStr[0] != '\0') &&
7160          "Invalid types in PPC MMA builtin declaration");
7161 
7162   unsigned Mask = 0;
7163   unsigned ArgNum = 0;
7164 
7165   // The first type in TypeStr is the type of the value returned by the
7166   // builtin. So we first read that type and change the type of TheCall.
7167   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7168   TheCall->setType(type);
7169 
7170   while (*TypeStr != '\0') {
7171     Mask = 0;
7172     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7173     if (ArgNum >= TheCall->getNumArgs()) {
7174       ArgNum++;
7175       break;
7176     }
7177 
7178     Expr *Arg = TheCall->getArg(ArgNum);
7179     QualType ArgType = Arg->getType();
7180 
7181     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7182         (!ExpectedType->isVoidPointerType() &&
7183            ArgType.getCanonicalType() != ExpectedType))
7184       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7185              << ArgType << ExpectedType << 1 << 0 << 0;
7186 
7187     // If the value of the Mask is not 0, we have a constraint in the size of
7188     // the integer argument so here we ensure the argument is a constant that
7189     // is in the valid range.
7190     if (Mask != 0 &&
7191         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7192       return true;
7193 
7194     ArgNum++;
7195   }
7196 
7197   // In case we exited early from the previous loop, there are other types to
7198   // read from TypeStr. So we need to read them all to ensure we have the right
7199   // number of arguments in TheCall and if it is not the case, to display a
7200   // better error message.
7201   while (*TypeStr != '\0') {
7202     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7203     ArgNum++;
7204   }
7205   if (checkArgCount(*this, TheCall, ArgNum))
7206     return true;
7207 
7208   return false;
7209 }
7210 
7211 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7212 /// This checks that the target supports __builtin_longjmp and
7213 /// that val is a constant 1.
7214 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7215   if (!Context.getTargetInfo().hasSjLjLowering())
7216     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7217            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7218 
7219   Expr *Arg = TheCall->getArg(1);
7220   llvm::APSInt Result;
7221 
7222   // TODO: This is less than ideal. Overload this to take a value.
7223   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7224     return true;
7225 
7226   if (Result != 1)
7227     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7228            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7229 
7230   return false;
7231 }
7232 
7233 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7234 /// This checks that the target supports __builtin_setjmp.
7235 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7236   if (!Context.getTargetInfo().hasSjLjLowering())
7237     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7238            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7239   return false;
7240 }
7241 
7242 namespace {
7243 
7244 class UncoveredArgHandler {
7245   enum { Unknown = -1, AllCovered = -2 };
7246 
7247   signed FirstUncoveredArg = Unknown;
7248   SmallVector<const Expr *, 4> DiagnosticExprs;
7249 
7250 public:
7251   UncoveredArgHandler() = default;
7252 
7253   bool hasUncoveredArg() const {
7254     return (FirstUncoveredArg >= 0);
7255   }
7256 
7257   unsigned getUncoveredArg() const {
7258     assert(hasUncoveredArg() && "no uncovered argument");
7259     return FirstUncoveredArg;
7260   }
7261 
7262   void setAllCovered() {
7263     // A string has been found with all arguments covered, so clear out
7264     // the diagnostics.
7265     DiagnosticExprs.clear();
7266     FirstUncoveredArg = AllCovered;
7267   }
7268 
7269   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7270     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7271 
7272     // Don't update if a previous string covers all arguments.
7273     if (FirstUncoveredArg == AllCovered)
7274       return;
7275 
7276     // UncoveredArgHandler tracks the highest uncovered argument index
7277     // and with it all the strings that match this index.
7278     if (NewFirstUncoveredArg == FirstUncoveredArg)
7279       DiagnosticExprs.push_back(StrExpr);
7280     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7281       DiagnosticExprs.clear();
7282       DiagnosticExprs.push_back(StrExpr);
7283       FirstUncoveredArg = NewFirstUncoveredArg;
7284     }
7285   }
7286 
7287   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7288 };
7289 
7290 enum StringLiteralCheckType {
7291   SLCT_NotALiteral,
7292   SLCT_UncheckedLiteral,
7293   SLCT_CheckedLiteral
7294 };
7295 
7296 } // namespace
7297 
7298 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7299                                      BinaryOperatorKind BinOpKind,
7300                                      bool AddendIsRight) {
7301   unsigned BitWidth = Offset.getBitWidth();
7302   unsigned AddendBitWidth = Addend.getBitWidth();
7303   // There might be negative interim results.
7304   if (Addend.isUnsigned()) {
7305     Addend = Addend.zext(++AddendBitWidth);
7306     Addend.setIsSigned(true);
7307   }
7308   // Adjust the bit width of the APSInts.
7309   if (AddendBitWidth > BitWidth) {
7310     Offset = Offset.sext(AddendBitWidth);
7311     BitWidth = AddendBitWidth;
7312   } else if (BitWidth > AddendBitWidth) {
7313     Addend = Addend.sext(BitWidth);
7314   }
7315 
7316   bool Ov = false;
7317   llvm::APSInt ResOffset = Offset;
7318   if (BinOpKind == BO_Add)
7319     ResOffset = Offset.sadd_ov(Addend, Ov);
7320   else {
7321     assert(AddendIsRight && BinOpKind == BO_Sub &&
7322            "operator must be add or sub with addend on the right");
7323     ResOffset = Offset.ssub_ov(Addend, Ov);
7324   }
7325 
7326   // We add an offset to a pointer here so we should support an offset as big as
7327   // possible.
7328   if (Ov) {
7329     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7330            "index (intermediate) result too big");
7331     Offset = Offset.sext(2 * BitWidth);
7332     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7333     return;
7334   }
7335 
7336   Offset = ResOffset;
7337 }
7338 
7339 namespace {
7340 
7341 // This is a wrapper class around StringLiteral to support offsetted string
7342 // literals as format strings. It takes the offset into account when returning
7343 // the string and its length or the source locations to display notes correctly.
7344 class FormatStringLiteral {
7345   const StringLiteral *FExpr;
7346   int64_t Offset;
7347 
7348  public:
7349   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7350       : FExpr(fexpr), Offset(Offset) {}
7351 
7352   StringRef getString() const {
7353     return FExpr->getString().drop_front(Offset);
7354   }
7355 
7356   unsigned getByteLength() const {
7357     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7358   }
7359 
7360   unsigned getLength() const { return FExpr->getLength() - Offset; }
7361   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7362 
7363   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7364 
7365   QualType getType() const { return FExpr->getType(); }
7366 
7367   bool isAscii() const { return FExpr->isAscii(); }
7368   bool isWide() const { return FExpr->isWide(); }
7369   bool isUTF8() const { return FExpr->isUTF8(); }
7370   bool isUTF16() const { return FExpr->isUTF16(); }
7371   bool isUTF32() const { return FExpr->isUTF32(); }
7372   bool isPascal() const { return FExpr->isPascal(); }
7373 
7374   SourceLocation getLocationOfByte(
7375       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7376       const TargetInfo &Target, unsigned *StartToken = nullptr,
7377       unsigned *StartTokenByteOffset = nullptr) const {
7378     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7379                                     StartToken, StartTokenByteOffset);
7380   }
7381 
7382   SourceLocation getBeginLoc() const LLVM_READONLY {
7383     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7384   }
7385 
7386   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7387 };
7388 
7389 }  // namespace
7390 
7391 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7392                               const Expr *OrigFormatExpr,
7393                               ArrayRef<const Expr *> Args,
7394                               bool HasVAListArg, unsigned format_idx,
7395                               unsigned firstDataArg,
7396                               Sema::FormatStringType Type,
7397                               bool inFunctionCall,
7398                               Sema::VariadicCallType CallType,
7399                               llvm::SmallBitVector &CheckedVarArgs,
7400                               UncoveredArgHandler &UncoveredArg,
7401                               bool IgnoreStringsWithoutSpecifiers);
7402 
7403 // Determine if an expression is a string literal or constant string.
7404 // If this function returns false on the arguments to a function expecting a
7405 // format string, we will usually need to emit a warning.
7406 // True string literals are then checked by CheckFormatString.
7407 static StringLiteralCheckType
7408 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7409                       bool HasVAListArg, unsigned format_idx,
7410                       unsigned firstDataArg, Sema::FormatStringType Type,
7411                       Sema::VariadicCallType CallType, bool InFunctionCall,
7412                       llvm::SmallBitVector &CheckedVarArgs,
7413                       UncoveredArgHandler &UncoveredArg,
7414                       llvm::APSInt Offset,
7415                       bool IgnoreStringsWithoutSpecifiers = false) {
7416   if (S.isConstantEvaluated())
7417     return SLCT_NotALiteral;
7418  tryAgain:
7419   assert(Offset.isSigned() && "invalid offset");
7420 
7421   if (E->isTypeDependent() || E->isValueDependent())
7422     return SLCT_NotALiteral;
7423 
7424   E = E->IgnoreParenCasts();
7425 
7426   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7427     // Technically -Wformat-nonliteral does not warn about this case.
7428     // The behavior of printf and friends in this case is implementation
7429     // dependent.  Ideally if the format string cannot be null then
7430     // it should have a 'nonnull' attribute in the function prototype.
7431     return SLCT_UncheckedLiteral;
7432 
7433   switch (E->getStmtClass()) {
7434   case Stmt::BinaryConditionalOperatorClass:
7435   case Stmt::ConditionalOperatorClass: {
7436     // The expression is a literal if both sub-expressions were, and it was
7437     // completely checked only if both sub-expressions were checked.
7438     const AbstractConditionalOperator *C =
7439         cast<AbstractConditionalOperator>(E);
7440 
7441     // Determine whether it is necessary to check both sub-expressions, for
7442     // example, because the condition expression is a constant that can be
7443     // evaluated at compile time.
7444     bool CheckLeft = true, CheckRight = true;
7445 
7446     bool Cond;
7447     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7448                                                  S.isConstantEvaluated())) {
7449       if (Cond)
7450         CheckRight = false;
7451       else
7452         CheckLeft = false;
7453     }
7454 
7455     // We need to maintain the offsets for the right and the left hand side
7456     // separately to check if every possible indexed expression is a valid
7457     // string literal. They might have different offsets for different string
7458     // literals in the end.
7459     StringLiteralCheckType Left;
7460     if (!CheckLeft)
7461       Left = SLCT_UncheckedLiteral;
7462     else {
7463       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7464                                    HasVAListArg, format_idx, firstDataArg,
7465                                    Type, CallType, InFunctionCall,
7466                                    CheckedVarArgs, UncoveredArg, Offset,
7467                                    IgnoreStringsWithoutSpecifiers);
7468       if (Left == SLCT_NotALiteral || !CheckRight) {
7469         return Left;
7470       }
7471     }
7472 
7473     StringLiteralCheckType Right = checkFormatStringExpr(
7474         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7475         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7476         IgnoreStringsWithoutSpecifiers);
7477 
7478     return (CheckLeft && Left < Right) ? Left : Right;
7479   }
7480 
7481   case Stmt::ImplicitCastExprClass:
7482     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7483     goto tryAgain;
7484 
7485   case Stmt::OpaqueValueExprClass:
7486     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7487       E = src;
7488       goto tryAgain;
7489     }
7490     return SLCT_NotALiteral;
7491 
7492   case Stmt::PredefinedExprClass:
7493     // While __func__, etc., are technically not string literals, they
7494     // cannot contain format specifiers and thus are not a security
7495     // liability.
7496     return SLCT_UncheckedLiteral;
7497 
7498   case Stmt::DeclRefExprClass: {
7499     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7500 
7501     // As an exception, do not flag errors for variables binding to
7502     // const string literals.
7503     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7504       bool isConstant = false;
7505       QualType T = DR->getType();
7506 
7507       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7508         isConstant = AT->getElementType().isConstant(S.Context);
7509       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7510         isConstant = T.isConstant(S.Context) &&
7511                      PT->getPointeeType().isConstant(S.Context);
7512       } else if (T->isObjCObjectPointerType()) {
7513         // In ObjC, there is usually no "const ObjectPointer" type,
7514         // so don't check if the pointee type is constant.
7515         isConstant = T.isConstant(S.Context);
7516       }
7517 
7518       if (isConstant) {
7519         if (const Expr *Init = VD->getAnyInitializer()) {
7520           // Look through initializers like const char c[] = { "foo" }
7521           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7522             if (InitList->isStringLiteralInit())
7523               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7524           }
7525           return checkFormatStringExpr(S, Init, Args,
7526                                        HasVAListArg, format_idx,
7527                                        firstDataArg, Type, CallType,
7528                                        /*InFunctionCall*/ false, CheckedVarArgs,
7529                                        UncoveredArg, Offset);
7530         }
7531       }
7532 
7533       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7534       // special check to see if the format string is a function parameter
7535       // of the function calling the printf function.  If the function
7536       // has an attribute indicating it is a printf-like function, then we
7537       // should suppress warnings concerning non-literals being used in a call
7538       // to a vprintf function.  For example:
7539       //
7540       // void
7541       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7542       //      va_list ap;
7543       //      va_start(ap, fmt);
7544       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7545       //      ...
7546       // }
7547       if (HasVAListArg) {
7548         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7549           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7550             int PVIndex = PV->getFunctionScopeIndex() + 1;
7551             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7552               // adjust for implicit parameter
7553               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7554                 if (MD->isInstance())
7555                   ++PVIndex;
7556               // We also check if the formats are compatible.
7557               // We can't pass a 'scanf' string to a 'printf' function.
7558               if (PVIndex == PVFormat->getFormatIdx() &&
7559                   Type == S.GetFormatStringType(PVFormat))
7560                 return SLCT_UncheckedLiteral;
7561             }
7562           }
7563         }
7564       }
7565     }
7566 
7567     return SLCT_NotALiteral;
7568   }
7569 
7570   case Stmt::CallExprClass:
7571   case Stmt::CXXMemberCallExprClass: {
7572     const CallExpr *CE = cast<CallExpr>(E);
7573     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7574       bool IsFirst = true;
7575       StringLiteralCheckType CommonResult;
7576       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7577         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7578         StringLiteralCheckType Result = checkFormatStringExpr(
7579             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7580             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7581             IgnoreStringsWithoutSpecifiers);
7582         if (IsFirst) {
7583           CommonResult = Result;
7584           IsFirst = false;
7585         }
7586       }
7587       if (!IsFirst)
7588         return CommonResult;
7589 
7590       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7591         unsigned BuiltinID = FD->getBuiltinID();
7592         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7593             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7594           const Expr *Arg = CE->getArg(0);
7595           return checkFormatStringExpr(S, Arg, Args,
7596                                        HasVAListArg, format_idx,
7597                                        firstDataArg, Type, CallType,
7598                                        InFunctionCall, CheckedVarArgs,
7599                                        UncoveredArg, Offset,
7600                                        IgnoreStringsWithoutSpecifiers);
7601         }
7602       }
7603     }
7604 
7605     return SLCT_NotALiteral;
7606   }
7607   case Stmt::ObjCMessageExprClass: {
7608     const auto *ME = cast<ObjCMessageExpr>(E);
7609     if (const auto *MD = ME->getMethodDecl()) {
7610       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7611         // As a special case heuristic, if we're using the method -[NSBundle
7612         // localizedStringForKey:value:table:], ignore any key strings that lack
7613         // format specifiers. The idea is that if the key doesn't have any
7614         // format specifiers then its probably just a key to map to the
7615         // localized strings. If it does have format specifiers though, then its
7616         // likely that the text of the key is the format string in the
7617         // programmer's language, and should be checked.
7618         const ObjCInterfaceDecl *IFace;
7619         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7620             IFace->getIdentifier()->isStr("NSBundle") &&
7621             MD->getSelector().isKeywordSelector(
7622                 {"localizedStringForKey", "value", "table"})) {
7623           IgnoreStringsWithoutSpecifiers = true;
7624         }
7625 
7626         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7627         return checkFormatStringExpr(
7628             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7629             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7630             IgnoreStringsWithoutSpecifiers);
7631       }
7632     }
7633 
7634     return SLCT_NotALiteral;
7635   }
7636   case Stmt::ObjCStringLiteralClass:
7637   case Stmt::StringLiteralClass: {
7638     const StringLiteral *StrE = nullptr;
7639 
7640     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7641       StrE = ObjCFExpr->getString();
7642     else
7643       StrE = cast<StringLiteral>(E);
7644 
7645     if (StrE) {
7646       if (Offset.isNegative() || Offset > StrE->getLength()) {
7647         // TODO: It would be better to have an explicit warning for out of
7648         // bounds literals.
7649         return SLCT_NotALiteral;
7650       }
7651       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7652       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7653                         firstDataArg, Type, InFunctionCall, CallType,
7654                         CheckedVarArgs, UncoveredArg,
7655                         IgnoreStringsWithoutSpecifiers);
7656       return SLCT_CheckedLiteral;
7657     }
7658 
7659     return SLCT_NotALiteral;
7660   }
7661   case Stmt::BinaryOperatorClass: {
7662     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7663 
7664     // A string literal + an int offset is still a string literal.
7665     if (BinOp->isAdditiveOp()) {
7666       Expr::EvalResult LResult, RResult;
7667 
7668       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7669           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7670       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7671           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7672 
7673       if (LIsInt != RIsInt) {
7674         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7675 
7676         if (LIsInt) {
7677           if (BinOpKind == BO_Add) {
7678             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7679             E = BinOp->getRHS();
7680             goto tryAgain;
7681           }
7682         } else {
7683           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7684           E = BinOp->getLHS();
7685           goto tryAgain;
7686         }
7687       }
7688     }
7689 
7690     return SLCT_NotALiteral;
7691   }
7692   case Stmt::UnaryOperatorClass: {
7693     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7694     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7695     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7696       Expr::EvalResult IndexResult;
7697       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7698                                        Expr::SE_NoSideEffects,
7699                                        S.isConstantEvaluated())) {
7700         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7701                    /*RHS is int*/ true);
7702         E = ASE->getBase();
7703         goto tryAgain;
7704       }
7705     }
7706 
7707     return SLCT_NotALiteral;
7708   }
7709 
7710   default:
7711     return SLCT_NotALiteral;
7712   }
7713 }
7714 
7715 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7716   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7717       .Case("scanf", FST_Scanf)
7718       .Cases("printf", "printf0", FST_Printf)
7719       .Cases("NSString", "CFString", FST_NSString)
7720       .Case("strftime", FST_Strftime)
7721       .Case("strfmon", FST_Strfmon)
7722       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7723       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7724       .Case("os_trace", FST_OSLog)
7725       .Case("os_log", FST_OSLog)
7726       .Default(FST_Unknown);
7727 }
7728 
7729 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7730 /// functions) for correct use of format strings.
7731 /// Returns true if a format string has been fully checked.
7732 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7733                                 ArrayRef<const Expr *> Args,
7734                                 bool IsCXXMember,
7735                                 VariadicCallType CallType,
7736                                 SourceLocation Loc, SourceRange Range,
7737                                 llvm::SmallBitVector &CheckedVarArgs) {
7738   FormatStringInfo FSI;
7739   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7740     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7741                                 FSI.FirstDataArg, GetFormatStringType(Format),
7742                                 CallType, Loc, Range, CheckedVarArgs);
7743   return false;
7744 }
7745 
7746 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7747                                 bool HasVAListArg, unsigned format_idx,
7748                                 unsigned firstDataArg, FormatStringType Type,
7749                                 VariadicCallType CallType,
7750                                 SourceLocation Loc, SourceRange Range,
7751                                 llvm::SmallBitVector &CheckedVarArgs) {
7752   // CHECK: printf/scanf-like function is called with no format string.
7753   if (format_idx >= Args.size()) {
7754     Diag(Loc, diag::warn_missing_format_string) << Range;
7755     return false;
7756   }
7757 
7758   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7759 
7760   // CHECK: format string is not a string literal.
7761   //
7762   // Dynamically generated format strings are difficult to
7763   // automatically vet at compile time.  Requiring that format strings
7764   // are string literals: (1) permits the checking of format strings by
7765   // the compiler and thereby (2) can practically remove the source of
7766   // many format string exploits.
7767 
7768   // Format string can be either ObjC string (e.g. @"%d") or
7769   // C string (e.g. "%d")
7770   // ObjC string uses the same format specifiers as C string, so we can use
7771   // the same format string checking logic for both ObjC and C strings.
7772   UncoveredArgHandler UncoveredArg;
7773   StringLiteralCheckType CT =
7774       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7775                             format_idx, firstDataArg, Type, CallType,
7776                             /*IsFunctionCall*/ true, CheckedVarArgs,
7777                             UncoveredArg,
7778                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7779 
7780   // Generate a diagnostic where an uncovered argument is detected.
7781   if (UncoveredArg.hasUncoveredArg()) {
7782     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7783     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7784     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7785   }
7786 
7787   if (CT != SLCT_NotALiteral)
7788     // Literal format string found, check done!
7789     return CT == SLCT_CheckedLiteral;
7790 
7791   // Strftime is particular as it always uses a single 'time' argument,
7792   // so it is safe to pass a non-literal string.
7793   if (Type == FST_Strftime)
7794     return false;
7795 
7796   // Do not emit diag when the string param is a macro expansion and the
7797   // format is either NSString or CFString. This is a hack to prevent
7798   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7799   // which are usually used in place of NS and CF string literals.
7800   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7801   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7802     return false;
7803 
7804   // If there are no arguments specified, warn with -Wformat-security, otherwise
7805   // warn only with -Wformat-nonliteral.
7806   if (Args.size() == firstDataArg) {
7807     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7808       << OrigFormatExpr->getSourceRange();
7809     switch (Type) {
7810     default:
7811       break;
7812     case FST_Kprintf:
7813     case FST_FreeBSDKPrintf:
7814     case FST_Printf:
7815       Diag(FormatLoc, diag::note_format_security_fixit)
7816         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7817       break;
7818     case FST_NSString:
7819       Diag(FormatLoc, diag::note_format_security_fixit)
7820         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7821       break;
7822     }
7823   } else {
7824     Diag(FormatLoc, diag::warn_format_nonliteral)
7825       << OrigFormatExpr->getSourceRange();
7826   }
7827   return false;
7828 }
7829 
7830 namespace {
7831 
7832 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7833 protected:
7834   Sema &S;
7835   const FormatStringLiteral *FExpr;
7836   const Expr *OrigFormatExpr;
7837   const Sema::FormatStringType FSType;
7838   const unsigned FirstDataArg;
7839   const unsigned NumDataArgs;
7840   const char *Beg; // Start of format string.
7841   const bool HasVAListArg;
7842   ArrayRef<const Expr *> Args;
7843   unsigned FormatIdx;
7844   llvm::SmallBitVector CoveredArgs;
7845   bool usesPositionalArgs = false;
7846   bool atFirstArg = true;
7847   bool inFunctionCall;
7848   Sema::VariadicCallType CallType;
7849   llvm::SmallBitVector &CheckedVarArgs;
7850   UncoveredArgHandler &UncoveredArg;
7851 
7852 public:
7853   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7854                      const Expr *origFormatExpr,
7855                      const Sema::FormatStringType type, unsigned firstDataArg,
7856                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7857                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7858                      bool inFunctionCall, Sema::VariadicCallType callType,
7859                      llvm::SmallBitVector &CheckedVarArgs,
7860                      UncoveredArgHandler &UncoveredArg)
7861       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7862         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7863         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7864         inFunctionCall(inFunctionCall), CallType(callType),
7865         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7866     CoveredArgs.resize(numDataArgs);
7867     CoveredArgs.reset();
7868   }
7869 
7870   void DoneProcessing();
7871 
7872   void HandleIncompleteSpecifier(const char *startSpecifier,
7873                                  unsigned specifierLen) override;
7874 
7875   void HandleInvalidLengthModifier(
7876                            const analyze_format_string::FormatSpecifier &FS,
7877                            const analyze_format_string::ConversionSpecifier &CS,
7878                            const char *startSpecifier, unsigned specifierLen,
7879                            unsigned DiagID);
7880 
7881   void HandleNonStandardLengthModifier(
7882                     const analyze_format_string::FormatSpecifier &FS,
7883                     const char *startSpecifier, unsigned specifierLen);
7884 
7885   void HandleNonStandardConversionSpecifier(
7886                     const analyze_format_string::ConversionSpecifier &CS,
7887                     const char *startSpecifier, unsigned specifierLen);
7888 
7889   void HandlePosition(const char *startPos, unsigned posLen) override;
7890 
7891   void HandleInvalidPosition(const char *startSpecifier,
7892                              unsigned specifierLen,
7893                              analyze_format_string::PositionContext p) override;
7894 
7895   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7896 
7897   void HandleNullChar(const char *nullCharacter) override;
7898 
7899   template <typename Range>
7900   static void
7901   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7902                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7903                        bool IsStringLocation, Range StringRange,
7904                        ArrayRef<FixItHint> Fixit = None);
7905 
7906 protected:
7907   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7908                                         const char *startSpec,
7909                                         unsigned specifierLen,
7910                                         const char *csStart, unsigned csLen);
7911 
7912   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7913                                          const char *startSpec,
7914                                          unsigned specifierLen);
7915 
7916   SourceRange getFormatStringRange();
7917   CharSourceRange getSpecifierRange(const char *startSpecifier,
7918                                     unsigned specifierLen);
7919   SourceLocation getLocationOfByte(const char *x);
7920 
7921   const Expr *getDataArg(unsigned i) const;
7922 
7923   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7924                     const analyze_format_string::ConversionSpecifier &CS,
7925                     const char *startSpecifier, unsigned specifierLen,
7926                     unsigned argIndex);
7927 
7928   template <typename Range>
7929   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7930                             bool IsStringLocation, Range StringRange,
7931                             ArrayRef<FixItHint> Fixit = None);
7932 };
7933 
7934 } // namespace
7935 
7936 SourceRange CheckFormatHandler::getFormatStringRange() {
7937   return OrigFormatExpr->getSourceRange();
7938 }
7939 
7940 CharSourceRange CheckFormatHandler::
7941 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7942   SourceLocation Start = getLocationOfByte(startSpecifier);
7943   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7944 
7945   // Advance the end SourceLocation by one due to half-open ranges.
7946   End = End.getLocWithOffset(1);
7947 
7948   return CharSourceRange::getCharRange(Start, End);
7949 }
7950 
7951 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7952   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7953                                   S.getLangOpts(), S.Context.getTargetInfo());
7954 }
7955 
7956 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7957                                                    unsigned specifierLen){
7958   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7959                        getLocationOfByte(startSpecifier),
7960                        /*IsStringLocation*/true,
7961                        getSpecifierRange(startSpecifier, specifierLen));
7962 }
7963 
7964 void CheckFormatHandler::HandleInvalidLengthModifier(
7965     const analyze_format_string::FormatSpecifier &FS,
7966     const analyze_format_string::ConversionSpecifier &CS,
7967     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7968   using namespace analyze_format_string;
7969 
7970   const LengthModifier &LM = FS.getLengthModifier();
7971   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7972 
7973   // See if we know how to fix this length modifier.
7974   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7975   if (FixedLM) {
7976     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7977                          getLocationOfByte(LM.getStart()),
7978                          /*IsStringLocation*/true,
7979                          getSpecifierRange(startSpecifier, specifierLen));
7980 
7981     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7982       << FixedLM->toString()
7983       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7984 
7985   } else {
7986     FixItHint Hint;
7987     if (DiagID == diag::warn_format_nonsensical_length)
7988       Hint = FixItHint::CreateRemoval(LMRange);
7989 
7990     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7991                          getLocationOfByte(LM.getStart()),
7992                          /*IsStringLocation*/true,
7993                          getSpecifierRange(startSpecifier, specifierLen),
7994                          Hint);
7995   }
7996 }
7997 
7998 void CheckFormatHandler::HandleNonStandardLengthModifier(
7999     const analyze_format_string::FormatSpecifier &FS,
8000     const char *startSpecifier, unsigned specifierLen) {
8001   using namespace analyze_format_string;
8002 
8003   const LengthModifier &LM = FS.getLengthModifier();
8004   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8005 
8006   // See if we know how to fix this length modifier.
8007   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8008   if (FixedLM) {
8009     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8010                            << LM.toString() << 0,
8011                          getLocationOfByte(LM.getStart()),
8012                          /*IsStringLocation*/true,
8013                          getSpecifierRange(startSpecifier, specifierLen));
8014 
8015     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8016       << FixedLM->toString()
8017       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8018 
8019   } else {
8020     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8021                            << LM.toString() << 0,
8022                          getLocationOfByte(LM.getStart()),
8023                          /*IsStringLocation*/true,
8024                          getSpecifierRange(startSpecifier, specifierLen));
8025   }
8026 }
8027 
8028 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8029     const analyze_format_string::ConversionSpecifier &CS,
8030     const char *startSpecifier, unsigned specifierLen) {
8031   using namespace analyze_format_string;
8032 
8033   // See if we know how to fix this conversion specifier.
8034   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8035   if (FixedCS) {
8036     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8037                           << CS.toString() << /*conversion specifier*/1,
8038                          getLocationOfByte(CS.getStart()),
8039                          /*IsStringLocation*/true,
8040                          getSpecifierRange(startSpecifier, specifierLen));
8041 
8042     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8043     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8044       << FixedCS->toString()
8045       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8046   } else {
8047     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8048                           << CS.toString() << /*conversion specifier*/1,
8049                          getLocationOfByte(CS.getStart()),
8050                          /*IsStringLocation*/true,
8051                          getSpecifierRange(startSpecifier, specifierLen));
8052   }
8053 }
8054 
8055 void CheckFormatHandler::HandlePosition(const char *startPos,
8056                                         unsigned posLen) {
8057   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8058                                getLocationOfByte(startPos),
8059                                /*IsStringLocation*/true,
8060                                getSpecifierRange(startPos, posLen));
8061 }
8062 
8063 void
8064 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8065                                      analyze_format_string::PositionContext p) {
8066   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8067                          << (unsigned) p,
8068                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8069                        getSpecifierRange(startPos, posLen));
8070 }
8071 
8072 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8073                                             unsigned posLen) {
8074   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8075                                getLocationOfByte(startPos),
8076                                /*IsStringLocation*/true,
8077                                getSpecifierRange(startPos, posLen));
8078 }
8079 
8080 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8081   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8082     // The presence of a null character is likely an error.
8083     EmitFormatDiagnostic(
8084       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8085       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8086       getFormatStringRange());
8087   }
8088 }
8089 
8090 // Note that this may return NULL if there was an error parsing or building
8091 // one of the argument expressions.
8092 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8093   return Args[FirstDataArg + i];
8094 }
8095 
8096 void CheckFormatHandler::DoneProcessing() {
8097   // Does the number of data arguments exceed the number of
8098   // format conversions in the format string?
8099   if (!HasVAListArg) {
8100       // Find any arguments that weren't covered.
8101     CoveredArgs.flip();
8102     signed notCoveredArg = CoveredArgs.find_first();
8103     if (notCoveredArg >= 0) {
8104       assert((unsigned)notCoveredArg < NumDataArgs);
8105       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8106     } else {
8107       UncoveredArg.setAllCovered();
8108     }
8109   }
8110 }
8111 
8112 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8113                                    const Expr *ArgExpr) {
8114   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8115          "Invalid state");
8116 
8117   if (!ArgExpr)
8118     return;
8119 
8120   SourceLocation Loc = ArgExpr->getBeginLoc();
8121 
8122   if (S.getSourceManager().isInSystemMacro(Loc))
8123     return;
8124 
8125   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8126   for (auto E : DiagnosticExprs)
8127     PDiag << E->getSourceRange();
8128 
8129   CheckFormatHandler::EmitFormatDiagnostic(
8130                                   S, IsFunctionCall, DiagnosticExprs[0],
8131                                   PDiag, Loc, /*IsStringLocation*/false,
8132                                   DiagnosticExprs[0]->getSourceRange());
8133 }
8134 
8135 bool
8136 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8137                                                      SourceLocation Loc,
8138                                                      const char *startSpec,
8139                                                      unsigned specifierLen,
8140                                                      const char *csStart,
8141                                                      unsigned csLen) {
8142   bool keepGoing = true;
8143   if (argIndex < NumDataArgs) {
8144     // Consider the argument coverered, even though the specifier doesn't
8145     // make sense.
8146     CoveredArgs.set(argIndex);
8147   }
8148   else {
8149     // If argIndex exceeds the number of data arguments we
8150     // don't issue a warning because that is just a cascade of warnings (and
8151     // they may have intended '%%' anyway). We don't want to continue processing
8152     // the format string after this point, however, as we will like just get
8153     // gibberish when trying to match arguments.
8154     keepGoing = false;
8155   }
8156 
8157   StringRef Specifier(csStart, csLen);
8158 
8159   // If the specifier in non-printable, it could be the first byte of a UTF-8
8160   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8161   // hex value.
8162   std::string CodePointStr;
8163   if (!llvm::sys::locale::isPrint(*csStart)) {
8164     llvm::UTF32 CodePoint;
8165     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8166     const llvm::UTF8 *E =
8167         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8168     llvm::ConversionResult Result =
8169         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8170 
8171     if (Result != llvm::conversionOK) {
8172       unsigned char FirstChar = *csStart;
8173       CodePoint = (llvm::UTF32)FirstChar;
8174     }
8175 
8176     llvm::raw_string_ostream OS(CodePointStr);
8177     if (CodePoint < 256)
8178       OS << "\\x" << llvm::format("%02x", CodePoint);
8179     else if (CodePoint <= 0xFFFF)
8180       OS << "\\u" << llvm::format("%04x", CodePoint);
8181     else
8182       OS << "\\U" << llvm::format("%08x", CodePoint);
8183     OS.flush();
8184     Specifier = CodePointStr;
8185   }
8186 
8187   EmitFormatDiagnostic(
8188       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8189       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8190 
8191   return keepGoing;
8192 }
8193 
8194 void
8195 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8196                                                       const char *startSpec,
8197                                                       unsigned specifierLen) {
8198   EmitFormatDiagnostic(
8199     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8200     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8201 }
8202 
8203 bool
8204 CheckFormatHandler::CheckNumArgs(
8205   const analyze_format_string::FormatSpecifier &FS,
8206   const analyze_format_string::ConversionSpecifier &CS,
8207   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8208 
8209   if (argIndex >= NumDataArgs) {
8210     PartialDiagnostic PDiag = FS.usesPositionalArg()
8211       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8212            << (argIndex+1) << NumDataArgs)
8213       : S.PDiag(diag::warn_printf_insufficient_data_args);
8214     EmitFormatDiagnostic(
8215       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8216       getSpecifierRange(startSpecifier, specifierLen));
8217 
8218     // Since more arguments than conversion tokens are given, by extension
8219     // all arguments are covered, so mark this as so.
8220     UncoveredArg.setAllCovered();
8221     return false;
8222   }
8223   return true;
8224 }
8225 
8226 template<typename Range>
8227 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8228                                               SourceLocation Loc,
8229                                               bool IsStringLocation,
8230                                               Range StringRange,
8231                                               ArrayRef<FixItHint> FixIt) {
8232   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8233                        Loc, IsStringLocation, StringRange, FixIt);
8234 }
8235 
8236 /// If the format string is not within the function call, emit a note
8237 /// so that the function call and string are in diagnostic messages.
8238 ///
8239 /// \param InFunctionCall if true, the format string is within the function
8240 /// call and only one diagnostic message will be produced.  Otherwise, an
8241 /// extra note will be emitted pointing to location of the format string.
8242 ///
8243 /// \param ArgumentExpr the expression that is passed as the format string
8244 /// argument in the function call.  Used for getting locations when two
8245 /// diagnostics are emitted.
8246 ///
8247 /// \param PDiag the callee should already have provided any strings for the
8248 /// diagnostic message.  This function only adds locations and fixits
8249 /// to diagnostics.
8250 ///
8251 /// \param Loc primary location for diagnostic.  If two diagnostics are
8252 /// required, one will be at Loc and a new SourceLocation will be created for
8253 /// the other one.
8254 ///
8255 /// \param IsStringLocation if true, Loc points to the format string should be
8256 /// used for the note.  Otherwise, Loc points to the argument list and will
8257 /// be used with PDiag.
8258 ///
8259 /// \param StringRange some or all of the string to highlight.  This is
8260 /// templated so it can accept either a CharSourceRange or a SourceRange.
8261 ///
8262 /// \param FixIt optional fix it hint for the format string.
8263 template <typename Range>
8264 void CheckFormatHandler::EmitFormatDiagnostic(
8265     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8266     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8267     Range StringRange, ArrayRef<FixItHint> FixIt) {
8268   if (InFunctionCall) {
8269     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8270     D << StringRange;
8271     D << FixIt;
8272   } else {
8273     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8274       << ArgumentExpr->getSourceRange();
8275 
8276     const Sema::SemaDiagnosticBuilder &Note =
8277       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8278              diag::note_format_string_defined);
8279 
8280     Note << StringRange;
8281     Note << FixIt;
8282   }
8283 }
8284 
8285 //===--- CHECK: Printf format string checking ------------------------------===//
8286 
8287 namespace {
8288 
8289 class CheckPrintfHandler : public CheckFormatHandler {
8290 public:
8291   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8292                      const Expr *origFormatExpr,
8293                      const Sema::FormatStringType type, unsigned firstDataArg,
8294                      unsigned numDataArgs, bool isObjC, const char *beg,
8295                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8296                      unsigned formatIdx, bool inFunctionCall,
8297                      Sema::VariadicCallType CallType,
8298                      llvm::SmallBitVector &CheckedVarArgs,
8299                      UncoveredArgHandler &UncoveredArg)
8300       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8301                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8302                            inFunctionCall, CallType, CheckedVarArgs,
8303                            UncoveredArg) {}
8304 
8305   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8306 
8307   /// Returns true if '%@' specifiers are allowed in the format string.
8308   bool allowsObjCArg() const {
8309     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8310            FSType == Sema::FST_OSTrace;
8311   }
8312 
8313   bool HandleInvalidPrintfConversionSpecifier(
8314                                       const analyze_printf::PrintfSpecifier &FS,
8315                                       const char *startSpecifier,
8316                                       unsigned specifierLen) override;
8317 
8318   void handleInvalidMaskType(StringRef MaskType) override;
8319 
8320   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8321                              const char *startSpecifier,
8322                              unsigned specifierLen) override;
8323   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8324                        const char *StartSpecifier,
8325                        unsigned SpecifierLen,
8326                        const Expr *E);
8327 
8328   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8329                     const char *startSpecifier, unsigned specifierLen);
8330   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8331                            const analyze_printf::OptionalAmount &Amt,
8332                            unsigned type,
8333                            const char *startSpecifier, unsigned specifierLen);
8334   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8335                   const analyze_printf::OptionalFlag &flag,
8336                   const char *startSpecifier, unsigned specifierLen);
8337   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8338                          const analyze_printf::OptionalFlag &ignoredFlag,
8339                          const analyze_printf::OptionalFlag &flag,
8340                          const char *startSpecifier, unsigned specifierLen);
8341   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8342                            const Expr *E);
8343 
8344   void HandleEmptyObjCModifierFlag(const char *startFlag,
8345                                    unsigned flagLen) override;
8346 
8347   void HandleInvalidObjCModifierFlag(const char *startFlag,
8348                                             unsigned flagLen) override;
8349 
8350   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8351                                            const char *flagsEnd,
8352                                            const char *conversionPosition)
8353                                              override;
8354 };
8355 
8356 } // namespace
8357 
8358 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8359                                       const analyze_printf::PrintfSpecifier &FS,
8360                                       const char *startSpecifier,
8361                                       unsigned specifierLen) {
8362   const analyze_printf::PrintfConversionSpecifier &CS =
8363     FS.getConversionSpecifier();
8364 
8365   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8366                                           getLocationOfByte(CS.getStart()),
8367                                           startSpecifier, specifierLen,
8368                                           CS.getStart(), CS.getLength());
8369 }
8370 
8371 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8372   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8373 }
8374 
8375 bool CheckPrintfHandler::HandleAmount(
8376                                const analyze_format_string::OptionalAmount &Amt,
8377                                unsigned k, const char *startSpecifier,
8378                                unsigned specifierLen) {
8379   if (Amt.hasDataArgument()) {
8380     if (!HasVAListArg) {
8381       unsigned argIndex = Amt.getArgIndex();
8382       if (argIndex >= NumDataArgs) {
8383         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8384                                << k,
8385                              getLocationOfByte(Amt.getStart()),
8386                              /*IsStringLocation*/true,
8387                              getSpecifierRange(startSpecifier, specifierLen));
8388         // Don't do any more checking.  We will just emit
8389         // spurious errors.
8390         return false;
8391       }
8392 
8393       // Type check the data argument.  It should be an 'int'.
8394       // Although not in conformance with C99, we also allow the argument to be
8395       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8396       // doesn't emit a warning for that case.
8397       CoveredArgs.set(argIndex);
8398       const Expr *Arg = getDataArg(argIndex);
8399       if (!Arg)
8400         return false;
8401 
8402       QualType T = Arg->getType();
8403 
8404       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8405       assert(AT.isValid());
8406 
8407       if (!AT.matchesType(S.Context, T)) {
8408         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8409                                << k << AT.getRepresentativeTypeName(S.Context)
8410                                << T << Arg->getSourceRange(),
8411                              getLocationOfByte(Amt.getStart()),
8412                              /*IsStringLocation*/true,
8413                              getSpecifierRange(startSpecifier, specifierLen));
8414         // Don't do any more checking.  We will just emit
8415         // spurious errors.
8416         return false;
8417       }
8418     }
8419   }
8420   return true;
8421 }
8422 
8423 void CheckPrintfHandler::HandleInvalidAmount(
8424                                       const analyze_printf::PrintfSpecifier &FS,
8425                                       const analyze_printf::OptionalAmount &Amt,
8426                                       unsigned type,
8427                                       const char *startSpecifier,
8428                                       unsigned specifierLen) {
8429   const analyze_printf::PrintfConversionSpecifier &CS =
8430     FS.getConversionSpecifier();
8431 
8432   FixItHint fixit =
8433     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8434       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8435                                  Amt.getConstantLength()))
8436       : FixItHint();
8437 
8438   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8439                          << type << CS.toString(),
8440                        getLocationOfByte(Amt.getStart()),
8441                        /*IsStringLocation*/true,
8442                        getSpecifierRange(startSpecifier, specifierLen),
8443                        fixit);
8444 }
8445 
8446 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8447                                     const analyze_printf::OptionalFlag &flag,
8448                                     const char *startSpecifier,
8449                                     unsigned specifierLen) {
8450   // Warn about pointless flag with a fixit removal.
8451   const analyze_printf::PrintfConversionSpecifier &CS =
8452     FS.getConversionSpecifier();
8453   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8454                          << flag.toString() << CS.toString(),
8455                        getLocationOfByte(flag.getPosition()),
8456                        /*IsStringLocation*/true,
8457                        getSpecifierRange(startSpecifier, specifierLen),
8458                        FixItHint::CreateRemoval(
8459                          getSpecifierRange(flag.getPosition(), 1)));
8460 }
8461 
8462 void CheckPrintfHandler::HandleIgnoredFlag(
8463                                 const analyze_printf::PrintfSpecifier &FS,
8464                                 const analyze_printf::OptionalFlag &ignoredFlag,
8465                                 const analyze_printf::OptionalFlag &flag,
8466                                 const char *startSpecifier,
8467                                 unsigned specifierLen) {
8468   // Warn about ignored flag with a fixit removal.
8469   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8470                          << ignoredFlag.toString() << flag.toString(),
8471                        getLocationOfByte(ignoredFlag.getPosition()),
8472                        /*IsStringLocation*/true,
8473                        getSpecifierRange(startSpecifier, specifierLen),
8474                        FixItHint::CreateRemoval(
8475                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8476 }
8477 
8478 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8479                                                      unsigned flagLen) {
8480   // Warn about an empty flag.
8481   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8482                        getLocationOfByte(startFlag),
8483                        /*IsStringLocation*/true,
8484                        getSpecifierRange(startFlag, flagLen));
8485 }
8486 
8487 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8488                                                        unsigned flagLen) {
8489   // Warn about an invalid flag.
8490   auto Range = getSpecifierRange(startFlag, flagLen);
8491   StringRef flag(startFlag, flagLen);
8492   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8493                       getLocationOfByte(startFlag),
8494                       /*IsStringLocation*/true,
8495                       Range, FixItHint::CreateRemoval(Range));
8496 }
8497 
8498 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8499     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8500     // Warn about using '[...]' without a '@' conversion.
8501     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8502     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8503     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8504                          getLocationOfByte(conversionPosition),
8505                          /*IsStringLocation*/true,
8506                          Range, FixItHint::CreateRemoval(Range));
8507 }
8508 
8509 // Determines if the specified is a C++ class or struct containing
8510 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8511 // "c_str()").
8512 template<typename MemberKind>
8513 static llvm::SmallPtrSet<MemberKind*, 1>
8514 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8515   const RecordType *RT = Ty->getAs<RecordType>();
8516   llvm::SmallPtrSet<MemberKind*, 1> Results;
8517 
8518   if (!RT)
8519     return Results;
8520   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8521   if (!RD || !RD->getDefinition())
8522     return Results;
8523 
8524   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8525                  Sema::LookupMemberName);
8526   R.suppressDiagnostics();
8527 
8528   // We just need to include all members of the right kind turned up by the
8529   // filter, at this point.
8530   if (S.LookupQualifiedName(R, RT->getDecl()))
8531     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8532       NamedDecl *decl = (*I)->getUnderlyingDecl();
8533       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8534         Results.insert(FK);
8535     }
8536   return Results;
8537 }
8538 
8539 /// Check if we could call '.c_str()' on an object.
8540 ///
8541 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8542 /// allow the call, or if it would be ambiguous).
8543 bool Sema::hasCStrMethod(const Expr *E) {
8544   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8545 
8546   MethodSet Results =
8547       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8548   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8549        MI != ME; ++MI)
8550     if ((*MI)->getMinRequiredArguments() == 0)
8551       return true;
8552   return false;
8553 }
8554 
8555 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8556 // better diagnostic if so. AT is assumed to be valid.
8557 // Returns true when a c_str() conversion method is found.
8558 bool CheckPrintfHandler::checkForCStrMembers(
8559     const analyze_printf::ArgType &AT, const Expr *E) {
8560   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8561 
8562   MethodSet Results =
8563       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8564 
8565   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8566        MI != ME; ++MI) {
8567     const CXXMethodDecl *Method = *MI;
8568     if (Method->getMinRequiredArguments() == 0 &&
8569         AT.matchesType(S.Context, Method->getReturnType())) {
8570       // FIXME: Suggest parens if the expression needs them.
8571       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8572       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8573           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8574       return true;
8575     }
8576   }
8577 
8578   return false;
8579 }
8580 
8581 bool
8582 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8583                                             &FS,
8584                                           const char *startSpecifier,
8585                                           unsigned specifierLen) {
8586   using namespace analyze_format_string;
8587   using namespace analyze_printf;
8588 
8589   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8590 
8591   if (FS.consumesDataArgument()) {
8592     if (atFirstArg) {
8593         atFirstArg = false;
8594         usesPositionalArgs = FS.usesPositionalArg();
8595     }
8596     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8597       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8598                                         startSpecifier, specifierLen);
8599       return false;
8600     }
8601   }
8602 
8603   // First check if the field width, precision, and conversion specifier
8604   // have matching data arguments.
8605   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8606                     startSpecifier, specifierLen)) {
8607     return false;
8608   }
8609 
8610   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8611                     startSpecifier, specifierLen)) {
8612     return false;
8613   }
8614 
8615   if (!CS.consumesDataArgument()) {
8616     // FIXME: Technically specifying a precision or field width here
8617     // makes no sense.  Worth issuing a warning at some point.
8618     return true;
8619   }
8620 
8621   // Consume the argument.
8622   unsigned argIndex = FS.getArgIndex();
8623   if (argIndex < NumDataArgs) {
8624     // The check to see if the argIndex is valid will come later.
8625     // We set the bit here because we may exit early from this
8626     // function if we encounter some other error.
8627     CoveredArgs.set(argIndex);
8628   }
8629 
8630   // FreeBSD kernel extensions.
8631   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8632       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8633     // We need at least two arguments.
8634     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8635       return false;
8636 
8637     // Claim the second argument.
8638     CoveredArgs.set(argIndex + 1);
8639 
8640     // Type check the first argument (int for %b, pointer for %D)
8641     const Expr *Ex = getDataArg(argIndex);
8642     const analyze_printf::ArgType &AT =
8643       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8644         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8645     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8646       EmitFormatDiagnostic(
8647           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8648               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8649               << false << Ex->getSourceRange(),
8650           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8651           getSpecifierRange(startSpecifier, specifierLen));
8652 
8653     // Type check the second argument (char * for both %b and %D)
8654     Ex = getDataArg(argIndex + 1);
8655     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8656     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8657       EmitFormatDiagnostic(
8658           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8659               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8660               << false << Ex->getSourceRange(),
8661           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8662           getSpecifierRange(startSpecifier, specifierLen));
8663 
8664      return true;
8665   }
8666 
8667   // Check for using an Objective-C specific conversion specifier
8668   // in a non-ObjC literal.
8669   if (!allowsObjCArg() && CS.isObjCArg()) {
8670     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8671                                                   specifierLen);
8672   }
8673 
8674   // %P can only be used with os_log.
8675   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8676     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8677                                                   specifierLen);
8678   }
8679 
8680   // %n is not allowed with os_log.
8681   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8682     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8683                          getLocationOfByte(CS.getStart()),
8684                          /*IsStringLocation*/ false,
8685                          getSpecifierRange(startSpecifier, specifierLen));
8686 
8687     return true;
8688   }
8689 
8690   // Only scalars are allowed for os_trace.
8691   if (FSType == Sema::FST_OSTrace &&
8692       (CS.getKind() == ConversionSpecifier::PArg ||
8693        CS.getKind() == ConversionSpecifier::sArg ||
8694        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8695     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8696                                                   specifierLen);
8697   }
8698 
8699   // Check for use of public/private annotation outside of os_log().
8700   if (FSType != Sema::FST_OSLog) {
8701     if (FS.isPublic().isSet()) {
8702       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8703                                << "public",
8704                            getLocationOfByte(FS.isPublic().getPosition()),
8705                            /*IsStringLocation*/ false,
8706                            getSpecifierRange(startSpecifier, specifierLen));
8707     }
8708     if (FS.isPrivate().isSet()) {
8709       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8710                                << "private",
8711                            getLocationOfByte(FS.isPrivate().getPosition()),
8712                            /*IsStringLocation*/ false,
8713                            getSpecifierRange(startSpecifier, specifierLen));
8714     }
8715   }
8716 
8717   // Check for invalid use of field width
8718   if (!FS.hasValidFieldWidth()) {
8719     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8720         startSpecifier, specifierLen);
8721   }
8722 
8723   // Check for invalid use of precision
8724   if (!FS.hasValidPrecision()) {
8725     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8726         startSpecifier, specifierLen);
8727   }
8728 
8729   // Precision is mandatory for %P specifier.
8730   if (CS.getKind() == ConversionSpecifier::PArg &&
8731       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8732     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8733                          getLocationOfByte(startSpecifier),
8734                          /*IsStringLocation*/ false,
8735                          getSpecifierRange(startSpecifier, specifierLen));
8736   }
8737 
8738   // Check each flag does not conflict with any other component.
8739   if (!FS.hasValidThousandsGroupingPrefix())
8740     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8741   if (!FS.hasValidLeadingZeros())
8742     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8743   if (!FS.hasValidPlusPrefix())
8744     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8745   if (!FS.hasValidSpacePrefix())
8746     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8747   if (!FS.hasValidAlternativeForm())
8748     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8749   if (!FS.hasValidLeftJustified())
8750     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8751 
8752   // Check that flags are not ignored by another flag
8753   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8754     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8755         startSpecifier, specifierLen);
8756   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8757     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8758             startSpecifier, specifierLen);
8759 
8760   // Check the length modifier is valid with the given conversion specifier.
8761   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8762                                  S.getLangOpts()))
8763     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8764                                 diag::warn_format_nonsensical_length);
8765   else if (!FS.hasStandardLengthModifier())
8766     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8767   else if (!FS.hasStandardLengthConversionCombination())
8768     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8769                                 diag::warn_format_non_standard_conversion_spec);
8770 
8771   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8772     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8773 
8774   // The remaining checks depend on the data arguments.
8775   if (HasVAListArg)
8776     return true;
8777 
8778   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8779     return false;
8780 
8781   const Expr *Arg = getDataArg(argIndex);
8782   if (!Arg)
8783     return true;
8784 
8785   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8786 }
8787 
8788 static bool requiresParensToAddCast(const Expr *E) {
8789   // FIXME: We should have a general way to reason about operator
8790   // precedence and whether parens are actually needed here.
8791   // Take care of a few common cases where they aren't.
8792   const Expr *Inside = E->IgnoreImpCasts();
8793   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8794     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8795 
8796   switch (Inside->getStmtClass()) {
8797   case Stmt::ArraySubscriptExprClass:
8798   case Stmt::CallExprClass:
8799   case Stmt::CharacterLiteralClass:
8800   case Stmt::CXXBoolLiteralExprClass:
8801   case Stmt::DeclRefExprClass:
8802   case Stmt::FloatingLiteralClass:
8803   case Stmt::IntegerLiteralClass:
8804   case Stmt::MemberExprClass:
8805   case Stmt::ObjCArrayLiteralClass:
8806   case Stmt::ObjCBoolLiteralExprClass:
8807   case Stmt::ObjCBoxedExprClass:
8808   case Stmt::ObjCDictionaryLiteralClass:
8809   case Stmt::ObjCEncodeExprClass:
8810   case Stmt::ObjCIvarRefExprClass:
8811   case Stmt::ObjCMessageExprClass:
8812   case Stmt::ObjCPropertyRefExprClass:
8813   case Stmt::ObjCStringLiteralClass:
8814   case Stmt::ObjCSubscriptRefExprClass:
8815   case Stmt::ParenExprClass:
8816   case Stmt::StringLiteralClass:
8817   case Stmt::UnaryOperatorClass:
8818     return false;
8819   default:
8820     return true;
8821   }
8822 }
8823 
8824 static std::pair<QualType, StringRef>
8825 shouldNotPrintDirectly(const ASTContext &Context,
8826                        QualType IntendedTy,
8827                        const Expr *E) {
8828   // Use a 'while' to peel off layers of typedefs.
8829   QualType TyTy = IntendedTy;
8830   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8831     StringRef Name = UserTy->getDecl()->getName();
8832     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8833       .Case("CFIndex", Context.getNSIntegerType())
8834       .Case("NSInteger", Context.getNSIntegerType())
8835       .Case("NSUInteger", Context.getNSUIntegerType())
8836       .Case("SInt32", Context.IntTy)
8837       .Case("UInt32", Context.UnsignedIntTy)
8838       .Default(QualType());
8839 
8840     if (!CastTy.isNull())
8841       return std::make_pair(CastTy, Name);
8842 
8843     TyTy = UserTy->desugar();
8844   }
8845 
8846   // Strip parens if necessary.
8847   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8848     return shouldNotPrintDirectly(Context,
8849                                   PE->getSubExpr()->getType(),
8850                                   PE->getSubExpr());
8851 
8852   // If this is a conditional expression, then its result type is constructed
8853   // via usual arithmetic conversions and thus there might be no necessary
8854   // typedef sugar there.  Recurse to operands to check for NSInteger &
8855   // Co. usage condition.
8856   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8857     QualType TrueTy, FalseTy;
8858     StringRef TrueName, FalseName;
8859 
8860     std::tie(TrueTy, TrueName) =
8861       shouldNotPrintDirectly(Context,
8862                              CO->getTrueExpr()->getType(),
8863                              CO->getTrueExpr());
8864     std::tie(FalseTy, FalseName) =
8865       shouldNotPrintDirectly(Context,
8866                              CO->getFalseExpr()->getType(),
8867                              CO->getFalseExpr());
8868 
8869     if (TrueTy == FalseTy)
8870       return std::make_pair(TrueTy, TrueName);
8871     else if (TrueTy.isNull())
8872       return std::make_pair(FalseTy, FalseName);
8873     else if (FalseTy.isNull())
8874       return std::make_pair(TrueTy, TrueName);
8875   }
8876 
8877   return std::make_pair(QualType(), StringRef());
8878 }
8879 
8880 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8881 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8882 /// type do not count.
8883 static bool
8884 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8885   QualType From = ICE->getSubExpr()->getType();
8886   QualType To = ICE->getType();
8887   // It's an integer promotion if the destination type is the promoted
8888   // source type.
8889   if (ICE->getCastKind() == CK_IntegralCast &&
8890       From->isPromotableIntegerType() &&
8891       S.Context.getPromotedIntegerType(From) == To)
8892     return true;
8893   // Look through vector types, since we do default argument promotion for
8894   // those in OpenCL.
8895   if (const auto *VecTy = From->getAs<ExtVectorType>())
8896     From = VecTy->getElementType();
8897   if (const auto *VecTy = To->getAs<ExtVectorType>())
8898     To = VecTy->getElementType();
8899   // It's a floating promotion if the source type is a lower rank.
8900   return ICE->getCastKind() == CK_FloatingCast &&
8901          S.Context.getFloatingTypeOrder(From, To) < 0;
8902 }
8903 
8904 bool
8905 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8906                                     const char *StartSpecifier,
8907                                     unsigned SpecifierLen,
8908                                     const Expr *E) {
8909   using namespace analyze_format_string;
8910   using namespace analyze_printf;
8911 
8912   // Now type check the data expression that matches the
8913   // format specifier.
8914   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8915   if (!AT.isValid())
8916     return true;
8917 
8918   QualType ExprTy = E->getType();
8919   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8920     ExprTy = TET->getUnderlyingExpr()->getType();
8921   }
8922 
8923   // Diagnose attempts to print a boolean value as a character. Unlike other
8924   // -Wformat diagnostics, this is fine from a type perspective, but it still
8925   // doesn't make sense.
8926   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8927       E->isKnownToHaveBooleanValue()) {
8928     const CharSourceRange &CSR =
8929         getSpecifierRange(StartSpecifier, SpecifierLen);
8930     SmallString<4> FSString;
8931     llvm::raw_svector_ostream os(FSString);
8932     FS.toString(os);
8933     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8934                              << FSString,
8935                          E->getExprLoc(), false, CSR);
8936     return true;
8937   }
8938 
8939   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8940   if (Match == analyze_printf::ArgType::Match)
8941     return true;
8942 
8943   // Look through argument promotions for our error message's reported type.
8944   // This includes the integral and floating promotions, but excludes array
8945   // and function pointer decay (seeing that an argument intended to be a
8946   // string has type 'char [6]' is probably more confusing than 'char *') and
8947   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8948   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8949     if (isArithmeticArgumentPromotion(S, ICE)) {
8950       E = ICE->getSubExpr();
8951       ExprTy = E->getType();
8952 
8953       // Check if we didn't match because of an implicit cast from a 'char'
8954       // or 'short' to an 'int'.  This is done because printf is a varargs
8955       // function.
8956       if (ICE->getType() == S.Context.IntTy ||
8957           ICE->getType() == S.Context.UnsignedIntTy) {
8958         // All further checking is done on the subexpression
8959         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8960             AT.matchesType(S.Context, ExprTy);
8961         if (ImplicitMatch == analyze_printf::ArgType::Match)
8962           return true;
8963         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8964             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8965           Match = ImplicitMatch;
8966       }
8967     }
8968   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8969     // Special case for 'a', which has type 'int' in C.
8970     // Note, however, that we do /not/ want to treat multibyte constants like
8971     // 'MooV' as characters! This form is deprecated but still exists. In
8972     // addition, don't treat expressions as of type 'char' if one byte length
8973     // modifier is provided.
8974     if (ExprTy == S.Context.IntTy &&
8975         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8976       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8977         ExprTy = S.Context.CharTy;
8978   }
8979 
8980   // Look through enums to their underlying type.
8981   bool IsEnum = false;
8982   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8983     ExprTy = EnumTy->getDecl()->getIntegerType();
8984     IsEnum = true;
8985   }
8986 
8987   // %C in an Objective-C context prints a unichar, not a wchar_t.
8988   // If the argument is an integer of some kind, believe the %C and suggest
8989   // a cast instead of changing the conversion specifier.
8990   QualType IntendedTy = ExprTy;
8991   if (isObjCContext() &&
8992       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8993     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8994         !ExprTy->isCharType()) {
8995       // 'unichar' is defined as a typedef of unsigned short, but we should
8996       // prefer using the typedef if it is visible.
8997       IntendedTy = S.Context.UnsignedShortTy;
8998 
8999       // While we are here, check if the value is an IntegerLiteral that happens
9000       // to be within the valid range.
9001       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9002         const llvm::APInt &V = IL->getValue();
9003         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9004           return true;
9005       }
9006 
9007       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9008                           Sema::LookupOrdinaryName);
9009       if (S.LookupName(Result, S.getCurScope())) {
9010         NamedDecl *ND = Result.getFoundDecl();
9011         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9012           if (TD->getUnderlyingType() == IntendedTy)
9013             IntendedTy = S.Context.getTypedefType(TD);
9014       }
9015     }
9016   }
9017 
9018   // Special-case some of Darwin's platform-independence types by suggesting
9019   // casts to primitive types that are known to be large enough.
9020   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9021   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9022     QualType CastTy;
9023     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9024     if (!CastTy.isNull()) {
9025       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9026       // (long in ASTContext). Only complain to pedants.
9027       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9028           (AT.isSizeT() || AT.isPtrdiffT()) &&
9029           AT.matchesType(S.Context, CastTy))
9030         Match = ArgType::NoMatchPedantic;
9031       IntendedTy = CastTy;
9032       ShouldNotPrintDirectly = true;
9033     }
9034   }
9035 
9036   // We may be able to offer a FixItHint if it is a supported type.
9037   PrintfSpecifier fixedFS = FS;
9038   bool Success =
9039       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9040 
9041   if (Success) {
9042     // Get the fix string from the fixed format specifier
9043     SmallString<16> buf;
9044     llvm::raw_svector_ostream os(buf);
9045     fixedFS.toString(os);
9046 
9047     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9048 
9049     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9050       unsigned Diag;
9051       switch (Match) {
9052       case ArgType::Match: llvm_unreachable("expected non-matching");
9053       case ArgType::NoMatchPedantic:
9054         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9055         break;
9056       case ArgType::NoMatchTypeConfusion:
9057         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9058         break;
9059       case ArgType::NoMatch:
9060         Diag = diag::warn_format_conversion_argument_type_mismatch;
9061         break;
9062       }
9063 
9064       // In this case, the specifier is wrong and should be changed to match
9065       // the argument.
9066       EmitFormatDiagnostic(S.PDiag(Diag)
9067                                << AT.getRepresentativeTypeName(S.Context)
9068                                << IntendedTy << IsEnum << E->getSourceRange(),
9069                            E->getBeginLoc(),
9070                            /*IsStringLocation*/ false, SpecRange,
9071                            FixItHint::CreateReplacement(SpecRange, os.str()));
9072     } else {
9073       // The canonical type for formatting this value is different from the
9074       // actual type of the expression. (This occurs, for example, with Darwin's
9075       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9076       // should be printed as 'long' for 64-bit compatibility.)
9077       // Rather than emitting a normal format/argument mismatch, we want to
9078       // add a cast to the recommended type (and correct the format string
9079       // if necessary).
9080       SmallString<16> CastBuf;
9081       llvm::raw_svector_ostream CastFix(CastBuf);
9082       CastFix << "(";
9083       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9084       CastFix << ")";
9085 
9086       SmallVector<FixItHint,4> Hints;
9087       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9088         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9089 
9090       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9091         // If there's already a cast present, just replace it.
9092         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9093         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9094 
9095       } else if (!requiresParensToAddCast(E)) {
9096         // If the expression has high enough precedence,
9097         // just write the C-style cast.
9098         Hints.push_back(
9099             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9100       } else {
9101         // Otherwise, add parens around the expression as well as the cast.
9102         CastFix << "(";
9103         Hints.push_back(
9104             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9105 
9106         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9107         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9108       }
9109 
9110       if (ShouldNotPrintDirectly) {
9111         // The expression has a type that should not be printed directly.
9112         // We extract the name from the typedef because we don't want to show
9113         // the underlying type in the diagnostic.
9114         StringRef Name;
9115         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9116           Name = TypedefTy->getDecl()->getName();
9117         else
9118           Name = CastTyName;
9119         unsigned Diag = Match == ArgType::NoMatchPedantic
9120                             ? diag::warn_format_argument_needs_cast_pedantic
9121                             : diag::warn_format_argument_needs_cast;
9122         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9123                                            << E->getSourceRange(),
9124                              E->getBeginLoc(), /*IsStringLocation=*/false,
9125                              SpecRange, Hints);
9126       } else {
9127         // In this case, the expression could be printed using a different
9128         // specifier, but we've decided that the specifier is probably correct
9129         // and we should cast instead. Just use the normal warning message.
9130         EmitFormatDiagnostic(
9131             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9132                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9133                 << E->getSourceRange(),
9134             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9135       }
9136     }
9137   } else {
9138     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9139                                                    SpecifierLen);
9140     // Since the warning for passing non-POD types to variadic functions
9141     // was deferred until now, we emit a warning for non-POD
9142     // arguments here.
9143     switch (S.isValidVarArgType(ExprTy)) {
9144     case Sema::VAK_Valid:
9145     case Sema::VAK_ValidInCXX11: {
9146       unsigned Diag;
9147       switch (Match) {
9148       case ArgType::Match: llvm_unreachable("expected non-matching");
9149       case ArgType::NoMatchPedantic:
9150         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9151         break;
9152       case ArgType::NoMatchTypeConfusion:
9153         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9154         break;
9155       case ArgType::NoMatch:
9156         Diag = diag::warn_format_conversion_argument_type_mismatch;
9157         break;
9158       }
9159 
9160       EmitFormatDiagnostic(
9161           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9162                         << IsEnum << CSR << E->getSourceRange(),
9163           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9164       break;
9165     }
9166     case Sema::VAK_Undefined:
9167     case Sema::VAK_MSVCUndefined:
9168       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9169                                << S.getLangOpts().CPlusPlus11 << ExprTy
9170                                << CallType
9171                                << AT.getRepresentativeTypeName(S.Context) << CSR
9172                                << E->getSourceRange(),
9173                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9174       checkForCStrMembers(AT, E);
9175       break;
9176 
9177     case Sema::VAK_Invalid:
9178       if (ExprTy->isObjCObjectType())
9179         EmitFormatDiagnostic(
9180             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9181                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9182                 << AT.getRepresentativeTypeName(S.Context) << CSR
9183                 << E->getSourceRange(),
9184             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9185       else
9186         // FIXME: If this is an initializer list, suggest removing the braces
9187         // or inserting a cast to the target type.
9188         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9189             << isa<InitListExpr>(E) << ExprTy << CallType
9190             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9191       break;
9192     }
9193 
9194     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9195            "format string specifier index out of range");
9196     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9197   }
9198 
9199   return true;
9200 }
9201 
9202 //===--- CHECK: Scanf format string checking ------------------------------===//
9203 
9204 namespace {
9205 
9206 class CheckScanfHandler : public CheckFormatHandler {
9207 public:
9208   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9209                     const Expr *origFormatExpr, Sema::FormatStringType type,
9210                     unsigned firstDataArg, unsigned numDataArgs,
9211                     const char *beg, bool hasVAListArg,
9212                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9213                     bool inFunctionCall, Sema::VariadicCallType CallType,
9214                     llvm::SmallBitVector &CheckedVarArgs,
9215                     UncoveredArgHandler &UncoveredArg)
9216       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9217                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9218                            inFunctionCall, CallType, CheckedVarArgs,
9219                            UncoveredArg) {}
9220 
9221   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9222                             const char *startSpecifier,
9223                             unsigned specifierLen) override;
9224 
9225   bool HandleInvalidScanfConversionSpecifier(
9226           const analyze_scanf::ScanfSpecifier &FS,
9227           const char *startSpecifier,
9228           unsigned specifierLen) override;
9229 
9230   void HandleIncompleteScanList(const char *start, const char *end) override;
9231 };
9232 
9233 } // namespace
9234 
9235 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9236                                                  const char *end) {
9237   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9238                        getLocationOfByte(end), /*IsStringLocation*/true,
9239                        getSpecifierRange(start, end - start));
9240 }
9241 
9242 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9243                                         const analyze_scanf::ScanfSpecifier &FS,
9244                                         const char *startSpecifier,
9245                                         unsigned specifierLen) {
9246   const analyze_scanf::ScanfConversionSpecifier &CS =
9247     FS.getConversionSpecifier();
9248 
9249   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9250                                           getLocationOfByte(CS.getStart()),
9251                                           startSpecifier, specifierLen,
9252                                           CS.getStart(), CS.getLength());
9253 }
9254 
9255 bool CheckScanfHandler::HandleScanfSpecifier(
9256                                        const analyze_scanf::ScanfSpecifier &FS,
9257                                        const char *startSpecifier,
9258                                        unsigned specifierLen) {
9259   using namespace analyze_scanf;
9260   using namespace analyze_format_string;
9261 
9262   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9263 
9264   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9265   // be used to decide if we are using positional arguments consistently.
9266   if (FS.consumesDataArgument()) {
9267     if (atFirstArg) {
9268       atFirstArg = false;
9269       usesPositionalArgs = FS.usesPositionalArg();
9270     }
9271     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9272       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9273                                         startSpecifier, specifierLen);
9274       return false;
9275     }
9276   }
9277 
9278   // Check if the field with is non-zero.
9279   const OptionalAmount &Amt = FS.getFieldWidth();
9280   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9281     if (Amt.getConstantAmount() == 0) {
9282       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9283                                                    Amt.getConstantLength());
9284       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9285                            getLocationOfByte(Amt.getStart()),
9286                            /*IsStringLocation*/true, R,
9287                            FixItHint::CreateRemoval(R));
9288     }
9289   }
9290 
9291   if (!FS.consumesDataArgument()) {
9292     // FIXME: Technically specifying a precision or field width here
9293     // makes no sense.  Worth issuing a warning at some point.
9294     return true;
9295   }
9296 
9297   // Consume the argument.
9298   unsigned argIndex = FS.getArgIndex();
9299   if (argIndex < NumDataArgs) {
9300       // The check to see if the argIndex is valid will come later.
9301       // We set the bit here because we may exit early from this
9302       // function if we encounter some other error.
9303     CoveredArgs.set(argIndex);
9304   }
9305 
9306   // Check the length modifier is valid with the given conversion specifier.
9307   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9308                                  S.getLangOpts()))
9309     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9310                                 diag::warn_format_nonsensical_length);
9311   else if (!FS.hasStandardLengthModifier())
9312     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9313   else if (!FS.hasStandardLengthConversionCombination())
9314     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9315                                 diag::warn_format_non_standard_conversion_spec);
9316 
9317   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9318     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9319 
9320   // The remaining checks depend on the data arguments.
9321   if (HasVAListArg)
9322     return true;
9323 
9324   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9325     return false;
9326 
9327   // Check that the argument type matches the format specifier.
9328   const Expr *Ex = getDataArg(argIndex);
9329   if (!Ex)
9330     return true;
9331 
9332   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9333 
9334   if (!AT.isValid()) {
9335     return true;
9336   }
9337 
9338   analyze_format_string::ArgType::MatchKind Match =
9339       AT.matchesType(S.Context, Ex->getType());
9340   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9341   if (Match == analyze_format_string::ArgType::Match)
9342     return true;
9343 
9344   ScanfSpecifier fixedFS = FS;
9345   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9346                                  S.getLangOpts(), S.Context);
9347 
9348   unsigned Diag =
9349       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9350                : diag::warn_format_conversion_argument_type_mismatch;
9351 
9352   if (Success) {
9353     // Get the fix string from the fixed format specifier.
9354     SmallString<128> buf;
9355     llvm::raw_svector_ostream os(buf);
9356     fixedFS.toString(os);
9357 
9358     EmitFormatDiagnostic(
9359         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9360                       << Ex->getType() << false << Ex->getSourceRange(),
9361         Ex->getBeginLoc(),
9362         /*IsStringLocation*/ false,
9363         getSpecifierRange(startSpecifier, specifierLen),
9364         FixItHint::CreateReplacement(
9365             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9366   } else {
9367     EmitFormatDiagnostic(S.PDiag(Diag)
9368                              << AT.getRepresentativeTypeName(S.Context)
9369                              << Ex->getType() << false << Ex->getSourceRange(),
9370                          Ex->getBeginLoc(),
9371                          /*IsStringLocation*/ false,
9372                          getSpecifierRange(startSpecifier, specifierLen));
9373   }
9374 
9375   return true;
9376 }
9377 
9378 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9379                               const Expr *OrigFormatExpr,
9380                               ArrayRef<const Expr *> Args,
9381                               bool HasVAListArg, unsigned format_idx,
9382                               unsigned firstDataArg,
9383                               Sema::FormatStringType Type,
9384                               bool inFunctionCall,
9385                               Sema::VariadicCallType CallType,
9386                               llvm::SmallBitVector &CheckedVarArgs,
9387                               UncoveredArgHandler &UncoveredArg,
9388                               bool IgnoreStringsWithoutSpecifiers) {
9389   // CHECK: is the format string a wide literal?
9390   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9391     CheckFormatHandler::EmitFormatDiagnostic(
9392         S, inFunctionCall, Args[format_idx],
9393         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9394         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9395     return;
9396   }
9397 
9398   // Str - The format string.  NOTE: this is NOT null-terminated!
9399   StringRef StrRef = FExpr->getString();
9400   const char *Str = StrRef.data();
9401   // Account for cases where the string literal is truncated in a declaration.
9402   const ConstantArrayType *T =
9403     S.Context.getAsConstantArrayType(FExpr->getType());
9404   assert(T && "String literal not of constant array type!");
9405   size_t TypeSize = T->getSize().getZExtValue();
9406   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9407   const unsigned numDataArgs = Args.size() - firstDataArg;
9408 
9409   if (IgnoreStringsWithoutSpecifiers &&
9410       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9411           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9412     return;
9413 
9414   // Emit a warning if the string literal is truncated and does not contain an
9415   // embedded null character.
9416   if (TypeSize <= StrRef.size() &&
9417       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9418     CheckFormatHandler::EmitFormatDiagnostic(
9419         S, inFunctionCall, Args[format_idx],
9420         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9421         FExpr->getBeginLoc(),
9422         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9423     return;
9424   }
9425 
9426   // CHECK: empty format string?
9427   if (StrLen == 0 && numDataArgs > 0) {
9428     CheckFormatHandler::EmitFormatDiagnostic(
9429         S, inFunctionCall, Args[format_idx],
9430         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9431         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9432     return;
9433   }
9434 
9435   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9436       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9437       Type == Sema::FST_OSTrace) {
9438     CheckPrintfHandler H(
9439         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9440         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9441         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9442         CheckedVarArgs, UncoveredArg);
9443 
9444     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9445                                                   S.getLangOpts(),
9446                                                   S.Context.getTargetInfo(),
9447                                             Type == Sema::FST_FreeBSDKPrintf))
9448       H.DoneProcessing();
9449   } else if (Type == Sema::FST_Scanf) {
9450     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9451                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9452                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9453 
9454     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9455                                                  S.getLangOpts(),
9456                                                  S.Context.getTargetInfo()))
9457       H.DoneProcessing();
9458   } // TODO: handle other formats
9459 }
9460 
9461 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9462   // Str - The format string.  NOTE: this is NOT null-terminated!
9463   StringRef StrRef = FExpr->getString();
9464   const char *Str = StrRef.data();
9465   // Account for cases where the string literal is truncated in a declaration.
9466   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9467   assert(T && "String literal not of constant array type!");
9468   size_t TypeSize = T->getSize().getZExtValue();
9469   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9470   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9471                                                          getLangOpts(),
9472                                                          Context.getTargetInfo());
9473 }
9474 
9475 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9476 
9477 // Returns the related absolute value function that is larger, of 0 if one
9478 // does not exist.
9479 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9480   switch (AbsFunction) {
9481   default:
9482     return 0;
9483 
9484   case Builtin::BI__builtin_abs:
9485     return Builtin::BI__builtin_labs;
9486   case Builtin::BI__builtin_labs:
9487     return Builtin::BI__builtin_llabs;
9488   case Builtin::BI__builtin_llabs:
9489     return 0;
9490 
9491   case Builtin::BI__builtin_fabsf:
9492     return Builtin::BI__builtin_fabs;
9493   case Builtin::BI__builtin_fabs:
9494     return Builtin::BI__builtin_fabsl;
9495   case Builtin::BI__builtin_fabsl:
9496     return 0;
9497 
9498   case Builtin::BI__builtin_cabsf:
9499     return Builtin::BI__builtin_cabs;
9500   case Builtin::BI__builtin_cabs:
9501     return Builtin::BI__builtin_cabsl;
9502   case Builtin::BI__builtin_cabsl:
9503     return 0;
9504 
9505   case Builtin::BIabs:
9506     return Builtin::BIlabs;
9507   case Builtin::BIlabs:
9508     return Builtin::BIllabs;
9509   case Builtin::BIllabs:
9510     return 0;
9511 
9512   case Builtin::BIfabsf:
9513     return Builtin::BIfabs;
9514   case Builtin::BIfabs:
9515     return Builtin::BIfabsl;
9516   case Builtin::BIfabsl:
9517     return 0;
9518 
9519   case Builtin::BIcabsf:
9520    return Builtin::BIcabs;
9521   case Builtin::BIcabs:
9522     return Builtin::BIcabsl;
9523   case Builtin::BIcabsl:
9524     return 0;
9525   }
9526 }
9527 
9528 // Returns the argument type of the absolute value function.
9529 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9530                                              unsigned AbsType) {
9531   if (AbsType == 0)
9532     return QualType();
9533 
9534   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9535   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9536   if (Error != ASTContext::GE_None)
9537     return QualType();
9538 
9539   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9540   if (!FT)
9541     return QualType();
9542 
9543   if (FT->getNumParams() != 1)
9544     return QualType();
9545 
9546   return FT->getParamType(0);
9547 }
9548 
9549 // Returns the best absolute value function, or zero, based on type and
9550 // current absolute value function.
9551 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9552                                    unsigned AbsFunctionKind) {
9553   unsigned BestKind = 0;
9554   uint64_t ArgSize = Context.getTypeSize(ArgType);
9555   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9556        Kind = getLargerAbsoluteValueFunction(Kind)) {
9557     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9558     if (Context.getTypeSize(ParamType) >= ArgSize) {
9559       if (BestKind == 0)
9560         BestKind = Kind;
9561       else if (Context.hasSameType(ParamType, ArgType)) {
9562         BestKind = Kind;
9563         break;
9564       }
9565     }
9566   }
9567   return BestKind;
9568 }
9569 
9570 enum AbsoluteValueKind {
9571   AVK_Integer,
9572   AVK_Floating,
9573   AVK_Complex
9574 };
9575 
9576 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9577   if (T->isIntegralOrEnumerationType())
9578     return AVK_Integer;
9579   if (T->isRealFloatingType())
9580     return AVK_Floating;
9581   if (T->isAnyComplexType())
9582     return AVK_Complex;
9583 
9584   llvm_unreachable("Type not integer, floating, or complex");
9585 }
9586 
9587 // Changes the absolute value function to a different type.  Preserves whether
9588 // the function is a builtin.
9589 static unsigned changeAbsFunction(unsigned AbsKind,
9590                                   AbsoluteValueKind ValueKind) {
9591   switch (ValueKind) {
9592   case AVK_Integer:
9593     switch (AbsKind) {
9594     default:
9595       return 0;
9596     case Builtin::BI__builtin_fabsf:
9597     case Builtin::BI__builtin_fabs:
9598     case Builtin::BI__builtin_fabsl:
9599     case Builtin::BI__builtin_cabsf:
9600     case Builtin::BI__builtin_cabs:
9601     case Builtin::BI__builtin_cabsl:
9602       return Builtin::BI__builtin_abs;
9603     case Builtin::BIfabsf:
9604     case Builtin::BIfabs:
9605     case Builtin::BIfabsl:
9606     case Builtin::BIcabsf:
9607     case Builtin::BIcabs:
9608     case Builtin::BIcabsl:
9609       return Builtin::BIabs;
9610     }
9611   case AVK_Floating:
9612     switch (AbsKind) {
9613     default:
9614       return 0;
9615     case Builtin::BI__builtin_abs:
9616     case Builtin::BI__builtin_labs:
9617     case Builtin::BI__builtin_llabs:
9618     case Builtin::BI__builtin_cabsf:
9619     case Builtin::BI__builtin_cabs:
9620     case Builtin::BI__builtin_cabsl:
9621       return Builtin::BI__builtin_fabsf;
9622     case Builtin::BIabs:
9623     case Builtin::BIlabs:
9624     case Builtin::BIllabs:
9625     case Builtin::BIcabsf:
9626     case Builtin::BIcabs:
9627     case Builtin::BIcabsl:
9628       return Builtin::BIfabsf;
9629     }
9630   case AVK_Complex:
9631     switch (AbsKind) {
9632     default:
9633       return 0;
9634     case Builtin::BI__builtin_abs:
9635     case Builtin::BI__builtin_labs:
9636     case Builtin::BI__builtin_llabs:
9637     case Builtin::BI__builtin_fabsf:
9638     case Builtin::BI__builtin_fabs:
9639     case Builtin::BI__builtin_fabsl:
9640       return Builtin::BI__builtin_cabsf;
9641     case Builtin::BIabs:
9642     case Builtin::BIlabs:
9643     case Builtin::BIllabs:
9644     case Builtin::BIfabsf:
9645     case Builtin::BIfabs:
9646     case Builtin::BIfabsl:
9647       return Builtin::BIcabsf;
9648     }
9649   }
9650   llvm_unreachable("Unable to convert function");
9651 }
9652 
9653 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9654   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9655   if (!FnInfo)
9656     return 0;
9657 
9658   switch (FDecl->getBuiltinID()) {
9659   default:
9660     return 0;
9661   case Builtin::BI__builtin_abs:
9662   case Builtin::BI__builtin_fabs:
9663   case Builtin::BI__builtin_fabsf:
9664   case Builtin::BI__builtin_fabsl:
9665   case Builtin::BI__builtin_labs:
9666   case Builtin::BI__builtin_llabs:
9667   case Builtin::BI__builtin_cabs:
9668   case Builtin::BI__builtin_cabsf:
9669   case Builtin::BI__builtin_cabsl:
9670   case Builtin::BIabs:
9671   case Builtin::BIlabs:
9672   case Builtin::BIllabs:
9673   case Builtin::BIfabs:
9674   case Builtin::BIfabsf:
9675   case Builtin::BIfabsl:
9676   case Builtin::BIcabs:
9677   case Builtin::BIcabsf:
9678   case Builtin::BIcabsl:
9679     return FDecl->getBuiltinID();
9680   }
9681   llvm_unreachable("Unknown Builtin type");
9682 }
9683 
9684 // If the replacement is valid, emit a note with replacement function.
9685 // Additionally, suggest including the proper header if not already included.
9686 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9687                             unsigned AbsKind, QualType ArgType) {
9688   bool EmitHeaderHint = true;
9689   const char *HeaderName = nullptr;
9690   const char *FunctionName = nullptr;
9691   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9692     FunctionName = "std::abs";
9693     if (ArgType->isIntegralOrEnumerationType()) {
9694       HeaderName = "cstdlib";
9695     } else if (ArgType->isRealFloatingType()) {
9696       HeaderName = "cmath";
9697     } else {
9698       llvm_unreachable("Invalid Type");
9699     }
9700 
9701     // Lookup all std::abs
9702     if (NamespaceDecl *Std = S.getStdNamespace()) {
9703       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9704       R.suppressDiagnostics();
9705       S.LookupQualifiedName(R, Std);
9706 
9707       for (const auto *I : R) {
9708         const FunctionDecl *FDecl = nullptr;
9709         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9710           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9711         } else {
9712           FDecl = dyn_cast<FunctionDecl>(I);
9713         }
9714         if (!FDecl)
9715           continue;
9716 
9717         // Found std::abs(), check that they are the right ones.
9718         if (FDecl->getNumParams() != 1)
9719           continue;
9720 
9721         // Check that the parameter type can handle the argument.
9722         QualType ParamType = FDecl->getParamDecl(0)->getType();
9723         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9724             S.Context.getTypeSize(ArgType) <=
9725                 S.Context.getTypeSize(ParamType)) {
9726           // Found a function, don't need the header hint.
9727           EmitHeaderHint = false;
9728           break;
9729         }
9730       }
9731     }
9732   } else {
9733     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9734     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9735 
9736     if (HeaderName) {
9737       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9738       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9739       R.suppressDiagnostics();
9740       S.LookupName(R, S.getCurScope());
9741 
9742       if (R.isSingleResult()) {
9743         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9744         if (FD && FD->getBuiltinID() == AbsKind) {
9745           EmitHeaderHint = false;
9746         } else {
9747           return;
9748         }
9749       } else if (!R.empty()) {
9750         return;
9751       }
9752     }
9753   }
9754 
9755   S.Diag(Loc, diag::note_replace_abs_function)
9756       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9757 
9758   if (!HeaderName)
9759     return;
9760 
9761   if (!EmitHeaderHint)
9762     return;
9763 
9764   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9765                                                     << FunctionName;
9766 }
9767 
9768 template <std::size_t StrLen>
9769 static bool IsStdFunction(const FunctionDecl *FDecl,
9770                           const char (&Str)[StrLen]) {
9771   if (!FDecl)
9772     return false;
9773   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9774     return false;
9775   if (!FDecl->isInStdNamespace())
9776     return false;
9777 
9778   return true;
9779 }
9780 
9781 // Warn when using the wrong abs() function.
9782 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9783                                       const FunctionDecl *FDecl) {
9784   if (Call->getNumArgs() != 1)
9785     return;
9786 
9787   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9788   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9789   if (AbsKind == 0 && !IsStdAbs)
9790     return;
9791 
9792   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9793   QualType ParamType = Call->getArg(0)->getType();
9794 
9795   // Unsigned types cannot be negative.  Suggest removing the absolute value
9796   // function call.
9797   if (ArgType->isUnsignedIntegerType()) {
9798     const char *FunctionName =
9799         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9800     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9801     Diag(Call->getExprLoc(), diag::note_remove_abs)
9802         << FunctionName
9803         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9804     return;
9805   }
9806 
9807   // Taking the absolute value of a pointer is very suspicious, they probably
9808   // wanted to index into an array, dereference a pointer, call a function, etc.
9809   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9810     unsigned DiagType = 0;
9811     if (ArgType->isFunctionType())
9812       DiagType = 1;
9813     else if (ArgType->isArrayType())
9814       DiagType = 2;
9815 
9816     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9817     return;
9818   }
9819 
9820   // std::abs has overloads which prevent most of the absolute value problems
9821   // from occurring.
9822   if (IsStdAbs)
9823     return;
9824 
9825   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9826   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9827 
9828   // The argument and parameter are the same kind.  Check if they are the right
9829   // size.
9830   if (ArgValueKind == ParamValueKind) {
9831     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9832       return;
9833 
9834     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9835     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9836         << FDecl << ArgType << ParamType;
9837 
9838     if (NewAbsKind == 0)
9839       return;
9840 
9841     emitReplacement(*this, Call->getExprLoc(),
9842                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9843     return;
9844   }
9845 
9846   // ArgValueKind != ParamValueKind
9847   // The wrong type of absolute value function was used.  Attempt to find the
9848   // proper one.
9849   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9850   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9851   if (NewAbsKind == 0)
9852     return;
9853 
9854   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9855       << FDecl << ParamValueKind << ArgValueKind;
9856 
9857   emitReplacement(*this, Call->getExprLoc(),
9858                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9859 }
9860 
9861 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9862 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9863                                 const FunctionDecl *FDecl) {
9864   if (!Call || !FDecl) return;
9865 
9866   // Ignore template specializations and macros.
9867   if (inTemplateInstantiation()) return;
9868   if (Call->getExprLoc().isMacroID()) return;
9869 
9870   // Only care about the one template argument, two function parameter std::max
9871   if (Call->getNumArgs() != 2) return;
9872   if (!IsStdFunction(FDecl, "max")) return;
9873   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9874   if (!ArgList) return;
9875   if (ArgList->size() != 1) return;
9876 
9877   // Check that template type argument is unsigned integer.
9878   const auto& TA = ArgList->get(0);
9879   if (TA.getKind() != TemplateArgument::Type) return;
9880   QualType ArgType = TA.getAsType();
9881   if (!ArgType->isUnsignedIntegerType()) return;
9882 
9883   // See if either argument is a literal zero.
9884   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9885     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9886     if (!MTE) return false;
9887     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9888     if (!Num) return false;
9889     if (Num->getValue() != 0) return false;
9890     return true;
9891   };
9892 
9893   const Expr *FirstArg = Call->getArg(0);
9894   const Expr *SecondArg = Call->getArg(1);
9895   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9896   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9897 
9898   // Only warn when exactly one argument is zero.
9899   if (IsFirstArgZero == IsSecondArgZero) return;
9900 
9901   SourceRange FirstRange = FirstArg->getSourceRange();
9902   SourceRange SecondRange = SecondArg->getSourceRange();
9903 
9904   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9905 
9906   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9907       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9908 
9909   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9910   SourceRange RemovalRange;
9911   if (IsFirstArgZero) {
9912     RemovalRange = SourceRange(FirstRange.getBegin(),
9913                                SecondRange.getBegin().getLocWithOffset(-1));
9914   } else {
9915     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9916                                SecondRange.getEnd());
9917   }
9918 
9919   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9920         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9921         << FixItHint::CreateRemoval(RemovalRange);
9922 }
9923 
9924 //===--- CHECK: Standard memory functions ---------------------------------===//
9925 
9926 /// Takes the expression passed to the size_t parameter of functions
9927 /// such as memcmp, strncat, etc and warns if it's a comparison.
9928 ///
9929 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9930 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9931                                            IdentifierInfo *FnName,
9932                                            SourceLocation FnLoc,
9933                                            SourceLocation RParenLoc) {
9934   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9935   if (!Size)
9936     return false;
9937 
9938   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9939   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9940     return false;
9941 
9942   SourceRange SizeRange = Size->getSourceRange();
9943   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9944       << SizeRange << FnName;
9945   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9946       << FnName
9947       << FixItHint::CreateInsertion(
9948              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9949       << FixItHint::CreateRemoval(RParenLoc);
9950   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9951       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9952       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9953                                     ")");
9954 
9955   return true;
9956 }
9957 
9958 /// Determine whether the given type is or contains a dynamic class type
9959 /// (e.g., whether it has a vtable).
9960 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9961                                                      bool &IsContained) {
9962   // Look through array types while ignoring qualifiers.
9963   const Type *Ty = T->getBaseElementTypeUnsafe();
9964   IsContained = false;
9965 
9966   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9967   RD = RD ? RD->getDefinition() : nullptr;
9968   if (!RD || RD->isInvalidDecl())
9969     return nullptr;
9970 
9971   if (RD->isDynamicClass())
9972     return RD;
9973 
9974   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9975   // It's impossible for a class to transitively contain itself by value, so
9976   // infinite recursion is impossible.
9977   for (auto *FD : RD->fields()) {
9978     bool SubContained;
9979     if (const CXXRecordDecl *ContainedRD =
9980             getContainedDynamicClass(FD->getType(), SubContained)) {
9981       IsContained = true;
9982       return ContainedRD;
9983     }
9984   }
9985 
9986   return nullptr;
9987 }
9988 
9989 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9990   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9991     if (Unary->getKind() == UETT_SizeOf)
9992       return Unary;
9993   return nullptr;
9994 }
9995 
9996 /// If E is a sizeof expression, returns its argument expression,
9997 /// otherwise returns NULL.
9998 static const Expr *getSizeOfExprArg(const Expr *E) {
9999   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10000     if (!SizeOf->isArgumentType())
10001       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10002   return nullptr;
10003 }
10004 
10005 /// If E is a sizeof expression, returns its argument type.
10006 static QualType getSizeOfArgType(const Expr *E) {
10007   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10008     return SizeOf->getTypeOfArgument();
10009   return QualType();
10010 }
10011 
10012 namespace {
10013 
10014 struct SearchNonTrivialToInitializeField
10015     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10016   using Super =
10017       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10018 
10019   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10020 
10021   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10022                      SourceLocation SL) {
10023     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10024       asDerived().visitArray(PDIK, AT, SL);
10025       return;
10026     }
10027 
10028     Super::visitWithKind(PDIK, FT, SL);
10029   }
10030 
10031   void visitARCStrong(QualType FT, SourceLocation SL) {
10032     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10033   }
10034   void visitARCWeak(QualType FT, SourceLocation SL) {
10035     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10036   }
10037   void visitStruct(QualType FT, SourceLocation SL) {
10038     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10039       visit(FD->getType(), FD->getLocation());
10040   }
10041   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10042                   const ArrayType *AT, SourceLocation SL) {
10043     visit(getContext().getBaseElementType(AT), SL);
10044   }
10045   void visitTrivial(QualType FT, SourceLocation SL) {}
10046 
10047   static void diag(QualType RT, const Expr *E, Sema &S) {
10048     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10049   }
10050 
10051   ASTContext &getContext() { return S.getASTContext(); }
10052 
10053   const Expr *E;
10054   Sema &S;
10055 };
10056 
10057 struct SearchNonTrivialToCopyField
10058     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10059   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10060 
10061   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10062 
10063   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10064                      SourceLocation SL) {
10065     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10066       asDerived().visitArray(PCK, AT, SL);
10067       return;
10068     }
10069 
10070     Super::visitWithKind(PCK, FT, SL);
10071   }
10072 
10073   void visitARCStrong(QualType FT, SourceLocation SL) {
10074     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10075   }
10076   void visitARCWeak(QualType FT, SourceLocation SL) {
10077     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10078   }
10079   void visitStruct(QualType FT, SourceLocation SL) {
10080     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10081       visit(FD->getType(), FD->getLocation());
10082   }
10083   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10084                   SourceLocation SL) {
10085     visit(getContext().getBaseElementType(AT), SL);
10086   }
10087   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10088                 SourceLocation SL) {}
10089   void visitTrivial(QualType FT, SourceLocation SL) {}
10090   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10091 
10092   static void diag(QualType RT, const Expr *E, Sema &S) {
10093     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10094   }
10095 
10096   ASTContext &getContext() { return S.getASTContext(); }
10097 
10098   const Expr *E;
10099   Sema &S;
10100 };
10101 
10102 }
10103 
10104 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10105 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10106   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10107 
10108   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10109     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10110       return false;
10111 
10112     return doesExprLikelyComputeSize(BO->getLHS()) ||
10113            doesExprLikelyComputeSize(BO->getRHS());
10114   }
10115 
10116   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10117 }
10118 
10119 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10120 ///
10121 /// \code
10122 ///   #define MACRO 0
10123 ///   foo(MACRO);
10124 ///   foo(0);
10125 /// \endcode
10126 ///
10127 /// This should return true for the first call to foo, but not for the second
10128 /// (regardless of whether foo is a macro or function).
10129 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10130                                         SourceLocation CallLoc,
10131                                         SourceLocation ArgLoc) {
10132   if (!CallLoc.isMacroID())
10133     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10134 
10135   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10136          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10137 }
10138 
10139 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10140 /// last two arguments transposed.
10141 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10142   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10143     return;
10144 
10145   const Expr *SizeArg =
10146     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10147 
10148   auto isLiteralZero = [](const Expr *E) {
10149     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10150   };
10151 
10152   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10153   SourceLocation CallLoc = Call->getRParenLoc();
10154   SourceManager &SM = S.getSourceManager();
10155   if (isLiteralZero(SizeArg) &&
10156       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10157 
10158     SourceLocation DiagLoc = SizeArg->getExprLoc();
10159 
10160     // Some platforms #define bzero to __builtin_memset. See if this is the
10161     // case, and if so, emit a better diagnostic.
10162     if (BId == Builtin::BIbzero ||
10163         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10164                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10165       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10166       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10167     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10168       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10169       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10170     }
10171     return;
10172   }
10173 
10174   // If the second argument to a memset is a sizeof expression and the third
10175   // isn't, this is also likely an error. This should catch
10176   // 'memset(buf, sizeof(buf), 0xff)'.
10177   if (BId == Builtin::BImemset &&
10178       doesExprLikelyComputeSize(Call->getArg(1)) &&
10179       !doesExprLikelyComputeSize(Call->getArg(2))) {
10180     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10181     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10182     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10183     return;
10184   }
10185 }
10186 
10187 /// Check for dangerous or invalid arguments to memset().
10188 ///
10189 /// This issues warnings on known problematic, dangerous or unspecified
10190 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10191 /// function calls.
10192 ///
10193 /// \param Call The call expression to diagnose.
10194 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10195                                    unsigned BId,
10196                                    IdentifierInfo *FnName) {
10197   assert(BId != 0);
10198 
10199   // It is possible to have a non-standard definition of memset.  Validate
10200   // we have enough arguments, and if not, abort further checking.
10201   unsigned ExpectedNumArgs =
10202       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10203   if (Call->getNumArgs() < ExpectedNumArgs)
10204     return;
10205 
10206   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10207                       BId == Builtin::BIstrndup ? 1 : 2);
10208   unsigned LenArg =
10209       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10210   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10211 
10212   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10213                                      Call->getBeginLoc(), Call->getRParenLoc()))
10214     return;
10215 
10216   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10217   CheckMemaccessSize(*this, BId, Call);
10218 
10219   // We have special checking when the length is a sizeof expression.
10220   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10221   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10222   llvm::FoldingSetNodeID SizeOfArgID;
10223 
10224   // Although widely used, 'bzero' is not a standard function. Be more strict
10225   // with the argument types before allowing diagnostics and only allow the
10226   // form bzero(ptr, sizeof(...)).
10227   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10228   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10229     return;
10230 
10231   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10232     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10233     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10234 
10235     QualType DestTy = Dest->getType();
10236     QualType PointeeTy;
10237     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10238       PointeeTy = DestPtrTy->getPointeeType();
10239 
10240       // Never warn about void type pointers. This can be used to suppress
10241       // false positives.
10242       if (PointeeTy->isVoidType())
10243         continue;
10244 
10245       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10246       // actually comparing the expressions for equality. Because computing the
10247       // expression IDs can be expensive, we only do this if the diagnostic is
10248       // enabled.
10249       if (SizeOfArg &&
10250           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10251                            SizeOfArg->getExprLoc())) {
10252         // We only compute IDs for expressions if the warning is enabled, and
10253         // cache the sizeof arg's ID.
10254         if (SizeOfArgID == llvm::FoldingSetNodeID())
10255           SizeOfArg->Profile(SizeOfArgID, Context, true);
10256         llvm::FoldingSetNodeID DestID;
10257         Dest->Profile(DestID, Context, true);
10258         if (DestID == SizeOfArgID) {
10259           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10260           //       over sizeof(src) as well.
10261           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10262           StringRef ReadableName = FnName->getName();
10263 
10264           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10265             if (UnaryOp->getOpcode() == UO_AddrOf)
10266               ActionIdx = 1; // If its an address-of operator, just remove it.
10267           if (!PointeeTy->isIncompleteType() &&
10268               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10269             ActionIdx = 2; // If the pointee's size is sizeof(char),
10270                            // suggest an explicit length.
10271 
10272           // If the function is defined as a builtin macro, do not show macro
10273           // expansion.
10274           SourceLocation SL = SizeOfArg->getExprLoc();
10275           SourceRange DSR = Dest->getSourceRange();
10276           SourceRange SSR = SizeOfArg->getSourceRange();
10277           SourceManager &SM = getSourceManager();
10278 
10279           if (SM.isMacroArgExpansion(SL)) {
10280             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10281             SL = SM.getSpellingLoc(SL);
10282             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10283                              SM.getSpellingLoc(DSR.getEnd()));
10284             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10285                              SM.getSpellingLoc(SSR.getEnd()));
10286           }
10287 
10288           DiagRuntimeBehavior(SL, SizeOfArg,
10289                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10290                                 << ReadableName
10291                                 << PointeeTy
10292                                 << DestTy
10293                                 << DSR
10294                                 << SSR);
10295           DiagRuntimeBehavior(SL, SizeOfArg,
10296                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10297                                 << ActionIdx
10298                                 << SSR);
10299 
10300           break;
10301         }
10302       }
10303 
10304       // Also check for cases where the sizeof argument is the exact same
10305       // type as the memory argument, and where it points to a user-defined
10306       // record type.
10307       if (SizeOfArgTy != QualType()) {
10308         if (PointeeTy->isRecordType() &&
10309             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10310           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10311                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10312                                 << FnName << SizeOfArgTy << ArgIdx
10313                                 << PointeeTy << Dest->getSourceRange()
10314                                 << LenExpr->getSourceRange());
10315           break;
10316         }
10317       }
10318     } else if (DestTy->isArrayType()) {
10319       PointeeTy = DestTy;
10320     }
10321 
10322     if (PointeeTy == QualType())
10323       continue;
10324 
10325     // Always complain about dynamic classes.
10326     bool IsContained;
10327     if (const CXXRecordDecl *ContainedRD =
10328             getContainedDynamicClass(PointeeTy, IsContained)) {
10329 
10330       unsigned OperationType = 0;
10331       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10332       // "overwritten" if we're warning about the destination for any call
10333       // but memcmp; otherwise a verb appropriate to the call.
10334       if (ArgIdx != 0 || IsCmp) {
10335         if (BId == Builtin::BImemcpy)
10336           OperationType = 1;
10337         else if(BId == Builtin::BImemmove)
10338           OperationType = 2;
10339         else if (IsCmp)
10340           OperationType = 3;
10341       }
10342 
10343       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10344                           PDiag(diag::warn_dyn_class_memaccess)
10345                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10346                               << IsContained << ContainedRD << OperationType
10347                               << Call->getCallee()->getSourceRange());
10348     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10349              BId != Builtin::BImemset)
10350       DiagRuntimeBehavior(
10351         Dest->getExprLoc(), Dest,
10352         PDiag(diag::warn_arc_object_memaccess)
10353           << ArgIdx << FnName << PointeeTy
10354           << Call->getCallee()->getSourceRange());
10355     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10356       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10357           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10358         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10359                             PDiag(diag::warn_cstruct_memaccess)
10360                                 << ArgIdx << FnName << PointeeTy << 0);
10361         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10362       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10363                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10364         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10365                             PDiag(diag::warn_cstruct_memaccess)
10366                                 << ArgIdx << FnName << PointeeTy << 1);
10367         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10368       } else {
10369         continue;
10370       }
10371     } else
10372       continue;
10373 
10374     DiagRuntimeBehavior(
10375       Dest->getExprLoc(), Dest,
10376       PDiag(diag::note_bad_memaccess_silence)
10377         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10378     break;
10379   }
10380 }
10381 
10382 // A little helper routine: ignore addition and subtraction of integer literals.
10383 // This intentionally does not ignore all integer constant expressions because
10384 // we don't want to remove sizeof().
10385 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10386   Ex = Ex->IgnoreParenCasts();
10387 
10388   while (true) {
10389     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10390     if (!BO || !BO->isAdditiveOp())
10391       break;
10392 
10393     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10394     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10395 
10396     if (isa<IntegerLiteral>(RHS))
10397       Ex = LHS;
10398     else if (isa<IntegerLiteral>(LHS))
10399       Ex = RHS;
10400     else
10401       break;
10402   }
10403 
10404   return Ex;
10405 }
10406 
10407 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10408                                                       ASTContext &Context) {
10409   // Only handle constant-sized or VLAs, but not flexible members.
10410   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10411     // Only issue the FIXIT for arrays of size > 1.
10412     if (CAT->getSize().getSExtValue() <= 1)
10413       return false;
10414   } else if (!Ty->isVariableArrayType()) {
10415     return false;
10416   }
10417   return true;
10418 }
10419 
10420 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10421 // be the size of the source, instead of the destination.
10422 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10423                                     IdentifierInfo *FnName) {
10424 
10425   // Don't crash if the user has the wrong number of arguments
10426   unsigned NumArgs = Call->getNumArgs();
10427   if ((NumArgs != 3) && (NumArgs != 4))
10428     return;
10429 
10430   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10431   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10432   const Expr *CompareWithSrc = nullptr;
10433 
10434   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10435                                      Call->getBeginLoc(), Call->getRParenLoc()))
10436     return;
10437 
10438   // Look for 'strlcpy(dst, x, sizeof(x))'
10439   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10440     CompareWithSrc = Ex;
10441   else {
10442     // Look for 'strlcpy(dst, x, strlen(x))'
10443     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10444       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10445           SizeCall->getNumArgs() == 1)
10446         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10447     }
10448   }
10449 
10450   if (!CompareWithSrc)
10451     return;
10452 
10453   // Determine if the argument to sizeof/strlen is equal to the source
10454   // argument.  In principle there's all kinds of things you could do
10455   // here, for instance creating an == expression and evaluating it with
10456   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10457   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10458   if (!SrcArgDRE)
10459     return;
10460 
10461   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10462   if (!CompareWithSrcDRE ||
10463       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10464     return;
10465 
10466   const Expr *OriginalSizeArg = Call->getArg(2);
10467   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10468       << OriginalSizeArg->getSourceRange() << FnName;
10469 
10470   // Output a FIXIT hint if the destination is an array (rather than a
10471   // pointer to an array).  This could be enhanced to handle some
10472   // pointers if we know the actual size, like if DstArg is 'array+2'
10473   // we could say 'sizeof(array)-2'.
10474   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10475   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10476     return;
10477 
10478   SmallString<128> sizeString;
10479   llvm::raw_svector_ostream OS(sizeString);
10480   OS << "sizeof(";
10481   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10482   OS << ")";
10483 
10484   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10485       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10486                                       OS.str());
10487 }
10488 
10489 /// Check if two expressions refer to the same declaration.
10490 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10491   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10492     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10493       return D1->getDecl() == D2->getDecl();
10494   return false;
10495 }
10496 
10497 static const Expr *getStrlenExprArg(const Expr *E) {
10498   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10499     const FunctionDecl *FD = CE->getDirectCallee();
10500     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10501       return nullptr;
10502     return CE->getArg(0)->IgnoreParenCasts();
10503   }
10504   return nullptr;
10505 }
10506 
10507 // Warn on anti-patterns as the 'size' argument to strncat.
10508 // The correct size argument should look like following:
10509 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10510 void Sema::CheckStrncatArguments(const CallExpr *CE,
10511                                  IdentifierInfo *FnName) {
10512   // Don't crash if the user has the wrong number of arguments.
10513   if (CE->getNumArgs() < 3)
10514     return;
10515   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10516   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10517   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10518 
10519   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10520                                      CE->getRParenLoc()))
10521     return;
10522 
10523   // Identify common expressions, which are wrongly used as the size argument
10524   // to strncat and may lead to buffer overflows.
10525   unsigned PatternType = 0;
10526   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10527     // - sizeof(dst)
10528     if (referToTheSameDecl(SizeOfArg, DstArg))
10529       PatternType = 1;
10530     // - sizeof(src)
10531     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10532       PatternType = 2;
10533   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10534     if (BE->getOpcode() == BO_Sub) {
10535       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10536       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10537       // - sizeof(dst) - strlen(dst)
10538       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10539           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10540         PatternType = 1;
10541       // - sizeof(src) - (anything)
10542       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10543         PatternType = 2;
10544     }
10545   }
10546 
10547   if (PatternType == 0)
10548     return;
10549 
10550   // Generate the diagnostic.
10551   SourceLocation SL = LenArg->getBeginLoc();
10552   SourceRange SR = LenArg->getSourceRange();
10553   SourceManager &SM = getSourceManager();
10554 
10555   // If the function is defined as a builtin macro, do not show macro expansion.
10556   if (SM.isMacroArgExpansion(SL)) {
10557     SL = SM.getSpellingLoc(SL);
10558     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10559                      SM.getSpellingLoc(SR.getEnd()));
10560   }
10561 
10562   // Check if the destination is an array (rather than a pointer to an array).
10563   QualType DstTy = DstArg->getType();
10564   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10565                                                                     Context);
10566   if (!isKnownSizeArray) {
10567     if (PatternType == 1)
10568       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10569     else
10570       Diag(SL, diag::warn_strncat_src_size) << SR;
10571     return;
10572   }
10573 
10574   if (PatternType == 1)
10575     Diag(SL, diag::warn_strncat_large_size) << SR;
10576   else
10577     Diag(SL, diag::warn_strncat_src_size) << SR;
10578 
10579   SmallString<128> sizeString;
10580   llvm::raw_svector_ostream OS(sizeString);
10581   OS << "sizeof(";
10582   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10583   OS << ") - ";
10584   OS << "strlen(";
10585   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10586   OS << ") - 1";
10587 
10588   Diag(SL, diag::note_strncat_wrong_size)
10589     << FixItHint::CreateReplacement(SR, OS.str());
10590 }
10591 
10592 namespace {
10593 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10594                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10595   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10596     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10597         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10598     return;
10599   }
10600 }
10601 
10602 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10603                                  const UnaryOperator *UnaryExpr) {
10604   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10605     const Decl *D = Lvalue->getDecl();
10606     if (isa<VarDecl, FunctionDecl>(D))
10607       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10608   }
10609 
10610   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10611     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10612                                       Lvalue->getMemberDecl());
10613 }
10614 
10615 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10616                             const UnaryOperator *UnaryExpr) {
10617   const auto *Lambda = dyn_cast<LambdaExpr>(
10618       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10619   if (!Lambda)
10620     return;
10621 
10622   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10623       << CalleeName << 2 /*object: lambda expression*/;
10624 }
10625 
10626 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10627                                   const DeclRefExpr *Lvalue) {
10628   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10629   if (Var == nullptr)
10630     return;
10631 
10632   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10633       << CalleeName << 0 /*object: */ << Var;
10634 }
10635 
10636 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10637                             const CastExpr *Cast) {
10638   SmallString<128> SizeString;
10639   llvm::raw_svector_ostream OS(SizeString);
10640 
10641   clang::CastKind Kind = Cast->getCastKind();
10642   if (Kind == clang::CK_BitCast &&
10643       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10644     return;
10645   if (Kind == clang::CK_IntegralToPointer &&
10646       !isa<IntegerLiteral>(
10647           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10648     return;
10649 
10650   switch (Cast->getCastKind()) {
10651   case clang::CK_BitCast:
10652   case clang::CK_IntegralToPointer:
10653   case clang::CK_FunctionToPointerDecay:
10654     OS << '\'';
10655     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10656     OS << '\'';
10657     break;
10658   default:
10659     return;
10660   }
10661 
10662   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10663       << CalleeName << 0 /*object: */ << OS.str();
10664 }
10665 } // namespace
10666 
10667 /// Alerts the user that they are attempting to free a non-malloc'd object.
10668 void Sema::CheckFreeArguments(const CallExpr *E) {
10669   const std::string CalleeName =
10670       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10671 
10672   { // Prefer something that doesn't involve a cast to make things simpler.
10673     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10674     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10675       switch (UnaryExpr->getOpcode()) {
10676       case UnaryOperator::Opcode::UO_AddrOf:
10677         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10678       case UnaryOperator::Opcode::UO_Plus:
10679         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10680       default:
10681         break;
10682       }
10683 
10684     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10685       if (Lvalue->getType()->isArrayType())
10686         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10687 
10688     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10689       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10690           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10691       return;
10692     }
10693 
10694     if (isa<BlockExpr>(Arg)) {
10695       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10696           << CalleeName << 1 /*object: block*/;
10697       return;
10698     }
10699   }
10700   // Maybe the cast was important, check after the other cases.
10701   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10702     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10703 }
10704 
10705 void
10706 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10707                          SourceLocation ReturnLoc,
10708                          bool isObjCMethod,
10709                          const AttrVec *Attrs,
10710                          const FunctionDecl *FD) {
10711   // Check if the return value is null but should not be.
10712   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10713        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10714       CheckNonNullExpr(*this, RetValExp))
10715     Diag(ReturnLoc, diag::warn_null_ret)
10716       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10717 
10718   // C++11 [basic.stc.dynamic.allocation]p4:
10719   //   If an allocation function declared with a non-throwing
10720   //   exception-specification fails to allocate storage, it shall return
10721   //   a null pointer. Any other allocation function that fails to allocate
10722   //   storage shall indicate failure only by throwing an exception [...]
10723   if (FD) {
10724     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10725     if (Op == OO_New || Op == OO_Array_New) {
10726       const FunctionProtoType *Proto
10727         = FD->getType()->castAs<FunctionProtoType>();
10728       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10729           CheckNonNullExpr(*this, RetValExp))
10730         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10731           << FD << getLangOpts().CPlusPlus11;
10732     }
10733   }
10734 
10735   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10736   // here prevent the user from using a PPC MMA type as trailing return type.
10737   if (Context.getTargetInfo().getTriple().isPPC64())
10738     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10739 }
10740 
10741 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10742 
10743 /// Check for comparisons of floating point operands using != and ==.
10744 /// Issue a warning if these are no self-comparisons, as they are not likely
10745 /// to do what the programmer intended.
10746 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10747   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10748   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10749 
10750   // Special case: check for x == x (which is OK).
10751   // Do not emit warnings for such cases.
10752   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10753     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10754       if (DRL->getDecl() == DRR->getDecl())
10755         return;
10756 
10757   // Special case: check for comparisons against literals that can be exactly
10758   //  represented by APFloat.  In such cases, do not emit a warning.  This
10759   //  is a heuristic: often comparison against such literals are used to
10760   //  detect if a value in a variable has not changed.  This clearly can
10761   //  lead to false negatives.
10762   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10763     if (FLL->isExact())
10764       return;
10765   } else
10766     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10767       if (FLR->isExact())
10768         return;
10769 
10770   // Check for comparisons with builtin types.
10771   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10772     if (CL->getBuiltinCallee())
10773       return;
10774 
10775   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10776     if (CR->getBuiltinCallee())
10777       return;
10778 
10779   // Emit the diagnostic.
10780   Diag(Loc, diag::warn_floatingpoint_eq)
10781     << LHS->getSourceRange() << RHS->getSourceRange();
10782 }
10783 
10784 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10785 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10786 
10787 namespace {
10788 
10789 /// Structure recording the 'active' range of an integer-valued
10790 /// expression.
10791 struct IntRange {
10792   /// The number of bits active in the int. Note that this includes exactly one
10793   /// sign bit if !NonNegative.
10794   unsigned Width;
10795 
10796   /// True if the int is known not to have negative values. If so, all leading
10797   /// bits before Width are known zero, otherwise they are known to be the
10798   /// same as the MSB within Width.
10799   bool NonNegative;
10800 
10801   IntRange(unsigned Width, bool NonNegative)
10802       : Width(Width), NonNegative(NonNegative) {}
10803 
10804   /// Number of bits excluding the sign bit.
10805   unsigned valueBits() const {
10806     return NonNegative ? Width : Width - 1;
10807   }
10808 
10809   /// Returns the range of the bool type.
10810   static IntRange forBoolType() {
10811     return IntRange(1, true);
10812   }
10813 
10814   /// Returns the range of an opaque value of the given integral type.
10815   static IntRange forValueOfType(ASTContext &C, QualType T) {
10816     return forValueOfCanonicalType(C,
10817                           T->getCanonicalTypeInternal().getTypePtr());
10818   }
10819 
10820   /// Returns the range of an opaque value of a canonical integral type.
10821   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10822     assert(T->isCanonicalUnqualified());
10823 
10824     if (const VectorType *VT = dyn_cast<VectorType>(T))
10825       T = VT->getElementType().getTypePtr();
10826     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10827       T = CT->getElementType().getTypePtr();
10828     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10829       T = AT->getValueType().getTypePtr();
10830 
10831     if (!C.getLangOpts().CPlusPlus) {
10832       // For enum types in C code, use the underlying datatype.
10833       if (const EnumType *ET = dyn_cast<EnumType>(T))
10834         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10835     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10836       // For enum types in C++, use the known bit width of the enumerators.
10837       EnumDecl *Enum = ET->getDecl();
10838       // In C++11, enums can have a fixed underlying type. Use this type to
10839       // compute the range.
10840       if (Enum->isFixed()) {
10841         return IntRange(C.getIntWidth(QualType(T, 0)),
10842                         !ET->isSignedIntegerOrEnumerationType());
10843       }
10844 
10845       unsigned NumPositive = Enum->getNumPositiveBits();
10846       unsigned NumNegative = Enum->getNumNegativeBits();
10847 
10848       if (NumNegative == 0)
10849         return IntRange(NumPositive, true/*NonNegative*/);
10850       else
10851         return IntRange(std::max(NumPositive + 1, NumNegative),
10852                         false/*NonNegative*/);
10853     }
10854 
10855     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10856       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10857 
10858     const BuiltinType *BT = cast<BuiltinType>(T);
10859     assert(BT->isInteger());
10860 
10861     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10862   }
10863 
10864   /// Returns the "target" range of a canonical integral type, i.e.
10865   /// the range of values expressible in the type.
10866   ///
10867   /// This matches forValueOfCanonicalType except that enums have the
10868   /// full range of their type, not the range of their enumerators.
10869   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10870     assert(T->isCanonicalUnqualified());
10871 
10872     if (const VectorType *VT = dyn_cast<VectorType>(T))
10873       T = VT->getElementType().getTypePtr();
10874     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10875       T = CT->getElementType().getTypePtr();
10876     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10877       T = AT->getValueType().getTypePtr();
10878     if (const EnumType *ET = dyn_cast<EnumType>(T))
10879       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10880 
10881     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10882       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10883 
10884     const BuiltinType *BT = cast<BuiltinType>(T);
10885     assert(BT->isInteger());
10886 
10887     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10888   }
10889 
10890   /// Returns the supremum of two ranges: i.e. their conservative merge.
10891   static IntRange join(IntRange L, IntRange R) {
10892     bool Unsigned = L.NonNegative && R.NonNegative;
10893     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10894                     L.NonNegative && R.NonNegative);
10895   }
10896 
10897   /// Return the range of a bitwise-AND of the two ranges.
10898   static IntRange bit_and(IntRange L, IntRange R) {
10899     unsigned Bits = std::max(L.Width, R.Width);
10900     bool NonNegative = false;
10901     if (L.NonNegative) {
10902       Bits = std::min(Bits, L.Width);
10903       NonNegative = true;
10904     }
10905     if (R.NonNegative) {
10906       Bits = std::min(Bits, R.Width);
10907       NonNegative = true;
10908     }
10909     return IntRange(Bits, NonNegative);
10910   }
10911 
10912   /// Return the range of a sum of the two ranges.
10913   static IntRange sum(IntRange L, IntRange R) {
10914     bool Unsigned = L.NonNegative && R.NonNegative;
10915     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10916                     Unsigned);
10917   }
10918 
10919   /// Return the range of a difference of the two ranges.
10920   static IntRange difference(IntRange L, IntRange R) {
10921     // We need a 1-bit-wider range if:
10922     //   1) LHS can be negative: least value can be reduced.
10923     //   2) RHS can be negative: greatest value can be increased.
10924     bool CanWiden = !L.NonNegative || !R.NonNegative;
10925     bool Unsigned = L.NonNegative && R.Width == 0;
10926     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10927                         !Unsigned,
10928                     Unsigned);
10929   }
10930 
10931   /// Return the range of a product of the two ranges.
10932   static IntRange product(IntRange L, IntRange R) {
10933     // If both LHS and RHS can be negative, we can form
10934     //   -2^L * -2^R = 2^(L + R)
10935     // which requires L + R + 1 value bits to represent.
10936     bool CanWiden = !L.NonNegative && !R.NonNegative;
10937     bool Unsigned = L.NonNegative && R.NonNegative;
10938     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10939                     Unsigned);
10940   }
10941 
10942   /// Return the range of a remainder operation between the two ranges.
10943   static IntRange rem(IntRange L, IntRange R) {
10944     // The result of a remainder can't be larger than the result of
10945     // either side. The sign of the result is the sign of the LHS.
10946     bool Unsigned = L.NonNegative;
10947     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10948                     Unsigned);
10949   }
10950 };
10951 
10952 } // namespace
10953 
10954 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10955                               unsigned MaxWidth) {
10956   if (value.isSigned() && value.isNegative())
10957     return IntRange(value.getMinSignedBits(), false);
10958 
10959   if (value.getBitWidth() > MaxWidth)
10960     value = value.trunc(MaxWidth);
10961 
10962   // isNonNegative() just checks the sign bit without considering
10963   // signedness.
10964   return IntRange(value.getActiveBits(), true);
10965 }
10966 
10967 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10968                               unsigned MaxWidth) {
10969   if (result.isInt())
10970     return GetValueRange(C, result.getInt(), MaxWidth);
10971 
10972   if (result.isVector()) {
10973     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10974     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10975       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10976       R = IntRange::join(R, El);
10977     }
10978     return R;
10979   }
10980 
10981   if (result.isComplexInt()) {
10982     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10983     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10984     return IntRange::join(R, I);
10985   }
10986 
10987   // This can happen with lossless casts to intptr_t of "based" lvalues.
10988   // Assume it might use arbitrary bits.
10989   // FIXME: The only reason we need to pass the type in here is to get
10990   // the sign right on this one case.  It would be nice if APValue
10991   // preserved this.
10992   assert(result.isLValue() || result.isAddrLabelDiff());
10993   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10994 }
10995 
10996 static QualType GetExprType(const Expr *E) {
10997   QualType Ty = E->getType();
10998   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10999     Ty = AtomicRHS->getValueType();
11000   return Ty;
11001 }
11002 
11003 /// Pseudo-evaluate the given integer expression, estimating the
11004 /// range of values it might take.
11005 ///
11006 /// \param MaxWidth The width to which the value will be truncated.
11007 /// \param Approximate If \c true, return a likely range for the result: in
11008 ///        particular, assume that aritmetic on narrower types doesn't leave
11009 ///        those types. If \c false, return a range including all possible
11010 ///        result values.
11011 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11012                              bool InConstantContext, bool Approximate) {
11013   E = E->IgnoreParens();
11014 
11015   // Try a full evaluation first.
11016   Expr::EvalResult result;
11017   if (E->EvaluateAsRValue(result, C, InConstantContext))
11018     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11019 
11020   // I think we only want to look through implicit casts here; if the
11021   // user has an explicit widening cast, we should treat the value as
11022   // being of the new, wider type.
11023   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11024     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11025       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11026                           Approximate);
11027 
11028     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11029 
11030     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11031                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11032 
11033     // Assume that non-integer casts can span the full range of the type.
11034     if (!isIntegerCast)
11035       return OutputTypeRange;
11036 
11037     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11038                                      std::min(MaxWidth, OutputTypeRange.Width),
11039                                      InConstantContext, Approximate);
11040 
11041     // Bail out if the subexpr's range is as wide as the cast type.
11042     if (SubRange.Width >= OutputTypeRange.Width)
11043       return OutputTypeRange;
11044 
11045     // Otherwise, we take the smaller width, and we're non-negative if
11046     // either the output type or the subexpr is.
11047     return IntRange(SubRange.Width,
11048                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11049   }
11050 
11051   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11052     // If we can fold the condition, just take that operand.
11053     bool CondResult;
11054     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11055       return GetExprRange(C,
11056                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11057                           MaxWidth, InConstantContext, Approximate);
11058 
11059     // Otherwise, conservatively merge.
11060     // GetExprRange requires an integer expression, but a throw expression
11061     // results in a void type.
11062     Expr *E = CO->getTrueExpr();
11063     IntRange L = E->getType()->isVoidType()
11064                      ? IntRange{0, true}
11065                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11066     E = CO->getFalseExpr();
11067     IntRange R = E->getType()->isVoidType()
11068                      ? IntRange{0, true}
11069                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11070     return IntRange::join(L, R);
11071   }
11072 
11073   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11074     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11075 
11076     switch (BO->getOpcode()) {
11077     case BO_Cmp:
11078       llvm_unreachable("builtin <=> should have class type");
11079 
11080     // Boolean-valued operations are single-bit and positive.
11081     case BO_LAnd:
11082     case BO_LOr:
11083     case BO_LT:
11084     case BO_GT:
11085     case BO_LE:
11086     case BO_GE:
11087     case BO_EQ:
11088     case BO_NE:
11089       return IntRange::forBoolType();
11090 
11091     // The type of the assignments is the type of the LHS, so the RHS
11092     // is not necessarily the same type.
11093     case BO_MulAssign:
11094     case BO_DivAssign:
11095     case BO_RemAssign:
11096     case BO_AddAssign:
11097     case BO_SubAssign:
11098     case BO_XorAssign:
11099     case BO_OrAssign:
11100       // TODO: bitfields?
11101       return IntRange::forValueOfType(C, GetExprType(E));
11102 
11103     // Simple assignments just pass through the RHS, which will have
11104     // been coerced to the LHS type.
11105     case BO_Assign:
11106       // TODO: bitfields?
11107       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11108                           Approximate);
11109 
11110     // Operations with opaque sources are black-listed.
11111     case BO_PtrMemD:
11112     case BO_PtrMemI:
11113       return IntRange::forValueOfType(C, GetExprType(E));
11114 
11115     // Bitwise-and uses the *infinum* of the two source ranges.
11116     case BO_And:
11117     case BO_AndAssign:
11118       Combine = IntRange::bit_and;
11119       break;
11120 
11121     // Left shift gets black-listed based on a judgement call.
11122     case BO_Shl:
11123       // ...except that we want to treat '1 << (blah)' as logically
11124       // positive.  It's an important idiom.
11125       if (IntegerLiteral *I
11126             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11127         if (I->getValue() == 1) {
11128           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11129           return IntRange(R.Width, /*NonNegative*/ true);
11130         }
11131       }
11132       LLVM_FALLTHROUGH;
11133 
11134     case BO_ShlAssign:
11135       return IntRange::forValueOfType(C, GetExprType(E));
11136 
11137     // Right shift by a constant can narrow its left argument.
11138     case BO_Shr:
11139     case BO_ShrAssign: {
11140       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11141                                 Approximate);
11142 
11143       // If the shift amount is a positive constant, drop the width by
11144       // that much.
11145       if (Optional<llvm::APSInt> shift =
11146               BO->getRHS()->getIntegerConstantExpr(C)) {
11147         if (shift->isNonNegative()) {
11148           unsigned zext = shift->getZExtValue();
11149           if (zext >= L.Width)
11150             L.Width = (L.NonNegative ? 0 : 1);
11151           else
11152             L.Width -= zext;
11153         }
11154       }
11155 
11156       return L;
11157     }
11158 
11159     // Comma acts as its right operand.
11160     case BO_Comma:
11161       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11162                           Approximate);
11163 
11164     case BO_Add:
11165       if (!Approximate)
11166         Combine = IntRange::sum;
11167       break;
11168 
11169     case BO_Sub:
11170       if (BO->getLHS()->getType()->isPointerType())
11171         return IntRange::forValueOfType(C, GetExprType(E));
11172       if (!Approximate)
11173         Combine = IntRange::difference;
11174       break;
11175 
11176     case BO_Mul:
11177       if (!Approximate)
11178         Combine = IntRange::product;
11179       break;
11180 
11181     // The width of a division result is mostly determined by the size
11182     // of the LHS.
11183     case BO_Div: {
11184       // Don't 'pre-truncate' the operands.
11185       unsigned opWidth = C.getIntWidth(GetExprType(E));
11186       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11187                                 Approximate);
11188 
11189       // If the divisor is constant, use that.
11190       if (Optional<llvm::APSInt> divisor =
11191               BO->getRHS()->getIntegerConstantExpr(C)) {
11192         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11193         if (log2 >= L.Width)
11194           L.Width = (L.NonNegative ? 0 : 1);
11195         else
11196           L.Width = std::min(L.Width - log2, MaxWidth);
11197         return L;
11198       }
11199 
11200       // Otherwise, just use the LHS's width.
11201       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11202       // could be -1.
11203       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11204                                 Approximate);
11205       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11206     }
11207 
11208     case BO_Rem:
11209       Combine = IntRange::rem;
11210       break;
11211 
11212     // The default behavior is okay for these.
11213     case BO_Xor:
11214     case BO_Or:
11215       break;
11216     }
11217 
11218     // Combine the two ranges, but limit the result to the type in which we
11219     // performed the computation.
11220     QualType T = GetExprType(E);
11221     unsigned opWidth = C.getIntWidth(T);
11222     IntRange L =
11223         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11224     IntRange R =
11225         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11226     IntRange C = Combine(L, R);
11227     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11228     C.Width = std::min(C.Width, MaxWidth);
11229     return C;
11230   }
11231 
11232   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11233     switch (UO->getOpcode()) {
11234     // Boolean-valued operations are white-listed.
11235     case UO_LNot:
11236       return IntRange::forBoolType();
11237 
11238     // Operations with opaque sources are black-listed.
11239     case UO_Deref:
11240     case UO_AddrOf: // should be impossible
11241       return IntRange::forValueOfType(C, GetExprType(E));
11242 
11243     default:
11244       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11245                           Approximate);
11246     }
11247   }
11248 
11249   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11250     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11251                         Approximate);
11252 
11253   if (const auto *BitField = E->getSourceBitField())
11254     return IntRange(BitField->getBitWidthValue(C),
11255                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11256 
11257   return IntRange::forValueOfType(C, GetExprType(E));
11258 }
11259 
11260 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11261                              bool InConstantContext, bool Approximate) {
11262   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11263                       Approximate);
11264 }
11265 
11266 /// Checks whether the given value, which currently has the given
11267 /// source semantics, has the same value when coerced through the
11268 /// target semantics.
11269 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11270                                  const llvm::fltSemantics &Src,
11271                                  const llvm::fltSemantics &Tgt) {
11272   llvm::APFloat truncated = value;
11273 
11274   bool ignored;
11275   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11276   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11277 
11278   return truncated.bitwiseIsEqual(value);
11279 }
11280 
11281 /// Checks whether the given value, which currently has the given
11282 /// source semantics, has the same value when coerced through the
11283 /// target semantics.
11284 ///
11285 /// The value might be a vector of floats (or a complex number).
11286 static bool IsSameFloatAfterCast(const APValue &value,
11287                                  const llvm::fltSemantics &Src,
11288                                  const llvm::fltSemantics &Tgt) {
11289   if (value.isFloat())
11290     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11291 
11292   if (value.isVector()) {
11293     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11294       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11295         return false;
11296     return true;
11297   }
11298 
11299   assert(value.isComplexFloat());
11300   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11301           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11302 }
11303 
11304 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11305                                        bool IsListInit = false);
11306 
11307 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11308   // Suppress cases where we are comparing against an enum constant.
11309   if (const DeclRefExpr *DR =
11310       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11311     if (isa<EnumConstantDecl>(DR->getDecl()))
11312       return true;
11313 
11314   // Suppress cases where the value is expanded from a macro, unless that macro
11315   // is how a language represents a boolean literal. This is the case in both C
11316   // and Objective-C.
11317   SourceLocation BeginLoc = E->getBeginLoc();
11318   if (BeginLoc.isMacroID()) {
11319     StringRef MacroName = Lexer::getImmediateMacroName(
11320         BeginLoc, S.getSourceManager(), S.getLangOpts());
11321     return MacroName != "YES" && MacroName != "NO" &&
11322            MacroName != "true" && MacroName != "false";
11323   }
11324 
11325   return false;
11326 }
11327 
11328 static bool isKnownToHaveUnsignedValue(Expr *E) {
11329   return E->getType()->isIntegerType() &&
11330          (!E->getType()->isSignedIntegerType() ||
11331           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11332 }
11333 
11334 namespace {
11335 /// The promoted range of values of a type. In general this has the
11336 /// following structure:
11337 ///
11338 ///     |-----------| . . . |-----------|
11339 ///     ^           ^       ^           ^
11340 ///    Min       HoleMin  HoleMax      Max
11341 ///
11342 /// ... where there is only a hole if a signed type is promoted to unsigned
11343 /// (in which case Min and Max are the smallest and largest representable
11344 /// values).
11345 struct PromotedRange {
11346   // Min, or HoleMax if there is a hole.
11347   llvm::APSInt PromotedMin;
11348   // Max, or HoleMin if there is a hole.
11349   llvm::APSInt PromotedMax;
11350 
11351   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11352     if (R.Width == 0)
11353       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11354     else if (R.Width >= BitWidth && !Unsigned) {
11355       // Promotion made the type *narrower*. This happens when promoting
11356       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11357       // Treat all values of 'signed int' as being in range for now.
11358       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11359       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11360     } else {
11361       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11362                         .extOrTrunc(BitWidth);
11363       PromotedMin.setIsUnsigned(Unsigned);
11364 
11365       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11366                         .extOrTrunc(BitWidth);
11367       PromotedMax.setIsUnsigned(Unsigned);
11368     }
11369   }
11370 
11371   // Determine whether this range is contiguous (has no hole).
11372   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11373 
11374   // Where a constant value is within the range.
11375   enum ComparisonResult {
11376     LT = 0x1,
11377     LE = 0x2,
11378     GT = 0x4,
11379     GE = 0x8,
11380     EQ = 0x10,
11381     NE = 0x20,
11382     InRangeFlag = 0x40,
11383 
11384     Less = LE | LT | NE,
11385     Min = LE | InRangeFlag,
11386     InRange = InRangeFlag,
11387     Max = GE | InRangeFlag,
11388     Greater = GE | GT | NE,
11389 
11390     OnlyValue = LE | GE | EQ | InRangeFlag,
11391     InHole = NE
11392   };
11393 
11394   ComparisonResult compare(const llvm::APSInt &Value) const {
11395     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11396            Value.isUnsigned() == PromotedMin.isUnsigned());
11397     if (!isContiguous()) {
11398       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11399       if (Value.isMinValue()) return Min;
11400       if (Value.isMaxValue()) return Max;
11401       if (Value >= PromotedMin) return InRange;
11402       if (Value <= PromotedMax) return InRange;
11403       return InHole;
11404     }
11405 
11406     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11407     case -1: return Less;
11408     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11409     case 1:
11410       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11411       case -1: return InRange;
11412       case 0: return Max;
11413       case 1: return Greater;
11414       }
11415     }
11416 
11417     llvm_unreachable("impossible compare result");
11418   }
11419 
11420   static llvm::Optional<StringRef>
11421   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11422     if (Op == BO_Cmp) {
11423       ComparisonResult LTFlag = LT, GTFlag = GT;
11424       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11425 
11426       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11427       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11428       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11429       return llvm::None;
11430     }
11431 
11432     ComparisonResult TrueFlag, FalseFlag;
11433     if (Op == BO_EQ) {
11434       TrueFlag = EQ;
11435       FalseFlag = NE;
11436     } else if (Op == BO_NE) {
11437       TrueFlag = NE;
11438       FalseFlag = EQ;
11439     } else {
11440       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11441         TrueFlag = LT;
11442         FalseFlag = GE;
11443       } else {
11444         TrueFlag = GT;
11445         FalseFlag = LE;
11446       }
11447       if (Op == BO_GE || Op == BO_LE)
11448         std::swap(TrueFlag, FalseFlag);
11449     }
11450     if (R & TrueFlag)
11451       return StringRef("true");
11452     if (R & FalseFlag)
11453       return StringRef("false");
11454     return llvm::None;
11455   }
11456 };
11457 }
11458 
11459 static bool HasEnumType(Expr *E) {
11460   // Strip off implicit integral promotions.
11461   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11462     if (ICE->getCastKind() != CK_IntegralCast &&
11463         ICE->getCastKind() != CK_NoOp)
11464       break;
11465     E = ICE->getSubExpr();
11466   }
11467 
11468   return E->getType()->isEnumeralType();
11469 }
11470 
11471 static int classifyConstantValue(Expr *Constant) {
11472   // The values of this enumeration are used in the diagnostics
11473   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11474   enum ConstantValueKind {
11475     Miscellaneous = 0,
11476     LiteralTrue,
11477     LiteralFalse
11478   };
11479   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11480     return BL->getValue() ? ConstantValueKind::LiteralTrue
11481                           : ConstantValueKind::LiteralFalse;
11482   return ConstantValueKind::Miscellaneous;
11483 }
11484 
11485 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11486                                         Expr *Constant, Expr *Other,
11487                                         const llvm::APSInt &Value,
11488                                         bool RhsConstant) {
11489   if (S.inTemplateInstantiation())
11490     return false;
11491 
11492   Expr *OriginalOther = Other;
11493 
11494   Constant = Constant->IgnoreParenImpCasts();
11495   Other = Other->IgnoreParenImpCasts();
11496 
11497   // Suppress warnings on tautological comparisons between values of the same
11498   // enumeration type. There are only two ways we could warn on this:
11499   //  - If the constant is outside the range of representable values of
11500   //    the enumeration. In such a case, we should warn about the cast
11501   //    to enumeration type, not about the comparison.
11502   //  - If the constant is the maximum / minimum in-range value. For an
11503   //    enumeratin type, such comparisons can be meaningful and useful.
11504   if (Constant->getType()->isEnumeralType() &&
11505       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11506     return false;
11507 
11508   IntRange OtherValueRange = GetExprRange(
11509       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11510 
11511   QualType OtherT = Other->getType();
11512   if (const auto *AT = OtherT->getAs<AtomicType>())
11513     OtherT = AT->getValueType();
11514   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11515 
11516   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11517   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11518   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11519                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11520                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11521 
11522   // Whether we're treating Other as being a bool because of the form of
11523   // expression despite it having another type (typically 'int' in C).
11524   bool OtherIsBooleanDespiteType =
11525       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11526   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11527     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11528 
11529   // Check if all values in the range of possible values of this expression
11530   // lead to the same comparison outcome.
11531   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11532                                         Value.isUnsigned());
11533   auto Cmp = OtherPromotedValueRange.compare(Value);
11534   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11535   if (!Result)
11536     return false;
11537 
11538   // Also consider the range determined by the type alone. This allows us to
11539   // classify the warning under the proper diagnostic group.
11540   bool TautologicalTypeCompare = false;
11541   {
11542     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11543                                          Value.isUnsigned());
11544     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11545     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11546                                                        RhsConstant)) {
11547       TautologicalTypeCompare = true;
11548       Cmp = TypeCmp;
11549       Result = TypeResult;
11550     }
11551   }
11552 
11553   // Don't warn if the non-constant operand actually always evaluates to the
11554   // same value.
11555   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11556     return false;
11557 
11558   // Suppress the diagnostic for an in-range comparison if the constant comes
11559   // from a macro or enumerator. We don't want to diagnose
11560   //
11561   //   some_long_value <= INT_MAX
11562   //
11563   // when sizeof(int) == sizeof(long).
11564   bool InRange = Cmp & PromotedRange::InRangeFlag;
11565   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11566     return false;
11567 
11568   // A comparison of an unsigned bit-field against 0 is really a type problem,
11569   // even though at the type level the bit-field might promote to 'signed int'.
11570   if (Other->refersToBitField() && InRange && Value == 0 &&
11571       Other->getType()->isUnsignedIntegerOrEnumerationType())
11572     TautologicalTypeCompare = true;
11573 
11574   // If this is a comparison to an enum constant, include that
11575   // constant in the diagnostic.
11576   const EnumConstantDecl *ED = nullptr;
11577   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11578     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11579 
11580   // Should be enough for uint128 (39 decimal digits)
11581   SmallString<64> PrettySourceValue;
11582   llvm::raw_svector_ostream OS(PrettySourceValue);
11583   if (ED) {
11584     OS << '\'' << *ED << "' (" << Value << ")";
11585   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11586                Constant->IgnoreParenImpCasts())) {
11587     OS << (BL->getValue() ? "YES" : "NO");
11588   } else {
11589     OS << Value;
11590   }
11591 
11592   if (!TautologicalTypeCompare) {
11593     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11594         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11595         << E->getOpcodeStr() << OS.str() << *Result
11596         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11597     return true;
11598   }
11599 
11600   if (IsObjCSignedCharBool) {
11601     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11602                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11603                               << OS.str() << *Result);
11604     return true;
11605   }
11606 
11607   // FIXME: We use a somewhat different formatting for the in-range cases and
11608   // cases involving boolean values for historical reasons. We should pick a
11609   // consistent way of presenting these diagnostics.
11610   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11611 
11612     S.DiagRuntimeBehavior(
11613         E->getOperatorLoc(), E,
11614         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11615                          : diag::warn_tautological_bool_compare)
11616             << OS.str() << classifyConstantValue(Constant) << OtherT
11617             << OtherIsBooleanDespiteType << *Result
11618             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11619   } else {
11620     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11621     unsigned Diag =
11622         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11623             ? (HasEnumType(OriginalOther)
11624                    ? diag::warn_unsigned_enum_always_true_comparison
11625                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11626                               : diag::warn_unsigned_always_true_comparison)
11627             : diag::warn_tautological_constant_compare;
11628 
11629     S.Diag(E->getOperatorLoc(), Diag)
11630         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11631         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11632   }
11633 
11634   return true;
11635 }
11636 
11637 /// Analyze the operands of the given comparison.  Implements the
11638 /// fallback case from AnalyzeComparison.
11639 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11640   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11641   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11642 }
11643 
11644 /// Implements -Wsign-compare.
11645 ///
11646 /// \param E the binary operator to check for warnings
11647 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11648   // The type the comparison is being performed in.
11649   QualType T = E->getLHS()->getType();
11650 
11651   // Only analyze comparison operators where both sides have been converted to
11652   // the same type.
11653   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11654     return AnalyzeImpConvsInComparison(S, E);
11655 
11656   // Don't analyze value-dependent comparisons directly.
11657   if (E->isValueDependent())
11658     return AnalyzeImpConvsInComparison(S, E);
11659 
11660   Expr *LHS = E->getLHS();
11661   Expr *RHS = E->getRHS();
11662 
11663   if (T->isIntegralType(S.Context)) {
11664     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11665     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11666 
11667     // We don't care about expressions whose result is a constant.
11668     if (RHSValue && LHSValue)
11669       return AnalyzeImpConvsInComparison(S, E);
11670 
11671     // We only care about expressions where just one side is literal
11672     if ((bool)RHSValue ^ (bool)LHSValue) {
11673       // Is the constant on the RHS or LHS?
11674       const bool RhsConstant = (bool)RHSValue;
11675       Expr *Const = RhsConstant ? RHS : LHS;
11676       Expr *Other = RhsConstant ? LHS : RHS;
11677       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11678 
11679       // Check whether an integer constant comparison results in a value
11680       // of 'true' or 'false'.
11681       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11682         return AnalyzeImpConvsInComparison(S, E);
11683     }
11684   }
11685 
11686   if (!T->hasUnsignedIntegerRepresentation()) {
11687     // We don't do anything special if this isn't an unsigned integral
11688     // comparison:  we're only interested in integral comparisons, and
11689     // signed comparisons only happen in cases we don't care to warn about.
11690     return AnalyzeImpConvsInComparison(S, E);
11691   }
11692 
11693   LHS = LHS->IgnoreParenImpCasts();
11694   RHS = RHS->IgnoreParenImpCasts();
11695 
11696   if (!S.getLangOpts().CPlusPlus) {
11697     // Avoid warning about comparison of integers with different signs when
11698     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11699     // the type of `E`.
11700     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11701       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11702     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11703       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11704   }
11705 
11706   // Check to see if one of the (unmodified) operands is of different
11707   // signedness.
11708   Expr *signedOperand, *unsignedOperand;
11709   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11710     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11711            "unsigned comparison between two signed integer expressions?");
11712     signedOperand = LHS;
11713     unsignedOperand = RHS;
11714   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11715     signedOperand = RHS;
11716     unsignedOperand = LHS;
11717   } else {
11718     return AnalyzeImpConvsInComparison(S, E);
11719   }
11720 
11721   // Otherwise, calculate the effective range of the signed operand.
11722   IntRange signedRange = GetExprRange(
11723       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11724 
11725   // Go ahead and analyze implicit conversions in the operands.  Note
11726   // that we skip the implicit conversions on both sides.
11727   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11728   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11729 
11730   // If the signed range is non-negative, -Wsign-compare won't fire.
11731   if (signedRange.NonNegative)
11732     return;
11733 
11734   // For (in)equality comparisons, if the unsigned operand is a
11735   // constant which cannot collide with a overflowed signed operand,
11736   // then reinterpreting the signed operand as unsigned will not
11737   // change the result of the comparison.
11738   if (E->isEqualityOp()) {
11739     unsigned comparisonWidth = S.Context.getIntWidth(T);
11740     IntRange unsignedRange =
11741         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11742                      /*Approximate*/ true);
11743 
11744     // We should never be unable to prove that the unsigned operand is
11745     // non-negative.
11746     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11747 
11748     if (unsignedRange.Width < comparisonWidth)
11749       return;
11750   }
11751 
11752   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11753                         S.PDiag(diag::warn_mixed_sign_comparison)
11754                             << LHS->getType() << RHS->getType()
11755                             << LHS->getSourceRange() << RHS->getSourceRange());
11756 }
11757 
11758 /// Analyzes an attempt to assign the given value to a bitfield.
11759 ///
11760 /// Returns true if there was something fishy about the attempt.
11761 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11762                                       SourceLocation InitLoc) {
11763   assert(Bitfield->isBitField());
11764   if (Bitfield->isInvalidDecl())
11765     return false;
11766 
11767   // White-list bool bitfields.
11768   QualType BitfieldType = Bitfield->getType();
11769   if (BitfieldType->isBooleanType())
11770      return false;
11771 
11772   if (BitfieldType->isEnumeralType()) {
11773     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11774     // If the underlying enum type was not explicitly specified as an unsigned
11775     // type and the enum contain only positive values, MSVC++ will cause an
11776     // inconsistency by storing this as a signed type.
11777     if (S.getLangOpts().CPlusPlus11 &&
11778         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11779         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11780         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11781       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11782           << BitfieldEnumDecl;
11783     }
11784   }
11785 
11786   if (Bitfield->getType()->isBooleanType())
11787     return false;
11788 
11789   // Ignore value- or type-dependent expressions.
11790   if (Bitfield->getBitWidth()->isValueDependent() ||
11791       Bitfield->getBitWidth()->isTypeDependent() ||
11792       Init->isValueDependent() ||
11793       Init->isTypeDependent())
11794     return false;
11795 
11796   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11797   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11798 
11799   Expr::EvalResult Result;
11800   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11801                                    Expr::SE_AllowSideEffects)) {
11802     // The RHS is not constant.  If the RHS has an enum type, make sure the
11803     // bitfield is wide enough to hold all the values of the enum without
11804     // truncation.
11805     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11806       EnumDecl *ED = EnumTy->getDecl();
11807       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11808 
11809       // Enum types are implicitly signed on Windows, so check if there are any
11810       // negative enumerators to see if the enum was intended to be signed or
11811       // not.
11812       bool SignedEnum = ED->getNumNegativeBits() > 0;
11813 
11814       // Check for surprising sign changes when assigning enum values to a
11815       // bitfield of different signedness.  If the bitfield is signed and we
11816       // have exactly the right number of bits to store this unsigned enum,
11817       // suggest changing the enum to an unsigned type. This typically happens
11818       // on Windows where unfixed enums always use an underlying type of 'int'.
11819       unsigned DiagID = 0;
11820       if (SignedEnum && !SignedBitfield) {
11821         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11822       } else if (SignedBitfield && !SignedEnum &&
11823                  ED->getNumPositiveBits() == FieldWidth) {
11824         DiagID = diag::warn_signed_bitfield_enum_conversion;
11825       }
11826 
11827       if (DiagID) {
11828         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11829         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11830         SourceRange TypeRange =
11831             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11832         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11833             << SignedEnum << TypeRange;
11834       }
11835 
11836       // Compute the required bitwidth. If the enum has negative values, we need
11837       // one more bit than the normal number of positive bits to represent the
11838       // sign bit.
11839       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11840                                                   ED->getNumNegativeBits())
11841                                        : ED->getNumPositiveBits();
11842 
11843       // Check the bitwidth.
11844       if (BitsNeeded > FieldWidth) {
11845         Expr *WidthExpr = Bitfield->getBitWidth();
11846         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11847             << Bitfield << ED;
11848         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11849             << BitsNeeded << ED << WidthExpr->getSourceRange();
11850       }
11851     }
11852 
11853     return false;
11854   }
11855 
11856   llvm::APSInt Value = Result.Val.getInt();
11857 
11858   unsigned OriginalWidth = Value.getBitWidth();
11859 
11860   if (!Value.isSigned() || Value.isNegative())
11861     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11862       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11863         OriginalWidth = Value.getMinSignedBits();
11864 
11865   if (OriginalWidth <= FieldWidth)
11866     return false;
11867 
11868   // Compute the value which the bitfield will contain.
11869   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11870   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11871 
11872   // Check whether the stored value is equal to the original value.
11873   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11874   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11875     return false;
11876 
11877   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11878   // therefore don't strictly fit into a signed bitfield of width 1.
11879   if (FieldWidth == 1 && Value == 1)
11880     return false;
11881 
11882   std::string PrettyValue = toString(Value, 10);
11883   std::string PrettyTrunc = toString(TruncatedValue, 10);
11884 
11885   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11886     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11887     << Init->getSourceRange();
11888 
11889   return true;
11890 }
11891 
11892 /// Analyze the given simple or compound assignment for warning-worthy
11893 /// operations.
11894 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11895   // Just recurse on the LHS.
11896   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11897 
11898   // We want to recurse on the RHS as normal unless we're assigning to
11899   // a bitfield.
11900   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11901     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11902                                   E->getOperatorLoc())) {
11903       // Recurse, ignoring any implicit conversions on the RHS.
11904       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11905                                         E->getOperatorLoc());
11906     }
11907   }
11908 
11909   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11910 
11911   // Diagnose implicitly sequentially-consistent atomic assignment.
11912   if (E->getLHS()->getType()->isAtomicType())
11913     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11914 }
11915 
11916 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11917 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11918                             SourceLocation CContext, unsigned diag,
11919                             bool pruneControlFlow = false) {
11920   if (pruneControlFlow) {
11921     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11922                           S.PDiag(diag)
11923                               << SourceType << T << E->getSourceRange()
11924                               << SourceRange(CContext));
11925     return;
11926   }
11927   S.Diag(E->getExprLoc(), diag)
11928     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11929 }
11930 
11931 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11932 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11933                             SourceLocation CContext,
11934                             unsigned diag, bool pruneControlFlow = false) {
11935   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11936 }
11937 
11938 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11939   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11940       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11941 }
11942 
11943 static void adornObjCBoolConversionDiagWithTernaryFixit(
11944     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11945   Expr *Ignored = SourceExpr->IgnoreImplicit();
11946   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11947     Ignored = OVE->getSourceExpr();
11948   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11949                      isa<BinaryOperator>(Ignored) ||
11950                      isa<CXXOperatorCallExpr>(Ignored);
11951   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11952   if (NeedsParens)
11953     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11954             << FixItHint::CreateInsertion(EndLoc, ")");
11955   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11956 }
11957 
11958 /// Diagnose an implicit cast from a floating point value to an integer value.
11959 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11960                                     SourceLocation CContext) {
11961   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11962   const bool PruneWarnings = S.inTemplateInstantiation();
11963 
11964   Expr *InnerE = E->IgnoreParenImpCasts();
11965   // We also want to warn on, e.g., "int i = -1.234"
11966   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11967     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11968       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11969 
11970   const bool IsLiteral =
11971       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11972 
11973   llvm::APFloat Value(0.0);
11974   bool IsConstant =
11975     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11976   if (!IsConstant) {
11977     if (isObjCSignedCharBool(S, T)) {
11978       return adornObjCBoolConversionDiagWithTernaryFixit(
11979           S, E,
11980           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11981               << E->getType());
11982     }
11983 
11984     return DiagnoseImpCast(S, E, T, CContext,
11985                            diag::warn_impcast_float_integer, PruneWarnings);
11986   }
11987 
11988   bool isExact = false;
11989 
11990   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11991                             T->hasUnsignedIntegerRepresentation());
11992   llvm::APFloat::opStatus Result = Value.convertToInteger(
11993       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11994 
11995   // FIXME: Force the precision of the source value down so we don't print
11996   // digits which are usually useless (we don't really care here if we
11997   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11998   // would automatically print the shortest representation, but it's a bit
11999   // tricky to implement.
12000   SmallString<16> PrettySourceValue;
12001   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12002   precision = (precision * 59 + 195) / 196;
12003   Value.toString(PrettySourceValue, precision);
12004 
12005   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12006     return adornObjCBoolConversionDiagWithTernaryFixit(
12007         S, E,
12008         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12009             << PrettySourceValue);
12010   }
12011 
12012   if (Result == llvm::APFloat::opOK && isExact) {
12013     if (IsLiteral) return;
12014     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12015                            PruneWarnings);
12016   }
12017 
12018   // Conversion of a floating-point value to a non-bool integer where the
12019   // integral part cannot be represented by the integer type is undefined.
12020   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12021     return DiagnoseImpCast(
12022         S, E, T, CContext,
12023         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12024                   : diag::warn_impcast_float_to_integer_out_of_range,
12025         PruneWarnings);
12026 
12027   unsigned DiagID = 0;
12028   if (IsLiteral) {
12029     // Warn on floating point literal to integer.
12030     DiagID = diag::warn_impcast_literal_float_to_integer;
12031   } else if (IntegerValue == 0) {
12032     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12033       return DiagnoseImpCast(S, E, T, CContext,
12034                              diag::warn_impcast_float_integer, PruneWarnings);
12035     }
12036     // Warn on non-zero to zero conversion.
12037     DiagID = diag::warn_impcast_float_to_integer_zero;
12038   } else {
12039     if (IntegerValue.isUnsigned()) {
12040       if (!IntegerValue.isMaxValue()) {
12041         return DiagnoseImpCast(S, E, T, CContext,
12042                                diag::warn_impcast_float_integer, PruneWarnings);
12043       }
12044     } else {  // IntegerValue.isSigned()
12045       if (!IntegerValue.isMaxSignedValue() &&
12046           !IntegerValue.isMinSignedValue()) {
12047         return DiagnoseImpCast(S, E, T, CContext,
12048                                diag::warn_impcast_float_integer, PruneWarnings);
12049       }
12050     }
12051     // Warn on evaluatable floating point expression to integer conversion.
12052     DiagID = diag::warn_impcast_float_to_integer;
12053   }
12054 
12055   SmallString<16> PrettyTargetValue;
12056   if (IsBool)
12057     PrettyTargetValue = Value.isZero() ? "false" : "true";
12058   else
12059     IntegerValue.toString(PrettyTargetValue);
12060 
12061   if (PruneWarnings) {
12062     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12063                           S.PDiag(DiagID)
12064                               << E->getType() << T.getUnqualifiedType()
12065                               << PrettySourceValue << PrettyTargetValue
12066                               << E->getSourceRange() << SourceRange(CContext));
12067   } else {
12068     S.Diag(E->getExprLoc(), DiagID)
12069         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12070         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12071   }
12072 }
12073 
12074 /// Analyze the given compound assignment for the possible losing of
12075 /// floating-point precision.
12076 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12077   assert(isa<CompoundAssignOperator>(E) &&
12078          "Must be compound assignment operation");
12079   // Recurse on the LHS and RHS in here
12080   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12081   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12082 
12083   if (E->getLHS()->getType()->isAtomicType())
12084     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12085 
12086   // Now check the outermost expression
12087   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12088   const auto *RBT = cast<CompoundAssignOperator>(E)
12089                         ->getComputationResultType()
12090                         ->getAs<BuiltinType>();
12091 
12092   // The below checks assume source is floating point.
12093   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12094 
12095   // If source is floating point but target is an integer.
12096   if (ResultBT->isInteger())
12097     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12098                            E->getExprLoc(), diag::warn_impcast_float_integer);
12099 
12100   if (!ResultBT->isFloatingPoint())
12101     return;
12102 
12103   // If both source and target are floating points, warn about losing precision.
12104   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12105       QualType(ResultBT, 0), QualType(RBT, 0));
12106   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12107     // warn about dropping FP rank.
12108     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12109                     diag::warn_impcast_float_result_precision);
12110 }
12111 
12112 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12113                                       IntRange Range) {
12114   if (!Range.Width) return "0";
12115 
12116   llvm::APSInt ValueInRange = Value;
12117   ValueInRange.setIsSigned(!Range.NonNegative);
12118   ValueInRange = ValueInRange.trunc(Range.Width);
12119   return toString(ValueInRange, 10);
12120 }
12121 
12122 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12123   if (!isa<ImplicitCastExpr>(Ex))
12124     return false;
12125 
12126   Expr *InnerE = Ex->IgnoreParenImpCasts();
12127   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12128   const Type *Source =
12129     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12130   if (Target->isDependentType())
12131     return false;
12132 
12133   const BuiltinType *FloatCandidateBT =
12134     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12135   const Type *BoolCandidateType = ToBool ? Target : Source;
12136 
12137   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12138           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12139 }
12140 
12141 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12142                                              SourceLocation CC) {
12143   unsigned NumArgs = TheCall->getNumArgs();
12144   for (unsigned i = 0; i < NumArgs; ++i) {
12145     Expr *CurrA = TheCall->getArg(i);
12146     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12147       continue;
12148 
12149     bool IsSwapped = ((i > 0) &&
12150         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12151     IsSwapped |= ((i < (NumArgs - 1)) &&
12152         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12153     if (IsSwapped) {
12154       // Warn on this floating-point to bool conversion.
12155       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12156                       CurrA->getType(), CC,
12157                       diag::warn_impcast_floating_point_to_bool);
12158     }
12159   }
12160 }
12161 
12162 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12163                                    SourceLocation CC) {
12164   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12165                         E->getExprLoc()))
12166     return;
12167 
12168   // Don't warn on functions which have return type nullptr_t.
12169   if (isa<CallExpr>(E))
12170     return;
12171 
12172   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12173   const Expr::NullPointerConstantKind NullKind =
12174       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12175   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12176     return;
12177 
12178   // Return if target type is a safe conversion.
12179   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12180       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12181     return;
12182 
12183   SourceLocation Loc = E->getSourceRange().getBegin();
12184 
12185   // Venture through the macro stacks to get to the source of macro arguments.
12186   // The new location is a better location than the complete location that was
12187   // passed in.
12188   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12189   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12190 
12191   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12192   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12193     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12194         Loc, S.SourceMgr, S.getLangOpts());
12195     if (MacroName == "NULL")
12196       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12197   }
12198 
12199   // Only warn if the null and context location are in the same macro expansion.
12200   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12201     return;
12202 
12203   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12204       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12205       << FixItHint::CreateReplacement(Loc,
12206                                       S.getFixItZeroLiteralForType(T, Loc));
12207 }
12208 
12209 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12210                                   ObjCArrayLiteral *ArrayLiteral);
12211 
12212 static void
12213 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12214                            ObjCDictionaryLiteral *DictionaryLiteral);
12215 
12216 /// Check a single element within a collection literal against the
12217 /// target element type.
12218 static void checkObjCCollectionLiteralElement(Sema &S,
12219                                               QualType TargetElementType,
12220                                               Expr *Element,
12221                                               unsigned ElementKind) {
12222   // Skip a bitcast to 'id' or qualified 'id'.
12223   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12224     if (ICE->getCastKind() == CK_BitCast &&
12225         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12226       Element = ICE->getSubExpr();
12227   }
12228 
12229   QualType ElementType = Element->getType();
12230   ExprResult ElementResult(Element);
12231   if (ElementType->getAs<ObjCObjectPointerType>() &&
12232       S.CheckSingleAssignmentConstraints(TargetElementType,
12233                                          ElementResult,
12234                                          false, false)
12235         != Sema::Compatible) {
12236     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12237         << ElementType << ElementKind << TargetElementType
12238         << Element->getSourceRange();
12239   }
12240 
12241   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12242     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12243   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12244     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12245 }
12246 
12247 /// Check an Objective-C array literal being converted to the given
12248 /// target type.
12249 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12250                                   ObjCArrayLiteral *ArrayLiteral) {
12251   if (!S.NSArrayDecl)
12252     return;
12253 
12254   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12255   if (!TargetObjCPtr)
12256     return;
12257 
12258   if (TargetObjCPtr->isUnspecialized() ||
12259       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12260         != S.NSArrayDecl->getCanonicalDecl())
12261     return;
12262 
12263   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12264   if (TypeArgs.size() != 1)
12265     return;
12266 
12267   QualType TargetElementType = TypeArgs[0];
12268   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12269     checkObjCCollectionLiteralElement(S, TargetElementType,
12270                                       ArrayLiteral->getElement(I),
12271                                       0);
12272   }
12273 }
12274 
12275 /// Check an Objective-C dictionary literal being converted to the given
12276 /// target type.
12277 static void
12278 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12279                            ObjCDictionaryLiteral *DictionaryLiteral) {
12280   if (!S.NSDictionaryDecl)
12281     return;
12282 
12283   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12284   if (!TargetObjCPtr)
12285     return;
12286 
12287   if (TargetObjCPtr->isUnspecialized() ||
12288       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12289         != S.NSDictionaryDecl->getCanonicalDecl())
12290     return;
12291 
12292   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12293   if (TypeArgs.size() != 2)
12294     return;
12295 
12296   QualType TargetKeyType = TypeArgs[0];
12297   QualType TargetObjectType = TypeArgs[1];
12298   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12299     auto Element = DictionaryLiteral->getKeyValueElement(I);
12300     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12301     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12302   }
12303 }
12304 
12305 // Helper function to filter out cases for constant width constant conversion.
12306 // Don't warn on char array initialization or for non-decimal values.
12307 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12308                                           SourceLocation CC) {
12309   // If initializing from a constant, and the constant starts with '0',
12310   // then it is a binary, octal, or hexadecimal.  Allow these constants
12311   // to fill all the bits, even if there is a sign change.
12312   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12313     const char FirstLiteralCharacter =
12314         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12315     if (FirstLiteralCharacter == '0')
12316       return false;
12317   }
12318 
12319   // If the CC location points to a '{', and the type is char, then assume
12320   // assume it is an array initialization.
12321   if (CC.isValid() && T->isCharType()) {
12322     const char FirstContextCharacter =
12323         S.getSourceManager().getCharacterData(CC)[0];
12324     if (FirstContextCharacter == '{')
12325       return false;
12326   }
12327 
12328   return true;
12329 }
12330 
12331 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12332   const auto *IL = dyn_cast<IntegerLiteral>(E);
12333   if (!IL) {
12334     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12335       if (UO->getOpcode() == UO_Minus)
12336         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12337     }
12338   }
12339 
12340   return IL;
12341 }
12342 
12343 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12344   E = E->IgnoreParenImpCasts();
12345   SourceLocation ExprLoc = E->getExprLoc();
12346 
12347   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12348     BinaryOperator::Opcode Opc = BO->getOpcode();
12349     Expr::EvalResult Result;
12350     // Do not diagnose unsigned shifts.
12351     if (Opc == BO_Shl) {
12352       const auto *LHS = getIntegerLiteral(BO->getLHS());
12353       const auto *RHS = getIntegerLiteral(BO->getRHS());
12354       if (LHS && LHS->getValue() == 0)
12355         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12356       else if (!E->isValueDependent() && LHS && RHS &&
12357                RHS->getValue().isNonNegative() &&
12358                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12359         S.Diag(ExprLoc, diag::warn_left_shift_always)
12360             << (Result.Val.getInt() != 0);
12361       else if (E->getType()->isSignedIntegerType())
12362         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12363     }
12364   }
12365 
12366   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12367     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12368     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12369     if (!LHS || !RHS)
12370       return;
12371     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12372         (RHS->getValue() == 0 || RHS->getValue() == 1))
12373       // Do not diagnose common idioms.
12374       return;
12375     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12376       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12377   }
12378 }
12379 
12380 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12381                                     SourceLocation CC,
12382                                     bool *ICContext = nullptr,
12383                                     bool IsListInit = false) {
12384   if (E->isTypeDependent() || E->isValueDependent()) return;
12385 
12386   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12387   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12388   if (Source == Target) return;
12389   if (Target->isDependentType()) return;
12390 
12391   // If the conversion context location is invalid don't complain. We also
12392   // don't want to emit a warning if the issue occurs from the expansion of
12393   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12394   // delay this check as long as possible. Once we detect we are in that
12395   // scenario, we just return.
12396   if (CC.isInvalid())
12397     return;
12398 
12399   if (Source->isAtomicType())
12400     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12401 
12402   // Diagnose implicit casts to bool.
12403   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12404     if (isa<StringLiteral>(E))
12405       // Warn on string literal to bool.  Checks for string literals in logical
12406       // and expressions, for instance, assert(0 && "error here"), are
12407       // prevented by a check in AnalyzeImplicitConversions().
12408       return DiagnoseImpCast(S, E, T, CC,
12409                              diag::warn_impcast_string_literal_to_bool);
12410     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12411         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12412       // This covers the literal expressions that evaluate to Objective-C
12413       // objects.
12414       return DiagnoseImpCast(S, E, T, CC,
12415                              diag::warn_impcast_objective_c_literal_to_bool);
12416     }
12417     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12418       // Warn on pointer to bool conversion that is always true.
12419       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12420                                      SourceRange(CC));
12421     }
12422   }
12423 
12424   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12425   // is a typedef for signed char (macOS), then that constant value has to be 1
12426   // or 0.
12427   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12428     Expr::EvalResult Result;
12429     if (E->EvaluateAsInt(Result, S.getASTContext(),
12430                          Expr::SE_AllowSideEffects)) {
12431       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12432         adornObjCBoolConversionDiagWithTernaryFixit(
12433             S, E,
12434             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12435                 << toString(Result.Val.getInt(), 10));
12436       }
12437       return;
12438     }
12439   }
12440 
12441   // Check implicit casts from Objective-C collection literals to specialized
12442   // collection types, e.g., NSArray<NSString *> *.
12443   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12444     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12445   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12446     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12447 
12448   // Strip vector types.
12449   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12450     if (Target->isVLSTBuiltinType()) {
12451       auto SourceVectorKind = SourceVT->getVectorKind();
12452       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12453           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12454           (SourceVectorKind == VectorType::GenericVector &&
12455            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12456         return;
12457     }
12458 
12459     if (!isa<VectorType>(Target)) {
12460       if (S.SourceMgr.isInSystemMacro(CC))
12461         return;
12462       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12463     }
12464 
12465     // If the vector cast is cast between two vectors of the same size, it is
12466     // a bitcast, not a conversion.
12467     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12468       return;
12469 
12470     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12471     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12472   }
12473   if (auto VecTy = dyn_cast<VectorType>(Target))
12474     Target = VecTy->getElementType().getTypePtr();
12475 
12476   // Strip complex types.
12477   if (isa<ComplexType>(Source)) {
12478     if (!isa<ComplexType>(Target)) {
12479       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12480         return;
12481 
12482       return DiagnoseImpCast(S, E, T, CC,
12483                              S.getLangOpts().CPlusPlus
12484                                  ? diag::err_impcast_complex_scalar
12485                                  : diag::warn_impcast_complex_scalar);
12486     }
12487 
12488     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12489     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12490   }
12491 
12492   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12493   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12494 
12495   // If the source is floating point...
12496   if (SourceBT && SourceBT->isFloatingPoint()) {
12497     // ...and the target is floating point...
12498     if (TargetBT && TargetBT->isFloatingPoint()) {
12499       // ...then warn if we're dropping FP rank.
12500 
12501       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12502           QualType(SourceBT, 0), QualType(TargetBT, 0));
12503       if (Order > 0) {
12504         // Don't warn about float constants that are precisely
12505         // representable in the target type.
12506         Expr::EvalResult result;
12507         if (E->EvaluateAsRValue(result, S.Context)) {
12508           // Value might be a float, a float vector, or a float complex.
12509           if (IsSameFloatAfterCast(result.Val,
12510                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12511                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12512             return;
12513         }
12514 
12515         if (S.SourceMgr.isInSystemMacro(CC))
12516           return;
12517 
12518         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12519       }
12520       // ... or possibly if we're increasing rank, too
12521       else if (Order < 0) {
12522         if (S.SourceMgr.isInSystemMacro(CC))
12523           return;
12524 
12525         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12526       }
12527       return;
12528     }
12529 
12530     // If the target is integral, always warn.
12531     if (TargetBT && TargetBT->isInteger()) {
12532       if (S.SourceMgr.isInSystemMacro(CC))
12533         return;
12534 
12535       DiagnoseFloatingImpCast(S, E, T, CC);
12536     }
12537 
12538     // Detect the case where a call result is converted from floating-point to
12539     // to bool, and the final argument to the call is converted from bool, to
12540     // discover this typo:
12541     //
12542     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12543     //
12544     // FIXME: This is an incredibly special case; is there some more general
12545     // way to detect this class of misplaced-parentheses bug?
12546     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12547       // Check last argument of function call to see if it is an
12548       // implicit cast from a type matching the type the result
12549       // is being cast to.
12550       CallExpr *CEx = cast<CallExpr>(E);
12551       if (unsigned NumArgs = CEx->getNumArgs()) {
12552         Expr *LastA = CEx->getArg(NumArgs - 1);
12553         Expr *InnerE = LastA->IgnoreParenImpCasts();
12554         if (isa<ImplicitCastExpr>(LastA) &&
12555             InnerE->getType()->isBooleanType()) {
12556           // Warn on this floating-point to bool conversion
12557           DiagnoseImpCast(S, E, T, CC,
12558                           diag::warn_impcast_floating_point_to_bool);
12559         }
12560       }
12561     }
12562     return;
12563   }
12564 
12565   // Valid casts involving fixed point types should be accounted for here.
12566   if (Source->isFixedPointType()) {
12567     if (Target->isUnsaturatedFixedPointType()) {
12568       Expr::EvalResult Result;
12569       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12570                                   S.isConstantEvaluated())) {
12571         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12572         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12573         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12574         if (Value > MaxVal || Value < MinVal) {
12575           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12576                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12577                                     << Value.toString() << T
12578                                     << E->getSourceRange()
12579                                     << clang::SourceRange(CC));
12580           return;
12581         }
12582       }
12583     } else if (Target->isIntegerType()) {
12584       Expr::EvalResult Result;
12585       if (!S.isConstantEvaluated() &&
12586           E->EvaluateAsFixedPoint(Result, S.Context,
12587                                   Expr::SE_AllowSideEffects)) {
12588         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12589 
12590         bool Overflowed;
12591         llvm::APSInt IntResult = FXResult.convertToInt(
12592             S.Context.getIntWidth(T),
12593             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12594 
12595         if (Overflowed) {
12596           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12597                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12598                                     << FXResult.toString() << T
12599                                     << E->getSourceRange()
12600                                     << clang::SourceRange(CC));
12601           return;
12602         }
12603       }
12604     }
12605   } else if (Target->isUnsaturatedFixedPointType()) {
12606     if (Source->isIntegerType()) {
12607       Expr::EvalResult Result;
12608       if (!S.isConstantEvaluated() &&
12609           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12610         llvm::APSInt Value = Result.Val.getInt();
12611 
12612         bool Overflowed;
12613         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12614             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12615 
12616         if (Overflowed) {
12617           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12618                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12619                                     << toString(Value, /*Radix=*/10) << T
12620                                     << E->getSourceRange()
12621                                     << clang::SourceRange(CC));
12622           return;
12623         }
12624       }
12625     }
12626   }
12627 
12628   // If we are casting an integer type to a floating point type without
12629   // initialization-list syntax, we might lose accuracy if the floating
12630   // point type has a narrower significand than the integer type.
12631   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12632       TargetBT->isFloatingType() && !IsListInit) {
12633     // Determine the number of precision bits in the source integer type.
12634     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12635                                         /*Approximate*/ true);
12636     unsigned int SourcePrecision = SourceRange.Width;
12637 
12638     // Determine the number of precision bits in the
12639     // target floating point type.
12640     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12641         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12642 
12643     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12644         SourcePrecision > TargetPrecision) {
12645 
12646       if (Optional<llvm::APSInt> SourceInt =
12647               E->getIntegerConstantExpr(S.Context)) {
12648         // If the source integer is a constant, convert it to the target
12649         // floating point type. Issue a warning if the value changes
12650         // during the whole conversion.
12651         llvm::APFloat TargetFloatValue(
12652             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12653         llvm::APFloat::opStatus ConversionStatus =
12654             TargetFloatValue.convertFromAPInt(
12655                 *SourceInt, SourceBT->isSignedInteger(),
12656                 llvm::APFloat::rmNearestTiesToEven);
12657 
12658         if (ConversionStatus != llvm::APFloat::opOK) {
12659           SmallString<32> PrettySourceValue;
12660           SourceInt->toString(PrettySourceValue, 10);
12661           SmallString<32> PrettyTargetValue;
12662           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12663 
12664           S.DiagRuntimeBehavior(
12665               E->getExprLoc(), E,
12666               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12667                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12668                   << E->getSourceRange() << clang::SourceRange(CC));
12669         }
12670       } else {
12671         // Otherwise, the implicit conversion may lose precision.
12672         DiagnoseImpCast(S, E, T, CC,
12673                         diag::warn_impcast_integer_float_precision);
12674       }
12675     }
12676   }
12677 
12678   DiagnoseNullConversion(S, E, T, CC);
12679 
12680   S.DiscardMisalignedMemberAddress(Target, E);
12681 
12682   if (Target->isBooleanType())
12683     DiagnoseIntInBoolContext(S, E);
12684 
12685   if (!Source->isIntegerType() || !Target->isIntegerType())
12686     return;
12687 
12688   // TODO: remove this early return once the false positives for constant->bool
12689   // in templates, macros, etc, are reduced or removed.
12690   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12691     return;
12692 
12693   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12694       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12695     return adornObjCBoolConversionDiagWithTernaryFixit(
12696         S, E,
12697         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12698             << E->getType());
12699   }
12700 
12701   IntRange SourceTypeRange =
12702       IntRange::forTargetOfCanonicalType(S.Context, Source);
12703   IntRange LikelySourceRange =
12704       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12705   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12706 
12707   if (LikelySourceRange.Width > TargetRange.Width) {
12708     // If the source is a constant, use a default-on diagnostic.
12709     // TODO: this should happen for bitfield stores, too.
12710     Expr::EvalResult Result;
12711     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12712                          S.isConstantEvaluated())) {
12713       llvm::APSInt Value(32);
12714       Value = Result.Val.getInt();
12715 
12716       if (S.SourceMgr.isInSystemMacro(CC))
12717         return;
12718 
12719       std::string PrettySourceValue = toString(Value, 10);
12720       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12721 
12722       S.DiagRuntimeBehavior(
12723           E->getExprLoc(), E,
12724           S.PDiag(diag::warn_impcast_integer_precision_constant)
12725               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12726               << E->getSourceRange() << SourceRange(CC));
12727       return;
12728     }
12729 
12730     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12731     if (S.SourceMgr.isInSystemMacro(CC))
12732       return;
12733 
12734     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12735       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12736                              /* pruneControlFlow */ true);
12737     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12738   }
12739 
12740   if (TargetRange.Width > SourceTypeRange.Width) {
12741     if (auto *UO = dyn_cast<UnaryOperator>(E))
12742       if (UO->getOpcode() == UO_Minus)
12743         if (Source->isUnsignedIntegerType()) {
12744           if (Target->isUnsignedIntegerType())
12745             return DiagnoseImpCast(S, E, T, CC,
12746                                    diag::warn_impcast_high_order_zero_bits);
12747           if (Target->isSignedIntegerType())
12748             return DiagnoseImpCast(S, E, T, CC,
12749                                    diag::warn_impcast_nonnegative_result);
12750         }
12751   }
12752 
12753   if (TargetRange.Width == LikelySourceRange.Width &&
12754       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12755       Source->isSignedIntegerType()) {
12756     // Warn when doing a signed to signed conversion, warn if the positive
12757     // source value is exactly the width of the target type, which will
12758     // cause a negative value to be stored.
12759 
12760     Expr::EvalResult Result;
12761     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12762         !S.SourceMgr.isInSystemMacro(CC)) {
12763       llvm::APSInt Value = Result.Val.getInt();
12764       if (isSameWidthConstantConversion(S, E, T, CC)) {
12765         std::string PrettySourceValue = toString(Value, 10);
12766         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12767 
12768         S.DiagRuntimeBehavior(
12769             E->getExprLoc(), E,
12770             S.PDiag(diag::warn_impcast_integer_precision_constant)
12771                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12772                 << E->getSourceRange() << SourceRange(CC));
12773         return;
12774       }
12775     }
12776 
12777     // Fall through for non-constants to give a sign conversion warning.
12778   }
12779 
12780   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12781       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12782        LikelySourceRange.Width == TargetRange.Width)) {
12783     if (S.SourceMgr.isInSystemMacro(CC))
12784       return;
12785 
12786     unsigned DiagID = diag::warn_impcast_integer_sign;
12787 
12788     // Traditionally, gcc has warned about this under -Wsign-compare.
12789     // We also want to warn about it in -Wconversion.
12790     // So if -Wconversion is off, use a completely identical diagnostic
12791     // in the sign-compare group.
12792     // The conditional-checking code will
12793     if (ICContext) {
12794       DiagID = diag::warn_impcast_integer_sign_conditional;
12795       *ICContext = true;
12796     }
12797 
12798     return DiagnoseImpCast(S, E, T, CC, DiagID);
12799   }
12800 
12801   // Diagnose conversions between different enumeration types.
12802   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12803   // type, to give us better diagnostics.
12804   QualType SourceType = E->getType();
12805   if (!S.getLangOpts().CPlusPlus) {
12806     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12807       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12808         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12809         SourceType = S.Context.getTypeDeclType(Enum);
12810         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12811       }
12812   }
12813 
12814   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12815     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12816       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12817           TargetEnum->getDecl()->hasNameForLinkage() &&
12818           SourceEnum != TargetEnum) {
12819         if (S.SourceMgr.isInSystemMacro(CC))
12820           return;
12821 
12822         return DiagnoseImpCast(S, E, SourceType, T, CC,
12823                                diag::warn_impcast_different_enum_types);
12824       }
12825 }
12826 
12827 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12828                                      SourceLocation CC, QualType T);
12829 
12830 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12831                                     SourceLocation CC, bool &ICContext) {
12832   E = E->IgnoreParenImpCasts();
12833 
12834   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12835     return CheckConditionalOperator(S, CO, CC, T);
12836 
12837   AnalyzeImplicitConversions(S, E, CC);
12838   if (E->getType() != T)
12839     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12840 }
12841 
12842 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12843                                      SourceLocation CC, QualType T) {
12844   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12845 
12846   Expr *TrueExpr = E->getTrueExpr();
12847   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12848     TrueExpr = BCO->getCommon();
12849 
12850   bool Suspicious = false;
12851   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12852   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12853 
12854   if (T->isBooleanType())
12855     DiagnoseIntInBoolContext(S, E);
12856 
12857   // If -Wconversion would have warned about either of the candidates
12858   // for a signedness conversion to the context type...
12859   if (!Suspicious) return;
12860 
12861   // ...but it's currently ignored...
12862   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12863     return;
12864 
12865   // ...then check whether it would have warned about either of the
12866   // candidates for a signedness conversion to the condition type.
12867   if (E->getType() == T) return;
12868 
12869   Suspicious = false;
12870   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12871                           E->getType(), CC, &Suspicious);
12872   if (!Suspicious)
12873     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12874                             E->getType(), CC, &Suspicious);
12875 }
12876 
12877 /// Check conversion of given expression to boolean.
12878 /// Input argument E is a logical expression.
12879 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12880   if (S.getLangOpts().Bool)
12881     return;
12882   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12883     return;
12884   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12885 }
12886 
12887 namespace {
12888 struct AnalyzeImplicitConversionsWorkItem {
12889   Expr *E;
12890   SourceLocation CC;
12891   bool IsListInit;
12892 };
12893 }
12894 
12895 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12896 /// that should be visited are added to WorkList.
12897 static void AnalyzeImplicitConversions(
12898     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12899     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12900   Expr *OrigE = Item.E;
12901   SourceLocation CC = Item.CC;
12902 
12903   QualType T = OrigE->getType();
12904   Expr *E = OrigE->IgnoreParenImpCasts();
12905 
12906   // Propagate whether we are in a C++ list initialization expression.
12907   // If so, we do not issue warnings for implicit int-float conversion
12908   // precision loss, because C++11 narrowing already handles it.
12909   bool IsListInit = Item.IsListInit ||
12910                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12911 
12912   if (E->isTypeDependent() || E->isValueDependent())
12913     return;
12914 
12915   Expr *SourceExpr = E;
12916   // Examine, but don't traverse into the source expression of an
12917   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12918   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12919   // evaluate it in the context of checking the specific conversion to T though.
12920   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12921     if (auto *Src = OVE->getSourceExpr())
12922       SourceExpr = Src;
12923 
12924   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12925     if (UO->getOpcode() == UO_Not &&
12926         UO->getSubExpr()->isKnownToHaveBooleanValue())
12927       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12928           << OrigE->getSourceRange() << T->isBooleanType()
12929           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12930 
12931   // For conditional operators, we analyze the arguments as if they
12932   // were being fed directly into the output.
12933   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12934     CheckConditionalOperator(S, CO, CC, T);
12935     return;
12936   }
12937 
12938   // Check implicit argument conversions for function calls.
12939   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12940     CheckImplicitArgumentConversions(S, Call, CC);
12941 
12942   // Go ahead and check any implicit conversions we might have skipped.
12943   // The non-canonical typecheck is just an optimization;
12944   // CheckImplicitConversion will filter out dead implicit conversions.
12945   if (SourceExpr->getType() != T)
12946     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12947 
12948   // Now continue drilling into this expression.
12949 
12950   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12951     // The bound subexpressions in a PseudoObjectExpr are not reachable
12952     // as transitive children.
12953     // FIXME: Use a more uniform representation for this.
12954     for (auto *SE : POE->semantics())
12955       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12956         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12957   }
12958 
12959   // Skip past explicit casts.
12960   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12961     E = CE->getSubExpr()->IgnoreParenImpCasts();
12962     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12963       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12964     WorkList.push_back({E, CC, IsListInit});
12965     return;
12966   }
12967 
12968   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12969     // Do a somewhat different check with comparison operators.
12970     if (BO->isComparisonOp())
12971       return AnalyzeComparison(S, BO);
12972 
12973     // And with simple assignments.
12974     if (BO->getOpcode() == BO_Assign)
12975       return AnalyzeAssignment(S, BO);
12976     // And with compound assignments.
12977     if (BO->isAssignmentOp())
12978       return AnalyzeCompoundAssignment(S, BO);
12979   }
12980 
12981   // These break the otherwise-useful invariant below.  Fortunately,
12982   // we don't really need to recurse into them, because any internal
12983   // expressions should have been analyzed already when they were
12984   // built into statements.
12985   if (isa<StmtExpr>(E)) return;
12986 
12987   // Don't descend into unevaluated contexts.
12988   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12989 
12990   // Now just recurse over the expression's children.
12991   CC = E->getExprLoc();
12992   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12993   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12994   for (Stmt *SubStmt : E->children()) {
12995     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12996     if (!ChildExpr)
12997       continue;
12998 
12999     if (IsLogicalAndOperator &&
13000         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13001       // Ignore checking string literals that are in logical and operators.
13002       // This is a common pattern for asserts.
13003       continue;
13004     WorkList.push_back({ChildExpr, CC, IsListInit});
13005   }
13006 
13007   if (BO && BO->isLogicalOp()) {
13008     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13009     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13010       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13011 
13012     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13013     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13014       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13015   }
13016 
13017   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13018     if (U->getOpcode() == UO_LNot) {
13019       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13020     } else if (U->getOpcode() != UO_AddrOf) {
13021       if (U->getSubExpr()->getType()->isAtomicType())
13022         S.Diag(U->getSubExpr()->getBeginLoc(),
13023                diag::warn_atomic_implicit_seq_cst);
13024     }
13025   }
13026 }
13027 
13028 /// AnalyzeImplicitConversions - Find and report any interesting
13029 /// implicit conversions in the given expression.  There are a couple
13030 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13031 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13032                                        bool IsListInit/*= false*/) {
13033   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13034   WorkList.push_back({OrigE, CC, IsListInit});
13035   while (!WorkList.empty())
13036     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13037 }
13038 
13039 /// Diagnose integer type and any valid implicit conversion to it.
13040 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13041   // Taking into account implicit conversions,
13042   // allow any integer.
13043   if (!E->getType()->isIntegerType()) {
13044     S.Diag(E->getBeginLoc(),
13045            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13046     return true;
13047   }
13048   // Potentially emit standard warnings for implicit conversions if enabled
13049   // using -Wconversion.
13050   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13051   return false;
13052 }
13053 
13054 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13055 // Returns true when emitting a warning about taking the address of a reference.
13056 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13057                               const PartialDiagnostic &PD) {
13058   E = E->IgnoreParenImpCasts();
13059 
13060   const FunctionDecl *FD = nullptr;
13061 
13062   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13063     if (!DRE->getDecl()->getType()->isReferenceType())
13064       return false;
13065   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13066     if (!M->getMemberDecl()->getType()->isReferenceType())
13067       return false;
13068   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13069     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13070       return false;
13071     FD = Call->getDirectCallee();
13072   } else {
13073     return false;
13074   }
13075 
13076   SemaRef.Diag(E->getExprLoc(), PD);
13077 
13078   // If possible, point to location of function.
13079   if (FD) {
13080     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13081   }
13082 
13083   return true;
13084 }
13085 
13086 // Returns true if the SourceLocation is expanded from any macro body.
13087 // Returns false if the SourceLocation is invalid, is from not in a macro
13088 // expansion, or is from expanded from a top-level macro argument.
13089 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13090   if (Loc.isInvalid())
13091     return false;
13092 
13093   while (Loc.isMacroID()) {
13094     if (SM.isMacroBodyExpansion(Loc))
13095       return true;
13096     Loc = SM.getImmediateMacroCallerLoc(Loc);
13097   }
13098 
13099   return false;
13100 }
13101 
13102 /// Diagnose pointers that are always non-null.
13103 /// \param E the expression containing the pointer
13104 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13105 /// compared to a null pointer
13106 /// \param IsEqual True when the comparison is equal to a null pointer
13107 /// \param Range Extra SourceRange to highlight in the diagnostic
13108 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13109                                         Expr::NullPointerConstantKind NullKind,
13110                                         bool IsEqual, SourceRange Range) {
13111   if (!E)
13112     return;
13113 
13114   // Don't warn inside macros.
13115   if (E->getExprLoc().isMacroID()) {
13116     const SourceManager &SM = getSourceManager();
13117     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13118         IsInAnyMacroBody(SM, Range.getBegin()))
13119       return;
13120   }
13121   E = E->IgnoreImpCasts();
13122 
13123   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13124 
13125   if (isa<CXXThisExpr>(E)) {
13126     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13127                                 : diag::warn_this_bool_conversion;
13128     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13129     return;
13130   }
13131 
13132   bool IsAddressOf = false;
13133 
13134   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13135     if (UO->getOpcode() != UO_AddrOf)
13136       return;
13137     IsAddressOf = true;
13138     E = UO->getSubExpr();
13139   }
13140 
13141   if (IsAddressOf) {
13142     unsigned DiagID = IsCompare
13143                           ? diag::warn_address_of_reference_null_compare
13144                           : diag::warn_address_of_reference_bool_conversion;
13145     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13146                                          << IsEqual;
13147     if (CheckForReference(*this, E, PD)) {
13148       return;
13149     }
13150   }
13151 
13152   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13153     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13154     std::string Str;
13155     llvm::raw_string_ostream S(Str);
13156     E->printPretty(S, nullptr, getPrintingPolicy());
13157     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13158                                 : diag::warn_cast_nonnull_to_bool;
13159     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13160       << E->getSourceRange() << Range << IsEqual;
13161     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13162   };
13163 
13164   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13165   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13166     if (auto *Callee = Call->getDirectCallee()) {
13167       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13168         ComplainAboutNonnullParamOrCall(A);
13169         return;
13170       }
13171     }
13172   }
13173 
13174   // Expect to find a single Decl.  Skip anything more complicated.
13175   ValueDecl *D = nullptr;
13176   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13177     D = R->getDecl();
13178   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13179     D = M->getMemberDecl();
13180   }
13181 
13182   // Weak Decls can be null.
13183   if (!D || D->isWeak())
13184     return;
13185 
13186   // Check for parameter decl with nonnull attribute
13187   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13188     if (getCurFunction() &&
13189         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13190       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13191         ComplainAboutNonnullParamOrCall(A);
13192         return;
13193       }
13194 
13195       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13196         // Skip function template not specialized yet.
13197         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13198           return;
13199         auto ParamIter = llvm::find(FD->parameters(), PV);
13200         assert(ParamIter != FD->param_end());
13201         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13202 
13203         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13204           if (!NonNull->args_size()) {
13205               ComplainAboutNonnullParamOrCall(NonNull);
13206               return;
13207           }
13208 
13209           for (const ParamIdx &ArgNo : NonNull->args()) {
13210             if (ArgNo.getASTIndex() == ParamNo) {
13211               ComplainAboutNonnullParamOrCall(NonNull);
13212               return;
13213             }
13214           }
13215         }
13216       }
13217     }
13218   }
13219 
13220   QualType T = D->getType();
13221   const bool IsArray = T->isArrayType();
13222   const bool IsFunction = T->isFunctionType();
13223 
13224   // Address of function is used to silence the function warning.
13225   if (IsAddressOf && IsFunction) {
13226     return;
13227   }
13228 
13229   // Found nothing.
13230   if (!IsAddressOf && !IsFunction && !IsArray)
13231     return;
13232 
13233   // Pretty print the expression for the diagnostic.
13234   std::string Str;
13235   llvm::raw_string_ostream S(Str);
13236   E->printPretty(S, nullptr, getPrintingPolicy());
13237 
13238   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13239                               : diag::warn_impcast_pointer_to_bool;
13240   enum {
13241     AddressOf,
13242     FunctionPointer,
13243     ArrayPointer
13244   } DiagType;
13245   if (IsAddressOf)
13246     DiagType = AddressOf;
13247   else if (IsFunction)
13248     DiagType = FunctionPointer;
13249   else if (IsArray)
13250     DiagType = ArrayPointer;
13251   else
13252     llvm_unreachable("Could not determine diagnostic.");
13253   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13254                                 << Range << IsEqual;
13255 
13256   if (!IsFunction)
13257     return;
13258 
13259   // Suggest '&' to silence the function warning.
13260   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13261       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13262 
13263   // Check to see if '()' fixit should be emitted.
13264   QualType ReturnType;
13265   UnresolvedSet<4> NonTemplateOverloads;
13266   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13267   if (ReturnType.isNull())
13268     return;
13269 
13270   if (IsCompare) {
13271     // There are two cases here.  If there is null constant, the only suggest
13272     // for a pointer return type.  If the null is 0, then suggest if the return
13273     // type is a pointer or an integer type.
13274     if (!ReturnType->isPointerType()) {
13275       if (NullKind == Expr::NPCK_ZeroExpression ||
13276           NullKind == Expr::NPCK_ZeroLiteral) {
13277         if (!ReturnType->isIntegerType())
13278           return;
13279       } else {
13280         return;
13281       }
13282     }
13283   } else { // !IsCompare
13284     // For function to bool, only suggest if the function pointer has bool
13285     // return type.
13286     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13287       return;
13288   }
13289   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13290       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13291 }
13292 
13293 /// Diagnoses "dangerous" implicit conversions within the given
13294 /// expression (which is a full expression).  Implements -Wconversion
13295 /// and -Wsign-compare.
13296 ///
13297 /// \param CC the "context" location of the implicit conversion, i.e.
13298 ///   the most location of the syntactic entity requiring the implicit
13299 ///   conversion
13300 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13301   // Don't diagnose in unevaluated contexts.
13302   if (isUnevaluatedContext())
13303     return;
13304 
13305   // Don't diagnose for value- or type-dependent expressions.
13306   if (E->isTypeDependent() || E->isValueDependent())
13307     return;
13308 
13309   // Check for array bounds violations in cases where the check isn't triggered
13310   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13311   // ArraySubscriptExpr is on the RHS of a variable initialization.
13312   CheckArrayAccess(E);
13313 
13314   // This is not the right CC for (e.g.) a variable initialization.
13315   AnalyzeImplicitConversions(*this, E, CC);
13316 }
13317 
13318 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13319 /// Input argument E is a logical expression.
13320 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13321   ::CheckBoolLikeConversion(*this, E, CC);
13322 }
13323 
13324 /// Diagnose when expression is an integer constant expression and its evaluation
13325 /// results in integer overflow
13326 void Sema::CheckForIntOverflow (Expr *E) {
13327   // Use a work list to deal with nested struct initializers.
13328   SmallVector<Expr *, 2> Exprs(1, E);
13329 
13330   do {
13331     Expr *OriginalE = Exprs.pop_back_val();
13332     Expr *E = OriginalE->IgnoreParenCasts();
13333 
13334     if (isa<BinaryOperator>(E)) {
13335       E->EvaluateForOverflow(Context);
13336       continue;
13337     }
13338 
13339     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13340       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13341     else if (isa<ObjCBoxedExpr>(OriginalE))
13342       E->EvaluateForOverflow(Context);
13343     else if (auto Call = dyn_cast<CallExpr>(E))
13344       Exprs.append(Call->arg_begin(), Call->arg_end());
13345     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13346       Exprs.append(Message->arg_begin(), Message->arg_end());
13347   } while (!Exprs.empty());
13348 }
13349 
13350 namespace {
13351 
13352 /// Visitor for expressions which looks for unsequenced operations on the
13353 /// same object.
13354 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13355   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13356 
13357   /// A tree of sequenced regions within an expression. Two regions are
13358   /// unsequenced if one is an ancestor or a descendent of the other. When we
13359   /// finish processing an expression with sequencing, such as a comma
13360   /// expression, we fold its tree nodes into its parent, since they are
13361   /// unsequenced with respect to nodes we will visit later.
13362   class SequenceTree {
13363     struct Value {
13364       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13365       unsigned Parent : 31;
13366       unsigned Merged : 1;
13367     };
13368     SmallVector<Value, 8> Values;
13369 
13370   public:
13371     /// A region within an expression which may be sequenced with respect
13372     /// to some other region.
13373     class Seq {
13374       friend class SequenceTree;
13375 
13376       unsigned Index;
13377 
13378       explicit Seq(unsigned N) : Index(N) {}
13379 
13380     public:
13381       Seq() : Index(0) {}
13382     };
13383 
13384     SequenceTree() { Values.push_back(Value(0)); }
13385     Seq root() const { return Seq(0); }
13386 
13387     /// Create a new sequence of operations, which is an unsequenced
13388     /// subset of \p Parent. This sequence of operations is sequenced with
13389     /// respect to other children of \p Parent.
13390     Seq allocate(Seq Parent) {
13391       Values.push_back(Value(Parent.Index));
13392       return Seq(Values.size() - 1);
13393     }
13394 
13395     /// Merge a sequence of operations into its parent.
13396     void merge(Seq S) {
13397       Values[S.Index].Merged = true;
13398     }
13399 
13400     /// Determine whether two operations are unsequenced. This operation
13401     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13402     /// should have been merged into its parent as appropriate.
13403     bool isUnsequenced(Seq Cur, Seq Old) {
13404       unsigned C = representative(Cur.Index);
13405       unsigned Target = representative(Old.Index);
13406       while (C >= Target) {
13407         if (C == Target)
13408           return true;
13409         C = Values[C].Parent;
13410       }
13411       return false;
13412     }
13413 
13414   private:
13415     /// Pick a representative for a sequence.
13416     unsigned representative(unsigned K) {
13417       if (Values[K].Merged)
13418         // Perform path compression as we go.
13419         return Values[K].Parent = representative(Values[K].Parent);
13420       return K;
13421     }
13422   };
13423 
13424   /// An object for which we can track unsequenced uses.
13425   using Object = const NamedDecl *;
13426 
13427   /// Different flavors of object usage which we track. We only track the
13428   /// least-sequenced usage of each kind.
13429   enum UsageKind {
13430     /// A read of an object. Multiple unsequenced reads are OK.
13431     UK_Use,
13432 
13433     /// A modification of an object which is sequenced before the value
13434     /// computation of the expression, such as ++n in C++.
13435     UK_ModAsValue,
13436 
13437     /// A modification of an object which is not sequenced before the value
13438     /// computation of the expression, such as n++.
13439     UK_ModAsSideEffect,
13440 
13441     UK_Count = UK_ModAsSideEffect + 1
13442   };
13443 
13444   /// Bundle together a sequencing region and the expression corresponding
13445   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13446   struct Usage {
13447     const Expr *UsageExpr;
13448     SequenceTree::Seq Seq;
13449 
13450     Usage() : UsageExpr(nullptr), Seq() {}
13451   };
13452 
13453   struct UsageInfo {
13454     Usage Uses[UK_Count];
13455 
13456     /// Have we issued a diagnostic for this object already?
13457     bool Diagnosed;
13458 
13459     UsageInfo() : Uses(), Diagnosed(false) {}
13460   };
13461   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13462 
13463   Sema &SemaRef;
13464 
13465   /// Sequenced regions within the expression.
13466   SequenceTree Tree;
13467 
13468   /// Declaration modifications and references which we have seen.
13469   UsageInfoMap UsageMap;
13470 
13471   /// The region we are currently within.
13472   SequenceTree::Seq Region;
13473 
13474   /// Filled in with declarations which were modified as a side-effect
13475   /// (that is, post-increment operations).
13476   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13477 
13478   /// Expressions to check later. We defer checking these to reduce
13479   /// stack usage.
13480   SmallVectorImpl<const Expr *> &WorkList;
13481 
13482   /// RAII object wrapping the visitation of a sequenced subexpression of an
13483   /// expression. At the end of this process, the side-effects of the evaluation
13484   /// become sequenced with respect to the value computation of the result, so
13485   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13486   /// UK_ModAsValue.
13487   struct SequencedSubexpression {
13488     SequencedSubexpression(SequenceChecker &Self)
13489       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13490       Self.ModAsSideEffect = &ModAsSideEffect;
13491     }
13492 
13493     ~SequencedSubexpression() {
13494       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13495         // Add a new usage with usage kind UK_ModAsValue, and then restore
13496         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13497         // the previous one was empty).
13498         UsageInfo &UI = Self.UsageMap[M.first];
13499         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13500         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13501         SideEffectUsage = M.second;
13502       }
13503       Self.ModAsSideEffect = OldModAsSideEffect;
13504     }
13505 
13506     SequenceChecker &Self;
13507     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13508     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13509   };
13510 
13511   /// RAII object wrapping the visitation of a subexpression which we might
13512   /// choose to evaluate as a constant. If any subexpression is evaluated and
13513   /// found to be non-constant, this allows us to suppress the evaluation of
13514   /// the outer expression.
13515   class EvaluationTracker {
13516   public:
13517     EvaluationTracker(SequenceChecker &Self)
13518         : Self(Self), Prev(Self.EvalTracker) {
13519       Self.EvalTracker = this;
13520     }
13521 
13522     ~EvaluationTracker() {
13523       Self.EvalTracker = Prev;
13524       if (Prev)
13525         Prev->EvalOK &= EvalOK;
13526     }
13527 
13528     bool evaluate(const Expr *E, bool &Result) {
13529       if (!EvalOK || E->isValueDependent())
13530         return false;
13531       EvalOK = E->EvaluateAsBooleanCondition(
13532           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13533       return EvalOK;
13534     }
13535 
13536   private:
13537     SequenceChecker &Self;
13538     EvaluationTracker *Prev;
13539     bool EvalOK = true;
13540   } *EvalTracker = nullptr;
13541 
13542   /// Find the object which is produced by the specified expression,
13543   /// if any.
13544   Object getObject(const Expr *E, bool Mod) const {
13545     E = E->IgnoreParenCasts();
13546     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13547       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13548         return getObject(UO->getSubExpr(), Mod);
13549     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13550       if (BO->getOpcode() == BO_Comma)
13551         return getObject(BO->getRHS(), Mod);
13552       if (Mod && BO->isAssignmentOp())
13553         return getObject(BO->getLHS(), Mod);
13554     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13555       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13556       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13557         return ME->getMemberDecl();
13558     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13559       // FIXME: If this is a reference, map through to its value.
13560       return DRE->getDecl();
13561     return nullptr;
13562   }
13563 
13564   /// Note that an object \p O was modified or used by an expression
13565   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13566   /// the object \p O as obtained via the \p UsageMap.
13567   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13568     // Get the old usage for the given object and usage kind.
13569     Usage &U = UI.Uses[UK];
13570     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13571       // If we have a modification as side effect and are in a sequenced
13572       // subexpression, save the old Usage so that we can restore it later
13573       // in SequencedSubexpression::~SequencedSubexpression.
13574       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13575         ModAsSideEffect->push_back(std::make_pair(O, U));
13576       // Then record the new usage with the current sequencing region.
13577       U.UsageExpr = UsageExpr;
13578       U.Seq = Region;
13579     }
13580   }
13581 
13582   /// Check whether a modification or use of an object \p O in an expression
13583   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13584   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13585   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13586   /// usage and false we are checking for a mod-use unsequenced usage.
13587   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13588                   UsageKind OtherKind, bool IsModMod) {
13589     if (UI.Diagnosed)
13590       return;
13591 
13592     const Usage &U = UI.Uses[OtherKind];
13593     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13594       return;
13595 
13596     const Expr *Mod = U.UsageExpr;
13597     const Expr *ModOrUse = UsageExpr;
13598     if (OtherKind == UK_Use)
13599       std::swap(Mod, ModOrUse);
13600 
13601     SemaRef.DiagRuntimeBehavior(
13602         Mod->getExprLoc(), {Mod, ModOrUse},
13603         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13604                                : diag::warn_unsequenced_mod_use)
13605             << O << SourceRange(ModOrUse->getExprLoc()));
13606     UI.Diagnosed = true;
13607   }
13608 
13609   // A note on note{Pre, Post}{Use, Mod}:
13610   //
13611   // (It helps to follow the algorithm with an expression such as
13612   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13613   //  operations before C++17 and both are well-defined in C++17).
13614   //
13615   // When visiting a node which uses/modify an object we first call notePreUse
13616   // or notePreMod before visiting its sub-expression(s). At this point the
13617   // children of the current node have not yet been visited and so the eventual
13618   // uses/modifications resulting from the children of the current node have not
13619   // been recorded yet.
13620   //
13621   // We then visit the children of the current node. After that notePostUse or
13622   // notePostMod is called. These will 1) detect an unsequenced modification
13623   // as side effect (as in "k++ + k") and 2) add a new usage with the
13624   // appropriate usage kind.
13625   //
13626   // We also have to be careful that some operation sequences modification as
13627   // side effect as well (for example: || or ,). To account for this we wrap
13628   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13629   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13630   // which record usages which are modifications as side effect, and then
13631   // downgrade them (or more accurately restore the previous usage which was a
13632   // modification as side effect) when exiting the scope of the sequenced
13633   // subexpression.
13634 
13635   void notePreUse(Object O, const Expr *UseExpr) {
13636     UsageInfo &UI = UsageMap[O];
13637     // Uses conflict with other modifications.
13638     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13639   }
13640 
13641   void notePostUse(Object O, const Expr *UseExpr) {
13642     UsageInfo &UI = UsageMap[O];
13643     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13644                /*IsModMod=*/false);
13645     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13646   }
13647 
13648   void notePreMod(Object O, const Expr *ModExpr) {
13649     UsageInfo &UI = UsageMap[O];
13650     // Modifications conflict with other modifications and with uses.
13651     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13652     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13653   }
13654 
13655   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13656     UsageInfo &UI = UsageMap[O];
13657     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13658                /*IsModMod=*/true);
13659     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13660   }
13661 
13662 public:
13663   SequenceChecker(Sema &S, const Expr *E,
13664                   SmallVectorImpl<const Expr *> &WorkList)
13665       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13666     Visit(E);
13667     // Silence a -Wunused-private-field since WorkList is now unused.
13668     // TODO: Evaluate if it can be used, and if not remove it.
13669     (void)this->WorkList;
13670   }
13671 
13672   void VisitStmt(const Stmt *S) {
13673     // Skip all statements which aren't expressions for now.
13674   }
13675 
13676   void VisitExpr(const Expr *E) {
13677     // By default, just recurse to evaluated subexpressions.
13678     Base::VisitStmt(E);
13679   }
13680 
13681   void VisitCastExpr(const CastExpr *E) {
13682     Object O = Object();
13683     if (E->getCastKind() == CK_LValueToRValue)
13684       O = getObject(E->getSubExpr(), false);
13685 
13686     if (O)
13687       notePreUse(O, E);
13688     VisitExpr(E);
13689     if (O)
13690       notePostUse(O, E);
13691   }
13692 
13693   void VisitSequencedExpressions(const Expr *SequencedBefore,
13694                                  const Expr *SequencedAfter) {
13695     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13696     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13697     SequenceTree::Seq OldRegion = Region;
13698 
13699     {
13700       SequencedSubexpression SeqBefore(*this);
13701       Region = BeforeRegion;
13702       Visit(SequencedBefore);
13703     }
13704 
13705     Region = AfterRegion;
13706     Visit(SequencedAfter);
13707 
13708     Region = OldRegion;
13709 
13710     Tree.merge(BeforeRegion);
13711     Tree.merge(AfterRegion);
13712   }
13713 
13714   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13715     // C++17 [expr.sub]p1:
13716     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13717     //   expression E1 is sequenced before the expression E2.
13718     if (SemaRef.getLangOpts().CPlusPlus17)
13719       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13720     else {
13721       Visit(ASE->getLHS());
13722       Visit(ASE->getRHS());
13723     }
13724   }
13725 
13726   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13727   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13728   void VisitBinPtrMem(const BinaryOperator *BO) {
13729     // C++17 [expr.mptr.oper]p4:
13730     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13731     //  the expression E1 is sequenced before the expression E2.
13732     if (SemaRef.getLangOpts().CPlusPlus17)
13733       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13734     else {
13735       Visit(BO->getLHS());
13736       Visit(BO->getRHS());
13737     }
13738   }
13739 
13740   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13741   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13742   void VisitBinShlShr(const BinaryOperator *BO) {
13743     // C++17 [expr.shift]p4:
13744     //  The expression E1 is sequenced before the expression E2.
13745     if (SemaRef.getLangOpts().CPlusPlus17)
13746       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13747     else {
13748       Visit(BO->getLHS());
13749       Visit(BO->getRHS());
13750     }
13751   }
13752 
13753   void VisitBinComma(const BinaryOperator *BO) {
13754     // C++11 [expr.comma]p1:
13755     //   Every value computation and side effect associated with the left
13756     //   expression is sequenced before every value computation and side
13757     //   effect associated with the right expression.
13758     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13759   }
13760 
13761   void VisitBinAssign(const BinaryOperator *BO) {
13762     SequenceTree::Seq RHSRegion;
13763     SequenceTree::Seq LHSRegion;
13764     if (SemaRef.getLangOpts().CPlusPlus17) {
13765       RHSRegion = Tree.allocate(Region);
13766       LHSRegion = Tree.allocate(Region);
13767     } else {
13768       RHSRegion = Region;
13769       LHSRegion = Region;
13770     }
13771     SequenceTree::Seq OldRegion = Region;
13772 
13773     // C++11 [expr.ass]p1:
13774     //  [...] the assignment is sequenced after the value computation
13775     //  of the right and left operands, [...]
13776     //
13777     // so check it before inspecting the operands and update the
13778     // map afterwards.
13779     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13780     if (O)
13781       notePreMod(O, BO);
13782 
13783     if (SemaRef.getLangOpts().CPlusPlus17) {
13784       // C++17 [expr.ass]p1:
13785       //  [...] The right operand is sequenced before the left operand. [...]
13786       {
13787         SequencedSubexpression SeqBefore(*this);
13788         Region = RHSRegion;
13789         Visit(BO->getRHS());
13790       }
13791 
13792       Region = LHSRegion;
13793       Visit(BO->getLHS());
13794 
13795       if (O && isa<CompoundAssignOperator>(BO))
13796         notePostUse(O, BO);
13797 
13798     } else {
13799       // C++11 does not specify any sequencing between the LHS and RHS.
13800       Region = LHSRegion;
13801       Visit(BO->getLHS());
13802 
13803       if (O && isa<CompoundAssignOperator>(BO))
13804         notePostUse(O, BO);
13805 
13806       Region = RHSRegion;
13807       Visit(BO->getRHS());
13808     }
13809 
13810     // C++11 [expr.ass]p1:
13811     //  the assignment is sequenced [...] before the value computation of the
13812     //  assignment expression.
13813     // C11 6.5.16/3 has no such rule.
13814     Region = OldRegion;
13815     if (O)
13816       notePostMod(O, BO,
13817                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13818                                                   : UK_ModAsSideEffect);
13819     if (SemaRef.getLangOpts().CPlusPlus17) {
13820       Tree.merge(RHSRegion);
13821       Tree.merge(LHSRegion);
13822     }
13823   }
13824 
13825   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13826     VisitBinAssign(CAO);
13827   }
13828 
13829   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13830   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13831   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13832     Object O = getObject(UO->getSubExpr(), true);
13833     if (!O)
13834       return VisitExpr(UO);
13835 
13836     notePreMod(O, UO);
13837     Visit(UO->getSubExpr());
13838     // C++11 [expr.pre.incr]p1:
13839     //   the expression ++x is equivalent to x+=1
13840     notePostMod(O, UO,
13841                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13842                                                 : UK_ModAsSideEffect);
13843   }
13844 
13845   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13846   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13847   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13848     Object O = getObject(UO->getSubExpr(), true);
13849     if (!O)
13850       return VisitExpr(UO);
13851 
13852     notePreMod(O, UO);
13853     Visit(UO->getSubExpr());
13854     notePostMod(O, UO, UK_ModAsSideEffect);
13855   }
13856 
13857   void VisitBinLOr(const BinaryOperator *BO) {
13858     // C++11 [expr.log.or]p2:
13859     //  If the second expression is evaluated, every value computation and
13860     //  side effect associated with the first expression is sequenced before
13861     //  every value computation and side effect associated with the
13862     //  second expression.
13863     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13864     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13865     SequenceTree::Seq OldRegion = Region;
13866 
13867     EvaluationTracker Eval(*this);
13868     {
13869       SequencedSubexpression Sequenced(*this);
13870       Region = LHSRegion;
13871       Visit(BO->getLHS());
13872     }
13873 
13874     // C++11 [expr.log.or]p1:
13875     //  [...] the second operand is not evaluated if the first operand
13876     //  evaluates to true.
13877     bool EvalResult = false;
13878     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13879     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13880     if (ShouldVisitRHS) {
13881       Region = RHSRegion;
13882       Visit(BO->getRHS());
13883     }
13884 
13885     Region = OldRegion;
13886     Tree.merge(LHSRegion);
13887     Tree.merge(RHSRegion);
13888   }
13889 
13890   void VisitBinLAnd(const BinaryOperator *BO) {
13891     // C++11 [expr.log.and]p2:
13892     //  If the second expression is evaluated, every value computation and
13893     //  side effect associated with the first expression is sequenced before
13894     //  every value computation and side effect associated with the
13895     //  second expression.
13896     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13897     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13898     SequenceTree::Seq OldRegion = Region;
13899 
13900     EvaluationTracker Eval(*this);
13901     {
13902       SequencedSubexpression Sequenced(*this);
13903       Region = LHSRegion;
13904       Visit(BO->getLHS());
13905     }
13906 
13907     // C++11 [expr.log.and]p1:
13908     //  [...] the second operand is not evaluated if the first operand is false.
13909     bool EvalResult = false;
13910     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13911     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13912     if (ShouldVisitRHS) {
13913       Region = RHSRegion;
13914       Visit(BO->getRHS());
13915     }
13916 
13917     Region = OldRegion;
13918     Tree.merge(LHSRegion);
13919     Tree.merge(RHSRegion);
13920   }
13921 
13922   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13923     // C++11 [expr.cond]p1:
13924     //  [...] Every value computation and side effect associated with the first
13925     //  expression is sequenced before every value computation and side effect
13926     //  associated with the second or third expression.
13927     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13928 
13929     // No sequencing is specified between the true and false expression.
13930     // However since exactly one of both is going to be evaluated we can
13931     // consider them to be sequenced. This is needed to avoid warning on
13932     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13933     // both the true and false expressions because we can't evaluate x.
13934     // This will still allow us to detect an expression like (pre C++17)
13935     // "(x ? y += 1 : y += 2) = y".
13936     //
13937     // We don't wrap the visitation of the true and false expression with
13938     // SequencedSubexpression because we don't want to downgrade modifications
13939     // as side effect in the true and false expressions after the visition
13940     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13941     // not warn between the two "y++", but we should warn between the "y++"
13942     // and the "y".
13943     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13944     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13945     SequenceTree::Seq OldRegion = Region;
13946 
13947     EvaluationTracker Eval(*this);
13948     {
13949       SequencedSubexpression Sequenced(*this);
13950       Region = ConditionRegion;
13951       Visit(CO->getCond());
13952     }
13953 
13954     // C++11 [expr.cond]p1:
13955     // [...] The first expression is contextually converted to bool (Clause 4).
13956     // It is evaluated and if it is true, the result of the conditional
13957     // expression is the value of the second expression, otherwise that of the
13958     // third expression. Only one of the second and third expressions is
13959     // evaluated. [...]
13960     bool EvalResult = false;
13961     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13962     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13963     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13964     if (ShouldVisitTrueExpr) {
13965       Region = TrueRegion;
13966       Visit(CO->getTrueExpr());
13967     }
13968     if (ShouldVisitFalseExpr) {
13969       Region = FalseRegion;
13970       Visit(CO->getFalseExpr());
13971     }
13972 
13973     Region = OldRegion;
13974     Tree.merge(ConditionRegion);
13975     Tree.merge(TrueRegion);
13976     Tree.merge(FalseRegion);
13977   }
13978 
13979   void VisitCallExpr(const CallExpr *CE) {
13980     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13981 
13982     if (CE->isUnevaluatedBuiltinCall(Context))
13983       return;
13984 
13985     // C++11 [intro.execution]p15:
13986     //   When calling a function [...], every value computation and side effect
13987     //   associated with any argument expression, or with the postfix expression
13988     //   designating the called function, is sequenced before execution of every
13989     //   expression or statement in the body of the function [and thus before
13990     //   the value computation of its result].
13991     SequencedSubexpression Sequenced(*this);
13992     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13993       // C++17 [expr.call]p5
13994       //   The postfix-expression is sequenced before each expression in the
13995       //   expression-list and any default argument. [...]
13996       SequenceTree::Seq CalleeRegion;
13997       SequenceTree::Seq OtherRegion;
13998       if (SemaRef.getLangOpts().CPlusPlus17) {
13999         CalleeRegion = Tree.allocate(Region);
14000         OtherRegion = Tree.allocate(Region);
14001       } else {
14002         CalleeRegion = Region;
14003         OtherRegion = Region;
14004       }
14005       SequenceTree::Seq OldRegion = Region;
14006 
14007       // Visit the callee expression first.
14008       Region = CalleeRegion;
14009       if (SemaRef.getLangOpts().CPlusPlus17) {
14010         SequencedSubexpression Sequenced(*this);
14011         Visit(CE->getCallee());
14012       } else {
14013         Visit(CE->getCallee());
14014       }
14015 
14016       // Then visit the argument expressions.
14017       Region = OtherRegion;
14018       for (const Expr *Argument : CE->arguments())
14019         Visit(Argument);
14020 
14021       Region = OldRegion;
14022       if (SemaRef.getLangOpts().CPlusPlus17) {
14023         Tree.merge(CalleeRegion);
14024         Tree.merge(OtherRegion);
14025       }
14026     });
14027   }
14028 
14029   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14030     // C++17 [over.match.oper]p2:
14031     //   [...] the operator notation is first transformed to the equivalent
14032     //   function-call notation as summarized in Table 12 (where @ denotes one
14033     //   of the operators covered in the specified subclause). However, the
14034     //   operands are sequenced in the order prescribed for the built-in
14035     //   operator (Clause 8).
14036     //
14037     // From the above only overloaded binary operators and overloaded call
14038     // operators have sequencing rules in C++17 that we need to handle
14039     // separately.
14040     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14041         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14042       return VisitCallExpr(CXXOCE);
14043 
14044     enum {
14045       NoSequencing,
14046       LHSBeforeRHS,
14047       RHSBeforeLHS,
14048       LHSBeforeRest
14049     } SequencingKind;
14050     switch (CXXOCE->getOperator()) {
14051     case OO_Equal:
14052     case OO_PlusEqual:
14053     case OO_MinusEqual:
14054     case OO_StarEqual:
14055     case OO_SlashEqual:
14056     case OO_PercentEqual:
14057     case OO_CaretEqual:
14058     case OO_AmpEqual:
14059     case OO_PipeEqual:
14060     case OO_LessLessEqual:
14061     case OO_GreaterGreaterEqual:
14062       SequencingKind = RHSBeforeLHS;
14063       break;
14064 
14065     case OO_LessLess:
14066     case OO_GreaterGreater:
14067     case OO_AmpAmp:
14068     case OO_PipePipe:
14069     case OO_Comma:
14070     case OO_ArrowStar:
14071     case OO_Subscript:
14072       SequencingKind = LHSBeforeRHS;
14073       break;
14074 
14075     case OO_Call:
14076       SequencingKind = LHSBeforeRest;
14077       break;
14078 
14079     default:
14080       SequencingKind = NoSequencing;
14081       break;
14082     }
14083 
14084     if (SequencingKind == NoSequencing)
14085       return VisitCallExpr(CXXOCE);
14086 
14087     // This is a call, so all subexpressions are sequenced before the result.
14088     SequencedSubexpression Sequenced(*this);
14089 
14090     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14091       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14092              "Should only get there with C++17 and above!");
14093       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14094              "Should only get there with an overloaded binary operator"
14095              " or an overloaded call operator!");
14096 
14097       if (SequencingKind == LHSBeforeRest) {
14098         assert(CXXOCE->getOperator() == OO_Call &&
14099                "We should only have an overloaded call operator here!");
14100 
14101         // This is very similar to VisitCallExpr, except that we only have the
14102         // C++17 case. The postfix-expression is the first argument of the
14103         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14104         // are in the following arguments.
14105         //
14106         // Note that we intentionally do not visit the callee expression since
14107         // it is just a decayed reference to a function.
14108         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14109         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14110         SequenceTree::Seq OldRegion = Region;
14111 
14112         assert(CXXOCE->getNumArgs() >= 1 &&
14113                "An overloaded call operator must have at least one argument"
14114                " for the postfix-expression!");
14115         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14116         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14117                                           CXXOCE->getNumArgs() - 1);
14118 
14119         // Visit the postfix-expression first.
14120         {
14121           Region = PostfixExprRegion;
14122           SequencedSubexpression Sequenced(*this);
14123           Visit(PostfixExpr);
14124         }
14125 
14126         // Then visit the argument expressions.
14127         Region = ArgsRegion;
14128         for (const Expr *Arg : Args)
14129           Visit(Arg);
14130 
14131         Region = OldRegion;
14132         Tree.merge(PostfixExprRegion);
14133         Tree.merge(ArgsRegion);
14134       } else {
14135         assert(CXXOCE->getNumArgs() == 2 &&
14136                "Should only have two arguments here!");
14137         assert((SequencingKind == LHSBeforeRHS ||
14138                 SequencingKind == RHSBeforeLHS) &&
14139                "Unexpected sequencing kind!");
14140 
14141         // We do not visit the callee expression since it is just a decayed
14142         // reference to a function.
14143         const Expr *E1 = CXXOCE->getArg(0);
14144         const Expr *E2 = CXXOCE->getArg(1);
14145         if (SequencingKind == RHSBeforeLHS)
14146           std::swap(E1, E2);
14147 
14148         return VisitSequencedExpressions(E1, E2);
14149       }
14150     });
14151   }
14152 
14153   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14154     // This is a call, so all subexpressions are sequenced before the result.
14155     SequencedSubexpression Sequenced(*this);
14156 
14157     if (!CCE->isListInitialization())
14158       return VisitExpr(CCE);
14159 
14160     // In C++11, list initializations are sequenced.
14161     SmallVector<SequenceTree::Seq, 32> Elts;
14162     SequenceTree::Seq Parent = Region;
14163     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14164                                               E = CCE->arg_end();
14165          I != E; ++I) {
14166       Region = Tree.allocate(Parent);
14167       Elts.push_back(Region);
14168       Visit(*I);
14169     }
14170 
14171     // Forget that the initializers are sequenced.
14172     Region = Parent;
14173     for (unsigned I = 0; I < Elts.size(); ++I)
14174       Tree.merge(Elts[I]);
14175   }
14176 
14177   void VisitInitListExpr(const InitListExpr *ILE) {
14178     if (!SemaRef.getLangOpts().CPlusPlus11)
14179       return VisitExpr(ILE);
14180 
14181     // In C++11, list initializations are sequenced.
14182     SmallVector<SequenceTree::Seq, 32> Elts;
14183     SequenceTree::Seq Parent = Region;
14184     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14185       const Expr *E = ILE->getInit(I);
14186       if (!E)
14187         continue;
14188       Region = Tree.allocate(Parent);
14189       Elts.push_back(Region);
14190       Visit(E);
14191     }
14192 
14193     // Forget that the initializers are sequenced.
14194     Region = Parent;
14195     for (unsigned I = 0; I < Elts.size(); ++I)
14196       Tree.merge(Elts[I]);
14197   }
14198 };
14199 
14200 } // namespace
14201 
14202 void Sema::CheckUnsequencedOperations(const Expr *E) {
14203   SmallVector<const Expr *, 8> WorkList;
14204   WorkList.push_back(E);
14205   while (!WorkList.empty()) {
14206     const Expr *Item = WorkList.pop_back_val();
14207     SequenceChecker(*this, Item, WorkList);
14208   }
14209 }
14210 
14211 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14212                               bool IsConstexpr) {
14213   llvm::SaveAndRestore<bool> ConstantContext(
14214       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14215   CheckImplicitConversions(E, CheckLoc);
14216   if (!E->isInstantiationDependent())
14217     CheckUnsequencedOperations(E);
14218   if (!IsConstexpr && !E->isValueDependent())
14219     CheckForIntOverflow(E);
14220   DiagnoseMisalignedMembers();
14221 }
14222 
14223 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14224                                        FieldDecl *BitField,
14225                                        Expr *Init) {
14226   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14227 }
14228 
14229 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14230                                          SourceLocation Loc) {
14231   if (!PType->isVariablyModifiedType())
14232     return;
14233   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14234     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14235     return;
14236   }
14237   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14238     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14239     return;
14240   }
14241   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14242     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14243     return;
14244   }
14245 
14246   const ArrayType *AT = S.Context.getAsArrayType(PType);
14247   if (!AT)
14248     return;
14249 
14250   if (AT->getSizeModifier() != ArrayType::Star) {
14251     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14252     return;
14253   }
14254 
14255   S.Diag(Loc, diag::err_array_star_in_function_definition);
14256 }
14257 
14258 /// CheckParmsForFunctionDef - Check that the parameters of the given
14259 /// function are appropriate for the definition of a function. This
14260 /// takes care of any checks that cannot be performed on the
14261 /// declaration itself, e.g., that the types of each of the function
14262 /// parameters are complete.
14263 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14264                                     bool CheckParameterNames) {
14265   bool HasInvalidParm = false;
14266   for (ParmVarDecl *Param : Parameters) {
14267     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14268     // function declarator that is part of a function definition of
14269     // that function shall not have incomplete type.
14270     //
14271     // This is also C++ [dcl.fct]p6.
14272     if (!Param->isInvalidDecl() &&
14273         RequireCompleteType(Param->getLocation(), Param->getType(),
14274                             diag::err_typecheck_decl_incomplete_type)) {
14275       Param->setInvalidDecl();
14276       HasInvalidParm = true;
14277     }
14278 
14279     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14280     // declaration of each parameter shall include an identifier.
14281     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14282         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14283       // Diagnose this as an extension in C17 and earlier.
14284       if (!getLangOpts().C2x)
14285         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14286     }
14287 
14288     // C99 6.7.5.3p12:
14289     //   If the function declarator is not part of a definition of that
14290     //   function, parameters may have incomplete type and may use the [*]
14291     //   notation in their sequences of declarator specifiers to specify
14292     //   variable length array types.
14293     QualType PType = Param->getOriginalType();
14294     // FIXME: This diagnostic should point the '[*]' if source-location
14295     // information is added for it.
14296     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14297 
14298     // If the parameter is a c++ class type and it has to be destructed in the
14299     // callee function, declare the destructor so that it can be called by the
14300     // callee function. Do not perform any direct access check on the dtor here.
14301     if (!Param->isInvalidDecl()) {
14302       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14303         if (!ClassDecl->isInvalidDecl() &&
14304             !ClassDecl->hasIrrelevantDestructor() &&
14305             !ClassDecl->isDependentContext() &&
14306             ClassDecl->isParamDestroyedInCallee()) {
14307           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14308           MarkFunctionReferenced(Param->getLocation(), Destructor);
14309           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14310         }
14311       }
14312     }
14313 
14314     // Parameters with the pass_object_size attribute only need to be marked
14315     // constant at function definitions. Because we lack information about
14316     // whether we're on a declaration or definition when we're instantiating the
14317     // attribute, we need to check for constness here.
14318     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14319       if (!Param->getType().isConstQualified())
14320         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14321             << Attr->getSpelling() << 1;
14322 
14323     // Check for parameter names shadowing fields from the class.
14324     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14325       // The owning context for the parameter should be the function, but we
14326       // want to see if this function's declaration context is a record.
14327       DeclContext *DC = Param->getDeclContext();
14328       if (DC && DC->isFunctionOrMethod()) {
14329         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14330           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14331                                      RD, /*DeclIsField*/ false);
14332       }
14333     }
14334   }
14335 
14336   return HasInvalidParm;
14337 }
14338 
14339 Optional<std::pair<CharUnits, CharUnits>>
14340 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14341 
14342 /// Compute the alignment and offset of the base class object given the
14343 /// derived-to-base cast expression and the alignment and offset of the derived
14344 /// class object.
14345 static std::pair<CharUnits, CharUnits>
14346 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14347                                    CharUnits BaseAlignment, CharUnits Offset,
14348                                    ASTContext &Ctx) {
14349   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14350        ++PathI) {
14351     const CXXBaseSpecifier *Base = *PathI;
14352     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14353     if (Base->isVirtual()) {
14354       // The complete object may have a lower alignment than the non-virtual
14355       // alignment of the base, in which case the base may be misaligned. Choose
14356       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14357       // conservative lower bound of the complete object alignment.
14358       CharUnits NonVirtualAlignment =
14359           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14360       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14361       Offset = CharUnits::Zero();
14362     } else {
14363       const ASTRecordLayout &RL =
14364           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14365       Offset += RL.getBaseClassOffset(BaseDecl);
14366     }
14367     DerivedType = Base->getType();
14368   }
14369 
14370   return std::make_pair(BaseAlignment, Offset);
14371 }
14372 
14373 /// Compute the alignment and offset of a binary additive operator.
14374 static Optional<std::pair<CharUnits, CharUnits>>
14375 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14376                                      bool IsSub, ASTContext &Ctx) {
14377   QualType PointeeType = PtrE->getType()->getPointeeType();
14378 
14379   if (!PointeeType->isConstantSizeType())
14380     return llvm::None;
14381 
14382   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14383 
14384   if (!P)
14385     return llvm::None;
14386 
14387   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14388   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14389     CharUnits Offset = EltSize * IdxRes->getExtValue();
14390     if (IsSub)
14391       Offset = -Offset;
14392     return std::make_pair(P->first, P->second + Offset);
14393   }
14394 
14395   // If the integer expression isn't a constant expression, compute the lower
14396   // bound of the alignment using the alignment and offset of the pointer
14397   // expression and the element size.
14398   return std::make_pair(
14399       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14400       CharUnits::Zero());
14401 }
14402 
14403 /// This helper function takes an lvalue expression and returns the alignment of
14404 /// a VarDecl and a constant offset from the VarDecl.
14405 Optional<std::pair<CharUnits, CharUnits>>
14406 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14407   E = E->IgnoreParens();
14408   switch (E->getStmtClass()) {
14409   default:
14410     break;
14411   case Stmt::CStyleCastExprClass:
14412   case Stmt::CXXStaticCastExprClass:
14413   case Stmt::ImplicitCastExprClass: {
14414     auto *CE = cast<CastExpr>(E);
14415     const Expr *From = CE->getSubExpr();
14416     switch (CE->getCastKind()) {
14417     default:
14418       break;
14419     case CK_NoOp:
14420       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14421     case CK_UncheckedDerivedToBase:
14422     case CK_DerivedToBase: {
14423       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14424       if (!P)
14425         break;
14426       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14427                                                 P->second, Ctx);
14428     }
14429     }
14430     break;
14431   }
14432   case Stmt::ArraySubscriptExprClass: {
14433     auto *ASE = cast<ArraySubscriptExpr>(E);
14434     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14435                                                 false, Ctx);
14436   }
14437   case Stmt::DeclRefExprClass: {
14438     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14439       // FIXME: If VD is captured by copy or is an escaping __block variable,
14440       // use the alignment of VD's type.
14441       if (!VD->getType()->isReferenceType())
14442         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14443       if (VD->hasInit())
14444         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14445     }
14446     break;
14447   }
14448   case Stmt::MemberExprClass: {
14449     auto *ME = cast<MemberExpr>(E);
14450     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14451     if (!FD || FD->getType()->isReferenceType())
14452       break;
14453     Optional<std::pair<CharUnits, CharUnits>> P;
14454     if (ME->isArrow())
14455       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14456     else
14457       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14458     if (!P)
14459       break;
14460     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14461     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14462     return std::make_pair(P->first,
14463                           P->second + CharUnits::fromQuantity(Offset));
14464   }
14465   case Stmt::UnaryOperatorClass: {
14466     auto *UO = cast<UnaryOperator>(E);
14467     switch (UO->getOpcode()) {
14468     default:
14469       break;
14470     case UO_Deref:
14471       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14472     }
14473     break;
14474   }
14475   case Stmt::BinaryOperatorClass: {
14476     auto *BO = cast<BinaryOperator>(E);
14477     auto Opcode = BO->getOpcode();
14478     switch (Opcode) {
14479     default:
14480       break;
14481     case BO_Comma:
14482       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14483     }
14484     break;
14485   }
14486   }
14487   return llvm::None;
14488 }
14489 
14490 /// This helper function takes a pointer expression and returns the alignment of
14491 /// a VarDecl and a constant offset from the VarDecl.
14492 Optional<std::pair<CharUnits, CharUnits>>
14493 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14494   E = E->IgnoreParens();
14495   switch (E->getStmtClass()) {
14496   default:
14497     break;
14498   case Stmt::CStyleCastExprClass:
14499   case Stmt::CXXStaticCastExprClass:
14500   case Stmt::ImplicitCastExprClass: {
14501     auto *CE = cast<CastExpr>(E);
14502     const Expr *From = CE->getSubExpr();
14503     switch (CE->getCastKind()) {
14504     default:
14505       break;
14506     case CK_NoOp:
14507       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14508     case CK_ArrayToPointerDecay:
14509       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14510     case CK_UncheckedDerivedToBase:
14511     case CK_DerivedToBase: {
14512       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14513       if (!P)
14514         break;
14515       return getDerivedToBaseAlignmentAndOffset(
14516           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14517     }
14518     }
14519     break;
14520   }
14521   case Stmt::CXXThisExprClass: {
14522     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14523     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14524     return std::make_pair(Alignment, CharUnits::Zero());
14525   }
14526   case Stmt::UnaryOperatorClass: {
14527     auto *UO = cast<UnaryOperator>(E);
14528     if (UO->getOpcode() == UO_AddrOf)
14529       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14530     break;
14531   }
14532   case Stmt::BinaryOperatorClass: {
14533     auto *BO = cast<BinaryOperator>(E);
14534     auto Opcode = BO->getOpcode();
14535     switch (Opcode) {
14536     default:
14537       break;
14538     case BO_Add:
14539     case BO_Sub: {
14540       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14541       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14542         std::swap(LHS, RHS);
14543       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14544                                                   Ctx);
14545     }
14546     case BO_Comma:
14547       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14548     }
14549     break;
14550   }
14551   }
14552   return llvm::None;
14553 }
14554 
14555 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14556   // See if we can compute the alignment of a VarDecl and an offset from it.
14557   Optional<std::pair<CharUnits, CharUnits>> P =
14558       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14559 
14560   if (P)
14561     return P->first.alignmentAtOffset(P->second);
14562 
14563   // If that failed, return the type's alignment.
14564   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14565 }
14566 
14567 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14568 /// pointer cast increases the alignment requirements.
14569 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14570   // This is actually a lot of work to potentially be doing on every
14571   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14572   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14573     return;
14574 
14575   // Ignore dependent types.
14576   if (T->isDependentType() || Op->getType()->isDependentType())
14577     return;
14578 
14579   // Require that the destination be a pointer type.
14580   const PointerType *DestPtr = T->getAs<PointerType>();
14581   if (!DestPtr) return;
14582 
14583   // If the destination has alignment 1, we're done.
14584   QualType DestPointee = DestPtr->getPointeeType();
14585   if (DestPointee->isIncompleteType()) return;
14586   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14587   if (DestAlign.isOne()) return;
14588 
14589   // Require that the source be a pointer type.
14590   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14591   if (!SrcPtr) return;
14592   QualType SrcPointee = SrcPtr->getPointeeType();
14593 
14594   // Explicitly allow casts from cv void*.  We already implicitly
14595   // allowed casts to cv void*, since they have alignment 1.
14596   // Also allow casts involving incomplete types, which implicitly
14597   // includes 'void'.
14598   if (SrcPointee->isIncompleteType()) return;
14599 
14600   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14601 
14602   if (SrcAlign >= DestAlign) return;
14603 
14604   Diag(TRange.getBegin(), diag::warn_cast_align)
14605     << Op->getType() << T
14606     << static_cast<unsigned>(SrcAlign.getQuantity())
14607     << static_cast<unsigned>(DestAlign.getQuantity())
14608     << TRange << Op->getSourceRange();
14609 }
14610 
14611 /// Check whether this array fits the idiom of a size-one tail padded
14612 /// array member of a struct.
14613 ///
14614 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14615 /// commonly used to emulate flexible arrays in C89 code.
14616 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14617                                     const NamedDecl *ND) {
14618   if (Size != 1 || !ND) return false;
14619 
14620   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14621   if (!FD) return false;
14622 
14623   // Don't consider sizes resulting from macro expansions or template argument
14624   // substitution to form C89 tail-padded arrays.
14625 
14626   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14627   while (TInfo) {
14628     TypeLoc TL = TInfo->getTypeLoc();
14629     // Look through typedefs.
14630     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14631       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14632       TInfo = TDL->getTypeSourceInfo();
14633       continue;
14634     }
14635     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14636       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14637       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14638         return false;
14639     }
14640     break;
14641   }
14642 
14643   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14644   if (!RD) return false;
14645   if (RD->isUnion()) return false;
14646   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14647     if (!CRD->isStandardLayout()) return false;
14648   }
14649 
14650   // See if this is the last field decl in the record.
14651   const Decl *D = FD;
14652   while ((D = D->getNextDeclInContext()))
14653     if (isa<FieldDecl>(D))
14654       return false;
14655   return true;
14656 }
14657 
14658 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14659                             const ArraySubscriptExpr *ASE,
14660                             bool AllowOnePastEnd, bool IndexNegated) {
14661   // Already diagnosed by the constant evaluator.
14662   if (isConstantEvaluated())
14663     return;
14664 
14665   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14666   if (IndexExpr->isValueDependent())
14667     return;
14668 
14669   const Type *EffectiveType =
14670       BaseExpr->getType()->getPointeeOrArrayElementType();
14671   BaseExpr = BaseExpr->IgnoreParenCasts();
14672   const ConstantArrayType *ArrayTy =
14673       Context.getAsConstantArrayType(BaseExpr->getType());
14674 
14675   const Type *BaseType =
14676       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14677   bool IsUnboundedArray = (BaseType == nullptr);
14678   if (EffectiveType->isDependentType() ||
14679       (!IsUnboundedArray && BaseType->isDependentType()))
14680     return;
14681 
14682   Expr::EvalResult Result;
14683   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14684     return;
14685 
14686   llvm::APSInt index = Result.Val.getInt();
14687   if (IndexNegated) {
14688     index.setIsUnsigned(false);
14689     index = -index;
14690   }
14691 
14692   const NamedDecl *ND = nullptr;
14693   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14694     ND = DRE->getDecl();
14695   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14696     ND = ME->getMemberDecl();
14697 
14698   if (IsUnboundedArray) {
14699     if (index.isUnsigned() || !index.isNegative()) {
14700       const auto &ASTC = getASTContext();
14701       unsigned AddrBits =
14702           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14703               EffectiveType->getCanonicalTypeInternal()));
14704       if (index.getBitWidth() < AddrBits)
14705         index = index.zext(AddrBits);
14706       Optional<CharUnits> ElemCharUnits =
14707           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14708       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14709       // pointer) bounds-checking isn't meaningful.
14710       if (!ElemCharUnits)
14711         return;
14712       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14713       // If index has more active bits than address space, we already know
14714       // we have a bounds violation to warn about.  Otherwise, compute
14715       // address of (index + 1)th element, and warn about bounds violation
14716       // only if that address exceeds address space.
14717       if (index.getActiveBits() <= AddrBits) {
14718         bool Overflow;
14719         llvm::APInt Product(index);
14720         Product += 1;
14721         Product = Product.umul_ov(ElemBytes, Overflow);
14722         if (!Overflow && Product.getActiveBits() <= AddrBits)
14723           return;
14724       }
14725 
14726       // Need to compute max possible elements in address space, since that
14727       // is included in diag message.
14728       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14729       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14730       MaxElems += 1;
14731       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14732       MaxElems = MaxElems.udiv(ElemBytes);
14733 
14734       unsigned DiagID =
14735           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14736               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14737 
14738       // Diag message shows element size in bits and in "bytes" (platform-
14739       // dependent CharUnits)
14740       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14741                           PDiag(DiagID)
14742                               << toString(index, 10, true) << AddrBits
14743                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14744                               << toString(ElemBytes, 10, false)
14745                               << toString(MaxElems, 10, false)
14746                               << (unsigned)MaxElems.getLimitedValue(~0U)
14747                               << IndexExpr->getSourceRange());
14748 
14749       if (!ND) {
14750         // Try harder to find a NamedDecl to point at in the note.
14751         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14752           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14753         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14754           ND = DRE->getDecl();
14755         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14756           ND = ME->getMemberDecl();
14757       }
14758 
14759       if (ND)
14760         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14761                             PDiag(diag::note_array_declared_here) << ND);
14762     }
14763     return;
14764   }
14765 
14766   if (index.isUnsigned() || !index.isNegative()) {
14767     // It is possible that the type of the base expression after
14768     // IgnoreParenCasts is incomplete, even though the type of the base
14769     // expression before IgnoreParenCasts is complete (see PR39746 for an
14770     // example). In this case we have no information about whether the array
14771     // access exceeds the array bounds. However we can still diagnose an array
14772     // access which precedes the array bounds.
14773     if (BaseType->isIncompleteType())
14774       return;
14775 
14776     llvm::APInt size = ArrayTy->getSize();
14777     if (!size.isStrictlyPositive())
14778       return;
14779 
14780     if (BaseType != EffectiveType) {
14781       // Make sure we're comparing apples to apples when comparing index to size
14782       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14783       uint64_t array_typesize = Context.getTypeSize(BaseType);
14784       // Handle ptrarith_typesize being zero, such as when casting to void*
14785       if (!ptrarith_typesize) ptrarith_typesize = 1;
14786       if (ptrarith_typesize != array_typesize) {
14787         // There's a cast to a different size type involved
14788         uint64_t ratio = array_typesize / ptrarith_typesize;
14789         // TODO: Be smarter about handling cases where array_typesize is not a
14790         // multiple of ptrarith_typesize
14791         if (ptrarith_typesize * ratio == array_typesize)
14792           size *= llvm::APInt(size.getBitWidth(), ratio);
14793       }
14794     }
14795 
14796     if (size.getBitWidth() > index.getBitWidth())
14797       index = index.zext(size.getBitWidth());
14798     else if (size.getBitWidth() < index.getBitWidth())
14799       size = size.zext(index.getBitWidth());
14800 
14801     // For array subscripting the index must be less than size, but for pointer
14802     // arithmetic also allow the index (offset) to be equal to size since
14803     // computing the next address after the end of the array is legal and
14804     // commonly done e.g. in C++ iterators and range-based for loops.
14805     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14806       return;
14807 
14808     // Also don't warn for arrays of size 1 which are members of some
14809     // structure. These are often used to approximate flexible arrays in C89
14810     // code.
14811     if (IsTailPaddedMemberArray(*this, size, ND))
14812       return;
14813 
14814     // Suppress the warning if the subscript expression (as identified by the
14815     // ']' location) and the index expression are both from macro expansions
14816     // within a system header.
14817     if (ASE) {
14818       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14819           ASE->getRBracketLoc());
14820       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14821         SourceLocation IndexLoc =
14822             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14823         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14824           return;
14825       }
14826     }
14827 
14828     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14829                           : diag::warn_ptr_arith_exceeds_bounds;
14830 
14831     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14832                         PDiag(DiagID) << toString(index, 10, true)
14833                                       << toString(size, 10, true)
14834                                       << (unsigned)size.getLimitedValue(~0U)
14835                                       << IndexExpr->getSourceRange());
14836   } else {
14837     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14838     if (!ASE) {
14839       DiagID = diag::warn_ptr_arith_precedes_bounds;
14840       if (index.isNegative()) index = -index;
14841     }
14842 
14843     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14844                         PDiag(DiagID) << toString(index, 10, true)
14845                                       << IndexExpr->getSourceRange());
14846   }
14847 
14848   if (!ND) {
14849     // Try harder to find a NamedDecl to point at in the note.
14850     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14851       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14852     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14853       ND = DRE->getDecl();
14854     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14855       ND = ME->getMemberDecl();
14856   }
14857 
14858   if (ND)
14859     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14860                         PDiag(diag::note_array_declared_here) << ND);
14861 }
14862 
14863 void Sema::CheckArrayAccess(const Expr *expr) {
14864   int AllowOnePastEnd = 0;
14865   while (expr) {
14866     expr = expr->IgnoreParenImpCasts();
14867     switch (expr->getStmtClass()) {
14868       case Stmt::ArraySubscriptExprClass: {
14869         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14870         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14871                          AllowOnePastEnd > 0);
14872         expr = ASE->getBase();
14873         break;
14874       }
14875       case Stmt::MemberExprClass: {
14876         expr = cast<MemberExpr>(expr)->getBase();
14877         break;
14878       }
14879       case Stmt::OMPArraySectionExprClass: {
14880         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14881         if (ASE->getLowerBound())
14882           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14883                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14884         return;
14885       }
14886       case Stmt::UnaryOperatorClass: {
14887         // Only unwrap the * and & unary operators
14888         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14889         expr = UO->getSubExpr();
14890         switch (UO->getOpcode()) {
14891           case UO_AddrOf:
14892             AllowOnePastEnd++;
14893             break;
14894           case UO_Deref:
14895             AllowOnePastEnd--;
14896             break;
14897           default:
14898             return;
14899         }
14900         break;
14901       }
14902       case Stmt::ConditionalOperatorClass: {
14903         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14904         if (const Expr *lhs = cond->getLHS())
14905           CheckArrayAccess(lhs);
14906         if (const Expr *rhs = cond->getRHS())
14907           CheckArrayAccess(rhs);
14908         return;
14909       }
14910       case Stmt::CXXOperatorCallExprClass: {
14911         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14912         for (const auto *Arg : OCE->arguments())
14913           CheckArrayAccess(Arg);
14914         return;
14915       }
14916       default:
14917         return;
14918     }
14919   }
14920 }
14921 
14922 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14923 
14924 namespace {
14925 
14926 struct RetainCycleOwner {
14927   VarDecl *Variable = nullptr;
14928   SourceRange Range;
14929   SourceLocation Loc;
14930   bool Indirect = false;
14931 
14932   RetainCycleOwner() = default;
14933 
14934   void setLocsFrom(Expr *e) {
14935     Loc = e->getExprLoc();
14936     Range = e->getSourceRange();
14937   }
14938 };
14939 
14940 } // namespace
14941 
14942 /// Consider whether capturing the given variable can possibly lead to
14943 /// a retain cycle.
14944 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14945   // In ARC, it's captured strongly iff the variable has __strong
14946   // lifetime.  In MRR, it's captured strongly if the variable is
14947   // __block and has an appropriate type.
14948   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14949     return false;
14950 
14951   owner.Variable = var;
14952   if (ref)
14953     owner.setLocsFrom(ref);
14954   return true;
14955 }
14956 
14957 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14958   while (true) {
14959     e = e->IgnoreParens();
14960     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14961       switch (cast->getCastKind()) {
14962       case CK_BitCast:
14963       case CK_LValueBitCast:
14964       case CK_LValueToRValue:
14965       case CK_ARCReclaimReturnedObject:
14966         e = cast->getSubExpr();
14967         continue;
14968 
14969       default:
14970         return false;
14971       }
14972     }
14973 
14974     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14975       ObjCIvarDecl *ivar = ref->getDecl();
14976       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14977         return false;
14978 
14979       // Try to find a retain cycle in the base.
14980       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14981         return false;
14982 
14983       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14984       owner.Indirect = true;
14985       return true;
14986     }
14987 
14988     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14989       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14990       if (!var) return false;
14991       return considerVariable(var, ref, owner);
14992     }
14993 
14994     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14995       if (member->isArrow()) return false;
14996 
14997       // Don't count this as an indirect ownership.
14998       e = member->getBase();
14999       continue;
15000     }
15001 
15002     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15003       // Only pay attention to pseudo-objects on property references.
15004       ObjCPropertyRefExpr *pre
15005         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15006                                               ->IgnoreParens());
15007       if (!pre) return false;
15008       if (pre->isImplicitProperty()) return false;
15009       ObjCPropertyDecl *property = pre->getExplicitProperty();
15010       if (!property->isRetaining() &&
15011           !(property->getPropertyIvarDecl() &&
15012             property->getPropertyIvarDecl()->getType()
15013               .getObjCLifetime() == Qualifiers::OCL_Strong))
15014           return false;
15015 
15016       owner.Indirect = true;
15017       if (pre->isSuperReceiver()) {
15018         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15019         if (!owner.Variable)
15020           return false;
15021         owner.Loc = pre->getLocation();
15022         owner.Range = pre->getSourceRange();
15023         return true;
15024       }
15025       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15026                               ->getSourceExpr());
15027       continue;
15028     }
15029 
15030     // Array ivars?
15031 
15032     return false;
15033   }
15034 }
15035 
15036 namespace {
15037 
15038   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15039     ASTContext &Context;
15040     VarDecl *Variable;
15041     Expr *Capturer = nullptr;
15042     bool VarWillBeReased = false;
15043 
15044     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15045         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15046           Context(Context), Variable(variable) {}
15047 
15048     void VisitDeclRefExpr(DeclRefExpr *ref) {
15049       if (ref->getDecl() == Variable && !Capturer)
15050         Capturer = ref;
15051     }
15052 
15053     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15054       if (Capturer) return;
15055       Visit(ref->getBase());
15056       if (Capturer && ref->isFreeIvar())
15057         Capturer = ref;
15058     }
15059 
15060     void VisitBlockExpr(BlockExpr *block) {
15061       // Look inside nested blocks
15062       if (block->getBlockDecl()->capturesVariable(Variable))
15063         Visit(block->getBlockDecl()->getBody());
15064     }
15065 
15066     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15067       if (Capturer) return;
15068       if (OVE->getSourceExpr())
15069         Visit(OVE->getSourceExpr());
15070     }
15071 
15072     void VisitBinaryOperator(BinaryOperator *BinOp) {
15073       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15074         return;
15075       Expr *LHS = BinOp->getLHS();
15076       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15077         if (DRE->getDecl() != Variable)
15078           return;
15079         if (Expr *RHS = BinOp->getRHS()) {
15080           RHS = RHS->IgnoreParenCasts();
15081           Optional<llvm::APSInt> Value;
15082           VarWillBeReased =
15083               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15084                *Value == 0);
15085         }
15086       }
15087     }
15088   };
15089 
15090 } // namespace
15091 
15092 /// Check whether the given argument is a block which captures a
15093 /// variable.
15094 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15095   assert(owner.Variable && owner.Loc.isValid());
15096 
15097   e = e->IgnoreParenCasts();
15098 
15099   // Look through [^{...} copy] and Block_copy(^{...}).
15100   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15101     Selector Cmd = ME->getSelector();
15102     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15103       e = ME->getInstanceReceiver();
15104       if (!e)
15105         return nullptr;
15106       e = e->IgnoreParenCasts();
15107     }
15108   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15109     if (CE->getNumArgs() == 1) {
15110       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15111       if (Fn) {
15112         const IdentifierInfo *FnI = Fn->getIdentifier();
15113         if (FnI && FnI->isStr("_Block_copy")) {
15114           e = CE->getArg(0)->IgnoreParenCasts();
15115         }
15116       }
15117     }
15118   }
15119 
15120   BlockExpr *block = dyn_cast<BlockExpr>(e);
15121   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15122     return nullptr;
15123 
15124   FindCaptureVisitor visitor(S.Context, owner.Variable);
15125   visitor.Visit(block->getBlockDecl()->getBody());
15126   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15127 }
15128 
15129 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15130                                 RetainCycleOwner &owner) {
15131   assert(capturer);
15132   assert(owner.Variable && owner.Loc.isValid());
15133 
15134   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15135     << owner.Variable << capturer->getSourceRange();
15136   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15137     << owner.Indirect << owner.Range;
15138 }
15139 
15140 /// Check for a keyword selector that starts with the word 'add' or
15141 /// 'set'.
15142 static bool isSetterLikeSelector(Selector sel) {
15143   if (sel.isUnarySelector()) return false;
15144 
15145   StringRef str = sel.getNameForSlot(0);
15146   while (!str.empty() && str.front() == '_') str = str.substr(1);
15147   if (str.startswith("set"))
15148     str = str.substr(3);
15149   else if (str.startswith("add")) {
15150     // Specially allow 'addOperationWithBlock:'.
15151     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15152       return false;
15153     str = str.substr(3);
15154   }
15155   else
15156     return false;
15157 
15158   if (str.empty()) return true;
15159   return !isLowercase(str.front());
15160 }
15161 
15162 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15163                                                     ObjCMessageExpr *Message) {
15164   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15165                                                 Message->getReceiverInterface(),
15166                                                 NSAPI::ClassId_NSMutableArray);
15167   if (!IsMutableArray) {
15168     return None;
15169   }
15170 
15171   Selector Sel = Message->getSelector();
15172 
15173   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15174     S.NSAPIObj->getNSArrayMethodKind(Sel);
15175   if (!MKOpt) {
15176     return None;
15177   }
15178 
15179   NSAPI::NSArrayMethodKind MK = *MKOpt;
15180 
15181   switch (MK) {
15182     case NSAPI::NSMutableArr_addObject:
15183     case NSAPI::NSMutableArr_insertObjectAtIndex:
15184     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15185       return 0;
15186     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15187       return 1;
15188 
15189     default:
15190       return None;
15191   }
15192 
15193   return None;
15194 }
15195 
15196 static
15197 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15198                                                   ObjCMessageExpr *Message) {
15199   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15200                                             Message->getReceiverInterface(),
15201                                             NSAPI::ClassId_NSMutableDictionary);
15202   if (!IsMutableDictionary) {
15203     return None;
15204   }
15205 
15206   Selector Sel = Message->getSelector();
15207 
15208   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15209     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15210   if (!MKOpt) {
15211     return None;
15212   }
15213 
15214   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15215 
15216   switch (MK) {
15217     case NSAPI::NSMutableDict_setObjectForKey:
15218     case NSAPI::NSMutableDict_setValueForKey:
15219     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15220       return 0;
15221 
15222     default:
15223       return None;
15224   }
15225 
15226   return None;
15227 }
15228 
15229 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15230   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15231                                                 Message->getReceiverInterface(),
15232                                                 NSAPI::ClassId_NSMutableSet);
15233 
15234   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15235                                             Message->getReceiverInterface(),
15236                                             NSAPI::ClassId_NSMutableOrderedSet);
15237   if (!IsMutableSet && !IsMutableOrderedSet) {
15238     return None;
15239   }
15240 
15241   Selector Sel = Message->getSelector();
15242 
15243   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15244   if (!MKOpt) {
15245     return None;
15246   }
15247 
15248   NSAPI::NSSetMethodKind MK = *MKOpt;
15249 
15250   switch (MK) {
15251     case NSAPI::NSMutableSet_addObject:
15252     case NSAPI::NSOrderedSet_setObjectAtIndex:
15253     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15254     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15255       return 0;
15256     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15257       return 1;
15258   }
15259 
15260   return None;
15261 }
15262 
15263 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15264   if (!Message->isInstanceMessage()) {
15265     return;
15266   }
15267 
15268   Optional<int> ArgOpt;
15269 
15270   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15271       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15272       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15273     return;
15274   }
15275 
15276   int ArgIndex = *ArgOpt;
15277 
15278   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15279   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15280     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15281   }
15282 
15283   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15284     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15285       if (ArgRE->isObjCSelfExpr()) {
15286         Diag(Message->getSourceRange().getBegin(),
15287              diag::warn_objc_circular_container)
15288           << ArgRE->getDecl() << StringRef("'super'");
15289       }
15290     }
15291   } else {
15292     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15293 
15294     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15295       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15296     }
15297 
15298     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15299       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15300         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15301           ValueDecl *Decl = ReceiverRE->getDecl();
15302           Diag(Message->getSourceRange().getBegin(),
15303                diag::warn_objc_circular_container)
15304             << Decl << Decl;
15305           if (!ArgRE->isObjCSelfExpr()) {
15306             Diag(Decl->getLocation(),
15307                  diag::note_objc_circular_container_declared_here)
15308               << Decl;
15309           }
15310         }
15311       }
15312     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15313       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15314         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15315           ObjCIvarDecl *Decl = IvarRE->getDecl();
15316           Diag(Message->getSourceRange().getBegin(),
15317                diag::warn_objc_circular_container)
15318             << Decl << Decl;
15319           Diag(Decl->getLocation(),
15320                diag::note_objc_circular_container_declared_here)
15321             << Decl;
15322         }
15323       }
15324     }
15325   }
15326 }
15327 
15328 /// Check a message send to see if it's likely to cause a retain cycle.
15329 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15330   // Only check instance methods whose selector looks like a setter.
15331   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15332     return;
15333 
15334   // Try to find a variable that the receiver is strongly owned by.
15335   RetainCycleOwner owner;
15336   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15337     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15338       return;
15339   } else {
15340     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15341     owner.Variable = getCurMethodDecl()->getSelfDecl();
15342     owner.Loc = msg->getSuperLoc();
15343     owner.Range = msg->getSuperLoc();
15344   }
15345 
15346   // Check whether the receiver is captured by any of the arguments.
15347   const ObjCMethodDecl *MD = msg->getMethodDecl();
15348   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15349     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15350       // noescape blocks should not be retained by the method.
15351       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15352         continue;
15353       return diagnoseRetainCycle(*this, capturer, owner);
15354     }
15355   }
15356 }
15357 
15358 /// Check a property assign to see if it's likely to cause a retain cycle.
15359 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15360   RetainCycleOwner owner;
15361   if (!findRetainCycleOwner(*this, receiver, owner))
15362     return;
15363 
15364   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15365     diagnoseRetainCycle(*this, capturer, owner);
15366 }
15367 
15368 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15369   RetainCycleOwner Owner;
15370   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15371     return;
15372 
15373   // Because we don't have an expression for the variable, we have to set the
15374   // location explicitly here.
15375   Owner.Loc = Var->getLocation();
15376   Owner.Range = Var->getSourceRange();
15377 
15378   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15379     diagnoseRetainCycle(*this, Capturer, Owner);
15380 }
15381 
15382 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15383                                      Expr *RHS, bool isProperty) {
15384   // Check if RHS is an Objective-C object literal, which also can get
15385   // immediately zapped in a weak reference.  Note that we explicitly
15386   // allow ObjCStringLiterals, since those are designed to never really die.
15387   RHS = RHS->IgnoreParenImpCasts();
15388 
15389   // This enum needs to match with the 'select' in
15390   // warn_objc_arc_literal_assign (off-by-1).
15391   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15392   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15393     return false;
15394 
15395   S.Diag(Loc, diag::warn_arc_literal_assign)
15396     << (unsigned) Kind
15397     << (isProperty ? 0 : 1)
15398     << RHS->getSourceRange();
15399 
15400   return true;
15401 }
15402 
15403 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15404                                     Qualifiers::ObjCLifetime LT,
15405                                     Expr *RHS, bool isProperty) {
15406   // Strip off any implicit cast added to get to the one ARC-specific.
15407   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15408     if (cast->getCastKind() == CK_ARCConsumeObject) {
15409       S.Diag(Loc, diag::warn_arc_retained_assign)
15410         << (LT == Qualifiers::OCL_ExplicitNone)
15411         << (isProperty ? 0 : 1)
15412         << RHS->getSourceRange();
15413       return true;
15414     }
15415     RHS = cast->getSubExpr();
15416   }
15417 
15418   if (LT == Qualifiers::OCL_Weak &&
15419       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15420     return true;
15421 
15422   return false;
15423 }
15424 
15425 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15426                               QualType LHS, Expr *RHS) {
15427   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15428 
15429   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15430     return false;
15431 
15432   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15433     return true;
15434 
15435   return false;
15436 }
15437 
15438 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15439                               Expr *LHS, Expr *RHS) {
15440   QualType LHSType;
15441   // PropertyRef on LHS type need be directly obtained from
15442   // its declaration as it has a PseudoType.
15443   ObjCPropertyRefExpr *PRE
15444     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15445   if (PRE && !PRE->isImplicitProperty()) {
15446     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15447     if (PD)
15448       LHSType = PD->getType();
15449   }
15450 
15451   if (LHSType.isNull())
15452     LHSType = LHS->getType();
15453 
15454   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15455 
15456   if (LT == Qualifiers::OCL_Weak) {
15457     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15458       getCurFunction()->markSafeWeakUse(LHS);
15459   }
15460 
15461   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15462     return;
15463 
15464   // FIXME. Check for other life times.
15465   if (LT != Qualifiers::OCL_None)
15466     return;
15467 
15468   if (PRE) {
15469     if (PRE->isImplicitProperty())
15470       return;
15471     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15472     if (!PD)
15473       return;
15474 
15475     unsigned Attributes = PD->getPropertyAttributes();
15476     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15477       // when 'assign' attribute was not explicitly specified
15478       // by user, ignore it and rely on property type itself
15479       // for lifetime info.
15480       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15481       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15482           LHSType->isObjCRetainableType())
15483         return;
15484 
15485       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15486         if (cast->getCastKind() == CK_ARCConsumeObject) {
15487           Diag(Loc, diag::warn_arc_retained_property_assign)
15488           << RHS->getSourceRange();
15489           return;
15490         }
15491         RHS = cast->getSubExpr();
15492       }
15493     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15494       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15495         return;
15496     }
15497   }
15498 }
15499 
15500 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15501 
15502 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15503                                         SourceLocation StmtLoc,
15504                                         const NullStmt *Body) {
15505   // Do not warn if the body is a macro that expands to nothing, e.g:
15506   //
15507   // #define CALL(x)
15508   // if (condition)
15509   //   CALL(0);
15510   if (Body->hasLeadingEmptyMacro())
15511     return false;
15512 
15513   // Get line numbers of statement and body.
15514   bool StmtLineInvalid;
15515   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15516                                                       &StmtLineInvalid);
15517   if (StmtLineInvalid)
15518     return false;
15519 
15520   bool BodyLineInvalid;
15521   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15522                                                       &BodyLineInvalid);
15523   if (BodyLineInvalid)
15524     return false;
15525 
15526   // Warn if null statement and body are on the same line.
15527   if (StmtLine != BodyLine)
15528     return false;
15529 
15530   return true;
15531 }
15532 
15533 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15534                                  const Stmt *Body,
15535                                  unsigned DiagID) {
15536   // Since this is a syntactic check, don't emit diagnostic for template
15537   // instantiations, this just adds noise.
15538   if (CurrentInstantiationScope)
15539     return;
15540 
15541   // The body should be a null statement.
15542   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15543   if (!NBody)
15544     return;
15545 
15546   // Do the usual checks.
15547   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15548     return;
15549 
15550   Diag(NBody->getSemiLoc(), DiagID);
15551   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15552 }
15553 
15554 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15555                                  const Stmt *PossibleBody) {
15556   assert(!CurrentInstantiationScope); // Ensured by caller
15557 
15558   SourceLocation StmtLoc;
15559   const Stmt *Body;
15560   unsigned DiagID;
15561   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15562     StmtLoc = FS->getRParenLoc();
15563     Body = FS->getBody();
15564     DiagID = diag::warn_empty_for_body;
15565   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15566     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15567     Body = WS->getBody();
15568     DiagID = diag::warn_empty_while_body;
15569   } else
15570     return; // Neither `for' nor `while'.
15571 
15572   // The body should be a null statement.
15573   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15574   if (!NBody)
15575     return;
15576 
15577   // Skip expensive checks if diagnostic is disabled.
15578   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15579     return;
15580 
15581   // Do the usual checks.
15582   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15583     return;
15584 
15585   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15586   // noise level low, emit diagnostics only if for/while is followed by a
15587   // CompoundStmt, e.g.:
15588   //    for (int i = 0; i < n; i++);
15589   //    {
15590   //      a(i);
15591   //    }
15592   // or if for/while is followed by a statement with more indentation
15593   // than for/while itself:
15594   //    for (int i = 0; i < n; i++);
15595   //      a(i);
15596   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15597   if (!ProbableTypo) {
15598     bool BodyColInvalid;
15599     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15600         PossibleBody->getBeginLoc(), &BodyColInvalid);
15601     if (BodyColInvalid)
15602       return;
15603 
15604     bool StmtColInvalid;
15605     unsigned StmtCol =
15606         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15607     if (StmtColInvalid)
15608       return;
15609 
15610     if (BodyCol > StmtCol)
15611       ProbableTypo = true;
15612   }
15613 
15614   if (ProbableTypo) {
15615     Diag(NBody->getSemiLoc(), DiagID);
15616     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15617   }
15618 }
15619 
15620 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15621 
15622 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15623 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15624                              SourceLocation OpLoc) {
15625   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15626     return;
15627 
15628   if (inTemplateInstantiation())
15629     return;
15630 
15631   // Strip parens and casts away.
15632   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15633   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15634 
15635   // Check for a call expression
15636   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15637   if (!CE || CE->getNumArgs() != 1)
15638     return;
15639 
15640   // Check for a call to std::move
15641   if (!CE->isCallToStdMove())
15642     return;
15643 
15644   // Get argument from std::move
15645   RHSExpr = CE->getArg(0);
15646 
15647   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15648   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15649 
15650   // Two DeclRefExpr's, check that the decls are the same.
15651   if (LHSDeclRef && RHSDeclRef) {
15652     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15653       return;
15654     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15655         RHSDeclRef->getDecl()->getCanonicalDecl())
15656       return;
15657 
15658     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15659                                         << LHSExpr->getSourceRange()
15660                                         << RHSExpr->getSourceRange();
15661     return;
15662   }
15663 
15664   // Member variables require a different approach to check for self moves.
15665   // MemberExpr's are the same if every nested MemberExpr refers to the same
15666   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15667   // the base Expr's are CXXThisExpr's.
15668   const Expr *LHSBase = LHSExpr;
15669   const Expr *RHSBase = RHSExpr;
15670   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15671   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15672   if (!LHSME || !RHSME)
15673     return;
15674 
15675   while (LHSME && RHSME) {
15676     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15677         RHSME->getMemberDecl()->getCanonicalDecl())
15678       return;
15679 
15680     LHSBase = LHSME->getBase();
15681     RHSBase = RHSME->getBase();
15682     LHSME = dyn_cast<MemberExpr>(LHSBase);
15683     RHSME = dyn_cast<MemberExpr>(RHSBase);
15684   }
15685 
15686   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15687   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15688   if (LHSDeclRef && RHSDeclRef) {
15689     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15690       return;
15691     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15692         RHSDeclRef->getDecl()->getCanonicalDecl())
15693       return;
15694 
15695     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15696                                         << LHSExpr->getSourceRange()
15697                                         << RHSExpr->getSourceRange();
15698     return;
15699   }
15700 
15701   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15702     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15703                                         << LHSExpr->getSourceRange()
15704                                         << RHSExpr->getSourceRange();
15705 }
15706 
15707 //===--- Layout compatibility ----------------------------------------------//
15708 
15709 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15710 
15711 /// Check if two enumeration types are layout-compatible.
15712 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15713   // C++11 [dcl.enum] p8:
15714   // Two enumeration types are layout-compatible if they have the same
15715   // underlying type.
15716   return ED1->isComplete() && ED2->isComplete() &&
15717          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15718 }
15719 
15720 /// Check if two fields are layout-compatible.
15721 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15722                                FieldDecl *Field2) {
15723   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15724     return false;
15725 
15726   if (Field1->isBitField() != Field2->isBitField())
15727     return false;
15728 
15729   if (Field1->isBitField()) {
15730     // Make sure that the bit-fields are the same length.
15731     unsigned Bits1 = Field1->getBitWidthValue(C);
15732     unsigned Bits2 = Field2->getBitWidthValue(C);
15733 
15734     if (Bits1 != Bits2)
15735       return false;
15736   }
15737 
15738   return true;
15739 }
15740 
15741 /// Check if two standard-layout structs are layout-compatible.
15742 /// (C++11 [class.mem] p17)
15743 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15744                                      RecordDecl *RD2) {
15745   // If both records are C++ classes, check that base classes match.
15746   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15747     // If one of records is a CXXRecordDecl we are in C++ mode,
15748     // thus the other one is a CXXRecordDecl, too.
15749     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15750     // Check number of base classes.
15751     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15752       return false;
15753 
15754     // Check the base classes.
15755     for (CXXRecordDecl::base_class_const_iterator
15756                Base1 = D1CXX->bases_begin(),
15757            BaseEnd1 = D1CXX->bases_end(),
15758               Base2 = D2CXX->bases_begin();
15759          Base1 != BaseEnd1;
15760          ++Base1, ++Base2) {
15761       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15762         return false;
15763     }
15764   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15765     // If only RD2 is a C++ class, it should have zero base classes.
15766     if (D2CXX->getNumBases() > 0)
15767       return false;
15768   }
15769 
15770   // Check the fields.
15771   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15772                              Field2End = RD2->field_end(),
15773                              Field1 = RD1->field_begin(),
15774                              Field1End = RD1->field_end();
15775   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15776     if (!isLayoutCompatible(C, *Field1, *Field2))
15777       return false;
15778   }
15779   if (Field1 != Field1End || Field2 != Field2End)
15780     return false;
15781 
15782   return true;
15783 }
15784 
15785 /// Check if two standard-layout unions are layout-compatible.
15786 /// (C++11 [class.mem] p18)
15787 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15788                                     RecordDecl *RD2) {
15789   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15790   for (auto *Field2 : RD2->fields())
15791     UnmatchedFields.insert(Field2);
15792 
15793   for (auto *Field1 : RD1->fields()) {
15794     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15795         I = UnmatchedFields.begin(),
15796         E = UnmatchedFields.end();
15797 
15798     for ( ; I != E; ++I) {
15799       if (isLayoutCompatible(C, Field1, *I)) {
15800         bool Result = UnmatchedFields.erase(*I);
15801         (void) Result;
15802         assert(Result);
15803         break;
15804       }
15805     }
15806     if (I == E)
15807       return false;
15808   }
15809 
15810   return UnmatchedFields.empty();
15811 }
15812 
15813 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15814                                RecordDecl *RD2) {
15815   if (RD1->isUnion() != RD2->isUnion())
15816     return false;
15817 
15818   if (RD1->isUnion())
15819     return isLayoutCompatibleUnion(C, RD1, RD2);
15820   else
15821     return isLayoutCompatibleStruct(C, RD1, RD2);
15822 }
15823 
15824 /// Check if two types are layout-compatible in C++11 sense.
15825 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15826   if (T1.isNull() || T2.isNull())
15827     return false;
15828 
15829   // C++11 [basic.types] p11:
15830   // If two types T1 and T2 are the same type, then T1 and T2 are
15831   // layout-compatible types.
15832   if (C.hasSameType(T1, T2))
15833     return true;
15834 
15835   T1 = T1.getCanonicalType().getUnqualifiedType();
15836   T2 = T2.getCanonicalType().getUnqualifiedType();
15837 
15838   const Type::TypeClass TC1 = T1->getTypeClass();
15839   const Type::TypeClass TC2 = T2->getTypeClass();
15840 
15841   if (TC1 != TC2)
15842     return false;
15843 
15844   if (TC1 == Type::Enum) {
15845     return isLayoutCompatible(C,
15846                               cast<EnumType>(T1)->getDecl(),
15847                               cast<EnumType>(T2)->getDecl());
15848   } else if (TC1 == Type::Record) {
15849     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15850       return false;
15851 
15852     return isLayoutCompatible(C,
15853                               cast<RecordType>(T1)->getDecl(),
15854                               cast<RecordType>(T2)->getDecl());
15855   }
15856 
15857   return false;
15858 }
15859 
15860 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15861 
15862 /// Given a type tag expression find the type tag itself.
15863 ///
15864 /// \param TypeExpr Type tag expression, as it appears in user's code.
15865 ///
15866 /// \param VD Declaration of an identifier that appears in a type tag.
15867 ///
15868 /// \param MagicValue Type tag magic value.
15869 ///
15870 /// \param isConstantEvaluated wether the evalaution should be performed in
15871 
15872 /// constant context.
15873 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15874                             const ValueDecl **VD, uint64_t *MagicValue,
15875                             bool isConstantEvaluated) {
15876   while(true) {
15877     if (!TypeExpr)
15878       return false;
15879 
15880     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15881 
15882     switch (TypeExpr->getStmtClass()) {
15883     case Stmt::UnaryOperatorClass: {
15884       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15885       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15886         TypeExpr = UO->getSubExpr();
15887         continue;
15888       }
15889       return false;
15890     }
15891 
15892     case Stmt::DeclRefExprClass: {
15893       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15894       *VD = DRE->getDecl();
15895       return true;
15896     }
15897 
15898     case Stmt::IntegerLiteralClass: {
15899       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15900       llvm::APInt MagicValueAPInt = IL->getValue();
15901       if (MagicValueAPInt.getActiveBits() <= 64) {
15902         *MagicValue = MagicValueAPInt.getZExtValue();
15903         return true;
15904       } else
15905         return false;
15906     }
15907 
15908     case Stmt::BinaryConditionalOperatorClass:
15909     case Stmt::ConditionalOperatorClass: {
15910       const AbstractConditionalOperator *ACO =
15911           cast<AbstractConditionalOperator>(TypeExpr);
15912       bool Result;
15913       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15914                                                      isConstantEvaluated)) {
15915         if (Result)
15916           TypeExpr = ACO->getTrueExpr();
15917         else
15918           TypeExpr = ACO->getFalseExpr();
15919         continue;
15920       }
15921       return false;
15922     }
15923 
15924     case Stmt::BinaryOperatorClass: {
15925       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15926       if (BO->getOpcode() == BO_Comma) {
15927         TypeExpr = BO->getRHS();
15928         continue;
15929       }
15930       return false;
15931     }
15932 
15933     default:
15934       return false;
15935     }
15936   }
15937 }
15938 
15939 /// Retrieve the C type corresponding to type tag TypeExpr.
15940 ///
15941 /// \param TypeExpr Expression that specifies a type tag.
15942 ///
15943 /// \param MagicValues Registered magic values.
15944 ///
15945 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15946 ///        kind.
15947 ///
15948 /// \param TypeInfo Information about the corresponding C type.
15949 ///
15950 /// \param isConstantEvaluated wether the evalaution should be performed in
15951 /// constant context.
15952 ///
15953 /// \returns true if the corresponding C type was found.
15954 static bool GetMatchingCType(
15955     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15956     const ASTContext &Ctx,
15957     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15958         *MagicValues,
15959     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15960     bool isConstantEvaluated) {
15961   FoundWrongKind = false;
15962 
15963   // Variable declaration that has type_tag_for_datatype attribute.
15964   const ValueDecl *VD = nullptr;
15965 
15966   uint64_t MagicValue;
15967 
15968   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15969     return false;
15970 
15971   if (VD) {
15972     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15973       if (I->getArgumentKind() != ArgumentKind) {
15974         FoundWrongKind = true;
15975         return false;
15976       }
15977       TypeInfo.Type = I->getMatchingCType();
15978       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15979       TypeInfo.MustBeNull = I->getMustBeNull();
15980       return true;
15981     }
15982     return false;
15983   }
15984 
15985   if (!MagicValues)
15986     return false;
15987 
15988   llvm::DenseMap<Sema::TypeTagMagicValue,
15989                  Sema::TypeTagData>::const_iterator I =
15990       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15991   if (I == MagicValues->end())
15992     return false;
15993 
15994   TypeInfo = I->second;
15995   return true;
15996 }
15997 
15998 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15999                                       uint64_t MagicValue, QualType Type,
16000                                       bool LayoutCompatible,
16001                                       bool MustBeNull) {
16002   if (!TypeTagForDatatypeMagicValues)
16003     TypeTagForDatatypeMagicValues.reset(
16004         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16005 
16006   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16007   (*TypeTagForDatatypeMagicValues)[Magic] =
16008       TypeTagData(Type, LayoutCompatible, MustBeNull);
16009 }
16010 
16011 static bool IsSameCharType(QualType T1, QualType T2) {
16012   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16013   if (!BT1)
16014     return false;
16015 
16016   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16017   if (!BT2)
16018     return false;
16019 
16020   BuiltinType::Kind T1Kind = BT1->getKind();
16021   BuiltinType::Kind T2Kind = BT2->getKind();
16022 
16023   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16024          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16025          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16026          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16027 }
16028 
16029 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16030                                     const ArrayRef<const Expr *> ExprArgs,
16031                                     SourceLocation CallSiteLoc) {
16032   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16033   bool IsPointerAttr = Attr->getIsPointer();
16034 
16035   // Retrieve the argument representing the 'type_tag'.
16036   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16037   if (TypeTagIdxAST >= ExprArgs.size()) {
16038     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16039         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16040     return;
16041   }
16042   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16043   bool FoundWrongKind;
16044   TypeTagData TypeInfo;
16045   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16046                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16047                         TypeInfo, isConstantEvaluated())) {
16048     if (FoundWrongKind)
16049       Diag(TypeTagExpr->getExprLoc(),
16050            diag::warn_type_tag_for_datatype_wrong_kind)
16051         << TypeTagExpr->getSourceRange();
16052     return;
16053   }
16054 
16055   // Retrieve the argument representing the 'arg_idx'.
16056   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16057   if (ArgumentIdxAST >= ExprArgs.size()) {
16058     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16059         << 1 << Attr->getArgumentIdx().getSourceIndex();
16060     return;
16061   }
16062   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16063   if (IsPointerAttr) {
16064     // Skip implicit cast of pointer to `void *' (as a function argument).
16065     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16066       if (ICE->getType()->isVoidPointerType() &&
16067           ICE->getCastKind() == CK_BitCast)
16068         ArgumentExpr = ICE->getSubExpr();
16069   }
16070   QualType ArgumentType = ArgumentExpr->getType();
16071 
16072   // Passing a `void*' pointer shouldn't trigger a warning.
16073   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16074     return;
16075 
16076   if (TypeInfo.MustBeNull) {
16077     // Type tag with matching void type requires a null pointer.
16078     if (!ArgumentExpr->isNullPointerConstant(Context,
16079                                              Expr::NPC_ValueDependentIsNotNull)) {
16080       Diag(ArgumentExpr->getExprLoc(),
16081            diag::warn_type_safety_null_pointer_required)
16082           << ArgumentKind->getName()
16083           << ArgumentExpr->getSourceRange()
16084           << TypeTagExpr->getSourceRange();
16085     }
16086     return;
16087   }
16088 
16089   QualType RequiredType = TypeInfo.Type;
16090   if (IsPointerAttr)
16091     RequiredType = Context.getPointerType(RequiredType);
16092 
16093   bool mismatch = false;
16094   if (!TypeInfo.LayoutCompatible) {
16095     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16096 
16097     // C++11 [basic.fundamental] p1:
16098     // Plain char, signed char, and unsigned char are three distinct types.
16099     //
16100     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16101     // char' depending on the current char signedness mode.
16102     if (mismatch)
16103       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16104                                            RequiredType->getPointeeType())) ||
16105           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16106         mismatch = false;
16107   } else
16108     if (IsPointerAttr)
16109       mismatch = !isLayoutCompatible(Context,
16110                                      ArgumentType->getPointeeType(),
16111                                      RequiredType->getPointeeType());
16112     else
16113       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16114 
16115   if (mismatch)
16116     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16117         << ArgumentType << ArgumentKind
16118         << TypeInfo.LayoutCompatible << RequiredType
16119         << ArgumentExpr->getSourceRange()
16120         << TypeTagExpr->getSourceRange();
16121 }
16122 
16123 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16124                                          CharUnits Alignment) {
16125   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16126 }
16127 
16128 void Sema::DiagnoseMisalignedMembers() {
16129   for (MisalignedMember &m : MisalignedMembers) {
16130     const NamedDecl *ND = m.RD;
16131     if (ND->getName().empty()) {
16132       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16133         ND = TD;
16134     }
16135     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16136         << m.MD << ND << m.E->getSourceRange();
16137   }
16138   MisalignedMembers.clear();
16139 }
16140 
16141 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16142   E = E->IgnoreParens();
16143   if (!T->isPointerType() && !T->isIntegerType())
16144     return;
16145   if (isa<UnaryOperator>(E) &&
16146       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16147     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16148     if (isa<MemberExpr>(Op)) {
16149       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16150       if (MA != MisalignedMembers.end() &&
16151           (T->isIntegerType() ||
16152            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16153                                    Context.getTypeAlignInChars(
16154                                        T->getPointeeType()) <= MA->Alignment))))
16155         MisalignedMembers.erase(MA);
16156     }
16157   }
16158 }
16159 
16160 void Sema::RefersToMemberWithReducedAlignment(
16161     Expr *E,
16162     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16163         Action) {
16164   const auto *ME = dyn_cast<MemberExpr>(E);
16165   if (!ME)
16166     return;
16167 
16168   // No need to check expressions with an __unaligned-qualified type.
16169   if (E->getType().getQualifiers().hasUnaligned())
16170     return;
16171 
16172   // For a chain of MemberExpr like "a.b.c.d" this list
16173   // will keep FieldDecl's like [d, c, b].
16174   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16175   const MemberExpr *TopME = nullptr;
16176   bool AnyIsPacked = false;
16177   do {
16178     QualType BaseType = ME->getBase()->getType();
16179     if (BaseType->isDependentType())
16180       return;
16181     if (ME->isArrow())
16182       BaseType = BaseType->getPointeeType();
16183     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16184     if (RD->isInvalidDecl())
16185       return;
16186 
16187     ValueDecl *MD = ME->getMemberDecl();
16188     auto *FD = dyn_cast<FieldDecl>(MD);
16189     // We do not care about non-data members.
16190     if (!FD || FD->isInvalidDecl())
16191       return;
16192 
16193     AnyIsPacked =
16194         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16195     ReverseMemberChain.push_back(FD);
16196 
16197     TopME = ME;
16198     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16199   } while (ME);
16200   assert(TopME && "We did not compute a topmost MemberExpr!");
16201 
16202   // Not the scope of this diagnostic.
16203   if (!AnyIsPacked)
16204     return;
16205 
16206   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16207   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16208   // TODO: The innermost base of the member expression may be too complicated.
16209   // For now, just disregard these cases. This is left for future
16210   // improvement.
16211   if (!DRE && !isa<CXXThisExpr>(TopBase))
16212       return;
16213 
16214   // Alignment expected by the whole expression.
16215   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16216 
16217   // No need to do anything else with this case.
16218   if (ExpectedAlignment.isOne())
16219     return;
16220 
16221   // Synthesize offset of the whole access.
16222   CharUnits Offset;
16223   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16224        I++) {
16225     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16226   }
16227 
16228   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16229   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16230       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16231 
16232   // The base expression of the innermost MemberExpr may give
16233   // stronger guarantees than the class containing the member.
16234   if (DRE && !TopME->isArrow()) {
16235     const ValueDecl *VD = DRE->getDecl();
16236     if (!VD->getType()->isReferenceType())
16237       CompleteObjectAlignment =
16238           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16239   }
16240 
16241   // Check if the synthesized offset fulfills the alignment.
16242   if (Offset % ExpectedAlignment != 0 ||
16243       // It may fulfill the offset it but the effective alignment may still be
16244       // lower than the expected expression alignment.
16245       CompleteObjectAlignment < ExpectedAlignment) {
16246     // If this happens, we want to determine a sensible culprit of this.
16247     // Intuitively, watching the chain of member expressions from right to
16248     // left, we start with the required alignment (as required by the field
16249     // type) but some packed attribute in that chain has reduced the alignment.
16250     // It may happen that another packed structure increases it again. But if
16251     // we are here such increase has not been enough. So pointing the first
16252     // FieldDecl that either is packed or else its RecordDecl is,
16253     // seems reasonable.
16254     FieldDecl *FD = nullptr;
16255     CharUnits Alignment;
16256     for (FieldDecl *FDI : ReverseMemberChain) {
16257       if (FDI->hasAttr<PackedAttr>() ||
16258           FDI->getParent()->hasAttr<PackedAttr>()) {
16259         FD = FDI;
16260         Alignment = std::min(
16261             Context.getTypeAlignInChars(FD->getType()),
16262             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16263         break;
16264       }
16265     }
16266     assert(FD && "We did not find a packed FieldDecl!");
16267     Action(E, FD->getParent(), FD, Alignment);
16268   }
16269 }
16270 
16271 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16272   using namespace std::placeholders;
16273 
16274   RefersToMemberWithReducedAlignment(
16275       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16276                      _2, _3, _4));
16277 }
16278 
16279 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16280                                             ExprResult CallResult) {
16281   if (checkArgCount(*this, TheCall, 1))
16282     return ExprError();
16283 
16284   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16285   if (MatrixArg.isInvalid())
16286     return MatrixArg;
16287   Expr *Matrix = MatrixArg.get();
16288 
16289   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16290   if (!MType) {
16291     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16292     return ExprError();
16293   }
16294 
16295   // Create returned matrix type by swapping rows and columns of the argument
16296   // matrix type.
16297   QualType ResultType = Context.getConstantMatrixType(
16298       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16299 
16300   // Change the return type to the type of the returned matrix.
16301   TheCall->setType(ResultType);
16302 
16303   // Update call argument to use the possibly converted matrix argument.
16304   TheCall->setArg(0, Matrix);
16305   return CallResult;
16306 }
16307 
16308 // Get and verify the matrix dimensions.
16309 static llvm::Optional<unsigned>
16310 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16311   SourceLocation ErrorPos;
16312   Optional<llvm::APSInt> Value =
16313       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16314   if (!Value) {
16315     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16316         << Name;
16317     return {};
16318   }
16319   uint64_t Dim = Value->getZExtValue();
16320   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16321     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16322         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16323     return {};
16324   }
16325   return Dim;
16326 }
16327 
16328 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16329                                                   ExprResult CallResult) {
16330   if (!getLangOpts().MatrixTypes) {
16331     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16332     return ExprError();
16333   }
16334 
16335   if (checkArgCount(*this, TheCall, 4))
16336     return ExprError();
16337 
16338   unsigned PtrArgIdx = 0;
16339   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16340   Expr *RowsExpr = TheCall->getArg(1);
16341   Expr *ColumnsExpr = TheCall->getArg(2);
16342   Expr *StrideExpr = TheCall->getArg(3);
16343 
16344   bool ArgError = false;
16345 
16346   // Check pointer argument.
16347   {
16348     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16349     if (PtrConv.isInvalid())
16350       return PtrConv;
16351     PtrExpr = PtrConv.get();
16352     TheCall->setArg(0, PtrExpr);
16353     if (PtrExpr->isTypeDependent()) {
16354       TheCall->setType(Context.DependentTy);
16355       return TheCall;
16356     }
16357   }
16358 
16359   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16360   QualType ElementTy;
16361   if (!PtrTy) {
16362     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16363         << PtrArgIdx + 1;
16364     ArgError = true;
16365   } else {
16366     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16367 
16368     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16369       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16370           << PtrArgIdx + 1;
16371       ArgError = true;
16372     }
16373   }
16374 
16375   // Apply default Lvalue conversions and convert the expression to size_t.
16376   auto ApplyArgumentConversions = [this](Expr *E) {
16377     ExprResult Conv = DefaultLvalueConversion(E);
16378     if (Conv.isInvalid())
16379       return Conv;
16380 
16381     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16382   };
16383 
16384   // Apply conversion to row and column expressions.
16385   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16386   if (!RowsConv.isInvalid()) {
16387     RowsExpr = RowsConv.get();
16388     TheCall->setArg(1, RowsExpr);
16389   } else
16390     RowsExpr = nullptr;
16391 
16392   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16393   if (!ColumnsConv.isInvalid()) {
16394     ColumnsExpr = ColumnsConv.get();
16395     TheCall->setArg(2, ColumnsExpr);
16396   } else
16397     ColumnsExpr = nullptr;
16398 
16399   // If any any part of the result matrix type is still pending, just use
16400   // Context.DependentTy, until all parts are resolved.
16401   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16402       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16403     TheCall->setType(Context.DependentTy);
16404     return CallResult;
16405   }
16406 
16407   // Check row and column dimenions.
16408   llvm::Optional<unsigned> MaybeRows;
16409   if (RowsExpr)
16410     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16411 
16412   llvm::Optional<unsigned> MaybeColumns;
16413   if (ColumnsExpr)
16414     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16415 
16416   // Check stride argument.
16417   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16418   if (StrideConv.isInvalid())
16419     return ExprError();
16420   StrideExpr = StrideConv.get();
16421   TheCall->setArg(3, StrideExpr);
16422 
16423   if (MaybeRows) {
16424     if (Optional<llvm::APSInt> Value =
16425             StrideExpr->getIntegerConstantExpr(Context)) {
16426       uint64_t Stride = Value->getZExtValue();
16427       if (Stride < *MaybeRows) {
16428         Diag(StrideExpr->getBeginLoc(),
16429              diag::err_builtin_matrix_stride_too_small);
16430         ArgError = true;
16431       }
16432     }
16433   }
16434 
16435   if (ArgError || !MaybeRows || !MaybeColumns)
16436     return ExprError();
16437 
16438   TheCall->setType(
16439       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16440   return CallResult;
16441 }
16442 
16443 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16444                                                    ExprResult CallResult) {
16445   if (checkArgCount(*this, TheCall, 3))
16446     return ExprError();
16447 
16448   unsigned PtrArgIdx = 1;
16449   Expr *MatrixExpr = TheCall->getArg(0);
16450   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16451   Expr *StrideExpr = TheCall->getArg(2);
16452 
16453   bool ArgError = false;
16454 
16455   {
16456     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16457     if (MatrixConv.isInvalid())
16458       return MatrixConv;
16459     MatrixExpr = MatrixConv.get();
16460     TheCall->setArg(0, MatrixExpr);
16461   }
16462   if (MatrixExpr->isTypeDependent()) {
16463     TheCall->setType(Context.DependentTy);
16464     return TheCall;
16465   }
16466 
16467   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16468   if (!MatrixTy) {
16469     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16470     ArgError = true;
16471   }
16472 
16473   {
16474     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16475     if (PtrConv.isInvalid())
16476       return PtrConv;
16477     PtrExpr = PtrConv.get();
16478     TheCall->setArg(1, PtrExpr);
16479     if (PtrExpr->isTypeDependent()) {
16480       TheCall->setType(Context.DependentTy);
16481       return TheCall;
16482     }
16483   }
16484 
16485   // Check pointer argument.
16486   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16487   if (!PtrTy) {
16488     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16489         << PtrArgIdx + 1;
16490     ArgError = true;
16491   } else {
16492     QualType ElementTy = PtrTy->getPointeeType();
16493     if (ElementTy.isConstQualified()) {
16494       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16495       ArgError = true;
16496     }
16497     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16498     if (MatrixTy &&
16499         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16500       Diag(PtrExpr->getBeginLoc(),
16501            diag::err_builtin_matrix_pointer_arg_mismatch)
16502           << ElementTy << MatrixTy->getElementType();
16503       ArgError = true;
16504     }
16505   }
16506 
16507   // Apply default Lvalue conversions and convert the stride expression to
16508   // size_t.
16509   {
16510     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16511     if (StrideConv.isInvalid())
16512       return StrideConv;
16513 
16514     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16515     if (StrideConv.isInvalid())
16516       return StrideConv;
16517     StrideExpr = StrideConv.get();
16518     TheCall->setArg(2, StrideExpr);
16519   }
16520 
16521   // Check stride argument.
16522   if (MatrixTy) {
16523     if (Optional<llvm::APSInt> Value =
16524             StrideExpr->getIntegerConstantExpr(Context)) {
16525       uint64_t Stride = Value->getZExtValue();
16526       if (Stride < MatrixTy->getNumRows()) {
16527         Diag(StrideExpr->getBeginLoc(),
16528              diag::err_builtin_matrix_stride_too_small);
16529         ArgError = true;
16530       }
16531     }
16532   }
16533 
16534   if (ArgError)
16535     return ExprError();
16536 
16537   return CallResult;
16538 }
16539 
16540 /// \brief Enforce the bounds of a TCB
16541 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16542 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16543 /// and enforce_tcb_leaf attributes.
16544 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16545                                const FunctionDecl *Callee) {
16546   const FunctionDecl *Caller = getCurFunctionDecl();
16547 
16548   // Calls to builtins are not enforced.
16549   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16550       Callee->getBuiltinID() != 0)
16551     return;
16552 
16553   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16554   // all TCBs the callee is a part of.
16555   llvm::StringSet<> CalleeTCBs;
16556   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16557            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16558   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16559            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16560 
16561   // Go through the TCBs the caller is a part of and emit warnings if Caller
16562   // is in a TCB that the Callee is not.
16563   for_each(
16564       Caller->specific_attrs<EnforceTCBAttr>(),
16565       [&](const auto *A) {
16566         StringRef CallerTCB = A->getTCBName();
16567         if (CalleeTCBs.count(CallerTCB) == 0) {
16568           this->Diag(TheCall->getExprLoc(),
16569                      diag::warn_tcb_enforcement_violation) << Callee
16570                                                            << CallerTCB;
16571         }
16572       });
16573 }
16574