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 that the argument to __builtin_function_start is a function.
199 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
200   if (checkArgCount(S, TheCall, 1))
201     return true;
202 
203   ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
204   if (Arg.isInvalid())
205     return true;
206 
207   TheCall->setArg(0, Arg.get());
208   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
209       Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
210 
211   if (!FD) {
212     S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
213         << TheCall->getSourceRange();
214     return true;
215   }
216 
217   return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
218                                               TheCall->getBeginLoc());
219 }
220 
221 /// Check the number of arguments and set the result type to
222 /// the argument type.
223 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
224   if (checkArgCount(S, TheCall, 1))
225     return true;
226 
227   TheCall->setType(TheCall->getArg(0)->getType());
228   return false;
229 }
230 
231 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
232 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
233 /// type (but not a function pointer) and that the alignment is a power-of-two.
234 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
235   if (checkArgCount(S, TheCall, 2))
236     return true;
237 
238   clang::Expr *Source = TheCall->getArg(0);
239   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
240 
241   auto IsValidIntegerType = [](QualType Ty) {
242     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
243   };
244   QualType SrcTy = Source->getType();
245   // We should also be able to use it with arrays (but not functions!).
246   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
247     SrcTy = S.Context.getDecayedType(SrcTy);
248   }
249   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
250       SrcTy->isFunctionPointerType()) {
251     // FIXME: this is not quite the right error message since we don't allow
252     // floating point types, or member pointers.
253     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
254         << SrcTy;
255     return true;
256   }
257 
258   clang::Expr *AlignOp = TheCall->getArg(1);
259   if (!IsValidIntegerType(AlignOp->getType())) {
260     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
261         << AlignOp->getType();
262     return true;
263   }
264   Expr::EvalResult AlignResult;
265   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
266   // We can't check validity of alignment if it is value dependent.
267   if (!AlignOp->isValueDependent() &&
268       AlignOp->EvaluateAsInt(AlignResult, S.Context,
269                              Expr::SE_AllowSideEffects)) {
270     llvm::APSInt AlignValue = AlignResult.Val.getInt();
271     llvm::APSInt MaxValue(
272         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
273     if (AlignValue < 1) {
274       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
275       return true;
276     }
277     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
278       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
279           << toString(MaxValue, 10);
280       return true;
281     }
282     if (!AlignValue.isPowerOf2()) {
283       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
284       return true;
285     }
286     if (AlignValue == 1) {
287       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
288           << IsBooleanAlignBuiltin;
289     }
290   }
291 
292   ExprResult SrcArg = S.PerformCopyInitialization(
293       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
294       SourceLocation(), Source);
295   if (SrcArg.isInvalid())
296     return true;
297   TheCall->setArg(0, SrcArg.get());
298   ExprResult AlignArg =
299       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
300                                       S.Context, AlignOp->getType(), false),
301                                   SourceLocation(), AlignOp);
302   if (AlignArg.isInvalid())
303     return true;
304   TheCall->setArg(1, AlignArg.get());
305   // For align_up/align_down, the return type is the same as the (potentially
306   // decayed) argument type including qualifiers. For is_aligned(), the result
307   // is always bool.
308   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
309   return false;
310 }
311 
312 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
313                                 unsigned BuiltinID) {
314   if (checkArgCount(S, TheCall, 3))
315     return true;
316 
317   // First two arguments should be integers.
318   for (unsigned I = 0; I < 2; ++I) {
319     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
320     if (Arg.isInvalid()) return true;
321     TheCall->setArg(I, Arg.get());
322 
323     QualType Ty = Arg.get()->getType();
324     if (!Ty->isIntegerType()) {
325       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
326           << Ty << Arg.get()->getSourceRange();
327       return true;
328     }
329   }
330 
331   // Third argument should be a pointer to a non-const integer.
332   // IRGen correctly handles volatile, restrict, and address spaces, and
333   // the other qualifiers aren't possible.
334   {
335     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
336     if (Arg.isInvalid()) return true;
337     TheCall->setArg(2, Arg.get());
338 
339     QualType Ty = Arg.get()->getType();
340     const auto *PtrTy = Ty->getAs<PointerType>();
341     if (!PtrTy ||
342         !PtrTy->getPointeeType()->isIntegerType() ||
343         PtrTy->getPointeeType().isConstQualified()) {
344       S.Diag(Arg.get()->getBeginLoc(),
345              diag::err_overflow_builtin_must_be_ptr_int)
346         << Ty << Arg.get()->getSourceRange();
347       return true;
348     }
349   }
350 
351   // Disallow signed bit-precise integer args larger than 128 bits to mul
352   // function until we improve backend support.
353   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
354     for (unsigned I = 0; I < 3; ++I) {
355       const auto Arg = TheCall->getArg(I);
356       // Third argument will be a pointer.
357       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
358       if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
359           S.getASTContext().getIntWidth(Ty) > 128)
360         return S.Diag(Arg->getBeginLoc(),
361                       diag::err_overflow_builtin_bit_int_max_size)
362                << 128;
363     }
364   }
365 
366   return false;
367 }
368 
369 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
370   if (checkArgCount(S, BuiltinCall, 2))
371     return true;
372 
373   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
374   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
375   Expr *Call = BuiltinCall->getArg(0);
376   Expr *Chain = BuiltinCall->getArg(1);
377 
378   if (Call->getStmtClass() != Stmt::CallExprClass) {
379     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
380         << Call->getSourceRange();
381     return true;
382   }
383 
384   auto CE = cast<CallExpr>(Call);
385   if (CE->getCallee()->getType()->isBlockPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
387         << Call->getSourceRange();
388     return true;
389   }
390 
391   const Decl *TargetDecl = CE->getCalleeDecl();
392   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
393     if (FD->getBuiltinID()) {
394       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
395           << Call->getSourceRange();
396       return true;
397     }
398 
399   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
400     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
401         << Call->getSourceRange();
402     return true;
403   }
404 
405   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
406   if (ChainResult.isInvalid())
407     return true;
408   if (!ChainResult.get()->getType()->isPointerType()) {
409     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
410         << Chain->getSourceRange();
411     return true;
412   }
413 
414   QualType ReturnTy = CE->getCallReturnType(S.Context);
415   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
416   QualType BuiltinTy = S.Context.getFunctionType(
417       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
418   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
419 
420   Builtin =
421       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
422 
423   BuiltinCall->setType(CE->getType());
424   BuiltinCall->setValueKind(CE->getValueKind());
425   BuiltinCall->setObjectKind(CE->getObjectKind());
426   BuiltinCall->setCallee(Builtin);
427   BuiltinCall->setArg(1, ChainResult.get());
428 
429   return false;
430 }
431 
432 namespace {
433 
434 class ScanfDiagnosticFormatHandler
435     : public analyze_format_string::FormatStringHandler {
436   // Accepts the argument index (relative to the first destination index) of the
437   // argument whose size we want.
438   using ComputeSizeFunction =
439       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
440 
441   // Accepts the argument index (relative to the first destination index), the
442   // destination size, and the source size).
443   using DiagnoseFunction =
444       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
445 
446   ComputeSizeFunction ComputeSizeArgument;
447   DiagnoseFunction Diagnose;
448 
449 public:
450   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
451                                DiagnoseFunction Diagnose)
452       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
453 
454   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
455                             const char *StartSpecifier,
456                             unsigned specifierLen) override {
457     if (!FS.consumesDataArgument())
458       return true;
459 
460     unsigned NulByte = 0;
461     switch ((FS.getConversionSpecifier().getKind())) {
462     default:
463       return true;
464     case analyze_format_string::ConversionSpecifier::sArg:
465     case analyze_format_string::ConversionSpecifier::ScanListArg:
466       NulByte = 1;
467       break;
468     case analyze_format_string::ConversionSpecifier::cArg:
469       break;
470     }
471 
472     analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
473     if (FW.getHowSpecified() !=
474         analyze_format_string::OptionalAmount::HowSpecified::Constant)
475       return true;
476 
477     unsigned SourceSize = FW.getConstantAmount() + NulByte;
478 
479     Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
480     if (!DestSizeAPS)
481       return true;
482 
483     unsigned DestSize = DestSizeAPS->getZExtValue();
484 
485     if (DestSize < SourceSize)
486       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
487 
488     return true;
489   }
490 };
491 
492 class EstimateSizeFormatHandler
493     : public analyze_format_string::FormatStringHandler {
494   size_t Size;
495 
496 public:
497   EstimateSizeFormatHandler(StringRef Format)
498       : Size(std::min(Format.find(0), Format.size()) +
499              1 /* null byte always written by sprintf */) {}
500 
501   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
502                              const char *, unsigned SpecifierLen) override {
503 
504     const size_t FieldWidth = computeFieldWidth(FS);
505     const size_t Precision = computePrecision(FS);
506 
507     // The actual format.
508     switch (FS.getConversionSpecifier().getKind()) {
509     // Just a char.
510     case analyze_format_string::ConversionSpecifier::cArg:
511     case analyze_format_string::ConversionSpecifier::CArg:
512       Size += std::max(FieldWidth, (size_t)1);
513       break;
514     // Just an integer.
515     case analyze_format_string::ConversionSpecifier::dArg:
516     case analyze_format_string::ConversionSpecifier::DArg:
517     case analyze_format_string::ConversionSpecifier::iArg:
518     case analyze_format_string::ConversionSpecifier::oArg:
519     case analyze_format_string::ConversionSpecifier::OArg:
520     case analyze_format_string::ConversionSpecifier::uArg:
521     case analyze_format_string::ConversionSpecifier::UArg:
522     case analyze_format_string::ConversionSpecifier::xArg:
523     case analyze_format_string::ConversionSpecifier::XArg:
524       Size += std::max(FieldWidth, Precision);
525       break;
526 
527     // %g style conversion switches between %f or %e style dynamically.
528     // %f always takes less space, so default to it.
529     case analyze_format_string::ConversionSpecifier::gArg:
530     case analyze_format_string::ConversionSpecifier::GArg:
531 
532     // Floating point number in the form '[+]ddd.ddd'.
533     case analyze_format_string::ConversionSpecifier::fArg:
534     case analyze_format_string::ConversionSpecifier::FArg:
535       Size += std::max(FieldWidth, 1 /* integer part */ +
536                                        (Precision ? 1 + Precision
537                                                   : 0) /* period + decimal */);
538       break;
539 
540     // Floating point number in the form '[-]d.ddde[+-]dd'.
541     case analyze_format_string::ConversionSpecifier::eArg:
542     case analyze_format_string::ConversionSpecifier::EArg:
543       Size +=
544           std::max(FieldWidth,
545                    1 /* integer part */ +
546                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
547                        1 /* e or E letter */ + 2 /* exponent */);
548       break;
549 
550     // Floating point number in the form '[-]0xh.hhhhp±dd'.
551     case analyze_format_string::ConversionSpecifier::aArg:
552     case analyze_format_string::ConversionSpecifier::AArg:
553       Size +=
554           std::max(FieldWidth,
555                    2 /* 0x */ + 1 /* integer part */ +
556                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
557                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
558       break;
559 
560     // Just a string.
561     case analyze_format_string::ConversionSpecifier::sArg:
562     case analyze_format_string::ConversionSpecifier::SArg:
563       Size += FieldWidth;
564       break;
565 
566     // Just a pointer in the form '0xddd'.
567     case analyze_format_string::ConversionSpecifier::pArg:
568       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
569       break;
570 
571     // A plain percent.
572     case analyze_format_string::ConversionSpecifier::PercentArg:
573       Size += 1;
574       break;
575 
576     default:
577       break;
578     }
579 
580     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
581 
582     if (FS.hasAlternativeForm()) {
583       switch (FS.getConversionSpecifier().getKind()) {
584       default:
585         break;
586       // Force a leading '0'.
587       case analyze_format_string::ConversionSpecifier::oArg:
588         Size += 1;
589         break;
590       // Force a leading '0x'.
591       case analyze_format_string::ConversionSpecifier::xArg:
592       case analyze_format_string::ConversionSpecifier::XArg:
593         Size += 2;
594         break;
595       // Force a period '.' before decimal, even if precision is 0.
596       case analyze_format_string::ConversionSpecifier::aArg:
597       case analyze_format_string::ConversionSpecifier::AArg:
598       case analyze_format_string::ConversionSpecifier::eArg:
599       case analyze_format_string::ConversionSpecifier::EArg:
600       case analyze_format_string::ConversionSpecifier::fArg:
601       case analyze_format_string::ConversionSpecifier::FArg:
602       case analyze_format_string::ConversionSpecifier::gArg:
603       case analyze_format_string::ConversionSpecifier::GArg:
604         Size += (Precision ? 0 : 1);
605         break;
606       }
607     }
608     assert(SpecifierLen <= Size && "no underflow");
609     Size -= SpecifierLen;
610     return true;
611   }
612 
613   size_t getSizeLowerBound() const { return Size; }
614 
615 private:
616   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
617     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
618     size_t FieldWidth = 0;
619     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
620       FieldWidth = FW.getConstantAmount();
621     return FieldWidth;
622   }
623 
624   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
625     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
626     size_t Precision = 0;
627 
628     // See man 3 printf for default precision value based on the specifier.
629     switch (FW.getHowSpecified()) {
630     case analyze_format_string::OptionalAmount::NotSpecified:
631       switch (FS.getConversionSpecifier().getKind()) {
632       default:
633         break;
634       case analyze_format_string::ConversionSpecifier::dArg: // %d
635       case analyze_format_string::ConversionSpecifier::DArg: // %D
636       case analyze_format_string::ConversionSpecifier::iArg: // %i
637         Precision = 1;
638         break;
639       case analyze_format_string::ConversionSpecifier::oArg: // %d
640       case analyze_format_string::ConversionSpecifier::OArg: // %D
641       case analyze_format_string::ConversionSpecifier::uArg: // %d
642       case analyze_format_string::ConversionSpecifier::UArg: // %D
643       case analyze_format_string::ConversionSpecifier::xArg: // %d
644       case analyze_format_string::ConversionSpecifier::XArg: // %D
645         Precision = 1;
646         break;
647       case analyze_format_string::ConversionSpecifier::fArg: // %f
648       case analyze_format_string::ConversionSpecifier::FArg: // %F
649       case analyze_format_string::ConversionSpecifier::eArg: // %e
650       case analyze_format_string::ConversionSpecifier::EArg: // %E
651       case analyze_format_string::ConversionSpecifier::gArg: // %g
652       case analyze_format_string::ConversionSpecifier::GArg: // %G
653         Precision = 6;
654         break;
655       case analyze_format_string::ConversionSpecifier::pArg: // %d
656         Precision = 1;
657         break;
658       }
659       break;
660     case analyze_format_string::OptionalAmount::Constant:
661       Precision = FW.getConstantAmount();
662       break;
663     default:
664       break;
665     }
666     return Precision;
667   }
668 };
669 
670 } // namespace
671 
672 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
673                                                CallExpr *TheCall) {
674   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
675       isConstantEvaluated())
676     return;
677 
678   bool UseDABAttr = false;
679   const FunctionDecl *UseDecl = FD;
680 
681   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
682   if (DABAttr) {
683     UseDecl = DABAttr->getFunction();
684     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
685     UseDABAttr = true;
686   }
687 
688   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
689 
690   if (!BuiltinID)
691     return;
692 
693   const TargetInfo &TI = getASTContext().getTargetInfo();
694   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
695 
696   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
697     // If we refer to a diagnose_as_builtin attribute, we need to change the
698     // argument index to refer to the arguments of the called function. Unless
699     // the index is out of bounds, which presumably means it's a variadic
700     // function.
701     if (!UseDABAttr)
702       return Index;
703     unsigned DABIndices = DABAttr->argIndices_size();
704     unsigned NewIndex = Index < DABIndices
705                             ? DABAttr->argIndices_begin()[Index]
706                             : Index - DABIndices + FD->getNumParams();
707     if (NewIndex >= TheCall->getNumArgs())
708       return llvm::None;
709     return NewIndex;
710   };
711 
712   auto ComputeExplicitObjectSizeArgument =
713       [&](unsigned Index) -> Optional<llvm::APSInt> {
714     Optional<unsigned> IndexOptional = TranslateIndex(Index);
715     if (!IndexOptional)
716       return llvm::None;
717     unsigned NewIndex = IndexOptional.getValue();
718     Expr::EvalResult Result;
719     Expr *SizeArg = TheCall->getArg(NewIndex);
720     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
721       return llvm::None;
722     llvm::APSInt Integer = Result.Val.getInt();
723     Integer.setIsUnsigned(true);
724     return Integer;
725   };
726 
727   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
728     // If the parameter has a pass_object_size attribute, then we should use its
729     // (potentially) more strict checking mode. Otherwise, conservatively assume
730     // type 0.
731     int BOSType = 0;
732     // This check can fail for variadic functions.
733     if (Index < FD->getNumParams()) {
734       if (const auto *POS =
735               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
736         BOSType = POS->getType();
737     }
738 
739     Optional<unsigned> IndexOptional = TranslateIndex(Index);
740     if (!IndexOptional)
741       return llvm::None;
742     unsigned NewIndex = IndexOptional.getValue();
743 
744     const Expr *ObjArg = TheCall->getArg(NewIndex);
745     uint64_t Result;
746     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
747       return llvm::None;
748 
749     // Get the object size in the target's size_t width.
750     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
751   };
752 
753   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
754     Optional<unsigned> IndexOptional = TranslateIndex(Index);
755     if (!IndexOptional)
756       return llvm::None;
757     unsigned NewIndex = IndexOptional.getValue();
758 
759     const Expr *ObjArg = TheCall->getArg(NewIndex);
760     uint64_t Result;
761     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
762       return llvm::None;
763     // Add 1 for null byte.
764     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
765   };
766 
767   Optional<llvm::APSInt> SourceSize;
768   Optional<llvm::APSInt> DestinationSize;
769   unsigned DiagID = 0;
770   bool IsChkVariant = false;
771 
772   auto GetFunctionName = [&]() {
773     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
774     // Skim off the details of whichever builtin was called to produce a better
775     // diagnostic, as it's unlikely that the user wrote the __builtin
776     // explicitly.
777     if (IsChkVariant) {
778       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780     } else if (FunctionName.startswith("__builtin_")) {
781       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782     }
783     return FunctionName;
784   };
785 
786   switch (BuiltinID) {
787   default:
788     return;
789   case Builtin::BI__builtin_strcpy:
790   case Builtin::BIstrcpy: {
791     DiagID = diag::warn_fortify_strlen_overflow;
792     SourceSize = ComputeStrLenArgument(1);
793     DestinationSize = ComputeSizeArgument(0);
794     break;
795   }
796 
797   case Builtin::BI__builtin___strcpy_chk: {
798     DiagID = diag::warn_fortify_strlen_overflow;
799     SourceSize = ComputeStrLenArgument(1);
800     DestinationSize = ComputeExplicitObjectSizeArgument(2);
801     IsChkVariant = true;
802     break;
803   }
804 
805   case Builtin::BIscanf:
806   case Builtin::BIfscanf:
807   case Builtin::BIsscanf: {
808     unsigned FormatIndex = 1;
809     unsigned DataIndex = 2;
810     if (BuiltinID == Builtin::BIscanf) {
811       FormatIndex = 0;
812       DataIndex = 1;
813     }
814 
815     const auto *FormatExpr =
816         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
817 
818     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
819     if (!Format)
820       return;
821 
822     if (!Format->isAscii() && !Format->isUTF8())
823       return;
824 
825     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
826                         unsigned SourceSize) {
827       DiagID = diag::warn_fortify_scanf_overflow;
828       unsigned Index = ArgIndex + DataIndex;
829       StringRef FunctionName = GetFunctionName();
830       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
831                           PDiag(DiagID) << FunctionName << (Index + 1)
832                                         << DestSize << SourceSize);
833     };
834 
835     StringRef FormatStrRef = Format->getString();
836     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
837       return ComputeSizeArgument(Index + DataIndex);
838     };
839     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
840     const char *FormatBytes = FormatStrRef.data();
841     const ConstantArrayType *T =
842         Context.getAsConstantArrayType(Format->getType());
843     assert(T && "String literal not of constant array type!");
844     size_t TypeSize = T->getSize().getZExtValue();
845 
846     // In case there's a null byte somewhere.
847     size_t StrLen =
848         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
849 
850     analyze_format_string::ParseScanfString(H, FormatBytes,
851                                             FormatBytes + StrLen, getLangOpts(),
852                                             Context.getTargetInfo());
853 
854     // Unlike the other cases, in this one we have already issued the diagnostic
855     // here, so no need to continue (because unlike the other cases, here the
856     // diagnostic refers to the argument number).
857     return;
858   }
859 
860   case Builtin::BIsprintf:
861   case Builtin::BI__builtin___sprintf_chk: {
862     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
863     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
864 
865     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
866 
867       if (!Format->isAscii() && !Format->isUTF8())
868         return;
869 
870       StringRef FormatStrRef = Format->getString();
871       EstimateSizeFormatHandler H(FormatStrRef);
872       const char *FormatBytes = FormatStrRef.data();
873       const ConstantArrayType *T =
874           Context.getAsConstantArrayType(Format->getType());
875       assert(T && "String literal not of constant array type!");
876       size_t TypeSize = T->getSize().getZExtValue();
877 
878       // In case there's a null byte somewhere.
879       size_t StrLen =
880           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
881       if (!analyze_format_string::ParsePrintfString(
882               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
883               Context.getTargetInfo(), false)) {
884         DiagID = diag::warn_fortify_source_format_overflow;
885         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
886                          .extOrTrunc(SizeTypeWidth);
887         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
888           DestinationSize = ComputeExplicitObjectSizeArgument(2);
889           IsChkVariant = true;
890         } else {
891           DestinationSize = ComputeSizeArgument(0);
892         }
893         break;
894       }
895     }
896     return;
897   }
898   case Builtin::BI__builtin___memcpy_chk:
899   case Builtin::BI__builtin___memmove_chk:
900   case Builtin::BI__builtin___memset_chk:
901   case Builtin::BI__builtin___strlcat_chk:
902   case Builtin::BI__builtin___strlcpy_chk:
903   case Builtin::BI__builtin___strncat_chk:
904   case Builtin::BI__builtin___strncpy_chk:
905   case Builtin::BI__builtin___stpncpy_chk:
906   case Builtin::BI__builtin___memccpy_chk:
907   case Builtin::BI__builtin___mempcpy_chk: {
908     DiagID = diag::warn_builtin_chk_overflow;
909     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
910     DestinationSize =
911         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
912     IsChkVariant = true;
913     break;
914   }
915 
916   case Builtin::BI__builtin___snprintf_chk:
917   case Builtin::BI__builtin___vsnprintf_chk: {
918     DiagID = diag::warn_builtin_chk_overflow;
919     SourceSize = ComputeExplicitObjectSizeArgument(1);
920     DestinationSize = ComputeExplicitObjectSizeArgument(3);
921     IsChkVariant = true;
922     break;
923   }
924 
925   case Builtin::BIstrncat:
926   case Builtin::BI__builtin_strncat:
927   case Builtin::BIstrncpy:
928   case Builtin::BI__builtin_strncpy:
929   case Builtin::BIstpncpy:
930   case Builtin::BI__builtin_stpncpy: {
931     // Whether these functions overflow depends on the runtime strlen of the
932     // string, not just the buffer size, so emitting the "always overflow"
933     // diagnostic isn't quite right. We should still diagnose passing a buffer
934     // size larger than the destination buffer though; this is a runtime abort
935     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
936     DiagID = diag::warn_fortify_source_size_mismatch;
937     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
938     DestinationSize = ComputeSizeArgument(0);
939     break;
940   }
941 
942   case Builtin::BImemcpy:
943   case Builtin::BI__builtin_memcpy:
944   case Builtin::BImemmove:
945   case Builtin::BI__builtin_memmove:
946   case Builtin::BImemset:
947   case Builtin::BI__builtin_memset:
948   case Builtin::BImempcpy:
949   case Builtin::BI__builtin_mempcpy: {
950     DiagID = diag::warn_fortify_source_overflow;
951     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
952     DestinationSize = ComputeSizeArgument(0);
953     break;
954   }
955   case Builtin::BIsnprintf:
956   case Builtin::BI__builtin_snprintf:
957   case Builtin::BIvsnprintf:
958   case Builtin::BI__builtin_vsnprintf: {
959     DiagID = diag::warn_fortify_source_size_mismatch;
960     SourceSize = ComputeExplicitObjectSizeArgument(1);
961     DestinationSize = ComputeSizeArgument(0);
962     break;
963   }
964   }
965 
966   if (!SourceSize || !DestinationSize ||
967       llvm::APSInt::compareValues(SourceSize.getValue(),
968                                   DestinationSize.getValue()) <= 0)
969     return;
970 
971   StringRef FunctionName = GetFunctionName();
972 
973   SmallString<16> DestinationStr;
974   SmallString<16> SourceStr;
975   DestinationSize->toString(DestinationStr, /*Radix=*/10);
976   SourceSize->toString(SourceStr, /*Radix=*/10);
977   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
978                       PDiag(DiagID)
979                           << FunctionName << DestinationStr << SourceStr);
980 }
981 
982 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
983                                      Scope::ScopeFlags NeededScopeFlags,
984                                      unsigned DiagID) {
985   // Scopes aren't available during instantiation. Fortunately, builtin
986   // functions cannot be template args so they cannot be formed through template
987   // instantiation. Therefore checking once during the parse is sufficient.
988   if (SemaRef.inTemplateInstantiation())
989     return false;
990 
991   Scope *S = SemaRef.getCurScope();
992   while (S && !S->isSEHExceptScope())
993     S = S->getParent();
994   if (!S || !(S->getFlags() & NeededScopeFlags)) {
995     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
996     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
997         << DRE->getDecl()->getIdentifier();
998     return true;
999   }
1000 
1001   return false;
1002 }
1003 
1004 static inline bool isBlockPointer(Expr *Arg) {
1005   return Arg->getType()->isBlockPointerType();
1006 }
1007 
1008 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1009 /// void*, which is a requirement of device side enqueue.
1010 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1011   const BlockPointerType *BPT =
1012       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1013   ArrayRef<QualType> Params =
1014       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1015   unsigned ArgCounter = 0;
1016   bool IllegalParams = false;
1017   // Iterate through the block parameters until either one is found that is not
1018   // a local void*, or the block is valid.
1019   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1020        I != E; ++I, ++ArgCounter) {
1021     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1022         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1023             LangAS::opencl_local) {
1024       // Get the location of the error. If a block literal has been passed
1025       // (BlockExpr) then we can point straight to the offending argument,
1026       // else we just point to the variable reference.
1027       SourceLocation ErrorLoc;
1028       if (isa<BlockExpr>(BlockArg)) {
1029         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1030         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1031       } else if (isa<DeclRefExpr>(BlockArg)) {
1032         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1033       }
1034       S.Diag(ErrorLoc,
1035              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1036       IllegalParams = true;
1037     }
1038   }
1039 
1040   return IllegalParams;
1041 }
1042 
1043 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1044   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
1045     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1046         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
1047     return true;
1048   }
1049   return false;
1050 }
1051 
1052 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1053   if (checkArgCount(S, TheCall, 2))
1054     return true;
1055 
1056   if (checkOpenCLSubgroupExt(S, TheCall))
1057     return true;
1058 
1059   // First argument is an ndrange_t type.
1060   Expr *NDRangeArg = TheCall->getArg(0);
1061   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1062     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1063         << TheCall->getDirectCallee() << "'ndrange_t'";
1064     return true;
1065   }
1066 
1067   Expr *BlockArg = TheCall->getArg(1);
1068   if (!isBlockPointer(BlockArg)) {
1069     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1070         << TheCall->getDirectCallee() << "block";
1071     return true;
1072   }
1073   return checkOpenCLBlockArgs(S, BlockArg);
1074 }
1075 
1076 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1077 /// get_kernel_work_group_size
1078 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1079 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1080   if (checkArgCount(S, TheCall, 1))
1081     return true;
1082 
1083   Expr *BlockArg = TheCall->getArg(0);
1084   if (!isBlockPointer(BlockArg)) {
1085     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1086         << TheCall->getDirectCallee() << "block";
1087     return true;
1088   }
1089   return checkOpenCLBlockArgs(S, BlockArg);
1090 }
1091 
1092 /// Diagnose integer type and any valid implicit conversion to it.
1093 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1094                                       const QualType &IntType);
1095 
1096 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1097                                             unsigned Start, unsigned End) {
1098   bool IllegalParams = false;
1099   for (unsigned I = Start; I <= End; ++I)
1100     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1101                                               S.Context.getSizeType());
1102   return IllegalParams;
1103 }
1104 
1105 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1106 /// 'local void*' parameter of passed block.
1107 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1108                                            Expr *BlockArg,
1109                                            unsigned NumNonVarArgs) {
1110   const BlockPointerType *BPT =
1111       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1112   unsigned NumBlockParams =
1113       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1114   unsigned TotalNumArgs = TheCall->getNumArgs();
1115 
1116   // For each argument passed to the block, a corresponding uint needs to
1117   // be passed to describe the size of the local memory.
1118   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1119     S.Diag(TheCall->getBeginLoc(),
1120            diag::err_opencl_enqueue_kernel_local_size_args);
1121     return true;
1122   }
1123 
1124   // Check that the sizes of the local memory are specified by integers.
1125   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1126                                          TotalNumArgs - 1);
1127 }
1128 
1129 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1130 /// overload formats specified in Table 6.13.17.1.
1131 /// int enqueue_kernel(queue_t queue,
1132 ///                    kernel_enqueue_flags_t flags,
1133 ///                    const ndrange_t ndrange,
1134 ///                    void (^block)(void))
1135 /// int enqueue_kernel(queue_t queue,
1136 ///                    kernel_enqueue_flags_t flags,
1137 ///                    const ndrange_t ndrange,
1138 ///                    uint num_events_in_wait_list,
1139 ///                    clk_event_t *event_wait_list,
1140 ///                    clk_event_t *event_ret,
1141 ///                    void (^block)(void))
1142 /// int enqueue_kernel(queue_t queue,
1143 ///                    kernel_enqueue_flags_t flags,
1144 ///                    const ndrange_t ndrange,
1145 ///                    void (^block)(local void*, ...),
1146 ///                    uint size0, ...)
1147 /// int enqueue_kernel(queue_t queue,
1148 ///                    kernel_enqueue_flags_t flags,
1149 ///                    const ndrange_t ndrange,
1150 ///                    uint num_events_in_wait_list,
1151 ///                    clk_event_t *event_wait_list,
1152 ///                    clk_event_t *event_ret,
1153 ///                    void (^block)(local void*, ...),
1154 ///                    uint size0, ...)
1155 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1156   unsigned NumArgs = TheCall->getNumArgs();
1157 
1158   if (NumArgs < 4) {
1159     S.Diag(TheCall->getBeginLoc(),
1160            diag::err_typecheck_call_too_few_args_at_least)
1161         << 0 << 4 << NumArgs;
1162     return true;
1163   }
1164 
1165   Expr *Arg0 = TheCall->getArg(0);
1166   Expr *Arg1 = TheCall->getArg(1);
1167   Expr *Arg2 = TheCall->getArg(2);
1168   Expr *Arg3 = TheCall->getArg(3);
1169 
1170   // First argument always needs to be a queue_t type.
1171   if (!Arg0->getType()->isQueueT()) {
1172     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1173            diag::err_opencl_builtin_expected_type)
1174         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1175     return true;
1176   }
1177 
1178   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1179   if (!Arg1->getType()->isIntegerType()) {
1180     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1181            diag::err_opencl_builtin_expected_type)
1182         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1183     return true;
1184   }
1185 
1186   // Third argument is always an ndrange_t type.
1187   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1188     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1189            diag::err_opencl_builtin_expected_type)
1190         << TheCall->getDirectCallee() << "'ndrange_t'";
1191     return true;
1192   }
1193 
1194   // With four arguments, there is only one form that the function could be
1195   // called in: no events and no variable arguments.
1196   if (NumArgs == 4) {
1197     // check that the last argument is the right block type.
1198     if (!isBlockPointer(Arg3)) {
1199       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1200           << TheCall->getDirectCallee() << "block";
1201       return true;
1202     }
1203     // we have a block type, check the prototype
1204     const BlockPointerType *BPT =
1205         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1206     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1207       S.Diag(Arg3->getBeginLoc(),
1208              diag::err_opencl_enqueue_kernel_blocks_no_args);
1209       return true;
1210     }
1211     return false;
1212   }
1213   // we can have block + varargs.
1214   if (isBlockPointer(Arg3))
1215     return (checkOpenCLBlockArgs(S, Arg3) ||
1216             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1217   // last two cases with either exactly 7 args or 7 args and varargs.
1218   if (NumArgs >= 7) {
1219     // check common block argument.
1220     Expr *Arg6 = TheCall->getArg(6);
1221     if (!isBlockPointer(Arg6)) {
1222       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1223           << TheCall->getDirectCallee() << "block";
1224       return true;
1225     }
1226     if (checkOpenCLBlockArgs(S, Arg6))
1227       return true;
1228 
1229     // Forth argument has to be any integer type.
1230     if (!Arg3->getType()->isIntegerType()) {
1231       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1232              diag::err_opencl_builtin_expected_type)
1233           << TheCall->getDirectCallee() << "integer";
1234       return true;
1235     }
1236     // check remaining common arguments.
1237     Expr *Arg4 = TheCall->getArg(4);
1238     Expr *Arg5 = TheCall->getArg(5);
1239 
1240     // Fifth argument is always passed as a pointer to clk_event_t.
1241     if (!Arg4->isNullPointerConstant(S.Context,
1242                                      Expr::NPC_ValueDependentIsNotNull) &&
1243         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1244       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1245              diag::err_opencl_builtin_expected_type)
1246           << TheCall->getDirectCallee()
1247           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1248       return true;
1249     }
1250 
1251     // Sixth argument is always passed as a pointer to clk_event_t.
1252     if (!Arg5->isNullPointerConstant(S.Context,
1253                                      Expr::NPC_ValueDependentIsNotNull) &&
1254         !(Arg5->getType()->isPointerType() &&
1255           Arg5->getType()->getPointeeType()->isClkEventT())) {
1256       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1257              diag::err_opencl_builtin_expected_type)
1258           << TheCall->getDirectCallee()
1259           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1260       return true;
1261     }
1262 
1263     if (NumArgs == 7)
1264       return false;
1265 
1266     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1267   }
1268 
1269   // None of the specific case has been detected, give generic error
1270   S.Diag(TheCall->getBeginLoc(),
1271          diag::err_opencl_enqueue_kernel_incorrect_args);
1272   return true;
1273 }
1274 
1275 /// Returns OpenCL access qual.
1276 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1277     return D->getAttr<OpenCLAccessAttr>();
1278 }
1279 
1280 /// Returns true if pipe element type is different from the pointer.
1281 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1282   const Expr *Arg0 = Call->getArg(0);
1283   // First argument type should always be pipe.
1284   if (!Arg0->getType()->isPipeType()) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1286         << Call->getDirectCallee() << Arg0->getSourceRange();
1287     return true;
1288   }
1289   OpenCLAccessAttr *AccessQual =
1290       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1291   // Validates the access qualifier is compatible with the call.
1292   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1293   // read_only and write_only, and assumed to be read_only if no qualifier is
1294   // specified.
1295   switch (Call->getDirectCallee()->getBuiltinID()) {
1296   case Builtin::BIread_pipe:
1297   case Builtin::BIreserve_read_pipe:
1298   case Builtin::BIcommit_read_pipe:
1299   case Builtin::BIwork_group_reserve_read_pipe:
1300   case Builtin::BIsub_group_reserve_read_pipe:
1301   case Builtin::BIwork_group_commit_read_pipe:
1302   case Builtin::BIsub_group_commit_read_pipe:
1303     if (!(!AccessQual || AccessQual->isReadOnly())) {
1304       S.Diag(Arg0->getBeginLoc(),
1305              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1306           << "read_only" << Arg0->getSourceRange();
1307       return true;
1308     }
1309     break;
1310   case Builtin::BIwrite_pipe:
1311   case Builtin::BIreserve_write_pipe:
1312   case Builtin::BIcommit_write_pipe:
1313   case Builtin::BIwork_group_reserve_write_pipe:
1314   case Builtin::BIsub_group_reserve_write_pipe:
1315   case Builtin::BIwork_group_commit_write_pipe:
1316   case Builtin::BIsub_group_commit_write_pipe:
1317     if (!(AccessQual && AccessQual->isWriteOnly())) {
1318       S.Diag(Arg0->getBeginLoc(),
1319              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1320           << "write_only" << Arg0->getSourceRange();
1321       return true;
1322     }
1323     break;
1324   default:
1325     break;
1326   }
1327   return false;
1328 }
1329 
1330 /// Returns true if pipe element type is different from the pointer.
1331 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1332   const Expr *Arg0 = Call->getArg(0);
1333   const Expr *ArgIdx = Call->getArg(Idx);
1334   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1335   const QualType EltTy = PipeTy->getElementType();
1336   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1337   // The Idx argument should be a pointer and the type of the pointer and
1338   // the type of pipe element should also be the same.
1339   if (!ArgTy ||
1340       !S.Context.hasSameType(
1341           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1342     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1343         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1344         << ArgIdx->getType() << ArgIdx->getSourceRange();
1345     return true;
1346   }
1347   return false;
1348 }
1349 
1350 // Performs semantic analysis for the read/write_pipe call.
1351 // \param S Reference to the semantic analyzer.
1352 // \param Call A pointer to the builtin call.
1353 // \return True if a semantic error has been found, false otherwise.
1354 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1355   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1356   // functions have two forms.
1357   switch (Call->getNumArgs()) {
1358   case 2:
1359     if (checkOpenCLPipeArg(S, Call))
1360       return true;
1361     // The call with 2 arguments should be
1362     // read/write_pipe(pipe T, T*).
1363     // Check packet type T.
1364     if (checkOpenCLPipePacketType(S, Call, 1))
1365       return true;
1366     break;
1367 
1368   case 4: {
1369     if (checkOpenCLPipeArg(S, Call))
1370       return true;
1371     // The call with 4 arguments should be
1372     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1373     // Check reserve_id_t.
1374     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1375       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1376           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1377           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1378       return true;
1379     }
1380 
1381     // Check the index.
1382     const Expr *Arg2 = Call->getArg(2);
1383     if (!Arg2->getType()->isIntegerType() &&
1384         !Arg2->getType()->isUnsignedIntegerType()) {
1385       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1386           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1387           << Arg2->getType() << Arg2->getSourceRange();
1388       return true;
1389     }
1390 
1391     // Check packet type T.
1392     if (checkOpenCLPipePacketType(S, Call, 3))
1393       return true;
1394   } break;
1395   default:
1396     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1397         << Call->getDirectCallee() << Call->getSourceRange();
1398     return true;
1399   }
1400 
1401   return false;
1402 }
1403 
1404 // Performs a semantic analysis on the {work_group_/sub_group_
1405 //        /_}reserve_{read/write}_pipe
1406 // \param S Reference to the semantic analyzer.
1407 // \param Call The call to the builtin function to be analyzed.
1408 // \return True if a semantic error was found, false otherwise.
1409 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1410   if (checkArgCount(S, Call, 2))
1411     return true;
1412 
1413   if (checkOpenCLPipeArg(S, Call))
1414     return true;
1415 
1416   // Check the reserve size.
1417   if (!Call->getArg(1)->getType()->isIntegerType() &&
1418       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1419     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1420         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1421         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1422     return true;
1423   }
1424 
1425   // Since return type of reserve_read/write_pipe built-in function is
1426   // reserve_id_t, which is not defined in the builtin def file , we used int
1427   // as return type and need to override the return type of these functions.
1428   Call->setType(S.Context.OCLReserveIDTy);
1429 
1430   return false;
1431 }
1432 
1433 // Performs a semantic analysis on {work_group_/sub_group_
1434 //        /_}commit_{read/write}_pipe
1435 // \param S Reference to the semantic analyzer.
1436 // \param Call The call to the builtin function to be analyzed.
1437 // \return True if a semantic error was found, false otherwise.
1438 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1439   if (checkArgCount(S, Call, 2))
1440     return true;
1441 
1442   if (checkOpenCLPipeArg(S, Call))
1443     return true;
1444 
1445   // Check reserve_id_t.
1446   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1447     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1448         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1449         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1450     return true;
1451   }
1452 
1453   return false;
1454 }
1455 
1456 // Performs a semantic analysis on the call to built-in Pipe
1457 //        Query Functions.
1458 // \param S Reference to the semantic analyzer.
1459 // \param Call The call to the builtin function to be analyzed.
1460 // \return True if a semantic error was found, false otherwise.
1461 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1462   if (checkArgCount(S, Call, 1))
1463     return true;
1464 
1465   if (!Call->getArg(0)->getType()->isPipeType()) {
1466     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1467         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1468     return true;
1469   }
1470 
1471   return false;
1472 }
1473 
1474 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1475 // Performs semantic analysis for the to_global/local/private call.
1476 // \param S Reference to the semantic analyzer.
1477 // \param BuiltinID ID of the builtin function.
1478 // \param Call A pointer to the builtin call.
1479 // \return True if a semantic error has been found, false otherwise.
1480 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1481                                     CallExpr *Call) {
1482   if (checkArgCount(S, Call, 1))
1483     return true;
1484 
1485   auto RT = Call->getArg(0)->getType();
1486   if (!RT->isPointerType() || RT->getPointeeType()
1487       .getAddressSpace() == LangAS::opencl_constant) {
1488     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1489         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1490     return true;
1491   }
1492 
1493   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1494     S.Diag(Call->getArg(0)->getBeginLoc(),
1495            diag::warn_opencl_generic_address_space_arg)
1496         << Call->getDirectCallee()->getNameInfo().getAsString()
1497         << Call->getArg(0)->getSourceRange();
1498   }
1499 
1500   RT = RT->getPointeeType();
1501   auto Qual = RT.getQualifiers();
1502   switch (BuiltinID) {
1503   case Builtin::BIto_global:
1504     Qual.setAddressSpace(LangAS::opencl_global);
1505     break;
1506   case Builtin::BIto_local:
1507     Qual.setAddressSpace(LangAS::opencl_local);
1508     break;
1509   case Builtin::BIto_private:
1510     Qual.setAddressSpace(LangAS::opencl_private);
1511     break;
1512   default:
1513     llvm_unreachable("Invalid builtin function");
1514   }
1515   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1516       RT.getUnqualifiedType(), Qual)));
1517 
1518   return false;
1519 }
1520 
1521 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1522   if (checkArgCount(S, TheCall, 1))
1523     return ExprError();
1524 
1525   // Compute __builtin_launder's parameter type from the argument.
1526   // The parameter type is:
1527   //  * The type of the argument if it's not an array or function type,
1528   //  Otherwise,
1529   //  * The decayed argument type.
1530   QualType ParamTy = [&]() {
1531     QualType ArgTy = TheCall->getArg(0)->getType();
1532     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1533       return S.Context.getPointerType(Ty->getElementType());
1534     if (ArgTy->isFunctionType()) {
1535       return S.Context.getPointerType(ArgTy);
1536     }
1537     return ArgTy;
1538   }();
1539 
1540   TheCall->setType(ParamTy);
1541 
1542   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1543     if (!ParamTy->isPointerType())
1544       return 0;
1545     if (ParamTy->isFunctionPointerType())
1546       return 1;
1547     if (ParamTy->isVoidPointerType())
1548       return 2;
1549     return llvm::Optional<unsigned>{};
1550   }();
1551   if (DiagSelect.hasValue()) {
1552     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1553         << DiagSelect.getValue() << TheCall->getSourceRange();
1554     return ExprError();
1555   }
1556 
1557   // We either have an incomplete class type, or we have a class template
1558   // whose instantiation has not been forced. Example:
1559   //
1560   //   template <class T> struct Foo { T value; };
1561   //   Foo<int> *p = nullptr;
1562   //   auto *d = __builtin_launder(p);
1563   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1564                             diag::err_incomplete_type))
1565     return ExprError();
1566 
1567   assert(ParamTy->getPointeeType()->isObjectType() &&
1568          "Unhandled non-object pointer case");
1569 
1570   InitializedEntity Entity =
1571       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1572   ExprResult Arg =
1573       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1574   if (Arg.isInvalid())
1575     return ExprError();
1576   TheCall->setArg(0, Arg.get());
1577 
1578   return TheCall;
1579 }
1580 
1581 // Emit an error and return true if the current architecture is not in the list
1582 // of supported architectures.
1583 static bool
1584 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1585                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1586   llvm::Triple::ArchType CurArch =
1587       S.getASTContext().getTargetInfo().getTriple().getArch();
1588   if (llvm::is_contained(SupportedArchs, CurArch))
1589     return false;
1590   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1591       << TheCall->getSourceRange();
1592   return true;
1593 }
1594 
1595 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1596                                  SourceLocation CallSiteLoc);
1597 
1598 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1599                                       CallExpr *TheCall) {
1600   switch (TI.getTriple().getArch()) {
1601   default:
1602     // Some builtins don't require additional checking, so just consider these
1603     // acceptable.
1604     return false;
1605   case llvm::Triple::arm:
1606   case llvm::Triple::armeb:
1607   case llvm::Triple::thumb:
1608   case llvm::Triple::thumbeb:
1609     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1610   case llvm::Triple::aarch64:
1611   case llvm::Triple::aarch64_32:
1612   case llvm::Triple::aarch64_be:
1613     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1614   case llvm::Triple::bpfeb:
1615   case llvm::Triple::bpfel:
1616     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1617   case llvm::Triple::hexagon:
1618     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1619   case llvm::Triple::mips:
1620   case llvm::Triple::mipsel:
1621   case llvm::Triple::mips64:
1622   case llvm::Triple::mips64el:
1623     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1624   case llvm::Triple::systemz:
1625     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1626   case llvm::Triple::x86:
1627   case llvm::Triple::x86_64:
1628     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1629   case llvm::Triple::ppc:
1630   case llvm::Triple::ppcle:
1631   case llvm::Triple::ppc64:
1632   case llvm::Triple::ppc64le:
1633     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1634   case llvm::Triple::amdgcn:
1635     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1636   case llvm::Triple::riscv32:
1637   case llvm::Triple::riscv64:
1638     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1639   }
1640 }
1641 
1642 ExprResult
1643 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1644                                CallExpr *TheCall) {
1645   ExprResult TheCallResult(TheCall);
1646 
1647   // Find out if any arguments are required to be integer constant expressions.
1648   unsigned ICEArguments = 0;
1649   ASTContext::GetBuiltinTypeError Error;
1650   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1651   if (Error != ASTContext::GE_None)
1652     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1653 
1654   // If any arguments are required to be ICE's, check and diagnose.
1655   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1656     // Skip arguments not required to be ICE's.
1657     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1658 
1659     llvm::APSInt Result;
1660     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1661       return true;
1662     ICEArguments &= ~(1 << ArgNo);
1663   }
1664 
1665   switch (BuiltinID) {
1666   case Builtin::BI__builtin___CFStringMakeConstantString:
1667     assert(TheCall->getNumArgs() == 1 &&
1668            "Wrong # arguments to builtin CFStringMakeConstantString");
1669     if (CheckObjCString(TheCall->getArg(0)))
1670       return ExprError();
1671     break;
1672   case Builtin::BI__builtin_ms_va_start:
1673   case Builtin::BI__builtin_stdarg_start:
1674   case Builtin::BI__builtin_va_start:
1675     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1676       return ExprError();
1677     break;
1678   case Builtin::BI__va_start: {
1679     switch (Context.getTargetInfo().getTriple().getArch()) {
1680     case llvm::Triple::aarch64:
1681     case llvm::Triple::arm:
1682     case llvm::Triple::thumb:
1683       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1684         return ExprError();
1685       break;
1686     default:
1687       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1688         return ExprError();
1689       break;
1690     }
1691     break;
1692   }
1693 
1694   // The acquire, release, and no fence variants are ARM and AArch64 only.
1695   case Builtin::BI_interlockedbittestandset_acq:
1696   case Builtin::BI_interlockedbittestandset_rel:
1697   case Builtin::BI_interlockedbittestandset_nf:
1698   case Builtin::BI_interlockedbittestandreset_acq:
1699   case Builtin::BI_interlockedbittestandreset_rel:
1700   case Builtin::BI_interlockedbittestandreset_nf:
1701     if (CheckBuiltinTargetSupport(
1702             *this, BuiltinID, TheCall,
1703             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1704       return ExprError();
1705     break;
1706 
1707   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1708   case Builtin::BI_bittest64:
1709   case Builtin::BI_bittestandcomplement64:
1710   case Builtin::BI_bittestandreset64:
1711   case Builtin::BI_bittestandset64:
1712   case Builtin::BI_interlockedbittestandreset64:
1713   case Builtin::BI_interlockedbittestandset64:
1714     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1715                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1716                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1717       return ExprError();
1718     break;
1719 
1720   case Builtin::BI__builtin_isgreater:
1721   case Builtin::BI__builtin_isgreaterequal:
1722   case Builtin::BI__builtin_isless:
1723   case Builtin::BI__builtin_islessequal:
1724   case Builtin::BI__builtin_islessgreater:
1725   case Builtin::BI__builtin_isunordered:
1726     if (SemaBuiltinUnorderedCompare(TheCall))
1727       return ExprError();
1728     break;
1729   case Builtin::BI__builtin_fpclassify:
1730     if (SemaBuiltinFPClassification(TheCall, 6))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_isfinite:
1734   case Builtin::BI__builtin_isinf:
1735   case Builtin::BI__builtin_isinf_sign:
1736   case Builtin::BI__builtin_isnan:
1737   case Builtin::BI__builtin_isnormal:
1738   case Builtin::BI__builtin_signbit:
1739   case Builtin::BI__builtin_signbitf:
1740   case Builtin::BI__builtin_signbitl:
1741     if (SemaBuiltinFPClassification(TheCall, 1))
1742       return ExprError();
1743     break;
1744   case Builtin::BI__builtin_shufflevector:
1745     return SemaBuiltinShuffleVector(TheCall);
1746     // TheCall will be freed by the smart pointer here, but that's fine, since
1747     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1748   case Builtin::BI__builtin_prefetch:
1749     if (SemaBuiltinPrefetch(TheCall))
1750       return ExprError();
1751     break;
1752   case Builtin::BI__builtin_alloca_with_align:
1753     if (SemaBuiltinAllocaWithAlign(TheCall))
1754       return ExprError();
1755     LLVM_FALLTHROUGH;
1756   case Builtin::BI__builtin_alloca:
1757     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1758         << TheCall->getDirectCallee();
1759     break;
1760   case Builtin::BI__arithmetic_fence:
1761     if (SemaBuiltinArithmeticFence(TheCall))
1762       return ExprError();
1763     break;
1764   case Builtin::BI__assume:
1765   case Builtin::BI__builtin_assume:
1766     if (SemaBuiltinAssume(TheCall))
1767       return ExprError();
1768     break;
1769   case Builtin::BI__builtin_assume_aligned:
1770     if (SemaBuiltinAssumeAligned(TheCall))
1771       return ExprError();
1772     break;
1773   case Builtin::BI__builtin_dynamic_object_size:
1774   case Builtin::BI__builtin_object_size:
1775     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1776       return ExprError();
1777     break;
1778   case Builtin::BI__builtin_longjmp:
1779     if (SemaBuiltinLongjmp(TheCall))
1780       return ExprError();
1781     break;
1782   case Builtin::BI__builtin_setjmp:
1783     if (SemaBuiltinSetjmp(TheCall))
1784       return ExprError();
1785     break;
1786   case Builtin::BI__builtin_classify_type:
1787     if (checkArgCount(*this, TheCall, 1)) return true;
1788     TheCall->setType(Context.IntTy);
1789     break;
1790   case Builtin::BI__builtin_complex:
1791     if (SemaBuiltinComplex(TheCall))
1792       return ExprError();
1793     break;
1794   case Builtin::BI__builtin_constant_p: {
1795     if (checkArgCount(*this, TheCall, 1)) return true;
1796     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1797     if (Arg.isInvalid()) return true;
1798     TheCall->setArg(0, Arg.get());
1799     TheCall->setType(Context.IntTy);
1800     break;
1801   }
1802   case Builtin::BI__builtin_launder:
1803     return SemaBuiltinLaunder(*this, TheCall);
1804   case Builtin::BI__sync_fetch_and_add:
1805   case Builtin::BI__sync_fetch_and_add_1:
1806   case Builtin::BI__sync_fetch_and_add_2:
1807   case Builtin::BI__sync_fetch_and_add_4:
1808   case Builtin::BI__sync_fetch_and_add_8:
1809   case Builtin::BI__sync_fetch_and_add_16:
1810   case Builtin::BI__sync_fetch_and_sub:
1811   case Builtin::BI__sync_fetch_and_sub_1:
1812   case Builtin::BI__sync_fetch_and_sub_2:
1813   case Builtin::BI__sync_fetch_and_sub_4:
1814   case Builtin::BI__sync_fetch_and_sub_8:
1815   case Builtin::BI__sync_fetch_and_sub_16:
1816   case Builtin::BI__sync_fetch_and_or:
1817   case Builtin::BI__sync_fetch_and_or_1:
1818   case Builtin::BI__sync_fetch_and_or_2:
1819   case Builtin::BI__sync_fetch_and_or_4:
1820   case Builtin::BI__sync_fetch_and_or_8:
1821   case Builtin::BI__sync_fetch_and_or_16:
1822   case Builtin::BI__sync_fetch_and_and:
1823   case Builtin::BI__sync_fetch_and_and_1:
1824   case Builtin::BI__sync_fetch_and_and_2:
1825   case Builtin::BI__sync_fetch_and_and_4:
1826   case Builtin::BI__sync_fetch_and_and_8:
1827   case Builtin::BI__sync_fetch_and_and_16:
1828   case Builtin::BI__sync_fetch_and_xor:
1829   case Builtin::BI__sync_fetch_and_xor_1:
1830   case Builtin::BI__sync_fetch_and_xor_2:
1831   case Builtin::BI__sync_fetch_and_xor_4:
1832   case Builtin::BI__sync_fetch_and_xor_8:
1833   case Builtin::BI__sync_fetch_and_xor_16:
1834   case Builtin::BI__sync_fetch_and_nand:
1835   case Builtin::BI__sync_fetch_and_nand_1:
1836   case Builtin::BI__sync_fetch_and_nand_2:
1837   case Builtin::BI__sync_fetch_and_nand_4:
1838   case Builtin::BI__sync_fetch_and_nand_8:
1839   case Builtin::BI__sync_fetch_and_nand_16:
1840   case Builtin::BI__sync_add_and_fetch:
1841   case Builtin::BI__sync_add_and_fetch_1:
1842   case Builtin::BI__sync_add_and_fetch_2:
1843   case Builtin::BI__sync_add_and_fetch_4:
1844   case Builtin::BI__sync_add_and_fetch_8:
1845   case Builtin::BI__sync_add_and_fetch_16:
1846   case Builtin::BI__sync_sub_and_fetch:
1847   case Builtin::BI__sync_sub_and_fetch_1:
1848   case Builtin::BI__sync_sub_and_fetch_2:
1849   case Builtin::BI__sync_sub_and_fetch_4:
1850   case Builtin::BI__sync_sub_and_fetch_8:
1851   case Builtin::BI__sync_sub_and_fetch_16:
1852   case Builtin::BI__sync_and_and_fetch:
1853   case Builtin::BI__sync_and_and_fetch_1:
1854   case Builtin::BI__sync_and_and_fetch_2:
1855   case Builtin::BI__sync_and_and_fetch_4:
1856   case Builtin::BI__sync_and_and_fetch_8:
1857   case Builtin::BI__sync_and_and_fetch_16:
1858   case Builtin::BI__sync_or_and_fetch:
1859   case Builtin::BI__sync_or_and_fetch_1:
1860   case Builtin::BI__sync_or_and_fetch_2:
1861   case Builtin::BI__sync_or_and_fetch_4:
1862   case Builtin::BI__sync_or_and_fetch_8:
1863   case Builtin::BI__sync_or_and_fetch_16:
1864   case Builtin::BI__sync_xor_and_fetch:
1865   case Builtin::BI__sync_xor_and_fetch_1:
1866   case Builtin::BI__sync_xor_and_fetch_2:
1867   case Builtin::BI__sync_xor_and_fetch_4:
1868   case Builtin::BI__sync_xor_and_fetch_8:
1869   case Builtin::BI__sync_xor_and_fetch_16:
1870   case Builtin::BI__sync_nand_and_fetch:
1871   case Builtin::BI__sync_nand_and_fetch_1:
1872   case Builtin::BI__sync_nand_and_fetch_2:
1873   case Builtin::BI__sync_nand_and_fetch_4:
1874   case Builtin::BI__sync_nand_and_fetch_8:
1875   case Builtin::BI__sync_nand_and_fetch_16:
1876   case Builtin::BI__sync_val_compare_and_swap:
1877   case Builtin::BI__sync_val_compare_and_swap_1:
1878   case Builtin::BI__sync_val_compare_and_swap_2:
1879   case Builtin::BI__sync_val_compare_and_swap_4:
1880   case Builtin::BI__sync_val_compare_and_swap_8:
1881   case Builtin::BI__sync_val_compare_and_swap_16:
1882   case Builtin::BI__sync_bool_compare_and_swap:
1883   case Builtin::BI__sync_bool_compare_and_swap_1:
1884   case Builtin::BI__sync_bool_compare_and_swap_2:
1885   case Builtin::BI__sync_bool_compare_and_swap_4:
1886   case Builtin::BI__sync_bool_compare_and_swap_8:
1887   case Builtin::BI__sync_bool_compare_and_swap_16:
1888   case Builtin::BI__sync_lock_test_and_set:
1889   case Builtin::BI__sync_lock_test_and_set_1:
1890   case Builtin::BI__sync_lock_test_and_set_2:
1891   case Builtin::BI__sync_lock_test_and_set_4:
1892   case Builtin::BI__sync_lock_test_and_set_8:
1893   case Builtin::BI__sync_lock_test_and_set_16:
1894   case Builtin::BI__sync_lock_release:
1895   case Builtin::BI__sync_lock_release_1:
1896   case Builtin::BI__sync_lock_release_2:
1897   case Builtin::BI__sync_lock_release_4:
1898   case Builtin::BI__sync_lock_release_8:
1899   case Builtin::BI__sync_lock_release_16:
1900   case Builtin::BI__sync_swap:
1901   case Builtin::BI__sync_swap_1:
1902   case Builtin::BI__sync_swap_2:
1903   case Builtin::BI__sync_swap_4:
1904   case Builtin::BI__sync_swap_8:
1905   case Builtin::BI__sync_swap_16:
1906     return SemaBuiltinAtomicOverloaded(TheCallResult);
1907   case Builtin::BI__sync_synchronize:
1908     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1909         << TheCall->getCallee()->getSourceRange();
1910     break;
1911   case Builtin::BI__builtin_nontemporal_load:
1912   case Builtin::BI__builtin_nontemporal_store:
1913     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1914   case Builtin::BI__builtin_memcpy_inline: {
1915     clang::Expr *SizeOp = TheCall->getArg(2);
1916     // We warn about copying to or from `nullptr` pointers when `size` is
1917     // greater than 0. When `size` is value dependent we cannot evaluate its
1918     // value so we bail out.
1919     if (SizeOp->isValueDependent())
1920       break;
1921     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1922       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1923       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1924     }
1925     break;
1926   }
1927 #define BUILTIN(ID, TYPE, ATTRS)
1928 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1929   case Builtin::BI##ID: \
1930     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1931 #include "clang/Basic/Builtins.def"
1932   case Builtin::BI__annotation:
1933     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1934       return ExprError();
1935     break;
1936   case Builtin::BI__builtin_annotation:
1937     if (SemaBuiltinAnnotation(*this, TheCall))
1938       return ExprError();
1939     break;
1940   case Builtin::BI__builtin_addressof:
1941     if (SemaBuiltinAddressof(*this, TheCall))
1942       return ExprError();
1943     break;
1944   case Builtin::BI__builtin_function_start:
1945     if (SemaBuiltinFunctionStart(*this, TheCall))
1946       return ExprError();
1947     break;
1948   case Builtin::BI__builtin_is_aligned:
1949   case Builtin::BI__builtin_align_up:
1950   case Builtin::BI__builtin_align_down:
1951     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1952       return ExprError();
1953     break;
1954   case Builtin::BI__builtin_add_overflow:
1955   case Builtin::BI__builtin_sub_overflow:
1956   case Builtin::BI__builtin_mul_overflow:
1957     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1958       return ExprError();
1959     break;
1960   case Builtin::BI__builtin_operator_new:
1961   case Builtin::BI__builtin_operator_delete: {
1962     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1963     ExprResult Res =
1964         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1965     if (Res.isInvalid())
1966       CorrectDelayedTyposInExpr(TheCallResult.get());
1967     return Res;
1968   }
1969   case Builtin::BI__builtin_dump_struct: {
1970     // We first want to ensure we are called with 2 arguments
1971     if (checkArgCount(*this, TheCall, 2))
1972       return ExprError();
1973     // Ensure that the first argument is of type 'struct XX *'
1974     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1975     const QualType PtrArgType = PtrArg->getType();
1976     if (!PtrArgType->isPointerType() ||
1977         !PtrArgType->getPointeeType()->isRecordType()) {
1978       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1979           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1980           << "structure pointer";
1981       return ExprError();
1982     }
1983 
1984     // Ensure that the second argument is of type 'FunctionType'
1985     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1986     const QualType FnPtrArgType = FnPtrArg->getType();
1987     if (!FnPtrArgType->isPointerType()) {
1988       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1989           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1990           << FnPtrArgType << "'int (*)(const char *, ...)'";
1991       return ExprError();
1992     }
1993 
1994     const auto *FuncType =
1995         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1996 
1997     if (!FuncType) {
1998       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1999           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2000           << FnPtrArgType << "'int (*)(const char *, ...)'";
2001       return ExprError();
2002     }
2003 
2004     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2005       if (!FT->getNumParams()) {
2006         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2007             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2008             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2009         return ExprError();
2010       }
2011       QualType PT = FT->getParamType(0);
2012       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2013           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2014           !PT->getPointeeType().isConstQualified()) {
2015         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2016             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2017             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2018         return ExprError();
2019       }
2020     }
2021 
2022     TheCall->setType(Context.IntTy);
2023     break;
2024   }
2025   case Builtin::BI__builtin_expect_with_probability: {
2026     // We first want to ensure we are called with 3 arguments
2027     if (checkArgCount(*this, TheCall, 3))
2028       return ExprError();
2029     // then check probability is constant float in range [0.0, 1.0]
2030     const Expr *ProbArg = TheCall->getArg(2);
2031     SmallVector<PartialDiagnosticAt, 8> Notes;
2032     Expr::EvalResult Eval;
2033     Eval.Diag = &Notes;
2034     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2035         !Eval.Val.isFloat()) {
2036       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2037           << ProbArg->getSourceRange();
2038       for (const PartialDiagnosticAt &PDiag : Notes)
2039         Diag(PDiag.first, PDiag.second);
2040       return ExprError();
2041     }
2042     llvm::APFloat Probability = Eval.Val.getFloat();
2043     bool LoseInfo = false;
2044     Probability.convert(llvm::APFloat::IEEEdouble(),
2045                         llvm::RoundingMode::Dynamic, &LoseInfo);
2046     if (!(Probability >= llvm::APFloat(0.0) &&
2047           Probability <= llvm::APFloat(1.0))) {
2048       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2049           << ProbArg->getSourceRange();
2050       return ExprError();
2051     }
2052     break;
2053   }
2054   case Builtin::BI__builtin_preserve_access_index:
2055     if (SemaBuiltinPreserveAI(*this, TheCall))
2056       return ExprError();
2057     break;
2058   case Builtin::BI__builtin_call_with_static_chain:
2059     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2060       return ExprError();
2061     break;
2062   case Builtin::BI__exception_code:
2063   case Builtin::BI_exception_code:
2064     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2065                                  diag::err_seh___except_block))
2066       return ExprError();
2067     break;
2068   case Builtin::BI__exception_info:
2069   case Builtin::BI_exception_info:
2070     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2071                                  diag::err_seh___except_filter))
2072       return ExprError();
2073     break;
2074   case Builtin::BI__GetExceptionInfo:
2075     if (checkArgCount(*this, TheCall, 1))
2076       return ExprError();
2077 
2078     if (CheckCXXThrowOperand(
2079             TheCall->getBeginLoc(),
2080             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2081             TheCall))
2082       return ExprError();
2083 
2084     TheCall->setType(Context.VoidPtrTy);
2085     break;
2086   // OpenCL v2.0, s6.13.16 - Pipe functions
2087   case Builtin::BIread_pipe:
2088   case Builtin::BIwrite_pipe:
2089     // Since those two functions are declared with var args, we need a semantic
2090     // check for the argument.
2091     if (SemaBuiltinRWPipe(*this, TheCall))
2092       return ExprError();
2093     break;
2094   case Builtin::BIreserve_read_pipe:
2095   case Builtin::BIreserve_write_pipe:
2096   case Builtin::BIwork_group_reserve_read_pipe:
2097   case Builtin::BIwork_group_reserve_write_pipe:
2098     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2099       return ExprError();
2100     break;
2101   case Builtin::BIsub_group_reserve_read_pipe:
2102   case Builtin::BIsub_group_reserve_write_pipe:
2103     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2104         SemaBuiltinReserveRWPipe(*this, TheCall))
2105       return ExprError();
2106     break;
2107   case Builtin::BIcommit_read_pipe:
2108   case Builtin::BIcommit_write_pipe:
2109   case Builtin::BIwork_group_commit_read_pipe:
2110   case Builtin::BIwork_group_commit_write_pipe:
2111     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2112       return ExprError();
2113     break;
2114   case Builtin::BIsub_group_commit_read_pipe:
2115   case Builtin::BIsub_group_commit_write_pipe:
2116     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2117         SemaBuiltinCommitRWPipe(*this, TheCall))
2118       return ExprError();
2119     break;
2120   case Builtin::BIget_pipe_num_packets:
2121   case Builtin::BIget_pipe_max_packets:
2122     if (SemaBuiltinPipePackets(*this, TheCall))
2123       return ExprError();
2124     break;
2125   case Builtin::BIto_global:
2126   case Builtin::BIto_local:
2127   case Builtin::BIto_private:
2128     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2129       return ExprError();
2130     break;
2131   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2132   case Builtin::BIenqueue_kernel:
2133     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2134       return ExprError();
2135     break;
2136   case Builtin::BIget_kernel_work_group_size:
2137   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2138     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2139       return ExprError();
2140     break;
2141   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2142   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2143     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2144       return ExprError();
2145     break;
2146   case Builtin::BI__builtin_os_log_format:
2147     Cleanup.setExprNeedsCleanups(true);
2148     LLVM_FALLTHROUGH;
2149   case Builtin::BI__builtin_os_log_format_buffer_size:
2150     if (SemaBuiltinOSLogFormat(TheCall))
2151       return ExprError();
2152     break;
2153   case Builtin::BI__builtin_frame_address:
2154   case Builtin::BI__builtin_return_address: {
2155     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2156       return ExprError();
2157 
2158     // -Wframe-address warning if non-zero passed to builtin
2159     // return/frame address.
2160     Expr::EvalResult Result;
2161     if (!TheCall->getArg(0)->isValueDependent() &&
2162         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2163         Result.Val.getInt() != 0)
2164       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2165           << ((BuiltinID == Builtin::BI__builtin_return_address)
2166                   ? "__builtin_return_address"
2167                   : "__builtin_frame_address")
2168           << TheCall->getSourceRange();
2169     break;
2170   }
2171 
2172   // __builtin_elementwise_abs restricts the element type to signed integers or
2173   // floating point types only.
2174   case Builtin::BI__builtin_elementwise_abs: {
2175     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2176       return ExprError();
2177 
2178     QualType ArgTy = TheCall->getArg(0)->getType();
2179     QualType EltTy = ArgTy;
2180 
2181     if (auto *VecTy = EltTy->getAs<VectorType>())
2182       EltTy = VecTy->getElementType();
2183     if (EltTy->isUnsignedIntegerType()) {
2184       Diag(TheCall->getArg(0)->getBeginLoc(),
2185            diag::err_builtin_invalid_arg_type)
2186           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2187       return ExprError();
2188     }
2189     break;
2190   }
2191 
2192   // __builtin_elementwise_ceil restricts the element type to floating point
2193   // types only.
2194   case Builtin::BI__builtin_elementwise_ceil: {
2195     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2196       return ExprError();
2197 
2198     QualType ArgTy = TheCall->getArg(0)->getType();
2199     QualType EltTy = ArgTy;
2200 
2201     if (auto *VecTy = EltTy->getAs<VectorType>())
2202       EltTy = VecTy->getElementType();
2203     if (!EltTy->isFloatingType()) {
2204       Diag(TheCall->getArg(0)->getBeginLoc(),
2205            diag::err_builtin_invalid_arg_type)
2206           << 1 << /* float ty*/ 5 << ArgTy;
2207 
2208       return ExprError();
2209     }
2210     break;
2211   }
2212 
2213   case Builtin::BI__builtin_elementwise_min:
2214   case Builtin::BI__builtin_elementwise_max:
2215     if (SemaBuiltinElementwiseMath(TheCall))
2216       return ExprError();
2217     break;
2218   case Builtin::BI__builtin_reduce_max:
2219   case Builtin::BI__builtin_reduce_min: {
2220     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2221       return ExprError();
2222 
2223     const Expr *Arg = TheCall->getArg(0);
2224     const auto *TyA = Arg->getType()->getAs<VectorType>();
2225     if (!TyA) {
2226       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2227           << 1 << /* vector ty*/ 4 << Arg->getType();
2228       return ExprError();
2229     }
2230 
2231     TheCall->setType(TyA->getElementType());
2232     break;
2233   }
2234 
2235   // __builtin_reduce_xor supports vector of integers only.
2236   case Builtin::BI__builtin_reduce_xor: {
2237     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2238       return ExprError();
2239 
2240     const Expr *Arg = TheCall->getArg(0);
2241     const auto *TyA = Arg->getType()->getAs<VectorType>();
2242     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2243       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2244           << 1  << /* vector of integers */ 6 << Arg->getType();
2245       return ExprError();
2246     }
2247     TheCall->setType(TyA->getElementType());
2248     break;
2249   }
2250 
2251   case Builtin::BI__builtin_matrix_transpose:
2252     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2253 
2254   case Builtin::BI__builtin_matrix_column_major_load:
2255     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2256 
2257   case Builtin::BI__builtin_matrix_column_major_store:
2258     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2259 
2260   case Builtin::BI__builtin_get_device_side_mangled_name: {
2261     auto Check = [](CallExpr *TheCall) {
2262       if (TheCall->getNumArgs() != 1)
2263         return false;
2264       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2265       if (!DRE)
2266         return false;
2267       auto *D = DRE->getDecl();
2268       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2269         return false;
2270       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2271              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2272     };
2273     if (!Check(TheCall)) {
2274       Diag(TheCall->getBeginLoc(),
2275            diag::err_hip_invalid_args_builtin_mangled_name);
2276       return ExprError();
2277     }
2278   }
2279   }
2280 
2281   // Since the target specific builtins for each arch overlap, only check those
2282   // of the arch we are compiling for.
2283   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2284     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2285       assert(Context.getAuxTargetInfo() &&
2286              "Aux Target Builtin, but not an aux target?");
2287 
2288       if (CheckTSBuiltinFunctionCall(
2289               *Context.getAuxTargetInfo(),
2290               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2291         return ExprError();
2292     } else {
2293       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2294                                      TheCall))
2295         return ExprError();
2296     }
2297   }
2298 
2299   return TheCallResult;
2300 }
2301 
2302 // Get the valid immediate range for the specified NEON type code.
2303 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2304   NeonTypeFlags Type(t);
2305   int IsQuad = ForceQuad ? true : Type.isQuad();
2306   switch (Type.getEltType()) {
2307   case NeonTypeFlags::Int8:
2308   case NeonTypeFlags::Poly8:
2309     return shift ? 7 : (8 << IsQuad) - 1;
2310   case NeonTypeFlags::Int16:
2311   case NeonTypeFlags::Poly16:
2312     return shift ? 15 : (4 << IsQuad) - 1;
2313   case NeonTypeFlags::Int32:
2314     return shift ? 31 : (2 << IsQuad) - 1;
2315   case NeonTypeFlags::Int64:
2316   case NeonTypeFlags::Poly64:
2317     return shift ? 63 : (1 << IsQuad) - 1;
2318   case NeonTypeFlags::Poly128:
2319     return shift ? 127 : (1 << IsQuad) - 1;
2320   case NeonTypeFlags::Float16:
2321     assert(!shift && "cannot shift float types!");
2322     return (4 << IsQuad) - 1;
2323   case NeonTypeFlags::Float32:
2324     assert(!shift && "cannot shift float types!");
2325     return (2 << IsQuad) - 1;
2326   case NeonTypeFlags::Float64:
2327     assert(!shift && "cannot shift float types!");
2328     return (1 << IsQuad) - 1;
2329   case NeonTypeFlags::BFloat16:
2330     assert(!shift && "cannot shift float types!");
2331     return (4 << IsQuad) - 1;
2332   }
2333   llvm_unreachable("Invalid NeonTypeFlag!");
2334 }
2335 
2336 /// getNeonEltType - Return the QualType corresponding to the elements of
2337 /// the vector type specified by the NeonTypeFlags.  This is used to check
2338 /// the pointer arguments for Neon load/store intrinsics.
2339 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2340                                bool IsPolyUnsigned, bool IsInt64Long) {
2341   switch (Flags.getEltType()) {
2342   case NeonTypeFlags::Int8:
2343     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2344   case NeonTypeFlags::Int16:
2345     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2346   case NeonTypeFlags::Int32:
2347     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2348   case NeonTypeFlags::Int64:
2349     if (IsInt64Long)
2350       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2351     else
2352       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2353                                 : Context.LongLongTy;
2354   case NeonTypeFlags::Poly8:
2355     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2356   case NeonTypeFlags::Poly16:
2357     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2358   case NeonTypeFlags::Poly64:
2359     if (IsInt64Long)
2360       return Context.UnsignedLongTy;
2361     else
2362       return Context.UnsignedLongLongTy;
2363   case NeonTypeFlags::Poly128:
2364     break;
2365   case NeonTypeFlags::Float16:
2366     return Context.HalfTy;
2367   case NeonTypeFlags::Float32:
2368     return Context.FloatTy;
2369   case NeonTypeFlags::Float64:
2370     return Context.DoubleTy;
2371   case NeonTypeFlags::BFloat16:
2372     return Context.BFloat16Ty;
2373   }
2374   llvm_unreachable("Invalid NeonTypeFlag!");
2375 }
2376 
2377 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2378   // Range check SVE intrinsics that take immediate values.
2379   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2380 
2381   switch (BuiltinID) {
2382   default:
2383     return false;
2384 #define GET_SVE_IMMEDIATE_CHECK
2385 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2386 #undef GET_SVE_IMMEDIATE_CHECK
2387   }
2388 
2389   // Perform all the immediate checks for this builtin call.
2390   bool HasError = false;
2391   for (auto &I : ImmChecks) {
2392     int ArgNum, CheckTy, ElementSizeInBits;
2393     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2394 
2395     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2396 
2397     // Function that checks whether the operand (ArgNum) is an immediate
2398     // that is one of the predefined values.
2399     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2400                                    int ErrDiag) -> bool {
2401       // We can't check the value of a dependent argument.
2402       Expr *Arg = TheCall->getArg(ArgNum);
2403       if (Arg->isTypeDependent() || Arg->isValueDependent())
2404         return false;
2405 
2406       // Check constant-ness first.
2407       llvm::APSInt Imm;
2408       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2409         return true;
2410 
2411       if (!CheckImm(Imm.getSExtValue()))
2412         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2413       return false;
2414     };
2415 
2416     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2417     case SVETypeFlags::ImmCheck0_31:
2418       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2419         HasError = true;
2420       break;
2421     case SVETypeFlags::ImmCheck0_13:
2422       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2423         HasError = true;
2424       break;
2425     case SVETypeFlags::ImmCheck1_16:
2426       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2427         HasError = true;
2428       break;
2429     case SVETypeFlags::ImmCheck0_7:
2430       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2431         HasError = true;
2432       break;
2433     case SVETypeFlags::ImmCheckExtract:
2434       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2435                                       (2048 / ElementSizeInBits) - 1))
2436         HasError = true;
2437       break;
2438     case SVETypeFlags::ImmCheckShiftRight:
2439       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2440         HasError = true;
2441       break;
2442     case SVETypeFlags::ImmCheckShiftRightNarrow:
2443       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2444                                       ElementSizeInBits / 2))
2445         HasError = true;
2446       break;
2447     case SVETypeFlags::ImmCheckShiftLeft:
2448       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2449                                       ElementSizeInBits - 1))
2450         HasError = true;
2451       break;
2452     case SVETypeFlags::ImmCheckLaneIndex:
2453       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2454                                       (128 / (1 * ElementSizeInBits)) - 1))
2455         HasError = true;
2456       break;
2457     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2458       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2459                                       (128 / (2 * ElementSizeInBits)) - 1))
2460         HasError = true;
2461       break;
2462     case SVETypeFlags::ImmCheckLaneIndexDot:
2463       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2464                                       (128 / (4 * ElementSizeInBits)) - 1))
2465         HasError = true;
2466       break;
2467     case SVETypeFlags::ImmCheckComplexRot90_270:
2468       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2469                               diag::err_rotation_argument_to_cadd))
2470         HasError = true;
2471       break;
2472     case SVETypeFlags::ImmCheckComplexRotAll90:
2473       if (CheckImmediateInSet(
2474               [](int64_t V) {
2475                 return V == 0 || V == 90 || V == 180 || V == 270;
2476               },
2477               diag::err_rotation_argument_to_cmla))
2478         HasError = true;
2479       break;
2480     case SVETypeFlags::ImmCheck0_1:
2481       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2482         HasError = true;
2483       break;
2484     case SVETypeFlags::ImmCheck0_2:
2485       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2486         HasError = true;
2487       break;
2488     case SVETypeFlags::ImmCheck0_3:
2489       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2490         HasError = true;
2491       break;
2492     }
2493   }
2494 
2495   return HasError;
2496 }
2497 
2498 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2499                                         unsigned BuiltinID, CallExpr *TheCall) {
2500   llvm::APSInt Result;
2501   uint64_t mask = 0;
2502   unsigned TV = 0;
2503   int PtrArgNum = -1;
2504   bool HasConstPtr = false;
2505   switch (BuiltinID) {
2506 #define GET_NEON_OVERLOAD_CHECK
2507 #include "clang/Basic/arm_neon.inc"
2508 #include "clang/Basic/arm_fp16.inc"
2509 #undef GET_NEON_OVERLOAD_CHECK
2510   }
2511 
2512   // For NEON intrinsics which are overloaded on vector element type, validate
2513   // the immediate which specifies which variant to emit.
2514   unsigned ImmArg = TheCall->getNumArgs()-1;
2515   if (mask) {
2516     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2517       return true;
2518 
2519     TV = Result.getLimitedValue(64);
2520     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2521       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2522              << TheCall->getArg(ImmArg)->getSourceRange();
2523   }
2524 
2525   if (PtrArgNum >= 0) {
2526     // Check that pointer arguments have the specified type.
2527     Expr *Arg = TheCall->getArg(PtrArgNum);
2528     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2529       Arg = ICE->getSubExpr();
2530     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2531     QualType RHSTy = RHS.get()->getType();
2532 
2533     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2534     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2535                           Arch == llvm::Triple::aarch64_32 ||
2536                           Arch == llvm::Triple::aarch64_be;
2537     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2538     QualType EltTy =
2539         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2540     if (HasConstPtr)
2541       EltTy = EltTy.withConst();
2542     QualType LHSTy = Context.getPointerType(EltTy);
2543     AssignConvertType ConvTy;
2544     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2545     if (RHS.isInvalid())
2546       return true;
2547     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2548                                  RHS.get(), AA_Assigning))
2549       return true;
2550   }
2551 
2552   // For NEON intrinsics which take an immediate value as part of the
2553   // instruction, range check them here.
2554   unsigned i = 0, l = 0, u = 0;
2555   switch (BuiltinID) {
2556   default:
2557     return false;
2558   #define GET_NEON_IMMEDIATE_CHECK
2559   #include "clang/Basic/arm_neon.inc"
2560   #include "clang/Basic/arm_fp16.inc"
2561   #undef GET_NEON_IMMEDIATE_CHECK
2562   }
2563 
2564   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2565 }
2566 
2567 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2568   switch (BuiltinID) {
2569   default:
2570     return false;
2571   #include "clang/Basic/arm_mve_builtin_sema.inc"
2572   }
2573 }
2574 
2575 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2576                                        CallExpr *TheCall) {
2577   bool Err = false;
2578   switch (BuiltinID) {
2579   default:
2580     return false;
2581 #include "clang/Basic/arm_cde_builtin_sema.inc"
2582   }
2583 
2584   if (Err)
2585     return true;
2586 
2587   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2588 }
2589 
2590 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2591                                         const Expr *CoprocArg, bool WantCDE) {
2592   if (isConstantEvaluated())
2593     return false;
2594 
2595   // We can't check the value of a dependent argument.
2596   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2597     return false;
2598 
2599   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2600   int64_t CoprocNo = CoprocNoAP.getExtValue();
2601   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2602 
2603   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2604   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2605 
2606   if (IsCDECoproc != WantCDE)
2607     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2608            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2609 
2610   return false;
2611 }
2612 
2613 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2614                                         unsigned MaxWidth) {
2615   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2616           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2617           BuiltinID == ARM::BI__builtin_arm_strex ||
2618           BuiltinID == ARM::BI__builtin_arm_stlex ||
2619           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2620           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2621           BuiltinID == AArch64::BI__builtin_arm_strex ||
2622           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2623          "unexpected ARM builtin");
2624   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2625                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2626                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2627                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2628 
2629   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2630 
2631   // Ensure that we have the proper number of arguments.
2632   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2633     return true;
2634 
2635   // Inspect the pointer argument of the atomic builtin.  This should always be
2636   // a pointer type, whose element is an integral scalar or pointer type.
2637   // Because it is a pointer type, we don't have to worry about any implicit
2638   // casts here.
2639   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2640   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2641   if (PointerArgRes.isInvalid())
2642     return true;
2643   PointerArg = PointerArgRes.get();
2644 
2645   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2646   if (!pointerType) {
2647     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2648         << PointerArg->getType() << PointerArg->getSourceRange();
2649     return true;
2650   }
2651 
2652   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2653   // task is to insert the appropriate casts into the AST. First work out just
2654   // what the appropriate type is.
2655   QualType ValType = pointerType->getPointeeType();
2656   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2657   if (IsLdrex)
2658     AddrType.addConst();
2659 
2660   // Issue a warning if the cast is dodgy.
2661   CastKind CastNeeded = CK_NoOp;
2662   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2663     CastNeeded = CK_BitCast;
2664     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2665         << PointerArg->getType() << Context.getPointerType(AddrType)
2666         << AA_Passing << PointerArg->getSourceRange();
2667   }
2668 
2669   // Finally, do the cast and replace the argument with the corrected version.
2670   AddrType = Context.getPointerType(AddrType);
2671   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2672   if (PointerArgRes.isInvalid())
2673     return true;
2674   PointerArg = PointerArgRes.get();
2675 
2676   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2677 
2678   // In general, we allow ints, floats and pointers to be loaded and stored.
2679   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2680       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2681     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2682         << PointerArg->getType() << PointerArg->getSourceRange();
2683     return true;
2684   }
2685 
2686   // But ARM doesn't have instructions to deal with 128-bit versions.
2687   if (Context.getTypeSize(ValType) > MaxWidth) {
2688     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2689     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2690         << PointerArg->getType() << PointerArg->getSourceRange();
2691     return true;
2692   }
2693 
2694   switch (ValType.getObjCLifetime()) {
2695   case Qualifiers::OCL_None:
2696   case Qualifiers::OCL_ExplicitNone:
2697     // okay
2698     break;
2699 
2700   case Qualifiers::OCL_Weak:
2701   case Qualifiers::OCL_Strong:
2702   case Qualifiers::OCL_Autoreleasing:
2703     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2704         << ValType << PointerArg->getSourceRange();
2705     return true;
2706   }
2707 
2708   if (IsLdrex) {
2709     TheCall->setType(ValType);
2710     return false;
2711   }
2712 
2713   // Initialize the argument to be stored.
2714   ExprResult ValArg = TheCall->getArg(0);
2715   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2716       Context, ValType, /*consume*/ false);
2717   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2718   if (ValArg.isInvalid())
2719     return true;
2720   TheCall->setArg(0, ValArg.get());
2721 
2722   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2723   // but the custom checker bypasses all default analysis.
2724   TheCall->setType(Context.IntTy);
2725   return false;
2726 }
2727 
2728 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2729                                        CallExpr *TheCall) {
2730   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2731       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2732       BuiltinID == ARM::BI__builtin_arm_strex ||
2733       BuiltinID == ARM::BI__builtin_arm_stlex) {
2734     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2735   }
2736 
2737   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2738     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2739       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2740   }
2741 
2742   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2743       BuiltinID == ARM::BI__builtin_arm_wsr64)
2744     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2745 
2746   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2747       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2748       BuiltinID == ARM::BI__builtin_arm_wsr ||
2749       BuiltinID == ARM::BI__builtin_arm_wsrp)
2750     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2751 
2752   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2753     return true;
2754   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2755     return true;
2756   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2757     return true;
2758 
2759   // For intrinsics which take an immediate value as part of the instruction,
2760   // range check them here.
2761   // FIXME: VFP Intrinsics should error if VFP not present.
2762   switch (BuiltinID) {
2763   default: return false;
2764   case ARM::BI__builtin_arm_ssat:
2765     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2766   case ARM::BI__builtin_arm_usat:
2767     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2768   case ARM::BI__builtin_arm_ssat16:
2769     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2770   case ARM::BI__builtin_arm_usat16:
2771     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2772   case ARM::BI__builtin_arm_vcvtr_f:
2773   case ARM::BI__builtin_arm_vcvtr_d:
2774     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2775   case ARM::BI__builtin_arm_dmb:
2776   case ARM::BI__builtin_arm_dsb:
2777   case ARM::BI__builtin_arm_isb:
2778   case ARM::BI__builtin_arm_dbg:
2779     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2780   case ARM::BI__builtin_arm_cdp:
2781   case ARM::BI__builtin_arm_cdp2:
2782   case ARM::BI__builtin_arm_mcr:
2783   case ARM::BI__builtin_arm_mcr2:
2784   case ARM::BI__builtin_arm_mrc:
2785   case ARM::BI__builtin_arm_mrc2:
2786   case ARM::BI__builtin_arm_mcrr:
2787   case ARM::BI__builtin_arm_mcrr2:
2788   case ARM::BI__builtin_arm_mrrc:
2789   case ARM::BI__builtin_arm_mrrc2:
2790   case ARM::BI__builtin_arm_ldc:
2791   case ARM::BI__builtin_arm_ldcl:
2792   case ARM::BI__builtin_arm_ldc2:
2793   case ARM::BI__builtin_arm_ldc2l:
2794   case ARM::BI__builtin_arm_stc:
2795   case ARM::BI__builtin_arm_stcl:
2796   case ARM::BI__builtin_arm_stc2:
2797   case ARM::BI__builtin_arm_stc2l:
2798     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2799            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2800                                         /*WantCDE*/ false);
2801   }
2802 }
2803 
2804 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2805                                            unsigned BuiltinID,
2806                                            CallExpr *TheCall) {
2807   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2808       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2809       BuiltinID == AArch64::BI__builtin_arm_strex ||
2810       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2811     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2812   }
2813 
2814   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2815     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2816       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2817       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2818       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2819   }
2820 
2821   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2822       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2823     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2824 
2825   // Memory Tagging Extensions (MTE) Intrinsics
2826   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2827       BuiltinID == AArch64::BI__builtin_arm_addg ||
2828       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2829       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2830       BuiltinID == AArch64::BI__builtin_arm_stg ||
2831       BuiltinID == AArch64::BI__builtin_arm_subp) {
2832     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2833   }
2834 
2835   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2836       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2837       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2838       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2839     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2840 
2841   // Only check the valid encoding range. Any constant in this range would be
2842   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2843   // an exception for incorrect registers. This matches MSVC behavior.
2844   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2845       BuiltinID == AArch64::BI_WriteStatusReg)
2846     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2847 
2848   if (BuiltinID == AArch64::BI__getReg)
2849     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2850 
2851   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2852     return true;
2853 
2854   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2855     return true;
2856 
2857   // For intrinsics which take an immediate value as part of the instruction,
2858   // range check them here.
2859   unsigned i = 0, l = 0, u = 0;
2860   switch (BuiltinID) {
2861   default: return false;
2862   case AArch64::BI__builtin_arm_dmb:
2863   case AArch64::BI__builtin_arm_dsb:
2864   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2865   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2866   }
2867 
2868   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2869 }
2870 
2871 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2872   if (Arg->getType()->getAsPlaceholderType())
2873     return false;
2874 
2875   // The first argument needs to be a record field access.
2876   // If it is an array element access, we delay decision
2877   // to BPF backend to check whether the access is a
2878   // field access or not.
2879   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2880           isa<MemberExpr>(Arg->IgnoreParens()) ||
2881           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2882 }
2883 
2884 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2885                             QualType VectorTy, QualType EltTy) {
2886   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2887   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2888     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2889         << Call->getSourceRange() << VectorEltTy << EltTy;
2890     return false;
2891   }
2892   return true;
2893 }
2894 
2895 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2896   QualType ArgType = Arg->getType();
2897   if (ArgType->getAsPlaceholderType())
2898     return false;
2899 
2900   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2901   // format:
2902   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2903   //   2. <type> var;
2904   //      __builtin_preserve_type_info(var, flag);
2905   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2906       !isa<UnaryOperator>(Arg->IgnoreParens()))
2907     return false;
2908 
2909   // Typedef type.
2910   if (ArgType->getAs<TypedefType>())
2911     return true;
2912 
2913   // Record type or Enum type.
2914   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2915   if (const auto *RT = Ty->getAs<RecordType>()) {
2916     if (!RT->getDecl()->getDeclName().isEmpty())
2917       return true;
2918   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2919     if (!ET->getDecl()->getDeclName().isEmpty())
2920       return true;
2921   }
2922 
2923   return false;
2924 }
2925 
2926 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2927   QualType ArgType = Arg->getType();
2928   if (ArgType->getAsPlaceholderType())
2929     return false;
2930 
2931   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2932   // format:
2933   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2934   //                                 flag);
2935   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2936   if (!UO)
2937     return false;
2938 
2939   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2940   if (!CE)
2941     return false;
2942   if (CE->getCastKind() != CK_IntegralToPointer &&
2943       CE->getCastKind() != CK_NullToPointer)
2944     return false;
2945 
2946   // The integer must be from an EnumConstantDecl.
2947   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2948   if (!DR)
2949     return false;
2950 
2951   const EnumConstantDecl *Enumerator =
2952       dyn_cast<EnumConstantDecl>(DR->getDecl());
2953   if (!Enumerator)
2954     return false;
2955 
2956   // The type must be EnumType.
2957   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2958   const auto *ET = Ty->getAs<EnumType>();
2959   if (!ET)
2960     return false;
2961 
2962   // The enum value must be supported.
2963   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2964 }
2965 
2966 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2967                                        CallExpr *TheCall) {
2968   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2969           BuiltinID == BPF::BI__builtin_btf_type_id ||
2970           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2971           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2972          "unexpected BPF builtin");
2973 
2974   if (checkArgCount(*this, TheCall, 2))
2975     return true;
2976 
2977   // The second argument needs to be a constant int
2978   Expr *Arg = TheCall->getArg(1);
2979   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2980   diag::kind kind;
2981   if (!Value) {
2982     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2983       kind = diag::err_preserve_field_info_not_const;
2984     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2985       kind = diag::err_btf_type_id_not_const;
2986     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2987       kind = diag::err_preserve_type_info_not_const;
2988     else
2989       kind = diag::err_preserve_enum_value_not_const;
2990     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2991     return true;
2992   }
2993 
2994   // The first argument
2995   Arg = TheCall->getArg(0);
2996   bool InvalidArg = false;
2997   bool ReturnUnsignedInt = true;
2998   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2999     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3000       InvalidArg = true;
3001       kind = diag::err_preserve_field_info_not_field;
3002     }
3003   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3004     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3005       InvalidArg = true;
3006       kind = diag::err_preserve_type_info_invalid;
3007     }
3008   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3009     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3010       InvalidArg = true;
3011       kind = diag::err_preserve_enum_value_invalid;
3012     }
3013     ReturnUnsignedInt = false;
3014   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3015     ReturnUnsignedInt = false;
3016   }
3017 
3018   if (InvalidArg) {
3019     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3020     return true;
3021   }
3022 
3023   if (ReturnUnsignedInt)
3024     TheCall->setType(Context.UnsignedIntTy);
3025   else
3026     TheCall->setType(Context.UnsignedLongTy);
3027   return false;
3028 }
3029 
3030 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3031   struct ArgInfo {
3032     uint8_t OpNum;
3033     bool IsSigned;
3034     uint8_t BitWidth;
3035     uint8_t Align;
3036   };
3037   struct BuiltinInfo {
3038     unsigned BuiltinID;
3039     ArgInfo Infos[2];
3040   };
3041 
3042   static BuiltinInfo Infos[] = {
3043     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3044     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3045     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3046     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3047     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3048     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3049     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3050     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3051     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3052     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3053     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3054 
3055     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3056     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3057     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3058     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3059     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3060     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3061     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3062     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3063     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3064     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3065     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3066 
3067     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3068     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3069     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3070     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3071     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3072     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3073     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3074     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3075     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3076     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3077     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3078     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3079     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3080     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3081     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3082     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3083     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3084     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3085     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3086     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3087     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3088     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3089     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3090     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3091     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3092     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3093     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3094     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3095     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3096     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3097     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3098     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3099     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3100     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3101     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3102     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3103     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3104     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3105     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3106     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3107     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3108     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3109     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3110     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3111     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3112     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3113     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3114     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3115     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3116     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3117     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3118     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3119                                                       {{ 1, false, 6,  0 }} },
3120     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3121     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3122     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3123     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3124     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3125     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3126     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3127                                                       {{ 1, false, 5,  0 }} },
3128     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3129     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3130     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3132     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3133     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3134                                                        { 2, false, 5,  0 }} },
3135     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3136                                                        { 2, false, 6,  0 }} },
3137     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3138                                                        { 3, false, 5,  0 }} },
3139     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3140                                                        { 3, false, 6,  0 }} },
3141     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3143     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3145     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3147     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3149     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3155     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3157                                                       {{ 2, false, 4,  0 },
3158                                                        { 3, false, 5,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3160                                                       {{ 2, false, 4,  0 },
3161                                                        { 3, false, 5,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3163                                                       {{ 2, false, 4,  0 },
3164                                                        { 3, false, 5,  0 }} },
3165     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3166                                                       {{ 2, false, 4,  0 },
3167                                                        { 3, false, 5,  0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3170     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3171     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3177     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3179                                                        { 2, false, 5,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3181                                                        { 2, false, 6,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3185     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3186     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3188     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3191                                                       {{ 1, false, 4,  0 }} },
3192     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3194                                                       {{ 1, false, 4,  0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3196     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3197     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3198     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3201     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3209     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3210     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3212     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3215                                                       {{ 3, false, 1,  0 }} },
3216     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3218     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3219     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3220                                                       {{ 3, false, 1,  0 }} },
3221     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3222     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3224     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3225                                                       {{ 3, false, 1,  0 }} },
3226   };
3227 
3228   // Use a dynamically initialized static to sort the table exactly once on
3229   // first run.
3230   static const bool SortOnce =
3231       (llvm::sort(Infos,
3232                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3233                    return LHS.BuiltinID < RHS.BuiltinID;
3234                  }),
3235        true);
3236   (void)SortOnce;
3237 
3238   const BuiltinInfo *F = llvm::partition_point(
3239       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3240   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3241     return false;
3242 
3243   bool Error = false;
3244 
3245   for (const ArgInfo &A : F->Infos) {
3246     // Ignore empty ArgInfo elements.
3247     if (A.BitWidth == 0)
3248       continue;
3249 
3250     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3251     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3252     if (!A.Align) {
3253       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3254     } else {
3255       unsigned M = 1 << A.Align;
3256       Min *= M;
3257       Max *= M;
3258       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3259       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3260     }
3261   }
3262   return Error;
3263 }
3264 
3265 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3266                                            CallExpr *TheCall) {
3267   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3268 }
3269 
3270 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3271                                         unsigned BuiltinID, CallExpr *TheCall) {
3272   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3273          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3274 }
3275 
3276 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3277                                CallExpr *TheCall) {
3278 
3279   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3280       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3281     if (!TI.hasFeature("dsp"))
3282       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3283   }
3284 
3285   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3286       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3287     if (!TI.hasFeature("dspr2"))
3288       return Diag(TheCall->getBeginLoc(),
3289                   diag::err_mips_builtin_requires_dspr2);
3290   }
3291 
3292   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3293       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3294     if (!TI.hasFeature("msa"))
3295       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3296   }
3297 
3298   return false;
3299 }
3300 
3301 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3302 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3303 // ordering for DSP is unspecified. MSA is ordered by the data format used
3304 // by the underlying instruction i.e., df/m, df/n and then by size.
3305 //
3306 // FIXME: The size tests here should instead be tablegen'd along with the
3307 //        definitions from include/clang/Basic/BuiltinsMips.def.
3308 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3309 //        be too.
3310 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3311   unsigned i = 0, l = 0, u = 0, m = 0;
3312   switch (BuiltinID) {
3313   default: return false;
3314   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3315   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3316   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3317   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3318   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3319   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3320   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3321   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3322   // df/m field.
3323   // These intrinsics take an unsigned 3 bit immediate.
3324   case Mips::BI__builtin_msa_bclri_b:
3325   case Mips::BI__builtin_msa_bnegi_b:
3326   case Mips::BI__builtin_msa_bseti_b:
3327   case Mips::BI__builtin_msa_sat_s_b:
3328   case Mips::BI__builtin_msa_sat_u_b:
3329   case Mips::BI__builtin_msa_slli_b:
3330   case Mips::BI__builtin_msa_srai_b:
3331   case Mips::BI__builtin_msa_srari_b:
3332   case Mips::BI__builtin_msa_srli_b:
3333   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3334   case Mips::BI__builtin_msa_binsli_b:
3335   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3336   // These intrinsics take an unsigned 4 bit immediate.
3337   case Mips::BI__builtin_msa_bclri_h:
3338   case Mips::BI__builtin_msa_bnegi_h:
3339   case Mips::BI__builtin_msa_bseti_h:
3340   case Mips::BI__builtin_msa_sat_s_h:
3341   case Mips::BI__builtin_msa_sat_u_h:
3342   case Mips::BI__builtin_msa_slli_h:
3343   case Mips::BI__builtin_msa_srai_h:
3344   case Mips::BI__builtin_msa_srari_h:
3345   case Mips::BI__builtin_msa_srli_h:
3346   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3347   case Mips::BI__builtin_msa_binsli_h:
3348   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3349   // These intrinsics take an unsigned 5 bit immediate.
3350   // The first block of intrinsics actually have an unsigned 5 bit field,
3351   // not a df/n field.
3352   case Mips::BI__builtin_msa_cfcmsa:
3353   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3354   case Mips::BI__builtin_msa_clei_u_b:
3355   case Mips::BI__builtin_msa_clei_u_h:
3356   case Mips::BI__builtin_msa_clei_u_w:
3357   case Mips::BI__builtin_msa_clei_u_d:
3358   case Mips::BI__builtin_msa_clti_u_b:
3359   case Mips::BI__builtin_msa_clti_u_h:
3360   case Mips::BI__builtin_msa_clti_u_w:
3361   case Mips::BI__builtin_msa_clti_u_d:
3362   case Mips::BI__builtin_msa_maxi_u_b:
3363   case Mips::BI__builtin_msa_maxi_u_h:
3364   case Mips::BI__builtin_msa_maxi_u_w:
3365   case Mips::BI__builtin_msa_maxi_u_d:
3366   case Mips::BI__builtin_msa_mini_u_b:
3367   case Mips::BI__builtin_msa_mini_u_h:
3368   case Mips::BI__builtin_msa_mini_u_w:
3369   case Mips::BI__builtin_msa_mini_u_d:
3370   case Mips::BI__builtin_msa_addvi_b:
3371   case Mips::BI__builtin_msa_addvi_h:
3372   case Mips::BI__builtin_msa_addvi_w:
3373   case Mips::BI__builtin_msa_addvi_d:
3374   case Mips::BI__builtin_msa_bclri_w:
3375   case Mips::BI__builtin_msa_bnegi_w:
3376   case Mips::BI__builtin_msa_bseti_w:
3377   case Mips::BI__builtin_msa_sat_s_w:
3378   case Mips::BI__builtin_msa_sat_u_w:
3379   case Mips::BI__builtin_msa_slli_w:
3380   case Mips::BI__builtin_msa_srai_w:
3381   case Mips::BI__builtin_msa_srari_w:
3382   case Mips::BI__builtin_msa_srli_w:
3383   case Mips::BI__builtin_msa_srlri_w:
3384   case Mips::BI__builtin_msa_subvi_b:
3385   case Mips::BI__builtin_msa_subvi_h:
3386   case Mips::BI__builtin_msa_subvi_w:
3387   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3388   case Mips::BI__builtin_msa_binsli_w:
3389   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3390   // These intrinsics take an unsigned 6 bit immediate.
3391   case Mips::BI__builtin_msa_bclri_d:
3392   case Mips::BI__builtin_msa_bnegi_d:
3393   case Mips::BI__builtin_msa_bseti_d:
3394   case Mips::BI__builtin_msa_sat_s_d:
3395   case Mips::BI__builtin_msa_sat_u_d:
3396   case Mips::BI__builtin_msa_slli_d:
3397   case Mips::BI__builtin_msa_srai_d:
3398   case Mips::BI__builtin_msa_srari_d:
3399   case Mips::BI__builtin_msa_srli_d:
3400   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3401   case Mips::BI__builtin_msa_binsli_d:
3402   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3403   // These intrinsics take a signed 5 bit immediate.
3404   case Mips::BI__builtin_msa_ceqi_b:
3405   case Mips::BI__builtin_msa_ceqi_h:
3406   case Mips::BI__builtin_msa_ceqi_w:
3407   case Mips::BI__builtin_msa_ceqi_d:
3408   case Mips::BI__builtin_msa_clti_s_b:
3409   case Mips::BI__builtin_msa_clti_s_h:
3410   case Mips::BI__builtin_msa_clti_s_w:
3411   case Mips::BI__builtin_msa_clti_s_d:
3412   case Mips::BI__builtin_msa_clei_s_b:
3413   case Mips::BI__builtin_msa_clei_s_h:
3414   case Mips::BI__builtin_msa_clei_s_w:
3415   case Mips::BI__builtin_msa_clei_s_d:
3416   case Mips::BI__builtin_msa_maxi_s_b:
3417   case Mips::BI__builtin_msa_maxi_s_h:
3418   case Mips::BI__builtin_msa_maxi_s_w:
3419   case Mips::BI__builtin_msa_maxi_s_d:
3420   case Mips::BI__builtin_msa_mini_s_b:
3421   case Mips::BI__builtin_msa_mini_s_h:
3422   case Mips::BI__builtin_msa_mini_s_w:
3423   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3424   // These intrinsics take an unsigned 8 bit immediate.
3425   case Mips::BI__builtin_msa_andi_b:
3426   case Mips::BI__builtin_msa_nori_b:
3427   case Mips::BI__builtin_msa_ori_b:
3428   case Mips::BI__builtin_msa_shf_b:
3429   case Mips::BI__builtin_msa_shf_h:
3430   case Mips::BI__builtin_msa_shf_w:
3431   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3432   case Mips::BI__builtin_msa_bseli_b:
3433   case Mips::BI__builtin_msa_bmnzi_b:
3434   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3435   // df/n format
3436   // These intrinsics take an unsigned 4 bit immediate.
3437   case Mips::BI__builtin_msa_copy_s_b:
3438   case Mips::BI__builtin_msa_copy_u_b:
3439   case Mips::BI__builtin_msa_insve_b:
3440   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3441   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3442   // These intrinsics take an unsigned 3 bit immediate.
3443   case Mips::BI__builtin_msa_copy_s_h:
3444   case Mips::BI__builtin_msa_copy_u_h:
3445   case Mips::BI__builtin_msa_insve_h:
3446   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3447   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3448   // These intrinsics take an unsigned 2 bit immediate.
3449   case Mips::BI__builtin_msa_copy_s_w:
3450   case Mips::BI__builtin_msa_copy_u_w:
3451   case Mips::BI__builtin_msa_insve_w:
3452   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3453   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3454   // These intrinsics take an unsigned 1 bit immediate.
3455   case Mips::BI__builtin_msa_copy_s_d:
3456   case Mips::BI__builtin_msa_copy_u_d:
3457   case Mips::BI__builtin_msa_insve_d:
3458   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3459   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3460   // Memory offsets and immediate loads.
3461   // These intrinsics take a signed 10 bit immediate.
3462   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3463   case Mips::BI__builtin_msa_ldi_h:
3464   case Mips::BI__builtin_msa_ldi_w:
3465   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3466   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3467   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3468   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3469   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3470   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3471   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3472   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3473   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3474   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3475   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3476   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3477   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3478   }
3479 
3480   if (!m)
3481     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3482 
3483   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3484          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3485 }
3486 
3487 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3488 /// advancing the pointer over the consumed characters. The decoded type is
3489 /// returned. If the decoded type represents a constant integer with a
3490 /// constraint on its value then Mask is set to that value. The type descriptors
3491 /// used in Str are specific to PPC MMA builtins and are documented in the file
3492 /// defining the PPC builtins.
3493 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3494                                         unsigned &Mask) {
3495   bool RequireICE = false;
3496   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3497   switch (*Str++) {
3498   case 'V':
3499     return Context.getVectorType(Context.UnsignedCharTy, 16,
3500                                  VectorType::VectorKind::AltiVecVector);
3501   case 'i': {
3502     char *End;
3503     unsigned size = strtoul(Str, &End, 10);
3504     assert(End != Str && "Missing constant parameter constraint");
3505     Str = End;
3506     Mask = size;
3507     return Context.IntTy;
3508   }
3509   case 'W': {
3510     char *End;
3511     unsigned size = strtoul(Str, &End, 10);
3512     assert(End != Str && "Missing PowerPC MMA type size");
3513     Str = End;
3514     QualType Type;
3515     switch (size) {
3516   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3517     case size: Type = Context.Id##Ty; break;
3518   #include "clang/Basic/PPCTypes.def"
3519     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3520     }
3521     bool CheckVectorArgs = false;
3522     while (!CheckVectorArgs) {
3523       switch (*Str++) {
3524       case '*':
3525         Type = Context.getPointerType(Type);
3526         break;
3527       case 'C':
3528         Type = Type.withConst();
3529         break;
3530       default:
3531         CheckVectorArgs = true;
3532         --Str;
3533         break;
3534       }
3535     }
3536     return Type;
3537   }
3538   default:
3539     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3540   }
3541 }
3542 
3543 static bool isPPC_64Builtin(unsigned BuiltinID) {
3544   // These builtins only work on PPC 64bit targets.
3545   switch (BuiltinID) {
3546   case PPC::BI__builtin_divde:
3547   case PPC::BI__builtin_divdeu:
3548   case PPC::BI__builtin_bpermd:
3549   case PPC::BI__builtin_ppc_ldarx:
3550   case PPC::BI__builtin_ppc_stdcx:
3551   case PPC::BI__builtin_ppc_tdw:
3552   case PPC::BI__builtin_ppc_trapd:
3553   case PPC::BI__builtin_ppc_cmpeqb:
3554   case PPC::BI__builtin_ppc_setb:
3555   case PPC::BI__builtin_ppc_mulhd:
3556   case PPC::BI__builtin_ppc_mulhdu:
3557   case PPC::BI__builtin_ppc_maddhd:
3558   case PPC::BI__builtin_ppc_maddhdu:
3559   case PPC::BI__builtin_ppc_maddld:
3560   case PPC::BI__builtin_ppc_load8r:
3561   case PPC::BI__builtin_ppc_store8r:
3562   case PPC::BI__builtin_ppc_insert_exp:
3563   case PPC::BI__builtin_ppc_extract_sig:
3564   case PPC::BI__builtin_ppc_addex:
3565   case PPC::BI__builtin_darn:
3566   case PPC::BI__builtin_darn_raw:
3567   case PPC::BI__builtin_ppc_compare_and_swaplp:
3568   case PPC::BI__builtin_ppc_fetch_and_addlp:
3569   case PPC::BI__builtin_ppc_fetch_and_andlp:
3570   case PPC::BI__builtin_ppc_fetch_and_orlp:
3571   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3572     return true;
3573   }
3574   return false;
3575 }
3576 
3577 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3578                              StringRef FeatureToCheck, unsigned DiagID,
3579                              StringRef DiagArg = "") {
3580   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3581     return false;
3582 
3583   if (DiagArg.empty())
3584     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3585   else
3586     S.Diag(TheCall->getBeginLoc(), DiagID)
3587         << DiagArg << TheCall->getSourceRange();
3588 
3589   return true;
3590 }
3591 
3592 /// Returns true if the argument consists of one contiguous run of 1s with any
3593 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3594 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3595 /// since all 1s are not contiguous.
3596 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3597   llvm::APSInt Result;
3598   // We can't check the value of a dependent argument.
3599   Expr *Arg = TheCall->getArg(ArgNum);
3600   if (Arg->isTypeDependent() || Arg->isValueDependent())
3601     return false;
3602 
3603   // Check constant-ness first.
3604   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3605     return true;
3606 
3607   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3608   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3609     return false;
3610 
3611   return Diag(TheCall->getBeginLoc(),
3612               diag::err_argument_not_contiguous_bit_field)
3613          << ArgNum << Arg->getSourceRange();
3614 }
3615 
3616 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3617                                        CallExpr *TheCall) {
3618   unsigned i = 0, l = 0, u = 0;
3619   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3620   llvm::APSInt Result;
3621 
3622   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3623     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3624            << TheCall->getSourceRange();
3625 
3626   switch (BuiltinID) {
3627   default: return false;
3628   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3629   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3630     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3631            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3632   case PPC::BI__builtin_altivec_dss:
3633     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3634   case PPC::BI__builtin_tbegin:
3635   case PPC::BI__builtin_tend:
3636     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3637            SemaFeatureCheck(*this, TheCall, "htm",
3638                             diag::err_ppc_builtin_requires_htm);
3639   case PPC::BI__builtin_tsr:
3640     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3641            SemaFeatureCheck(*this, TheCall, "htm",
3642                             diag::err_ppc_builtin_requires_htm);
3643   case PPC::BI__builtin_tabortwc:
3644   case PPC::BI__builtin_tabortdc:
3645     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3646            SemaFeatureCheck(*this, TheCall, "htm",
3647                             diag::err_ppc_builtin_requires_htm);
3648   case PPC::BI__builtin_tabortwci:
3649   case PPC::BI__builtin_tabortdci:
3650     return SemaFeatureCheck(*this, TheCall, "htm",
3651                             diag::err_ppc_builtin_requires_htm) ||
3652            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3653             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3654   case PPC::BI__builtin_tabort:
3655   case PPC::BI__builtin_tcheck:
3656   case PPC::BI__builtin_treclaim:
3657   case PPC::BI__builtin_trechkpt:
3658   case PPC::BI__builtin_tendall:
3659   case PPC::BI__builtin_tresume:
3660   case PPC::BI__builtin_tsuspend:
3661   case PPC::BI__builtin_get_texasr:
3662   case PPC::BI__builtin_get_texasru:
3663   case PPC::BI__builtin_get_tfhar:
3664   case PPC::BI__builtin_get_tfiar:
3665   case PPC::BI__builtin_set_texasr:
3666   case PPC::BI__builtin_set_texasru:
3667   case PPC::BI__builtin_set_tfhar:
3668   case PPC::BI__builtin_set_tfiar:
3669   case PPC::BI__builtin_ttest:
3670     return SemaFeatureCheck(*this, TheCall, "htm",
3671                             diag::err_ppc_builtin_requires_htm);
3672   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3673   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3674   // extended double representation.
3675   case PPC::BI__builtin_unpack_longdouble:
3676     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3677       return true;
3678     LLVM_FALLTHROUGH;
3679   case PPC::BI__builtin_pack_longdouble:
3680     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3681       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3682              << "ibmlongdouble";
3683     return false;
3684   case PPC::BI__builtin_altivec_dst:
3685   case PPC::BI__builtin_altivec_dstt:
3686   case PPC::BI__builtin_altivec_dstst:
3687   case PPC::BI__builtin_altivec_dststt:
3688     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3689   case PPC::BI__builtin_vsx_xxpermdi:
3690   case PPC::BI__builtin_vsx_xxsldwi:
3691     return SemaBuiltinVSX(TheCall);
3692   case PPC::BI__builtin_divwe:
3693   case PPC::BI__builtin_divweu:
3694   case PPC::BI__builtin_divde:
3695   case PPC::BI__builtin_divdeu:
3696     return SemaFeatureCheck(*this, TheCall, "extdiv",
3697                             diag::err_ppc_builtin_only_on_arch, "7");
3698   case PPC::BI__builtin_bpermd:
3699     return SemaFeatureCheck(*this, TheCall, "bpermd",
3700                             diag::err_ppc_builtin_only_on_arch, "7");
3701   case PPC::BI__builtin_unpack_vector_int128:
3702     return SemaFeatureCheck(*this, TheCall, "vsx",
3703                             diag::err_ppc_builtin_only_on_arch, "7") ||
3704            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3705   case PPC::BI__builtin_pack_vector_int128:
3706     return SemaFeatureCheck(*this, TheCall, "vsx",
3707                             diag::err_ppc_builtin_only_on_arch, "7");
3708   case PPC::BI__builtin_altivec_vgnb:
3709      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3710   case PPC::BI__builtin_altivec_vec_replace_elt:
3711   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3712     QualType VecTy = TheCall->getArg(0)->getType();
3713     QualType EltTy = TheCall->getArg(1)->getType();
3714     unsigned Width = Context.getIntWidth(EltTy);
3715     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3716            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3717   }
3718   case PPC::BI__builtin_vsx_xxeval:
3719      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3720   case PPC::BI__builtin_altivec_vsldbi:
3721      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3722   case PPC::BI__builtin_altivec_vsrdbi:
3723      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3724   case PPC::BI__builtin_vsx_xxpermx:
3725      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3726   case PPC::BI__builtin_ppc_tw:
3727   case PPC::BI__builtin_ppc_tdw:
3728     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3729   case PPC::BI__builtin_ppc_cmpeqb:
3730   case PPC::BI__builtin_ppc_setb:
3731   case PPC::BI__builtin_ppc_maddhd:
3732   case PPC::BI__builtin_ppc_maddhdu:
3733   case PPC::BI__builtin_ppc_maddld:
3734     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3735                             diag::err_ppc_builtin_only_on_arch, "9");
3736   case PPC::BI__builtin_ppc_cmprb:
3737     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3738                             diag::err_ppc_builtin_only_on_arch, "9") ||
3739            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3740   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3741   // be a constant that represents a contiguous bit field.
3742   case PPC::BI__builtin_ppc_rlwnm:
3743     return SemaValueIsRunOfOnes(TheCall, 2);
3744   case PPC::BI__builtin_ppc_rlwimi:
3745   case PPC::BI__builtin_ppc_rldimi:
3746     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3747            SemaValueIsRunOfOnes(TheCall, 3);
3748   case PPC::BI__builtin_ppc_extract_exp:
3749   case PPC::BI__builtin_ppc_extract_sig:
3750   case PPC::BI__builtin_ppc_insert_exp:
3751     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3752                             diag::err_ppc_builtin_only_on_arch, "9");
3753   case PPC::BI__builtin_ppc_addex: {
3754     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3755                          diag::err_ppc_builtin_only_on_arch, "9") ||
3756         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3757       return true;
3758     // Output warning for reserved values 1 to 3.
3759     int ArgValue =
3760         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3761     if (ArgValue != 0)
3762       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3763           << ArgValue;
3764     return false;
3765   }
3766   case PPC::BI__builtin_ppc_mtfsb0:
3767   case PPC::BI__builtin_ppc_mtfsb1:
3768     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3769   case PPC::BI__builtin_ppc_mtfsf:
3770     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3771   case PPC::BI__builtin_ppc_mtfsfi:
3772     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3773            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3774   case PPC::BI__builtin_ppc_alignx:
3775     return SemaBuiltinConstantArgPower2(TheCall, 0);
3776   case PPC::BI__builtin_ppc_rdlam:
3777     return SemaValueIsRunOfOnes(TheCall, 2);
3778   case PPC::BI__builtin_ppc_icbt:
3779   case PPC::BI__builtin_ppc_sthcx:
3780   case PPC::BI__builtin_ppc_stbcx:
3781   case PPC::BI__builtin_ppc_lharx:
3782   case PPC::BI__builtin_ppc_lbarx:
3783     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3784                             diag::err_ppc_builtin_only_on_arch, "8");
3785   case PPC::BI__builtin_vsx_ldrmb:
3786   case PPC::BI__builtin_vsx_strmb:
3787     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3788                             diag::err_ppc_builtin_only_on_arch, "8") ||
3789            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3790   case PPC::BI__builtin_altivec_vcntmbb:
3791   case PPC::BI__builtin_altivec_vcntmbh:
3792   case PPC::BI__builtin_altivec_vcntmbw:
3793   case PPC::BI__builtin_altivec_vcntmbd:
3794     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3795   case PPC::BI__builtin_darn:
3796   case PPC::BI__builtin_darn_raw:
3797   case PPC::BI__builtin_darn_32:
3798     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3799                             diag::err_ppc_builtin_only_on_arch, "9");
3800   case PPC::BI__builtin_vsx_xxgenpcvbm:
3801   case PPC::BI__builtin_vsx_xxgenpcvhm:
3802   case PPC::BI__builtin_vsx_xxgenpcvwm:
3803   case PPC::BI__builtin_vsx_xxgenpcvdm:
3804     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3805   case PPC::BI__builtin_ppc_compare_exp_uo:
3806   case PPC::BI__builtin_ppc_compare_exp_lt:
3807   case PPC::BI__builtin_ppc_compare_exp_gt:
3808   case PPC::BI__builtin_ppc_compare_exp_eq:
3809     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3810                             diag::err_ppc_builtin_only_on_arch, "9") ||
3811            SemaFeatureCheck(*this, TheCall, "vsx",
3812                             diag::err_ppc_builtin_requires_vsx);
3813   case PPC::BI__builtin_ppc_test_data_class: {
3814     // Check if the first argument of the __builtin_ppc_test_data_class call is
3815     // valid. The argument must be either a 'float' or a 'double'.
3816     QualType ArgType = TheCall->getArg(0)->getType();
3817     if (ArgType != QualType(Context.FloatTy) &&
3818         ArgType != QualType(Context.DoubleTy))
3819       return Diag(TheCall->getBeginLoc(),
3820                   diag::err_ppc_invalid_test_data_class_type);
3821     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3822                             diag::err_ppc_builtin_only_on_arch, "9") ||
3823            SemaFeatureCheck(*this, TheCall, "vsx",
3824                             diag::err_ppc_builtin_requires_vsx) ||
3825            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3826   }
3827   case PPC::BI__builtin_ppc_load8r:
3828   case PPC::BI__builtin_ppc_store8r:
3829     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3830                             diag::err_ppc_builtin_only_on_arch, "7");
3831 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3832   case PPC::BI__builtin_##Name:                                                \
3833     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3834 #include "clang/Basic/BuiltinsPPC.def"
3835   }
3836   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3837 }
3838 
3839 // Check if the given type is a non-pointer PPC MMA type. This function is used
3840 // in Sema to prevent invalid uses of restricted PPC MMA types.
3841 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3842   if (Type->isPointerType() || Type->isArrayType())
3843     return false;
3844 
3845   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3846 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3847   if (false
3848 #include "clang/Basic/PPCTypes.def"
3849      ) {
3850     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3851     return true;
3852   }
3853   return false;
3854 }
3855 
3856 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3857                                           CallExpr *TheCall) {
3858   // position of memory order and scope arguments in the builtin
3859   unsigned OrderIndex, ScopeIndex;
3860   switch (BuiltinID) {
3861   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3862   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3863   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3864   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3865     OrderIndex = 2;
3866     ScopeIndex = 3;
3867     break;
3868   case AMDGPU::BI__builtin_amdgcn_fence:
3869     OrderIndex = 0;
3870     ScopeIndex = 1;
3871     break;
3872   default:
3873     return false;
3874   }
3875 
3876   ExprResult Arg = TheCall->getArg(OrderIndex);
3877   auto ArgExpr = Arg.get();
3878   Expr::EvalResult ArgResult;
3879 
3880   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3881     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3882            << ArgExpr->getType();
3883   auto Ord = ArgResult.Val.getInt().getZExtValue();
3884 
3885   // Check validity of memory ordering as per C11 / C++11's memody model.
3886   // Only fence needs check. Atomic dec/inc allow all memory orders.
3887   if (!llvm::isValidAtomicOrderingCABI(Ord))
3888     return Diag(ArgExpr->getBeginLoc(),
3889                 diag::warn_atomic_op_has_invalid_memory_order)
3890            << ArgExpr->getSourceRange();
3891   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3892   case llvm::AtomicOrderingCABI::relaxed:
3893   case llvm::AtomicOrderingCABI::consume:
3894     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3895       return Diag(ArgExpr->getBeginLoc(),
3896                   diag::warn_atomic_op_has_invalid_memory_order)
3897              << ArgExpr->getSourceRange();
3898     break;
3899   case llvm::AtomicOrderingCABI::acquire:
3900   case llvm::AtomicOrderingCABI::release:
3901   case llvm::AtomicOrderingCABI::acq_rel:
3902   case llvm::AtomicOrderingCABI::seq_cst:
3903     break;
3904   }
3905 
3906   Arg = TheCall->getArg(ScopeIndex);
3907   ArgExpr = Arg.get();
3908   Expr::EvalResult ArgResult1;
3909   // Check that sync scope is a constant literal
3910   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3911     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3912            << ArgExpr->getType();
3913 
3914   return false;
3915 }
3916 
3917 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3918   llvm::APSInt Result;
3919 
3920   // We can't check the value of a dependent argument.
3921   Expr *Arg = TheCall->getArg(ArgNum);
3922   if (Arg->isTypeDependent() || Arg->isValueDependent())
3923     return false;
3924 
3925   // Check constant-ness first.
3926   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3927     return true;
3928 
3929   int64_t Val = Result.getSExtValue();
3930   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3931     return false;
3932 
3933   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3934          << Arg->getSourceRange();
3935 }
3936 
3937 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3938                                          unsigned BuiltinID,
3939                                          CallExpr *TheCall) {
3940   // CodeGenFunction can also detect this, but this gives a better error
3941   // message.
3942   bool FeatureMissing = false;
3943   SmallVector<StringRef> ReqFeatures;
3944   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3945   Features.split(ReqFeatures, ',');
3946 
3947   // Check if each required feature is included
3948   for (StringRef F : ReqFeatures) {
3949     if (TI.hasFeature(F))
3950       continue;
3951 
3952     // If the feature is 64bit, alter the string so it will print better in
3953     // the diagnostic.
3954     if (F == "64bit")
3955       F = "RV64";
3956 
3957     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3958     F.consume_front("experimental-");
3959     std::string FeatureStr = F.str();
3960     FeatureStr[0] = std::toupper(FeatureStr[0]);
3961 
3962     // Error message
3963     FeatureMissing = true;
3964     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3965         << TheCall->getSourceRange() << StringRef(FeatureStr);
3966   }
3967 
3968   if (FeatureMissing)
3969     return true;
3970 
3971   switch (BuiltinID) {
3972   case RISCVVector::BI__builtin_rvv_vsetvli:
3973     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3974            CheckRISCVLMUL(TheCall, 2);
3975   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3976     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3977            CheckRISCVLMUL(TheCall, 1);
3978   }
3979 
3980   return false;
3981 }
3982 
3983 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3984                                            CallExpr *TheCall) {
3985   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3986     Expr *Arg = TheCall->getArg(0);
3987     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3988       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3989         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3990                << Arg->getSourceRange();
3991   }
3992 
3993   // For intrinsics which take an immediate value as part of the instruction,
3994   // range check them here.
3995   unsigned i = 0, l = 0, u = 0;
3996   switch (BuiltinID) {
3997   default: return false;
3998   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3999   case SystemZ::BI__builtin_s390_verimb:
4000   case SystemZ::BI__builtin_s390_verimh:
4001   case SystemZ::BI__builtin_s390_verimf:
4002   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4003   case SystemZ::BI__builtin_s390_vfaeb:
4004   case SystemZ::BI__builtin_s390_vfaeh:
4005   case SystemZ::BI__builtin_s390_vfaef:
4006   case SystemZ::BI__builtin_s390_vfaebs:
4007   case SystemZ::BI__builtin_s390_vfaehs:
4008   case SystemZ::BI__builtin_s390_vfaefs:
4009   case SystemZ::BI__builtin_s390_vfaezb:
4010   case SystemZ::BI__builtin_s390_vfaezh:
4011   case SystemZ::BI__builtin_s390_vfaezf:
4012   case SystemZ::BI__builtin_s390_vfaezbs:
4013   case SystemZ::BI__builtin_s390_vfaezhs:
4014   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4015   case SystemZ::BI__builtin_s390_vfisb:
4016   case SystemZ::BI__builtin_s390_vfidb:
4017     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4018            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4019   case SystemZ::BI__builtin_s390_vftcisb:
4020   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4021   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4022   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4023   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4024   case SystemZ::BI__builtin_s390_vstrcb:
4025   case SystemZ::BI__builtin_s390_vstrch:
4026   case SystemZ::BI__builtin_s390_vstrcf:
4027   case SystemZ::BI__builtin_s390_vstrczb:
4028   case SystemZ::BI__builtin_s390_vstrczh:
4029   case SystemZ::BI__builtin_s390_vstrczf:
4030   case SystemZ::BI__builtin_s390_vstrcbs:
4031   case SystemZ::BI__builtin_s390_vstrchs:
4032   case SystemZ::BI__builtin_s390_vstrcfs:
4033   case SystemZ::BI__builtin_s390_vstrczbs:
4034   case SystemZ::BI__builtin_s390_vstrczhs:
4035   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4036   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4037   case SystemZ::BI__builtin_s390_vfminsb:
4038   case SystemZ::BI__builtin_s390_vfmaxsb:
4039   case SystemZ::BI__builtin_s390_vfmindb:
4040   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4041   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4042   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4043   case SystemZ::BI__builtin_s390_vclfnhs:
4044   case SystemZ::BI__builtin_s390_vclfnls:
4045   case SystemZ::BI__builtin_s390_vcfn:
4046   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4047   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4048   }
4049   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4050 }
4051 
4052 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4053 /// This checks that the target supports __builtin_cpu_supports and
4054 /// that the string argument is constant and valid.
4055 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4056                                    CallExpr *TheCall) {
4057   Expr *Arg = TheCall->getArg(0);
4058 
4059   // Check if the argument is a string literal.
4060   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4061     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4062            << Arg->getSourceRange();
4063 
4064   // Check the contents of the string.
4065   StringRef Feature =
4066       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4067   if (!TI.validateCpuSupports(Feature))
4068     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4069            << Arg->getSourceRange();
4070   return false;
4071 }
4072 
4073 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4074 /// This checks that the target supports __builtin_cpu_is and
4075 /// that the string argument is constant and valid.
4076 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4077   Expr *Arg = TheCall->getArg(0);
4078 
4079   // Check if the argument is a string literal.
4080   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4081     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4082            << Arg->getSourceRange();
4083 
4084   // Check the contents of the string.
4085   StringRef Feature =
4086       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4087   if (!TI.validateCpuIs(Feature))
4088     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4089            << Arg->getSourceRange();
4090   return false;
4091 }
4092 
4093 // Check if the rounding mode is legal.
4094 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4095   // Indicates if this instruction has rounding control or just SAE.
4096   bool HasRC = false;
4097 
4098   unsigned ArgNum = 0;
4099   switch (BuiltinID) {
4100   default:
4101     return false;
4102   case X86::BI__builtin_ia32_vcvttsd2si32:
4103   case X86::BI__builtin_ia32_vcvttsd2si64:
4104   case X86::BI__builtin_ia32_vcvttsd2usi32:
4105   case X86::BI__builtin_ia32_vcvttsd2usi64:
4106   case X86::BI__builtin_ia32_vcvttss2si32:
4107   case X86::BI__builtin_ia32_vcvttss2si64:
4108   case X86::BI__builtin_ia32_vcvttss2usi32:
4109   case X86::BI__builtin_ia32_vcvttss2usi64:
4110   case X86::BI__builtin_ia32_vcvttsh2si32:
4111   case X86::BI__builtin_ia32_vcvttsh2si64:
4112   case X86::BI__builtin_ia32_vcvttsh2usi32:
4113   case X86::BI__builtin_ia32_vcvttsh2usi64:
4114     ArgNum = 1;
4115     break;
4116   case X86::BI__builtin_ia32_maxpd512:
4117   case X86::BI__builtin_ia32_maxps512:
4118   case X86::BI__builtin_ia32_minpd512:
4119   case X86::BI__builtin_ia32_minps512:
4120   case X86::BI__builtin_ia32_maxph512:
4121   case X86::BI__builtin_ia32_minph512:
4122     ArgNum = 2;
4123     break;
4124   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4125   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4126   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4127   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4128   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4129   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4130   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4131   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4132   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4133   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4134   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4135   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4136   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4137   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4138   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4139   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4140   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4141   case X86::BI__builtin_ia32_exp2pd_mask:
4142   case X86::BI__builtin_ia32_exp2ps_mask:
4143   case X86::BI__builtin_ia32_getexppd512_mask:
4144   case X86::BI__builtin_ia32_getexpps512_mask:
4145   case X86::BI__builtin_ia32_getexpph512_mask:
4146   case X86::BI__builtin_ia32_rcp28pd_mask:
4147   case X86::BI__builtin_ia32_rcp28ps_mask:
4148   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4149   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4150   case X86::BI__builtin_ia32_vcomisd:
4151   case X86::BI__builtin_ia32_vcomiss:
4152   case X86::BI__builtin_ia32_vcomish:
4153   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4154     ArgNum = 3;
4155     break;
4156   case X86::BI__builtin_ia32_cmppd512_mask:
4157   case X86::BI__builtin_ia32_cmpps512_mask:
4158   case X86::BI__builtin_ia32_cmpsd_mask:
4159   case X86::BI__builtin_ia32_cmpss_mask:
4160   case X86::BI__builtin_ia32_cmpsh_mask:
4161   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4162   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4163   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4164   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4165   case X86::BI__builtin_ia32_getexpss128_round_mask:
4166   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4167   case X86::BI__builtin_ia32_getmantpd512_mask:
4168   case X86::BI__builtin_ia32_getmantps512_mask:
4169   case X86::BI__builtin_ia32_getmantph512_mask:
4170   case X86::BI__builtin_ia32_maxsd_round_mask:
4171   case X86::BI__builtin_ia32_maxss_round_mask:
4172   case X86::BI__builtin_ia32_maxsh_round_mask:
4173   case X86::BI__builtin_ia32_minsd_round_mask:
4174   case X86::BI__builtin_ia32_minss_round_mask:
4175   case X86::BI__builtin_ia32_minsh_round_mask:
4176   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4177   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4178   case X86::BI__builtin_ia32_reducepd512_mask:
4179   case X86::BI__builtin_ia32_reduceps512_mask:
4180   case X86::BI__builtin_ia32_reduceph512_mask:
4181   case X86::BI__builtin_ia32_rndscalepd_mask:
4182   case X86::BI__builtin_ia32_rndscaleps_mask:
4183   case X86::BI__builtin_ia32_rndscaleph_mask:
4184   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4185   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4186     ArgNum = 4;
4187     break;
4188   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4189   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4190   case X86::BI__builtin_ia32_fixupimmps512_mask:
4191   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4192   case X86::BI__builtin_ia32_fixupimmsd_mask:
4193   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4194   case X86::BI__builtin_ia32_fixupimmss_mask:
4195   case X86::BI__builtin_ia32_fixupimmss_maskz:
4196   case X86::BI__builtin_ia32_getmantsd_round_mask:
4197   case X86::BI__builtin_ia32_getmantss_round_mask:
4198   case X86::BI__builtin_ia32_getmantsh_round_mask:
4199   case X86::BI__builtin_ia32_rangepd512_mask:
4200   case X86::BI__builtin_ia32_rangeps512_mask:
4201   case X86::BI__builtin_ia32_rangesd128_round_mask:
4202   case X86::BI__builtin_ia32_rangess128_round_mask:
4203   case X86::BI__builtin_ia32_reducesd_mask:
4204   case X86::BI__builtin_ia32_reducess_mask:
4205   case X86::BI__builtin_ia32_reducesh_mask:
4206   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4207   case X86::BI__builtin_ia32_rndscaless_round_mask:
4208   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4209     ArgNum = 5;
4210     break;
4211   case X86::BI__builtin_ia32_vcvtsd2si64:
4212   case X86::BI__builtin_ia32_vcvtsd2si32:
4213   case X86::BI__builtin_ia32_vcvtsd2usi32:
4214   case X86::BI__builtin_ia32_vcvtsd2usi64:
4215   case X86::BI__builtin_ia32_vcvtss2si32:
4216   case X86::BI__builtin_ia32_vcvtss2si64:
4217   case X86::BI__builtin_ia32_vcvtss2usi32:
4218   case X86::BI__builtin_ia32_vcvtss2usi64:
4219   case X86::BI__builtin_ia32_vcvtsh2si32:
4220   case X86::BI__builtin_ia32_vcvtsh2si64:
4221   case X86::BI__builtin_ia32_vcvtsh2usi32:
4222   case X86::BI__builtin_ia32_vcvtsh2usi64:
4223   case X86::BI__builtin_ia32_sqrtpd512:
4224   case X86::BI__builtin_ia32_sqrtps512:
4225   case X86::BI__builtin_ia32_sqrtph512:
4226     ArgNum = 1;
4227     HasRC = true;
4228     break;
4229   case X86::BI__builtin_ia32_addph512:
4230   case X86::BI__builtin_ia32_divph512:
4231   case X86::BI__builtin_ia32_mulph512:
4232   case X86::BI__builtin_ia32_subph512:
4233   case X86::BI__builtin_ia32_addpd512:
4234   case X86::BI__builtin_ia32_addps512:
4235   case X86::BI__builtin_ia32_divpd512:
4236   case X86::BI__builtin_ia32_divps512:
4237   case X86::BI__builtin_ia32_mulpd512:
4238   case X86::BI__builtin_ia32_mulps512:
4239   case X86::BI__builtin_ia32_subpd512:
4240   case X86::BI__builtin_ia32_subps512:
4241   case X86::BI__builtin_ia32_cvtsi2sd64:
4242   case X86::BI__builtin_ia32_cvtsi2ss32:
4243   case X86::BI__builtin_ia32_cvtsi2ss64:
4244   case X86::BI__builtin_ia32_cvtusi2sd64:
4245   case X86::BI__builtin_ia32_cvtusi2ss32:
4246   case X86::BI__builtin_ia32_cvtusi2ss64:
4247   case X86::BI__builtin_ia32_vcvtusi2sh:
4248   case X86::BI__builtin_ia32_vcvtusi642sh:
4249   case X86::BI__builtin_ia32_vcvtsi2sh:
4250   case X86::BI__builtin_ia32_vcvtsi642sh:
4251     ArgNum = 2;
4252     HasRC = true;
4253     break;
4254   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4255   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4256   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4257   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4258   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4259   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4260   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4261   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4262   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4263   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4264   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4265   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4266   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4267   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4268   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4269   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4270   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4271   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4272   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4273   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4274   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4275   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4276   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4277   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4278   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4279   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4280   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4281   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4282   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4283     ArgNum = 3;
4284     HasRC = true;
4285     break;
4286   case X86::BI__builtin_ia32_addsh_round_mask:
4287   case X86::BI__builtin_ia32_addss_round_mask:
4288   case X86::BI__builtin_ia32_addsd_round_mask:
4289   case X86::BI__builtin_ia32_divsh_round_mask:
4290   case X86::BI__builtin_ia32_divss_round_mask:
4291   case X86::BI__builtin_ia32_divsd_round_mask:
4292   case X86::BI__builtin_ia32_mulsh_round_mask:
4293   case X86::BI__builtin_ia32_mulss_round_mask:
4294   case X86::BI__builtin_ia32_mulsd_round_mask:
4295   case X86::BI__builtin_ia32_subsh_round_mask:
4296   case X86::BI__builtin_ia32_subss_round_mask:
4297   case X86::BI__builtin_ia32_subsd_round_mask:
4298   case X86::BI__builtin_ia32_scalefph512_mask:
4299   case X86::BI__builtin_ia32_scalefpd512_mask:
4300   case X86::BI__builtin_ia32_scalefps512_mask:
4301   case X86::BI__builtin_ia32_scalefsd_round_mask:
4302   case X86::BI__builtin_ia32_scalefss_round_mask:
4303   case X86::BI__builtin_ia32_scalefsh_round_mask:
4304   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4305   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4306   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4307   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4308   case X86::BI__builtin_ia32_sqrtss_round_mask:
4309   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4310   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4311   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4312   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4313   case X86::BI__builtin_ia32_vfmaddss3_mask:
4314   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4315   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4316   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4317   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4318   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4319   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4320   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4321   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4322   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4323   case X86::BI__builtin_ia32_vfmaddps512_mask:
4324   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4325   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4326   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4327   case X86::BI__builtin_ia32_vfmaddph512_mask:
4328   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4329   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4330   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4331   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4332   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4333   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4334   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4335   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4336   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4337   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4338   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4339   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4340   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4341   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4342   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4343   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4344   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4345   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4346   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4347   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4348   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4349   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4350   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4351   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4352   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4353   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4354   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4355   case X86::BI__builtin_ia32_vfmulcsh_mask:
4356   case X86::BI__builtin_ia32_vfmulcph512_mask:
4357   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4358   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4359     ArgNum = 4;
4360     HasRC = true;
4361     break;
4362   }
4363 
4364   llvm::APSInt Result;
4365 
4366   // We can't check the value of a dependent argument.
4367   Expr *Arg = TheCall->getArg(ArgNum);
4368   if (Arg->isTypeDependent() || Arg->isValueDependent())
4369     return false;
4370 
4371   // Check constant-ness first.
4372   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4373     return true;
4374 
4375   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4376   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4377   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4378   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4379   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4380       Result == 8/*ROUND_NO_EXC*/ ||
4381       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4382       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4383     return false;
4384 
4385   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4386          << Arg->getSourceRange();
4387 }
4388 
4389 // Check if the gather/scatter scale is legal.
4390 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4391                                              CallExpr *TheCall) {
4392   unsigned ArgNum = 0;
4393   switch (BuiltinID) {
4394   default:
4395     return false;
4396   case X86::BI__builtin_ia32_gatherpfdpd:
4397   case X86::BI__builtin_ia32_gatherpfdps:
4398   case X86::BI__builtin_ia32_gatherpfqpd:
4399   case X86::BI__builtin_ia32_gatherpfqps:
4400   case X86::BI__builtin_ia32_scatterpfdpd:
4401   case X86::BI__builtin_ia32_scatterpfdps:
4402   case X86::BI__builtin_ia32_scatterpfqpd:
4403   case X86::BI__builtin_ia32_scatterpfqps:
4404     ArgNum = 3;
4405     break;
4406   case X86::BI__builtin_ia32_gatherd_pd:
4407   case X86::BI__builtin_ia32_gatherd_pd256:
4408   case X86::BI__builtin_ia32_gatherq_pd:
4409   case X86::BI__builtin_ia32_gatherq_pd256:
4410   case X86::BI__builtin_ia32_gatherd_ps:
4411   case X86::BI__builtin_ia32_gatherd_ps256:
4412   case X86::BI__builtin_ia32_gatherq_ps:
4413   case X86::BI__builtin_ia32_gatherq_ps256:
4414   case X86::BI__builtin_ia32_gatherd_q:
4415   case X86::BI__builtin_ia32_gatherd_q256:
4416   case X86::BI__builtin_ia32_gatherq_q:
4417   case X86::BI__builtin_ia32_gatherq_q256:
4418   case X86::BI__builtin_ia32_gatherd_d:
4419   case X86::BI__builtin_ia32_gatherd_d256:
4420   case X86::BI__builtin_ia32_gatherq_d:
4421   case X86::BI__builtin_ia32_gatherq_d256:
4422   case X86::BI__builtin_ia32_gather3div2df:
4423   case X86::BI__builtin_ia32_gather3div2di:
4424   case X86::BI__builtin_ia32_gather3div4df:
4425   case X86::BI__builtin_ia32_gather3div4di:
4426   case X86::BI__builtin_ia32_gather3div4sf:
4427   case X86::BI__builtin_ia32_gather3div4si:
4428   case X86::BI__builtin_ia32_gather3div8sf:
4429   case X86::BI__builtin_ia32_gather3div8si:
4430   case X86::BI__builtin_ia32_gather3siv2df:
4431   case X86::BI__builtin_ia32_gather3siv2di:
4432   case X86::BI__builtin_ia32_gather3siv4df:
4433   case X86::BI__builtin_ia32_gather3siv4di:
4434   case X86::BI__builtin_ia32_gather3siv4sf:
4435   case X86::BI__builtin_ia32_gather3siv4si:
4436   case X86::BI__builtin_ia32_gather3siv8sf:
4437   case X86::BI__builtin_ia32_gather3siv8si:
4438   case X86::BI__builtin_ia32_gathersiv8df:
4439   case X86::BI__builtin_ia32_gathersiv16sf:
4440   case X86::BI__builtin_ia32_gatherdiv8df:
4441   case X86::BI__builtin_ia32_gatherdiv16sf:
4442   case X86::BI__builtin_ia32_gathersiv8di:
4443   case X86::BI__builtin_ia32_gathersiv16si:
4444   case X86::BI__builtin_ia32_gatherdiv8di:
4445   case X86::BI__builtin_ia32_gatherdiv16si:
4446   case X86::BI__builtin_ia32_scatterdiv2df:
4447   case X86::BI__builtin_ia32_scatterdiv2di:
4448   case X86::BI__builtin_ia32_scatterdiv4df:
4449   case X86::BI__builtin_ia32_scatterdiv4di:
4450   case X86::BI__builtin_ia32_scatterdiv4sf:
4451   case X86::BI__builtin_ia32_scatterdiv4si:
4452   case X86::BI__builtin_ia32_scatterdiv8sf:
4453   case X86::BI__builtin_ia32_scatterdiv8si:
4454   case X86::BI__builtin_ia32_scattersiv2df:
4455   case X86::BI__builtin_ia32_scattersiv2di:
4456   case X86::BI__builtin_ia32_scattersiv4df:
4457   case X86::BI__builtin_ia32_scattersiv4di:
4458   case X86::BI__builtin_ia32_scattersiv4sf:
4459   case X86::BI__builtin_ia32_scattersiv4si:
4460   case X86::BI__builtin_ia32_scattersiv8sf:
4461   case X86::BI__builtin_ia32_scattersiv8si:
4462   case X86::BI__builtin_ia32_scattersiv8df:
4463   case X86::BI__builtin_ia32_scattersiv16sf:
4464   case X86::BI__builtin_ia32_scatterdiv8df:
4465   case X86::BI__builtin_ia32_scatterdiv16sf:
4466   case X86::BI__builtin_ia32_scattersiv8di:
4467   case X86::BI__builtin_ia32_scattersiv16si:
4468   case X86::BI__builtin_ia32_scatterdiv8di:
4469   case X86::BI__builtin_ia32_scatterdiv16si:
4470     ArgNum = 4;
4471     break;
4472   }
4473 
4474   llvm::APSInt Result;
4475 
4476   // We can't check the value of a dependent argument.
4477   Expr *Arg = TheCall->getArg(ArgNum);
4478   if (Arg->isTypeDependent() || Arg->isValueDependent())
4479     return false;
4480 
4481   // Check constant-ness first.
4482   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4483     return true;
4484 
4485   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4486     return false;
4487 
4488   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4489          << Arg->getSourceRange();
4490 }
4491 
4492 enum { TileRegLow = 0, TileRegHigh = 7 };
4493 
4494 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4495                                              ArrayRef<int> ArgNums) {
4496   for (int ArgNum : ArgNums) {
4497     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4498       return true;
4499   }
4500   return false;
4501 }
4502 
4503 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4504                                         ArrayRef<int> ArgNums) {
4505   // Because the max number of tile register is TileRegHigh + 1, so here we use
4506   // each bit to represent the usage of them in bitset.
4507   std::bitset<TileRegHigh + 1> ArgValues;
4508   for (int ArgNum : ArgNums) {
4509     Expr *Arg = TheCall->getArg(ArgNum);
4510     if (Arg->isTypeDependent() || Arg->isValueDependent())
4511       continue;
4512 
4513     llvm::APSInt Result;
4514     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4515       return true;
4516     int ArgExtValue = Result.getExtValue();
4517     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4518            "Incorrect tile register num.");
4519     if (ArgValues.test(ArgExtValue))
4520       return Diag(TheCall->getBeginLoc(),
4521                   diag::err_x86_builtin_tile_arg_duplicate)
4522              << TheCall->getArg(ArgNum)->getSourceRange();
4523     ArgValues.set(ArgExtValue);
4524   }
4525   return false;
4526 }
4527 
4528 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4529                                                 ArrayRef<int> ArgNums) {
4530   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4531          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4532 }
4533 
4534 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4535   switch (BuiltinID) {
4536   default:
4537     return false;
4538   case X86::BI__builtin_ia32_tileloadd64:
4539   case X86::BI__builtin_ia32_tileloaddt164:
4540   case X86::BI__builtin_ia32_tilestored64:
4541   case X86::BI__builtin_ia32_tilezero:
4542     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4543   case X86::BI__builtin_ia32_tdpbssd:
4544   case X86::BI__builtin_ia32_tdpbsud:
4545   case X86::BI__builtin_ia32_tdpbusd:
4546   case X86::BI__builtin_ia32_tdpbuud:
4547   case X86::BI__builtin_ia32_tdpbf16ps:
4548     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4549   }
4550 }
4551 static bool isX86_32Builtin(unsigned BuiltinID) {
4552   // These builtins only work on x86-32 targets.
4553   switch (BuiltinID) {
4554   case X86::BI__builtin_ia32_readeflags_u32:
4555   case X86::BI__builtin_ia32_writeeflags_u32:
4556     return true;
4557   }
4558 
4559   return false;
4560 }
4561 
4562 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4563                                        CallExpr *TheCall) {
4564   if (BuiltinID == X86::BI__builtin_cpu_supports)
4565     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4566 
4567   if (BuiltinID == X86::BI__builtin_cpu_is)
4568     return SemaBuiltinCpuIs(*this, TI, TheCall);
4569 
4570   // Check for 32-bit only builtins on a 64-bit target.
4571   const llvm::Triple &TT = TI.getTriple();
4572   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4573     return Diag(TheCall->getCallee()->getBeginLoc(),
4574                 diag::err_32_bit_builtin_64_bit_tgt);
4575 
4576   // If the intrinsic has rounding or SAE make sure its valid.
4577   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4578     return true;
4579 
4580   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4581   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4582     return true;
4583 
4584   // If the intrinsic has a tile arguments, make sure they are valid.
4585   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4586     return true;
4587 
4588   // For intrinsics which take an immediate value as part of the instruction,
4589   // range check them here.
4590   int i = 0, l = 0, u = 0;
4591   switch (BuiltinID) {
4592   default:
4593     return false;
4594   case X86::BI__builtin_ia32_vec_ext_v2si:
4595   case X86::BI__builtin_ia32_vec_ext_v2di:
4596   case X86::BI__builtin_ia32_vextractf128_pd256:
4597   case X86::BI__builtin_ia32_vextractf128_ps256:
4598   case X86::BI__builtin_ia32_vextractf128_si256:
4599   case X86::BI__builtin_ia32_extract128i256:
4600   case X86::BI__builtin_ia32_extractf64x4_mask:
4601   case X86::BI__builtin_ia32_extracti64x4_mask:
4602   case X86::BI__builtin_ia32_extractf32x8_mask:
4603   case X86::BI__builtin_ia32_extracti32x8_mask:
4604   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4605   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4606   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4607   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4608     i = 1; l = 0; u = 1;
4609     break;
4610   case X86::BI__builtin_ia32_vec_set_v2di:
4611   case X86::BI__builtin_ia32_vinsertf128_pd256:
4612   case X86::BI__builtin_ia32_vinsertf128_ps256:
4613   case X86::BI__builtin_ia32_vinsertf128_si256:
4614   case X86::BI__builtin_ia32_insert128i256:
4615   case X86::BI__builtin_ia32_insertf32x8:
4616   case X86::BI__builtin_ia32_inserti32x8:
4617   case X86::BI__builtin_ia32_insertf64x4:
4618   case X86::BI__builtin_ia32_inserti64x4:
4619   case X86::BI__builtin_ia32_insertf64x2_256:
4620   case X86::BI__builtin_ia32_inserti64x2_256:
4621   case X86::BI__builtin_ia32_insertf32x4_256:
4622   case X86::BI__builtin_ia32_inserti32x4_256:
4623     i = 2; l = 0; u = 1;
4624     break;
4625   case X86::BI__builtin_ia32_vpermilpd:
4626   case X86::BI__builtin_ia32_vec_ext_v4hi:
4627   case X86::BI__builtin_ia32_vec_ext_v4si:
4628   case X86::BI__builtin_ia32_vec_ext_v4sf:
4629   case X86::BI__builtin_ia32_vec_ext_v4di:
4630   case X86::BI__builtin_ia32_extractf32x4_mask:
4631   case X86::BI__builtin_ia32_extracti32x4_mask:
4632   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4633   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4634     i = 1; l = 0; u = 3;
4635     break;
4636   case X86::BI_mm_prefetch:
4637   case X86::BI__builtin_ia32_vec_ext_v8hi:
4638   case X86::BI__builtin_ia32_vec_ext_v8si:
4639     i = 1; l = 0; u = 7;
4640     break;
4641   case X86::BI__builtin_ia32_sha1rnds4:
4642   case X86::BI__builtin_ia32_blendpd:
4643   case X86::BI__builtin_ia32_shufpd:
4644   case X86::BI__builtin_ia32_vec_set_v4hi:
4645   case X86::BI__builtin_ia32_vec_set_v4si:
4646   case X86::BI__builtin_ia32_vec_set_v4di:
4647   case X86::BI__builtin_ia32_shuf_f32x4_256:
4648   case X86::BI__builtin_ia32_shuf_f64x2_256:
4649   case X86::BI__builtin_ia32_shuf_i32x4_256:
4650   case X86::BI__builtin_ia32_shuf_i64x2_256:
4651   case X86::BI__builtin_ia32_insertf64x2_512:
4652   case X86::BI__builtin_ia32_inserti64x2_512:
4653   case X86::BI__builtin_ia32_insertf32x4:
4654   case X86::BI__builtin_ia32_inserti32x4:
4655     i = 2; l = 0; u = 3;
4656     break;
4657   case X86::BI__builtin_ia32_vpermil2pd:
4658   case X86::BI__builtin_ia32_vpermil2pd256:
4659   case X86::BI__builtin_ia32_vpermil2ps:
4660   case X86::BI__builtin_ia32_vpermil2ps256:
4661     i = 3; l = 0; u = 3;
4662     break;
4663   case X86::BI__builtin_ia32_cmpb128_mask:
4664   case X86::BI__builtin_ia32_cmpw128_mask:
4665   case X86::BI__builtin_ia32_cmpd128_mask:
4666   case X86::BI__builtin_ia32_cmpq128_mask:
4667   case X86::BI__builtin_ia32_cmpb256_mask:
4668   case X86::BI__builtin_ia32_cmpw256_mask:
4669   case X86::BI__builtin_ia32_cmpd256_mask:
4670   case X86::BI__builtin_ia32_cmpq256_mask:
4671   case X86::BI__builtin_ia32_cmpb512_mask:
4672   case X86::BI__builtin_ia32_cmpw512_mask:
4673   case X86::BI__builtin_ia32_cmpd512_mask:
4674   case X86::BI__builtin_ia32_cmpq512_mask:
4675   case X86::BI__builtin_ia32_ucmpb128_mask:
4676   case X86::BI__builtin_ia32_ucmpw128_mask:
4677   case X86::BI__builtin_ia32_ucmpd128_mask:
4678   case X86::BI__builtin_ia32_ucmpq128_mask:
4679   case X86::BI__builtin_ia32_ucmpb256_mask:
4680   case X86::BI__builtin_ia32_ucmpw256_mask:
4681   case X86::BI__builtin_ia32_ucmpd256_mask:
4682   case X86::BI__builtin_ia32_ucmpq256_mask:
4683   case X86::BI__builtin_ia32_ucmpb512_mask:
4684   case X86::BI__builtin_ia32_ucmpw512_mask:
4685   case X86::BI__builtin_ia32_ucmpd512_mask:
4686   case X86::BI__builtin_ia32_ucmpq512_mask:
4687   case X86::BI__builtin_ia32_vpcomub:
4688   case X86::BI__builtin_ia32_vpcomuw:
4689   case X86::BI__builtin_ia32_vpcomud:
4690   case X86::BI__builtin_ia32_vpcomuq:
4691   case X86::BI__builtin_ia32_vpcomb:
4692   case X86::BI__builtin_ia32_vpcomw:
4693   case X86::BI__builtin_ia32_vpcomd:
4694   case X86::BI__builtin_ia32_vpcomq:
4695   case X86::BI__builtin_ia32_vec_set_v8hi:
4696   case X86::BI__builtin_ia32_vec_set_v8si:
4697     i = 2; l = 0; u = 7;
4698     break;
4699   case X86::BI__builtin_ia32_vpermilpd256:
4700   case X86::BI__builtin_ia32_roundps:
4701   case X86::BI__builtin_ia32_roundpd:
4702   case X86::BI__builtin_ia32_roundps256:
4703   case X86::BI__builtin_ia32_roundpd256:
4704   case X86::BI__builtin_ia32_getmantpd128_mask:
4705   case X86::BI__builtin_ia32_getmantpd256_mask:
4706   case X86::BI__builtin_ia32_getmantps128_mask:
4707   case X86::BI__builtin_ia32_getmantps256_mask:
4708   case X86::BI__builtin_ia32_getmantpd512_mask:
4709   case X86::BI__builtin_ia32_getmantps512_mask:
4710   case X86::BI__builtin_ia32_getmantph128_mask:
4711   case X86::BI__builtin_ia32_getmantph256_mask:
4712   case X86::BI__builtin_ia32_getmantph512_mask:
4713   case X86::BI__builtin_ia32_vec_ext_v16qi:
4714   case X86::BI__builtin_ia32_vec_ext_v16hi:
4715     i = 1; l = 0; u = 15;
4716     break;
4717   case X86::BI__builtin_ia32_pblendd128:
4718   case X86::BI__builtin_ia32_blendps:
4719   case X86::BI__builtin_ia32_blendpd256:
4720   case X86::BI__builtin_ia32_shufpd256:
4721   case X86::BI__builtin_ia32_roundss:
4722   case X86::BI__builtin_ia32_roundsd:
4723   case X86::BI__builtin_ia32_rangepd128_mask:
4724   case X86::BI__builtin_ia32_rangepd256_mask:
4725   case X86::BI__builtin_ia32_rangepd512_mask:
4726   case X86::BI__builtin_ia32_rangeps128_mask:
4727   case X86::BI__builtin_ia32_rangeps256_mask:
4728   case X86::BI__builtin_ia32_rangeps512_mask:
4729   case X86::BI__builtin_ia32_getmantsd_round_mask:
4730   case X86::BI__builtin_ia32_getmantss_round_mask:
4731   case X86::BI__builtin_ia32_getmantsh_round_mask:
4732   case X86::BI__builtin_ia32_vec_set_v16qi:
4733   case X86::BI__builtin_ia32_vec_set_v16hi:
4734     i = 2; l = 0; u = 15;
4735     break;
4736   case X86::BI__builtin_ia32_vec_ext_v32qi:
4737     i = 1; l = 0; u = 31;
4738     break;
4739   case X86::BI__builtin_ia32_cmpps:
4740   case X86::BI__builtin_ia32_cmpss:
4741   case X86::BI__builtin_ia32_cmppd:
4742   case X86::BI__builtin_ia32_cmpsd:
4743   case X86::BI__builtin_ia32_cmpps256:
4744   case X86::BI__builtin_ia32_cmppd256:
4745   case X86::BI__builtin_ia32_cmpps128_mask:
4746   case X86::BI__builtin_ia32_cmppd128_mask:
4747   case X86::BI__builtin_ia32_cmpps256_mask:
4748   case X86::BI__builtin_ia32_cmppd256_mask:
4749   case X86::BI__builtin_ia32_cmpps512_mask:
4750   case X86::BI__builtin_ia32_cmppd512_mask:
4751   case X86::BI__builtin_ia32_cmpsd_mask:
4752   case X86::BI__builtin_ia32_cmpss_mask:
4753   case X86::BI__builtin_ia32_vec_set_v32qi:
4754     i = 2; l = 0; u = 31;
4755     break;
4756   case X86::BI__builtin_ia32_permdf256:
4757   case X86::BI__builtin_ia32_permdi256:
4758   case X86::BI__builtin_ia32_permdf512:
4759   case X86::BI__builtin_ia32_permdi512:
4760   case X86::BI__builtin_ia32_vpermilps:
4761   case X86::BI__builtin_ia32_vpermilps256:
4762   case X86::BI__builtin_ia32_vpermilpd512:
4763   case X86::BI__builtin_ia32_vpermilps512:
4764   case X86::BI__builtin_ia32_pshufd:
4765   case X86::BI__builtin_ia32_pshufd256:
4766   case X86::BI__builtin_ia32_pshufd512:
4767   case X86::BI__builtin_ia32_pshufhw:
4768   case X86::BI__builtin_ia32_pshufhw256:
4769   case X86::BI__builtin_ia32_pshufhw512:
4770   case X86::BI__builtin_ia32_pshuflw:
4771   case X86::BI__builtin_ia32_pshuflw256:
4772   case X86::BI__builtin_ia32_pshuflw512:
4773   case X86::BI__builtin_ia32_vcvtps2ph:
4774   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4775   case X86::BI__builtin_ia32_vcvtps2ph256:
4776   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4777   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4778   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4779   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4780   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4781   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4782   case X86::BI__builtin_ia32_rndscaleps_mask:
4783   case X86::BI__builtin_ia32_rndscalepd_mask:
4784   case X86::BI__builtin_ia32_rndscaleph_mask:
4785   case X86::BI__builtin_ia32_reducepd128_mask:
4786   case X86::BI__builtin_ia32_reducepd256_mask:
4787   case X86::BI__builtin_ia32_reducepd512_mask:
4788   case X86::BI__builtin_ia32_reduceps128_mask:
4789   case X86::BI__builtin_ia32_reduceps256_mask:
4790   case X86::BI__builtin_ia32_reduceps512_mask:
4791   case X86::BI__builtin_ia32_reduceph128_mask:
4792   case X86::BI__builtin_ia32_reduceph256_mask:
4793   case X86::BI__builtin_ia32_reduceph512_mask:
4794   case X86::BI__builtin_ia32_prold512:
4795   case X86::BI__builtin_ia32_prolq512:
4796   case X86::BI__builtin_ia32_prold128:
4797   case X86::BI__builtin_ia32_prold256:
4798   case X86::BI__builtin_ia32_prolq128:
4799   case X86::BI__builtin_ia32_prolq256:
4800   case X86::BI__builtin_ia32_prord512:
4801   case X86::BI__builtin_ia32_prorq512:
4802   case X86::BI__builtin_ia32_prord128:
4803   case X86::BI__builtin_ia32_prord256:
4804   case X86::BI__builtin_ia32_prorq128:
4805   case X86::BI__builtin_ia32_prorq256:
4806   case X86::BI__builtin_ia32_fpclasspd128_mask:
4807   case X86::BI__builtin_ia32_fpclasspd256_mask:
4808   case X86::BI__builtin_ia32_fpclassps128_mask:
4809   case X86::BI__builtin_ia32_fpclassps256_mask:
4810   case X86::BI__builtin_ia32_fpclassps512_mask:
4811   case X86::BI__builtin_ia32_fpclasspd512_mask:
4812   case X86::BI__builtin_ia32_fpclassph128_mask:
4813   case X86::BI__builtin_ia32_fpclassph256_mask:
4814   case X86::BI__builtin_ia32_fpclassph512_mask:
4815   case X86::BI__builtin_ia32_fpclasssd_mask:
4816   case X86::BI__builtin_ia32_fpclassss_mask:
4817   case X86::BI__builtin_ia32_fpclasssh_mask:
4818   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4819   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4820   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4821   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4822   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4823   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4824   case X86::BI__builtin_ia32_kshiftliqi:
4825   case X86::BI__builtin_ia32_kshiftlihi:
4826   case X86::BI__builtin_ia32_kshiftlisi:
4827   case X86::BI__builtin_ia32_kshiftlidi:
4828   case X86::BI__builtin_ia32_kshiftriqi:
4829   case X86::BI__builtin_ia32_kshiftrihi:
4830   case X86::BI__builtin_ia32_kshiftrisi:
4831   case X86::BI__builtin_ia32_kshiftridi:
4832     i = 1; l = 0; u = 255;
4833     break;
4834   case X86::BI__builtin_ia32_vperm2f128_pd256:
4835   case X86::BI__builtin_ia32_vperm2f128_ps256:
4836   case X86::BI__builtin_ia32_vperm2f128_si256:
4837   case X86::BI__builtin_ia32_permti256:
4838   case X86::BI__builtin_ia32_pblendw128:
4839   case X86::BI__builtin_ia32_pblendw256:
4840   case X86::BI__builtin_ia32_blendps256:
4841   case X86::BI__builtin_ia32_pblendd256:
4842   case X86::BI__builtin_ia32_palignr128:
4843   case X86::BI__builtin_ia32_palignr256:
4844   case X86::BI__builtin_ia32_palignr512:
4845   case X86::BI__builtin_ia32_alignq512:
4846   case X86::BI__builtin_ia32_alignd512:
4847   case X86::BI__builtin_ia32_alignd128:
4848   case X86::BI__builtin_ia32_alignd256:
4849   case X86::BI__builtin_ia32_alignq128:
4850   case X86::BI__builtin_ia32_alignq256:
4851   case X86::BI__builtin_ia32_vcomisd:
4852   case X86::BI__builtin_ia32_vcomiss:
4853   case X86::BI__builtin_ia32_shuf_f32x4:
4854   case X86::BI__builtin_ia32_shuf_f64x2:
4855   case X86::BI__builtin_ia32_shuf_i32x4:
4856   case X86::BI__builtin_ia32_shuf_i64x2:
4857   case X86::BI__builtin_ia32_shufpd512:
4858   case X86::BI__builtin_ia32_shufps:
4859   case X86::BI__builtin_ia32_shufps256:
4860   case X86::BI__builtin_ia32_shufps512:
4861   case X86::BI__builtin_ia32_dbpsadbw128:
4862   case X86::BI__builtin_ia32_dbpsadbw256:
4863   case X86::BI__builtin_ia32_dbpsadbw512:
4864   case X86::BI__builtin_ia32_vpshldd128:
4865   case X86::BI__builtin_ia32_vpshldd256:
4866   case X86::BI__builtin_ia32_vpshldd512:
4867   case X86::BI__builtin_ia32_vpshldq128:
4868   case X86::BI__builtin_ia32_vpshldq256:
4869   case X86::BI__builtin_ia32_vpshldq512:
4870   case X86::BI__builtin_ia32_vpshldw128:
4871   case X86::BI__builtin_ia32_vpshldw256:
4872   case X86::BI__builtin_ia32_vpshldw512:
4873   case X86::BI__builtin_ia32_vpshrdd128:
4874   case X86::BI__builtin_ia32_vpshrdd256:
4875   case X86::BI__builtin_ia32_vpshrdd512:
4876   case X86::BI__builtin_ia32_vpshrdq128:
4877   case X86::BI__builtin_ia32_vpshrdq256:
4878   case X86::BI__builtin_ia32_vpshrdq512:
4879   case X86::BI__builtin_ia32_vpshrdw128:
4880   case X86::BI__builtin_ia32_vpshrdw256:
4881   case X86::BI__builtin_ia32_vpshrdw512:
4882     i = 2; l = 0; u = 255;
4883     break;
4884   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4885   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4886   case X86::BI__builtin_ia32_fixupimmps512_mask:
4887   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4888   case X86::BI__builtin_ia32_fixupimmsd_mask:
4889   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4890   case X86::BI__builtin_ia32_fixupimmss_mask:
4891   case X86::BI__builtin_ia32_fixupimmss_maskz:
4892   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4893   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4894   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4895   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4896   case X86::BI__builtin_ia32_fixupimmps128_mask:
4897   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4898   case X86::BI__builtin_ia32_fixupimmps256_mask:
4899   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4900   case X86::BI__builtin_ia32_pternlogd512_mask:
4901   case X86::BI__builtin_ia32_pternlogd512_maskz:
4902   case X86::BI__builtin_ia32_pternlogq512_mask:
4903   case X86::BI__builtin_ia32_pternlogq512_maskz:
4904   case X86::BI__builtin_ia32_pternlogd128_mask:
4905   case X86::BI__builtin_ia32_pternlogd128_maskz:
4906   case X86::BI__builtin_ia32_pternlogd256_mask:
4907   case X86::BI__builtin_ia32_pternlogd256_maskz:
4908   case X86::BI__builtin_ia32_pternlogq128_mask:
4909   case X86::BI__builtin_ia32_pternlogq128_maskz:
4910   case X86::BI__builtin_ia32_pternlogq256_mask:
4911   case X86::BI__builtin_ia32_pternlogq256_maskz:
4912     i = 3; l = 0; u = 255;
4913     break;
4914   case X86::BI__builtin_ia32_gatherpfdpd:
4915   case X86::BI__builtin_ia32_gatherpfdps:
4916   case X86::BI__builtin_ia32_gatherpfqpd:
4917   case X86::BI__builtin_ia32_gatherpfqps:
4918   case X86::BI__builtin_ia32_scatterpfdpd:
4919   case X86::BI__builtin_ia32_scatterpfdps:
4920   case X86::BI__builtin_ia32_scatterpfqpd:
4921   case X86::BI__builtin_ia32_scatterpfqps:
4922     i = 4; l = 2; u = 3;
4923     break;
4924   case X86::BI__builtin_ia32_reducesd_mask:
4925   case X86::BI__builtin_ia32_reducess_mask:
4926   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4927   case X86::BI__builtin_ia32_rndscaless_round_mask:
4928   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4929   case X86::BI__builtin_ia32_reducesh_mask:
4930     i = 4; l = 0; u = 255;
4931     break;
4932   }
4933 
4934   // Note that we don't force a hard error on the range check here, allowing
4935   // template-generated or macro-generated dead code to potentially have out-of-
4936   // range values. These need to code generate, but don't need to necessarily
4937   // make any sense. We use a warning that defaults to an error.
4938   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4939 }
4940 
4941 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4942 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4943 /// Returns true when the format fits the function and the FormatStringInfo has
4944 /// been populated.
4945 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4946                                FormatStringInfo *FSI) {
4947   FSI->HasVAListArg = Format->getFirstArg() == 0;
4948   FSI->FormatIdx = Format->getFormatIdx() - 1;
4949   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4950 
4951   // The way the format attribute works in GCC, the implicit this argument
4952   // of member functions is counted. However, it doesn't appear in our own
4953   // lists, so decrement format_idx in that case.
4954   if (IsCXXMember) {
4955     if(FSI->FormatIdx == 0)
4956       return false;
4957     --FSI->FormatIdx;
4958     if (FSI->FirstDataArg != 0)
4959       --FSI->FirstDataArg;
4960   }
4961   return true;
4962 }
4963 
4964 /// Checks if a the given expression evaluates to null.
4965 ///
4966 /// Returns true if the value evaluates to null.
4967 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4968   // If the expression has non-null type, it doesn't evaluate to null.
4969   if (auto nullability
4970         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4971     if (*nullability == NullabilityKind::NonNull)
4972       return false;
4973   }
4974 
4975   // As a special case, transparent unions initialized with zero are
4976   // considered null for the purposes of the nonnull attribute.
4977   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4978     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4979       if (const CompoundLiteralExpr *CLE =
4980           dyn_cast<CompoundLiteralExpr>(Expr))
4981         if (const InitListExpr *ILE =
4982             dyn_cast<InitListExpr>(CLE->getInitializer()))
4983           Expr = ILE->getInit(0);
4984   }
4985 
4986   bool Result;
4987   return (!Expr->isValueDependent() &&
4988           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4989           !Result);
4990 }
4991 
4992 static void CheckNonNullArgument(Sema &S,
4993                                  const Expr *ArgExpr,
4994                                  SourceLocation CallSiteLoc) {
4995   if (CheckNonNullExpr(S, ArgExpr))
4996     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4997                           S.PDiag(diag::warn_null_arg)
4998                               << ArgExpr->getSourceRange());
4999 }
5000 
5001 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5002   FormatStringInfo FSI;
5003   if ((GetFormatStringType(Format) == FST_NSString) &&
5004       getFormatStringInfo(Format, false, &FSI)) {
5005     Idx = FSI.FormatIdx;
5006     return true;
5007   }
5008   return false;
5009 }
5010 
5011 /// Diagnose use of %s directive in an NSString which is being passed
5012 /// as formatting string to formatting method.
5013 static void
5014 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5015                                         const NamedDecl *FDecl,
5016                                         Expr **Args,
5017                                         unsigned NumArgs) {
5018   unsigned Idx = 0;
5019   bool Format = false;
5020   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5021   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5022     Idx = 2;
5023     Format = true;
5024   }
5025   else
5026     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5027       if (S.GetFormatNSStringIdx(I, Idx)) {
5028         Format = true;
5029         break;
5030       }
5031     }
5032   if (!Format || NumArgs <= Idx)
5033     return;
5034   const Expr *FormatExpr = Args[Idx];
5035   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5036     FormatExpr = CSCE->getSubExpr();
5037   const StringLiteral *FormatString;
5038   if (const ObjCStringLiteral *OSL =
5039       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5040     FormatString = OSL->getString();
5041   else
5042     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5043   if (!FormatString)
5044     return;
5045   if (S.FormatStringHasSArg(FormatString)) {
5046     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5047       << "%s" << 1 << 1;
5048     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5049       << FDecl->getDeclName();
5050   }
5051 }
5052 
5053 /// Determine whether the given type has a non-null nullability annotation.
5054 static bool isNonNullType(ASTContext &ctx, QualType type) {
5055   if (auto nullability = type->getNullability(ctx))
5056     return *nullability == NullabilityKind::NonNull;
5057 
5058   return false;
5059 }
5060 
5061 static void CheckNonNullArguments(Sema &S,
5062                                   const NamedDecl *FDecl,
5063                                   const FunctionProtoType *Proto,
5064                                   ArrayRef<const Expr *> Args,
5065                                   SourceLocation CallSiteLoc) {
5066   assert((FDecl || Proto) && "Need a function declaration or prototype");
5067 
5068   // Already checked by by constant evaluator.
5069   if (S.isConstantEvaluated())
5070     return;
5071   // Check the attributes attached to the method/function itself.
5072   llvm::SmallBitVector NonNullArgs;
5073   if (FDecl) {
5074     // Handle the nonnull attribute on the function/method declaration itself.
5075     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5076       if (!NonNull->args_size()) {
5077         // Easy case: all pointer arguments are nonnull.
5078         for (const auto *Arg : Args)
5079           if (S.isValidPointerAttrType(Arg->getType()))
5080             CheckNonNullArgument(S, Arg, CallSiteLoc);
5081         return;
5082       }
5083 
5084       for (const ParamIdx &Idx : NonNull->args()) {
5085         unsigned IdxAST = Idx.getASTIndex();
5086         if (IdxAST >= Args.size())
5087           continue;
5088         if (NonNullArgs.empty())
5089           NonNullArgs.resize(Args.size());
5090         NonNullArgs.set(IdxAST);
5091       }
5092     }
5093   }
5094 
5095   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5096     // Handle the nonnull attribute on the parameters of the
5097     // function/method.
5098     ArrayRef<ParmVarDecl*> parms;
5099     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5100       parms = FD->parameters();
5101     else
5102       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5103 
5104     unsigned ParamIndex = 0;
5105     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5106          I != E; ++I, ++ParamIndex) {
5107       const ParmVarDecl *PVD = *I;
5108       if (PVD->hasAttr<NonNullAttr>() ||
5109           isNonNullType(S.Context, PVD->getType())) {
5110         if (NonNullArgs.empty())
5111           NonNullArgs.resize(Args.size());
5112 
5113         NonNullArgs.set(ParamIndex);
5114       }
5115     }
5116   } else {
5117     // If we have a non-function, non-method declaration but no
5118     // function prototype, try to dig out the function prototype.
5119     if (!Proto) {
5120       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5121         QualType type = VD->getType().getNonReferenceType();
5122         if (auto pointerType = type->getAs<PointerType>())
5123           type = pointerType->getPointeeType();
5124         else if (auto blockType = type->getAs<BlockPointerType>())
5125           type = blockType->getPointeeType();
5126         // FIXME: data member pointers?
5127 
5128         // Dig out the function prototype, if there is one.
5129         Proto = type->getAs<FunctionProtoType>();
5130       }
5131     }
5132 
5133     // Fill in non-null argument information from the nullability
5134     // information on the parameter types (if we have them).
5135     if (Proto) {
5136       unsigned Index = 0;
5137       for (auto paramType : Proto->getParamTypes()) {
5138         if (isNonNullType(S.Context, paramType)) {
5139           if (NonNullArgs.empty())
5140             NonNullArgs.resize(Args.size());
5141 
5142           NonNullArgs.set(Index);
5143         }
5144 
5145         ++Index;
5146       }
5147     }
5148   }
5149 
5150   // Check for non-null arguments.
5151   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5152        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5153     if (NonNullArgs[ArgIndex])
5154       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5155   }
5156 }
5157 
5158 /// Warn if a pointer or reference argument passed to a function points to an
5159 /// object that is less aligned than the parameter. This can happen when
5160 /// creating a typedef with a lower alignment than the original type and then
5161 /// calling functions defined in terms of the original type.
5162 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5163                              StringRef ParamName, QualType ArgTy,
5164                              QualType ParamTy) {
5165 
5166   // If a function accepts a pointer or reference type
5167   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5168     return;
5169 
5170   // If the parameter is a pointer type, get the pointee type for the
5171   // argument too. If the parameter is a reference type, don't try to get
5172   // the pointee type for the argument.
5173   if (ParamTy->isPointerType())
5174     ArgTy = ArgTy->getPointeeType();
5175 
5176   // Remove reference or pointer
5177   ParamTy = ParamTy->getPointeeType();
5178 
5179   // Find expected alignment, and the actual alignment of the passed object.
5180   // getTypeAlignInChars requires complete types
5181   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5182       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5183       ArgTy->isUndeducedType())
5184     return;
5185 
5186   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5187   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5188 
5189   // If the argument is less aligned than the parameter, there is a
5190   // potential alignment issue.
5191   if (ArgAlign < ParamAlign)
5192     Diag(Loc, diag::warn_param_mismatched_alignment)
5193         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5194         << ParamName << (FDecl != nullptr) << FDecl;
5195 }
5196 
5197 /// Handles the checks for format strings, non-POD arguments to vararg
5198 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5199 /// attributes.
5200 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5201                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5202                      bool IsMemberFunction, SourceLocation Loc,
5203                      SourceRange Range, VariadicCallType CallType) {
5204   // FIXME: We should check as much as we can in the template definition.
5205   if (CurContext->isDependentContext())
5206     return;
5207 
5208   // Printf and scanf checking.
5209   llvm::SmallBitVector CheckedVarArgs;
5210   if (FDecl) {
5211     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5212       // Only create vector if there are format attributes.
5213       CheckedVarArgs.resize(Args.size());
5214 
5215       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5216                            CheckedVarArgs);
5217     }
5218   }
5219 
5220   // Refuse POD arguments that weren't caught by the format string
5221   // checks above.
5222   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5223   if (CallType != VariadicDoesNotApply &&
5224       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5225     unsigned NumParams = Proto ? Proto->getNumParams()
5226                        : FDecl && isa<FunctionDecl>(FDecl)
5227                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5228                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5229                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5230                        : 0;
5231 
5232     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5233       // Args[ArgIdx] can be null in malformed code.
5234       if (const Expr *Arg = Args[ArgIdx]) {
5235         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5236           checkVariadicArgument(Arg, CallType);
5237       }
5238     }
5239   }
5240 
5241   if (FDecl || Proto) {
5242     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5243 
5244     // Type safety checking.
5245     if (FDecl) {
5246       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5247         CheckArgumentWithTypeTag(I, Args, Loc);
5248     }
5249   }
5250 
5251   // Check that passed arguments match the alignment of original arguments.
5252   // Try to get the missing prototype from the declaration.
5253   if (!Proto && FDecl) {
5254     const auto *FT = FDecl->getFunctionType();
5255     if (isa_and_nonnull<FunctionProtoType>(FT))
5256       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5257   }
5258   if (Proto) {
5259     // For variadic functions, we may have more args than parameters.
5260     // For some K&R functions, we may have less args than parameters.
5261     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5262     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5263       // Args[ArgIdx] can be null in malformed code.
5264       if (const Expr *Arg = Args[ArgIdx]) {
5265         if (Arg->containsErrors())
5266           continue;
5267 
5268         QualType ParamTy = Proto->getParamType(ArgIdx);
5269         QualType ArgTy = Arg->getType();
5270         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5271                           ArgTy, ParamTy);
5272       }
5273     }
5274   }
5275 
5276   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5277     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5278     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5279     if (!Arg->isValueDependent()) {
5280       Expr::EvalResult Align;
5281       if (Arg->EvaluateAsInt(Align, Context)) {
5282         const llvm::APSInt &I = Align.Val.getInt();
5283         if (!I.isPowerOf2())
5284           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5285               << Arg->getSourceRange();
5286 
5287         if (I > Sema::MaximumAlignment)
5288           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5289               << Arg->getSourceRange() << Sema::MaximumAlignment;
5290       }
5291     }
5292   }
5293 
5294   if (FD)
5295     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5296 }
5297 
5298 /// CheckConstructorCall - Check a constructor call for correctness and safety
5299 /// properties not enforced by the C type system.
5300 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5301                                 ArrayRef<const Expr *> Args,
5302                                 const FunctionProtoType *Proto,
5303                                 SourceLocation Loc) {
5304   VariadicCallType CallType =
5305       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5306 
5307   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5308   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5309                     Context.getPointerType(Ctor->getThisObjectType()));
5310 
5311   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5312             Loc, SourceRange(), CallType);
5313 }
5314 
5315 /// CheckFunctionCall - Check a direct function call for various correctness
5316 /// and safety properties not strictly enforced by the C type system.
5317 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5318                              const FunctionProtoType *Proto) {
5319   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5320                               isa<CXXMethodDecl>(FDecl);
5321   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5322                           IsMemberOperatorCall;
5323   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5324                                                   TheCall->getCallee());
5325   Expr** Args = TheCall->getArgs();
5326   unsigned NumArgs = TheCall->getNumArgs();
5327 
5328   Expr *ImplicitThis = nullptr;
5329   if (IsMemberOperatorCall) {
5330     // If this is a call to a member operator, hide the first argument
5331     // from checkCall.
5332     // FIXME: Our choice of AST representation here is less than ideal.
5333     ImplicitThis = Args[0];
5334     ++Args;
5335     --NumArgs;
5336   } else if (IsMemberFunction)
5337     ImplicitThis =
5338         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5339 
5340   if (ImplicitThis) {
5341     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5342     // used.
5343     QualType ThisType = ImplicitThis->getType();
5344     if (!ThisType->isPointerType()) {
5345       assert(!ThisType->isReferenceType());
5346       ThisType = Context.getPointerType(ThisType);
5347     }
5348 
5349     QualType ThisTypeFromDecl =
5350         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5351 
5352     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5353                       ThisTypeFromDecl);
5354   }
5355 
5356   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5357             IsMemberFunction, TheCall->getRParenLoc(),
5358             TheCall->getCallee()->getSourceRange(), CallType);
5359 
5360   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5361   // None of the checks below are needed for functions that don't have
5362   // simple names (e.g., C++ conversion functions).
5363   if (!FnInfo)
5364     return false;
5365 
5366   CheckTCBEnforcement(TheCall, FDecl);
5367 
5368   CheckAbsoluteValueFunction(TheCall, FDecl);
5369   CheckMaxUnsignedZero(TheCall, FDecl);
5370 
5371   if (getLangOpts().ObjC)
5372     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5373 
5374   unsigned CMId = FDecl->getMemoryFunctionKind();
5375 
5376   // Handle memory setting and copying functions.
5377   switch (CMId) {
5378   case 0:
5379     return false;
5380   case Builtin::BIstrlcpy: // fallthrough
5381   case Builtin::BIstrlcat:
5382     CheckStrlcpycatArguments(TheCall, FnInfo);
5383     break;
5384   case Builtin::BIstrncat:
5385     CheckStrncatArguments(TheCall, FnInfo);
5386     break;
5387   case Builtin::BIfree:
5388     CheckFreeArguments(TheCall);
5389     break;
5390   default:
5391     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5392   }
5393 
5394   return false;
5395 }
5396 
5397 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5398                                ArrayRef<const Expr *> Args) {
5399   VariadicCallType CallType =
5400       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5401 
5402   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5403             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5404             CallType);
5405 
5406   return false;
5407 }
5408 
5409 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5410                             const FunctionProtoType *Proto) {
5411   QualType Ty;
5412   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5413     Ty = V->getType().getNonReferenceType();
5414   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5415     Ty = F->getType().getNonReferenceType();
5416   else
5417     return false;
5418 
5419   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5420       !Ty->isFunctionProtoType())
5421     return false;
5422 
5423   VariadicCallType CallType;
5424   if (!Proto || !Proto->isVariadic()) {
5425     CallType = VariadicDoesNotApply;
5426   } else if (Ty->isBlockPointerType()) {
5427     CallType = VariadicBlock;
5428   } else { // Ty->isFunctionPointerType()
5429     CallType = VariadicFunction;
5430   }
5431 
5432   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5433             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5434             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5435             TheCall->getCallee()->getSourceRange(), CallType);
5436 
5437   return false;
5438 }
5439 
5440 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5441 /// such as function pointers returned from functions.
5442 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5443   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5444                                                   TheCall->getCallee());
5445   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5446             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5447             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5448             TheCall->getCallee()->getSourceRange(), CallType);
5449 
5450   return false;
5451 }
5452 
5453 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5454   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5455     return false;
5456 
5457   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5458   switch (Op) {
5459   case AtomicExpr::AO__c11_atomic_init:
5460   case AtomicExpr::AO__opencl_atomic_init:
5461     llvm_unreachable("There is no ordering argument for an init");
5462 
5463   case AtomicExpr::AO__c11_atomic_load:
5464   case AtomicExpr::AO__opencl_atomic_load:
5465   case AtomicExpr::AO__hip_atomic_load:
5466   case AtomicExpr::AO__atomic_load_n:
5467   case AtomicExpr::AO__atomic_load:
5468     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5469            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5470 
5471   case AtomicExpr::AO__c11_atomic_store:
5472   case AtomicExpr::AO__opencl_atomic_store:
5473   case AtomicExpr::AO__hip_atomic_store:
5474   case AtomicExpr::AO__atomic_store:
5475   case AtomicExpr::AO__atomic_store_n:
5476     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5477            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5478            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5479 
5480   default:
5481     return true;
5482   }
5483 }
5484 
5485 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5486                                          AtomicExpr::AtomicOp Op) {
5487   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5488   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5489   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5490   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5491                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5492                          Op);
5493 }
5494 
5495 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5496                                  SourceLocation RParenLoc, MultiExprArg Args,
5497                                  AtomicExpr::AtomicOp Op,
5498                                  AtomicArgumentOrder ArgOrder) {
5499   // All the non-OpenCL operations take one of the following forms.
5500   // The OpenCL operations take the __c11 forms with one extra argument for
5501   // synchronization scope.
5502   enum {
5503     // C    __c11_atomic_init(A *, C)
5504     Init,
5505 
5506     // C    __c11_atomic_load(A *, int)
5507     Load,
5508 
5509     // void __atomic_load(A *, CP, int)
5510     LoadCopy,
5511 
5512     // void __atomic_store(A *, CP, int)
5513     Copy,
5514 
5515     // C    __c11_atomic_add(A *, M, int)
5516     Arithmetic,
5517 
5518     // C    __atomic_exchange_n(A *, CP, int)
5519     Xchg,
5520 
5521     // void __atomic_exchange(A *, C *, CP, int)
5522     GNUXchg,
5523 
5524     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5525     C11CmpXchg,
5526 
5527     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5528     GNUCmpXchg
5529   } Form = Init;
5530 
5531   const unsigned NumForm = GNUCmpXchg + 1;
5532   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5533   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5534   // where:
5535   //   C is an appropriate type,
5536   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5537   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5538   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5539   //   the int parameters are for orderings.
5540 
5541   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5542       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5543       "need to update code for modified forms");
5544   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5545                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5546                         AtomicExpr::AO__atomic_load,
5547                 "need to update code for modified C11 atomics");
5548   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5549                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5550   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5551                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5552   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5553                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5554                IsOpenCL;
5555   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5556              Op == AtomicExpr::AO__atomic_store_n ||
5557              Op == AtomicExpr::AO__atomic_exchange_n ||
5558              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5559   bool IsAddSub = false;
5560 
5561   switch (Op) {
5562   case AtomicExpr::AO__c11_atomic_init:
5563   case AtomicExpr::AO__opencl_atomic_init:
5564     Form = Init;
5565     break;
5566 
5567   case AtomicExpr::AO__c11_atomic_load:
5568   case AtomicExpr::AO__opencl_atomic_load:
5569   case AtomicExpr::AO__hip_atomic_load:
5570   case AtomicExpr::AO__atomic_load_n:
5571     Form = Load;
5572     break;
5573 
5574   case AtomicExpr::AO__atomic_load:
5575     Form = LoadCopy;
5576     break;
5577 
5578   case AtomicExpr::AO__c11_atomic_store:
5579   case AtomicExpr::AO__opencl_atomic_store:
5580   case AtomicExpr::AO__hip_atomic_store:
5581   case AtomicExpr::AO__atomic_store:
5582   case AtomicExpr::AO__atomic_store_n:
5583     Form = Copy;
5584     break;
5585   case AtomicExpr::AO__hip_atomic_fetch_add:
5586   case AtomicExpr::AO__hip_atomic_fetch_min:
5587   case AtomicExpr::AO__hip_atomic_fetch_max:
5588   case AtomicExpr::AO__c11_atomic_fetch_add:
5589   case AtomicExpr::AO__c11_atomic_fetch_sub:
5590   case AtomicExpr::AO__opencl_atomic_fetch_add:
5591   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5592   case AtomicExpr::AO__atomic_fetch_add:
5593   case AtomicExpr::AO__atomic_fetch_sub:
5594   case AtomicExpr::AO__atomic_add_fetch:
5595   case AtomicExpr::AO__atomic_sub_fetch:
5596     IsAddSub = true;
5597     Form = Arithmetic;
5598     break;
5599   case AtomicExpr::AO__c11_atomic_fetch_and:
5600   case AtomicExpr::AO__c11_atomic_fetch_or:
5601   case AtomicExpr::AO__c11_atomic_fetch_xor:
5602   case AtomicExpr::AO__hip_atomic_fetch_and:
5603   case AtomicExpr::AO__hip_atomic_fetch_or:
5604   case AtomicExpr::AO__hip_atomic_fetch_xor:
5605   case AtomicExpr::AO__c11_atomic_fetch_nand:
5606   case AtomicExpr::AO__opencl_atomic_fetch_and:
5607   case AtomicExpr::AO__opencl_atomic_fetch_or:
5608   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5609   case AtomicExpr::AO__atomic_fetch_and:
5610   case AtomicExpr::AO__atomic_fetch_or:
5611   case AtomicExpr::AO__atomic_fetch_xor:
5612   case AtomicExpr::AO__atomic_fetch_nand:
5613   case AtomicExpr::AO__atomic_and_fetch:
5614   case AtomicExpr::AO__atomic_or_fetch:
5615   case AtomicExpr::AO__atomic_xor_fetch:
5616   case AtomicExpr::AO__atomic_nand_fetch:
5617     Form = Arithmetic;
5618     break;
5619   case AtomicExpr::AO__c11_atomic_fetch_min:
5620   case AtomicExpr::AO__c11_atomic_fetch_max:
5621   case AtomicExpr::AO__opencl_atomic_fetch_min:
5622   case AtomicExpr::AO__opencl_atomic_fetch_max:
5623   case AtomicExpr::AO__atomic_min_fetch:
5624   case AtomicExpr::AO__atomic_max_fetch:
5625   case AtomicExpr::AO__atomic_fetch_min:
5626   case AtomicExpr::AO__atomic_fetch_max:
5627     Form = Arithmetic;
5628     break;
5629 
5630   case AtomicExpr::AO__c11_atomic_exchange:
5631   case AtomicExpr::AO__hip_atomic_exchange:
5632   case AtomicExpr::AO__opencl_atomic_exchange:
5633   case AtomicExpr::AO__atomic_exchange_n:
5634     Form = Xchg;
5635     break;
5636 
5637   case AtomicExpr::AO__atomic_exchange:
5638     Form = GNUXchg;
5639     break;
5640 
5641   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5642   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5643   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5644   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5645   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5646   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5647     Form = C11CmpXchg;
5648     break;
5649 
5650   case AtomicExpr::AO__atomic_compare_exchange:
5651   case AtomicExpr::AO__atomic_compare_exchange_n:
5652     Form = GNUCmpXchg;
5653     break;
5654   }
5655 
5656   unsigned AdjustedNumArgs = NumArgs[Form];
5657   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5658     ++AdjustedNumArgs;
5659   // Check we have the right number of arguments.
5660   if (Args.size() < AdjustedNumArgs) {
5661     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5662         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5663         << ExprRange;
5664     return ExprError();
5665   } else if (Args.size() > AdjustedNumArgs) {
5666     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5667          diag::err_typecheck_call_too_many_args)
5668         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5669         << ExprRange;
5670     return ExprError();
5671   }
5672 
5673   // Inspect the first argument of the atomic operation.
5674   Expr *Ptr = Args[0];
5675   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5676   if (ConvertedPtr.isInvalid())
5677     return ExprError();
5678 
5679   Ptr = ConvertedPtr.get();
5680   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5681   if (!pointerType) {
5682     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5683         << Ptr->getType() << Ptr->getSourceRange();
5684     return ExprError();
5685   }
5686 
5687   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5688   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5689   QualType ValType = AtomTy; // 'C'
5690   if (IsC11) {
5691     if (!AtomTy->isAtomicType()) {
5692       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5693           << Ptr->getType() << Ptr->getSourceRange();
5694       return ExprError();
5695     }
5696     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5697         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5698       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5699           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5700           << Ptr->getSourceRange();
5701       return ExprError();
5702     }
5703     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5704   } else if (Form != Load && Form != LoadCopy) {
5705     if (ValType.isConstQualified()) {
5706       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5707           << Ptr->getType() << Ptr->getSourceRange();
5708       return ExprError();
5709     }
5710   }
5711 
5712   // For an arithmetic operation, the implied arithmetic must be well-formed.
5713   if (Form == Arithmetic) {
5714     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5715     // trivial type errors.
5716     auto IsAllowedValueType = [&](QualType ValType) {
5717       if (ValType->isIntegerType())
5718         return true;
5719       if (ValType->isPointerType())
5720         return true;
5721       if (!ValType->isFloatingType())
5722         return false;
5723       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5724       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5725           &Context.getTargetInfo().getLongDoubleFormat() ==
5726               &llvm::APFloat::x87DoubleExtended())
5727         return false;
5728       return true;
5729     };
5730     if (IsAddSub && !IsAllowedValueType(ValType)) {
5731       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5732           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5733       return ExprError();
5734     }
5735     if (!IsAddSub && !ValType->isIntegerType()) {
5736       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5737           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5738       return ExprError();
5739     }
5740     if (IsC11 && ValType->isPointerType() &&
5741         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5742                             diag::err_incomplete_type)) {
5743       return ExprError();
5744     }
5745   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5746     // For __atomic_*_n operations, the value type must be a scalar integral or
5747     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5748     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5749         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5750     return ExprError();
5751   }
5752 
5753   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5754       !AtomTy->isScalarType()) {
5755     // For GNU atomics, require a trivially-copyable type. This is not part of
5756     // the GNU atomics specification but we enforce it for consistency with
5757     // other atomics which generally all require a trivially-copyable type. This
5758     // is because atomics just copy bits.
5759     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5760         << Ptr->getType() << Ptr->getSourceRange();
5761     return ExprError();
5762   }
5763 
5764   switch (ValType.getObjCLifetime()) {
5765   case Qualifiers::OCL_None:
5766   case Qualifiers::OCL_ExplicitNone:
5767     // okay
5768     break;
5769 
5770   case Qualifiers::OCL_Weak:
5771   case Qualifiers::OCL_Strong:
5772   case Qualifiers::OCL_Autoreleasing:
5773     // FIXME: Can this happen? By this point, ValType should be known
5774     // to be trivially copyable.
5775     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5776         << ValType << Ptr->getSourceRange();
5777     return ExprError();
5778   }
5779 
5780   // All atomic operations have an overload which takes a pointer to a volatile
5781   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5782   // into the result or the other operands. Similarly atomic_load takes a
5783   // pointer to a const 'A'.
5784   ValType.removeLocalVolatile();
5785   ValType.removeLocalConst();
5786   QualType ResultType = ValType;
5787   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5788       Form == Init)
5789     ResultType = Context.VoidTy;
5790   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5791     ResultType = Context.BoolTy;
5792 
5793   // The type of a parameter passed 'by value'. In the GNU atomics, such
5794   // arguments are actually passed as pointers.
5795   QualType ByValType = ValType; // 'CP'
5796   bool IsPassedByAddress = false;
5797   if (!IsC11 && !IsHIP && !IsN) {
5798     ByValType = Ptr->getType();
5799     IsPassedByAddress = true;
5800   }
5801 
5802   SmallVector<Expr *, 5> APIOrderedArgs;
5803   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5804     APIOrderedArgs.push_back(Args[0]);
5805     switch (Form) {
5806     case Init:
5807     case Load:
5808       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5809       break;
5810     case LoadCopy:
5811     case Copy:
5812     case Arithmetic:
5813     case Xchg:
5814       APIOrderedArgs.push_back(Args[2]); // Val1
5815       APIOrderedArgs.push_back(Args[1]); // Order
5816       break;
5817     case GNUXchg:
5818       APIOrderedArgs.push_back(Args[2]); // Val1
5819       APIOrderedArgs.push_back(Args[3]); // Val2
5820       APIOrderedArgs.push_back(Args[1]); // Order
5821       break;
5822     case C11CmpXchg:
5823       APIOrderedArgs.push_back(Args[2]); // Val1
5824       APIOrderedArgs.push_back(Args[4]); // Val2
5825       APIOrderedArgs.push_back(Args[1]); // Order
5826       APIOrderedArgs.push_back(Args[3]); // OrderFail
5827       break;
5828     case GNUCmpXchg:
5829       APIOrderedArgs.push_back(Args[2]); // Val1
5830       APIOrderedArgs.push_back(Args[4]); // Val2
5831       APIOrderedArgs.push_back(Args[5]); // Weak
5832       APIOrderedArgs.push_back(Args[1]); // Order
5833       APIOrderedArgs.push_back(Args[3]); // OrderFail
5834       break;
5835     }
5836   } else
5837     APIOrderedArgs.append(Args.begin(), Args.end());
5838 
5839   // The first argument's non-CV pointer type is used to deduce the type of
5840   // subsequent arguments, except for:
5841   //  - weak flag (always converted to bool)
5842   //  - memory order (always converted to int)
5843   //  - scope  (always converted to int)
5844   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5845     QualType Ty;
5846     if (i < NumVals[Form] + 1) {
5847       switch (i) {
5848       case 0:
5849         // The first argument is always a pointer. It has a fixed type.
5850         // It is always dereferenced, a nullptr is undefined.
5851         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5852         // Nothing else to do: we already know all we want about this pointer.
5853         continue;
5854       case 1:
5855         // The second argument is the non-atomic operand. For arithmetic, this
5856         // is always passed by value, and for a compare_exchange it is always
5857         // passed by address. For the rest, GNU uses by-address and C11 uses
5858         // by-value.
5859         assert(Form != Load);
5860         if (Form == Arithmetic && ValType->isPointerType())
5861           Ty = Context.getPointerDiffType();
5862         else if (Form == Init || Form == Arithmetic)
5863           Ty = ValType;
5864         else if (Form == Copy || Form == Xchg) {
5865           if (IsPassedByAddress) {
5866             // The value pointer is always dereferenced, a nullptr is undefined.
5867             CheckNonNullArgument(*this, APIOrderedArgs[i],
5868                                  ExprRange.getBegin());
5869           }
5870           Ty = ByValType;
5871         } else {
5872           Expr *ValArg = APIOrderedArgs[i];
5873           // The value pointer is always dereferenced, a nullptr is undefined.
5874           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5875           LangAS AS = LangAS::Default;
5876           // Keep address space of non-atomic pointer type.
5877           if (const PointerType *PtrTy =
5878                   ValArg->getType()->getAs<PointerType>()) {
5879             AS = PtrTy->getPointeeType().getAddressSpace();
5880           }
5881           Ty = Context.getPointerType(
5882               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5883         }
5884         break;
5885       case 2:
5886         // The third argument to compare_exchange / GNU exchange is the desired
5887         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5888         if (IsPassedByAddress)
5889           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5890         Ty = ByValType;
5891         break;
5892       case 3:
5893         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5894         Ty = Context.BoolTy;
5895         break;
5896       }
5897     } else {
5898       // The order(s) and scope are always converted to int.
5899       Ty = Context.IntTy;
5900     }
5901 
5902     InitializedEntity Entity =
5903         InitializedEntity::InitializeParameter(Context, Ty, false);
5904     ExprResult Arg = APIOrderedArgs[i];
5905     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5906     if (Arg.isInvalid())
5907       return true;
5908     APIOrderedArgs[i] = Arg.get();
5909   }
5910 
5911   // Permute the arguments into a 'consistent' order.
5912   SmallVector<Expr*, 5> SubExprs;
5913   SubExprs.push_back(Ptr);
5914   switch (Form) {
5915   case Init:
5916     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5917     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5918     break;
5919   case Load:
5920     SubExprs.push_back(APIOrderedArgs[1]); // Order
5921     break;
5922   case LoadCopy:
5923   case Copy:
5924   case Arithmetic:
5925   case Xchg:
5926     SubExprs.push_back(APIOrderedArgs[2]); // Order
5927     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5928     break;
5929   case GNUXchg:
5930     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5931     SubExprs.push_back(APIOrderedArgs[3]); // Order
5932     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5933     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5934     break;
5935   case C11CmpXchg:
5936     SubExprs.push_back(APIOrderedArgs[3]); // Order
5937     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5938     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5939     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5940     break;
5941   case GNUCmpXchg:
5942     SubExprs.push_back(APIOrderedArgs[4]); // Order
5943     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5944     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5945     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5946     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5947     break;
5948   }
5949 
5950   if (SubExprs.size() >= 2 && Form != Init) {
5951     if (Optional<llvm::APSInt> Result =
5952             SubExprs[1]->getIntegerConstantExpr(Context))
5953       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5954         Diag(SubExprs[1]->getBeginLoc(),
5955              diag::warn_atomic_op_has_invalid_memory_order)
5956             << SubExprs[1]->getSourceRange();
5957   }
5958 
5959   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5960     auto *Scope = Args[Args.size() - 1];
5961     if (Optional<llvm::APSInt> Result =
5962             Scope->getIntegerConstantExpr(Context)) {
5963       if (!ScopeModel->isValid(Result->getZExtValue()))
5964         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5965             << Scope->getSourceRange();
5966     }
5967     SubExprs.push_back(Scope);
5968   }
5969 
5970   AtomicExpr *AE = new (Context)
5971       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5972 
5973   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5974        Op == AtomicExpr::AO__c11_atomic_store ||
5975        Op == AtomicExpr::AO__opencl_atomic_load ||
5976        Op == AtomicExpr::AO__hip_atomic_load ||
5977        Op == AtomicExpr::AO__opencl_atomic_store ||
5978        Op == AtomicExpr::AO__hip_atomic_store) &&
5979       Context.AtomicUsesUnsupportedLibcall(AE))
5980     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5981         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5982              Op == AtomicExpr::AO__opencl_atomic_load ||
5983              Op == AtomicExpr::AO__hip_atomic_load)
5984                 ? 0
5985                 : 1);
5986 
5987   if (ValType->isBitIntType()) {
5988     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5989     return ExprError();
5990   }
5991 
5992   return AE;
5993 }
5994 
5995 /// checkBuiltinArgument - Given a call to a builtin function, perform
5996 /// normal type-checking on the given argument, updating the call in
5997 /// place.  This is useful when a builtin function requires custom
5998 /// type-checking for some of its arguments but not necessarily all of
5999 /// them.
6000 ///
6001 /// Returns true on error.
6002 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6003   FunctionDecl *Fn = E->getDirectCallee();
6004   assert(Fn && "builtin call without direct callee!");
6005 
6006   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6007   InitializedEntity Entity =
6008     InitializedEntity::InitializeParameter(S.Context, Param);
6009 
6010   ExprResult Arg = E->getArg(0);
6011   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6012   if (Arg.isInvalid())
6013     return true;
6014 
6015   E->setArg(ArgIndex, Arg.get());
6016   return false;
6017 }
6018 
6019 /// We have a call to a function like __sync_fetch_and_add, which is an
6020 /// overloaded function based on the pointer type of its first argument.
6021 /// The main BuildCallExpr routines have already promoted the types of
6022 /// arguments because all of these calls are prototyped as void(...).
6023 ///
6024 /// This function goes through and does final semantic checking for these
6025 /// builtins, as well as generating any warnings.
6026 ExprResult
6027 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6028   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6029   Expr *Callee = TheCall->getCallee();
6030   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6031   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6032 
6033   // Ensure that we have at least one argument to do type inference from.
6034   if (TheCall->getNumArgs() < 1) {
6035     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6036         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6037     return ExprError();
6038   }
6039 
6040   // Inspect the first argument of the atomic builtin.  This should always be
6041   // a pointer type, whose element is an integral scalar or pointer type.
6042   // Because it is a pointer type, we don't have to worry about any implicit
6043   // casts here.
6044   // FIXME: We don't allow floating point scalars as input.
6045   Expr *FirstArg = TheCall->getArg(0);
6046   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6047   if (FirstArgResult.isInvalid())
6048     return ExprError();
6049   FirstArg = FirstArgResult.get();
6050   TheCall->setArg(0, FirstArg);
6051 
6052   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6053   if (!pointerType) {
6054     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6055         << FirstArg->getType() << FirstArg->getSourceRange();
6056     return ExprError();
6057   }
6058 
6059   QualType ValType = pointerType->getPointeeType();
6060   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6061       !ValType->isBlockPointerType()) {
6062     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6063         << FirstArg->getType() << FirstArg->getSourceRange();
6064     return ExprError();
6065   }
6066 
6067   if (ValType.isConstQualified()) {
6068     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6069         << FirstArg->getType() << FirstArg->getSourceRange();
6070     return ExprError();
6071   }
6072 
6073   switch (ValType.getObjCLifetime()) {
6074   case Qualifiers::OCL_None:
6075   case Qualifiers::OCL_ExplicitNone:
6076     // okay
6077     break;
6078 
6079   case Qualifiers::OCL_Weak:
6080   case Qualifiers::OCL_Strong:
6081   case Qualifiers::OCL_Autoreleasing:
6082     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6083         << ValType << FirstArg->getSourceRange();
6084     return ExprError();
6085   }
6086 
6087   // Strip any qualifiers off ValType.
6088   ValType = ValType.getUnqualifiedType();
6089 
6090   // The majority of builtins return a value, but a few have special return
6091   // types, so allow them to override appropriately below.
6092   QualType ResultType = ValType;
6093 
6094   // We need to figure out which concrete builtin this maps onto.  For example,
6095   // __sync_fetch_and_add with a 2 byte object turns into
6096   // __sync_fetch_and_add_2.
6097 #define BUILTIN_ROW(x) \
6098   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6099     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6100 
6101   static const unsigned BuiltinIndices[][5] = {
6102     BUILTIN_ROW(__sync_fetch_and_add),
6103     BUILTIN_ROW(__sync_fetch_and_sub),
6104     BUILTIN_ROW(__sync_fetch_and_or),
6105     BUILTIN_ROW(__sync_fetch_and_and),
6106     BUILTIN_ROW(__sync_fetch_and_xor),
6107     BUILTIN_ROW(__sync_fetch_and_nand),
6108 
6109     BUILTIN_ROW(__sync_add_and_fetch),
6110     BUILTIN_ROW(__sync_sub_and_fetch),
6111     BUILTIN_ROW(__sync_and_and_fetch),
6112     BUILTIN_ROW(__sync_or_and_fetch),
6113     BUILTIN_ROW(__sync_xor_and_fetch),
6114     BUILTIN_ROW(__sync_nand_and_fetch),
6115 
6116     BUILTIN_ROW(__sync_val_compare_and_swap),
6117     BUILTIN_ROW(__sync_bool_compare_and_swap),
6118     BUILTIN_ROW(__sync_lock_test_and_set),
6119     BUILTIN_ROW(__sync_lock_release),
6120     BUILTIN_ROW(__sync_swap)
6121   };
6122 #undef BUILTIN_ROW
6123 
6124   // Determine the index of the size.
6125   unsigned SizeIndex;
6126   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6127   case 1: SizeIndex = 0; break;
6128   case 2: SizeIndex = 1; break;
6129   case 4: SizeIndex = 2; break;
6130   case 8: SizeIndex = 3; break;
6131   case 16: SizeIndex = 4; break;
6132   default:
6133     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6134         << FirstArg->getType() << FirstArg->getSourceRange();
6135     return ExprError();
6136   }
6137 
6138   // Each of these builtins has one pointer argument, followed by some number of
6139   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6140   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6141   // as the number of fixed args.
6142   unsigned BuiltinID = FDecl->getBuiltinID();
6143   unsigned BuiltinIndex, NumFixed = 1;
6144   bool WarnAboutSemanticsChange = false;
6145   switch (BuiltinID) {
6146   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6147   case Builtin::BI__sync_fetch_and_add:
6148   case Builtin::BI__sync_fetch_and_add_1:
6149   case Builtin::BI__sync_fetch_and_add_2:
6150   case Builtin::BI__sync_fetch_and_add_4:
6151   case Builtin::BI__sync_fetch_and_add_8:
6152   case Builtin::BI__sync_fetch_and_add_16:
6153     BuiltinIndex = 0;
6154     break;
6155 
6156   case Builtin::BI__sync_fetch_and_sub:
6157   case Builtin::BI__sync_fetch_and_sub_1:
6158   case Builtin::BI__sync_fetch_and_sub_2:
6159   case Builtin::BI__sync_fetch_and_sub_4:
6160   case Builtin::BI__sync_fetch_and_sub_8:
6161   case Builtin::BI__sync_fetch_and_sub_16:
6162     BuiltinIndex = 1;
6163     break;
6164 
6165   case Builtin::BI__sync_fetch_and_or:
6166   case Builtin::BI__sync_fetch_and_or_1:
6167   case Builtin::BI__sync_fetch_and_or_2:
6168   case Builtin::BI__sync_fetch_and_or_4:
6169   case Builtin::BI__sync_fetch_and_or_8:
6170   case Builtin::BI__sync_fetch_and_or_16:
6171     BuiltinIndex = 2;
6172     break;
6173 
6174   case Builtin::BI__sync_fetch_and_and:
6175   case Builtin::BI__sync_fetch_and_and_1:
6176   case Builtin::BI__sync_fetch_and_and_2:
6177   case Builtin::BI__sync_fetch_and_and_4:
6178   case Builtin::BI__sync_fetch_and_and_8:
6179   case Builtin::BI__sync_fetch_and_and_16:
6180     BuiltinIndex = 3;
6181     break;
6182 
6183   case Builtin::BI__sync_fetch_and_xor:
6184   case Builtin::BI__sync_fetch_and_xor_1:
6185   case Builtin::BI__sync_fetch_and_xor_2:
6186   case Builtin::BI__sync_fetch_and_xor_4:
6187   case Builtin::BI__sync_fetch_and_xor_8:
6188   case Builtin::BI__sync_fetch_and_xor_16:
6189     BuiltinIndex = 4;
6190     break;
6191 
6192   case Builtin::BI__sync_fetch_and_nand:
6193   case Builtin::BI__sync_fetch_and_nand_1:
6194   case Builtin::BI__sync_fetch_and_nand_2:
6195   case Builtin::BI__sync_fetch_and_nand_4:
6196   case Builtin::BI__sync_fetch_and_nand_8:
6197   case Builtin::BI__sync_fetch_and_nand_16:
6198     BuiltinIndex = 5;
6199     WarnAboutSemanticsChange = true;
6200     break;
6201 
6202   case Builtin::BI__sync_add_and_fetch:
6203   case Builtin::BI__sync_add_and_fetch_1:
6204   case Builtin::BI__sync_add_and_fetch_2:
6205   case Builtin::BI__sync_add_and_fetch_4:
6206   case Builtin::BI__sync_add_and_fetch_8:
6207   case Builtin::BI__sync_add_and_fetch_16:
6208     BuiltinIndex = 6;
6209     break;
6210 
6211   case Builtin::BI__sync_sub_and_fetch:
6212   case Builtin::BI__sync_sub_and_fetch_1:
6213   case Builtin::BI__sync_sub_and_fetch_2:
6214   case Builtin::BI__sync_sub_and_fetch_4:
6215   case Builtin::BI__sync_sub_and_fetch_8:
6216   case Builtin::BI__sync_sub_and_fetch_16:
6217     BuiltinIndex = 7;
6218     break;
6219 
6220   case Builtin::BI__sync_and_and_fetch:
6221   case Builtin::BI__sync_and_and_fetch_1:
6222   case Builtin::BI__sync_and_and_fetch_2:
6223   case Builtin::BI__sync_and_and_fetch_4:
6224   case Builtin::BI__sync_and_and_fetch_8:
6225   case Builtin::BI__sync_and_and_fetch_16:
6226     BuiltinIndex = 8;
6227     break;
6228 
6229   case Builtin::BI__sync_or_and_fetch:
6230   case Builtin::BI__sync_or_and_fetch_1:
6231   case Builtin::BI__sync_or_and_fetch_2:
6232   case Builtin::BI__sync_or_and_fetch_4:
6233   case Builtin::BI__sync_or_and_fetch_8:
6234   case Builtin::BI__sync_or_and_fetch_16:
6235     BuiltinIndex = 9;
6236     break;
6237 
6238   case Builtin::BI__sync_xor_and_fetch:
6239   case Builtin::BI__sync_xor_and_fetch_1:
6240   case Builtin::BI__sync_xor_and_fetch_2:
6241   case Builtin::BI__sync_xor_and_fetch_4:
6242   case Builtin::BI__sync_xor_and_fetch_8:
6243   case Builtin::BI__sync_xor_and_fetch_16:
6244     BuiltinIndex = 10;
6245     break;
6246 
6247   case Builtin::BI__sync_nand_and_fetch:
6248   case Builtin::BI__sync_nand_and_fetch_1:
6249   case Builtin::BI__sync_nand_and_fetch_2:
6250   case Builtin::BI__sync_nand_and_fetch_4:
6251   case Builtin::BI__sync_nand_and_fetch_8:
6252   case Builtin::BI__sync_nand_and_fetch_16:
6253     BuiltinIndex = 11;
6254     WarnAboutSemanticsChange = true;
6255     break;
6256 
6257   case Builtin::BI__sync_val_compare_and_swap:
6258   case Builtin::BI__sync_val_compare_and_swap_1:
6259   case Builtin::BI__sync_val_compare_and_swap_2:
6260   case Builtin::BI__sync_val_compare_and_swap_4:
6261   case Builtin::BI__sync_val_compare_and_swap_8:
6262   case Builtin::BI__sync_val_compare_and_swap_16:
6263     BuiltinIndex = 12;
6264     NumFixed = 2;
6265     break;
6266 
6267   case Builtin::BI__sync_bool_compare_and_swap:
6268   case Builtin::BI__sync_bool_compare_and_swap_1:
6269   case Builtin::BI__sync_bool_compare_and_swap_2:
6270   case Builtin::BI__sync_bool_compare_and_swap_4:
6271   case Builtin::BI__sync_bool_compare_and_swap_8:
6272   case Builtin::BI__sync_bool_compare_and_swap_16:
6273     BuiltinIndex = 13;
6274     NumFixed = 2;
6275     ResultType = Context.BoolTy;
6276     break;
6277 
6278   case Builtin::BI__sync_lock_test_and_set:
6279   case Builtin::BI__sync_lock_test_and_set_1:
6280   case Builtin::BI__sync_lock_test_and_set_2:
6281   case Builtin::BI__sync_lock_test_and_set_4:
6282   case Builtin::BI__sync_lock_test_and_set_8:
6283   case Builtin::BI__sync_lock_test_and_set_16:
6284     BuiltinIndex = 14;
6285     break;
6286 
6287   case Builtin::BI__sync_lock_release:
6288   case Builtin::BI__sync_lock_release_1:
6289   case Builtin::BI__sync_lock_release_2:
6290   case Builtin::BI__sync_lock_release_4:
6291   case Builtin::BI__sync_lock_release_8:
6292   case Builtin::BI__sync_lock_release_16:
6293     BuiltinIndex = 15;
6294     NumFixed = 0;
6295     ResultType = Context.VoidTy;
6296     break;
6297 
6298   case Builtin::BI__sync_swap:
6299   case Builtin::BI__sync_swap_1:
6300   case Builtin::BI__sync_swap_2:
6301   case Builtin::BI__sync_swap_4:
6302   case Builtin::BI__sync_swap_8:
6303   case Builtin::BI__sync_swap_16:
6304     BuiltinIndex = 16;
6305     break;
6306   }
6307 
6308   // Now that we know how many fixed arguments we expect, first check that we
6309   // have at least that many.
6310   if (TheCall->getNumArgs() < 1+NumFixed) {
6311     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6312         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6313         << Callee->getSourceRange();
6314     return ExprError();
6315   }
6316 
6317   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6318       << Callee->getSourceRange();
6319 
6320   if (WarnAboutSemanticsChange) {
6321     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6322         << Callee->getSourceRange();
6323   }
6324 
6325   // Get the decl for the concrete builtin from this, we can tell what the
6326   // concrete integer type we should convert to is.
6327   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6328   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6329   FunctionDecl *NewBuiltinDecl;
6330   if (NewBuiltinID == BuiltinID)
6331     NewBuiltinDecl = FDecl;
6332   else {
6333     // Perform builtin lookup to avoid redeclaring it.
6334     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6335     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6336     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6337     assert(Res.getFoundDecl());
6338     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6339     if (!NewBuiltinDecl)
6340       return ExprError();
6341   }
6342 
6343   // The first argument --- the pointer --- has a fixed type; we
6344   // deduce the types of the rest of the arguments accordingly.  Walk
6345   // the remaining arguments, converting them to the deduced value type.
6346   for (unsigned i = 0; i != NumFixed; ++i) {
6347     ExprResult Arg = TheCall->getArg(i+1);
6348 
6349     // GCC does an implicit conversion to the pointer or integer ValType.  This
6350     // can fail in some cases (1i -> int**), check for this error case now.
6351     // Initialize the argument.
6352     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6353                                                    ValType, /*consume*/ false);
6354     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6355     if (Arg.isInvalid())
6356       return ExprError();
6357 
6358     // Okay, we have something that *can* be converted to the right type.  Check
6359     // to see if there is a potentially weird extension going on here.  This can
6360     // happen when you do an atomic operation on something like an char* and
6361     // pass in 42.  The 42 gets converted to char.  This is even more strange
6362     // for things like 45.123 -> char, etc.
6363     // FIXME: Do this check.
6364     TheCall->setArg(i+1, Arg.get());
6365   }
6366 
6367   // Create a new DeclRefExpr to refer to the new decl.
6368   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6369       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6370       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6371       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6372 
6373   // Set the callee in the CallExpr.
6374   // FIXME: This loses syntactic information.
6375   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6376   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6377                                               CK_BuiltinFnToFnPtr);
6378   TheCall->setCallee(PromotedCall.get());
6379 
6380   // Change the result type of the call to match the original value type. This
6381   // is arbitrary, but the codegen for these builtins ins design to handle it
6382   // gracefully.
6383   TheCall->setType(ResultType);
6384 
6385   // Prohibit problematic uses of bit-precise integer types with atomic
6386   // builtins. The arguments would have already been converted to the first
6387   // argument's type, so only need to check the first argument.
6388   const auto *BitIntValType = ValType->getAs<BitIntType>();
6389   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6390     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6391     return ExprError();
6392   }
6393 
6394   return TheCallResult;
6395 }
6396 
6397 /// SemaBuiltinNontemporalOverloaded - We have a call to
6398 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6399 /// overloaded function based on the pointer type of its last argument.
6400 ///
6401 /// This function goes through and does final semantic checking for these
6402 /// builtins.
6403 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6404   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6405   DeclRefExpr *DRE =
6406       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6407   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6408   unsigned BuiltinID = FDecl->getBuiltinID();
6409   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6410           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6411          "Unexpected nontemporal load/store builtin!");
6412   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6413   unsigned numArgs = isStore ? 2 : 1;
6414 
6415   // Ensure that we have the proper number of arguments.
6416   if (checkArgCount(*this, TheCall, numArgs))
6417     return ExprError();
6418 
6419   // Inspect the last argument of the nontemporal builtin.  This should always
6420   // be a pointer type, from which we imply the type of the memory access.
6421   // Because it is a pointer type, we don't have to worry about any implicit
6422   // casts here.
6423   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6424   ExprResult PointerArgResult =
6425       DefaultFunctionArrayLvalueConversion(PointerArg);
6426 
6427   if (PointerArgResult.isInvalid())
6428     return ExprError();
6429   PointerArg = PointerArgResult.get();
6430   TheCall->setArg(numArgs - 1, PointerArg);
6431 
6432   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6433   if (!pointerType) {
6434     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6435         << PointerArg->getType() << PointerArg->getSourceRange();
6436     return ExprError();
6437   }
6438 
6439   QualType ValType = pointerType->getPointeeType();
6440 
6441   // Strip any qualifiers off ValType.
6442   ValType = ValType.getUnqualifiedType();
6443   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6444       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6445       !ValType->isVectorType()) {
6446     Diag(DRE->getBeginLoc(),
6447          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6448         << PointerArg->getType() << PointerArg->getSourceRange();
6449     return ExprError();
6450   }
6451 
6452   if (!isStore) {
6453     TheCall->setType(ValType);
6454     return TheCallResult;
6455   }
6456 
6457   ExprResult ValArg = TheCall->getArg(0);
6458   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6459       Context, ValType, /*consume*/ false);
6460   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6461   if (ValArg.isInvalid())
6462     return ExprError();
6463 
6464   TheCall->setArg(0, ValArg.get());
6465   TheCall->setType(Context.VoidTy);
6466   return TheCallResult;
6467 }
6468 
6469 /// CheckObjCString - Checks that the argument to the builtin
6470 /// CFString constructor is correct
6471 /// Note: It might also make sense to do the UTF-16 conversion here (would
6472 /// simplify the backend).
6473 bool Sema::CheckObjCString(Expr *Arg) {
6474   Arg = Arg->IgnoreParenCasts();
6475   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6476 
6477   if (!Literal || !Literal->isAscii()) {
6478     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6479         << Arg->getSourceRange();
6480     return true;
6481   }
6482 
6483   if (Literal->containsNonAsciiOrNull()) {
6484     StringRef String = Literal->getString();
6485     unsigned NumBytes = String.size();
6486     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6487     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6488     llvm::UTF16 *ToPtr = &ToBuf[0];
6489 
6490     llvm::ConversionResult Result =
6491         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6492                                  ToPtr + NumBytes, llvm::strictConversion);
6493     // Check for conversion failure.
6494     if (Result != llvm::conversionOK)
6495       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6496           << Arg->getSourceRange();
6497   }
6498   return false;
6499 }
6500 
6501 /// CheckObjCString - Checks that the format string argument to the os_log()
6502 /// and os_trace() functions is correct, and converts it to const char *.
6503 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6504   Arg = Arg->IgnoreParenCasts();
6505   auto *Literal = dyn_cast<StringLiteral>(Arg);
6506   if (!Literal) {
6507     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6508       Literal = ObjcLiteral->getString();
6509     }
6510   }
6511 
6512   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6513     return ExprError(
6514         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6515         << Arg->getSourceRange());
6516   }
6517 
6518   ExprResult Result(Literal);
6519   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6520   InitializedEntity Entity =
6521       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6522   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6523   return Result;
6524 }
6525 
6526 /// Check that the user is calling the appropriate va_start builtin for the
6527 /// target and calling convention.
6528 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6529   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6530   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6531   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6532                     TT.getArch() == llvm::Triple::aarch64_32);
6533   bool IsWindows = TT.isOSWindows();
6534   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6535   if (IsX64 || IsAArch64) {
6536     CallingConv CC = CC_C;
6537     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6538       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6539     if (IsMSVAStart) {
6540       // Don't allow this in System V ABI functions.
6541       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6542         return S.Diag(Fn->getBeginLoc(),
6543                       diag::err_ms_va_start_used_in_sysv_function);
6544     } else {
6545       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6546       // On x64 Windows, don't allow this in System V ABI functions.
6547       // (Yes, that means there's no corresponding way to support variadic
6548       // System V ABI functions on Windows.)
6549       if ((IsWindows && CC == CC_X86_64SysV) ||
6550           (!IsWindows && CC == CC_Win64))
6551         return S.Diag(Fn->getBeginLoc(),
6552                       diag::err_va_start_used_in_wrong_abi_function)
6553                << !IsWindows;
6554     }
6555     return false;
6556   }
6557 
6558   if (IsMSVAStart)
6559     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6560   return false;
6561 }
6562 
6563 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6564                                              ParmVarDecl **LastParam = nullptr) {
6565   // Determine whether the current function, block, or obj-c method is variadic
6566   // and get its parameter list.
6567   bool IsVariadic = false;
6568   ArrayRef<ParmVarDecl *> Params;
6569   DeclContext *Caller = S.CurContext;
6570   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6571     IsVariadic = Block->isVariadic();
6572     Params = Block->parameters();
6573   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6574     IsVariadic = FD->isVariadic();
6575     Params = FD->parameters();
6576   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6577     IsVariadic = MD->isVariadic();
6578     // FIXME: This isn't correct for methods (results in bogus warning).
6579     Params = MD->parameters();
6580   } else if (isa<CapturedDecl>(Caller)) {
6581     // We don't support va_start in a CapturedDecl.
6582     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6583     return true;
6584   } else {
6585     // This must be some other declcontext that parses exprs.
6586     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6587     return true;
6588   }
6589 
6590   if (!IsVariadic) {
6591     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6592     return true;
6593   }
6594 
6595   if (LastParam)
6596     *LastParam = Params.empty() ? nullptr : Params.back();
6597 
6598   return false;
6599 }
6600 
6601 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6602 /// for validity.  Emit an error and return true on failure; return false
6603 /// on success.
6604 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6605   Expr *Fn = TheCall->getCallee();
6606 
6607   if (checkVAStartABI(*this, BuiltinID, Fn))
6608     return true;
6609 
6610   if (checkArgCount(*this, TheCall, 2))
6611     return true;
6612 
6613   // Type-check the first argument normally.
6614   if (checkBuiltinArgument(*this, TheCall, 0))
6615     return true;
6616 
6617   // Check that the current function is variadic, and get its last parameter.
6618   ParmVarDecl *LastParam;
6619   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6620     return true;
6621 
6622   // Verify that the second argument to the builtin is the last argument of the
6623   // current function or method.
6624   bool SecondArgIsLastNamedArgument = false;
6625   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6626 
6627   // These are valid if SecondArgIsLastNamedArgument is false after the next
6628   // block.
6629   QualType Type;
6630   SourceLocation ParamLoc;
6631   bool IsCRegister = false;
6632 
6633   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6634     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6635       SecondArgIsLastNamedArgument = PV == LastParam;
6636 
6637       Type = PV->getType();
6638       ParamLoc = PV->getLocation();
6639       IsCRegister =
6640           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6641     }
6642   }
6643 
6644   if (!SecondArgIsLastNamedArgument)
6645     Diag(TheCall->getArg(1)->getBeginLoc(),
6646          diag::warn_second_arg_of_va_start_not_last_named_param);
6647   else if (IsCRegister || Type->isReferenceType() ||
6648            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6649              // Promotable integers are UB, but enumerations need a bit of
6650              // extra checking to see what their promotable type actually is.
6651              if (!Type->isPromotableIntegerType())
6652                return false;
6653              if (!Type->isEnumeralType())
6654                return true;
6655              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6656              return !(ED &&
6657                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6658            }()) {
6659     unsigned Reason = 0;
6660     if (Type->isReferenceType())  Reason = 1;
6661     else if (IsCRegister)         Reason = 2;
6662     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6663     Diag(ParamLoc, diag::note_parameter_type) << Type;
6664   }
6665 
6666   TheCall->setType(Context.VoidTy);
6667   return false;
6668 }
6669 
6670 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6671   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6672     const LangOptions &LO = getLangOpts();
6673 
6674     if (LO.CPlusPlus)
6675       return Arg->getType()
6676                  .getCanonicalType()
6677                  .getTypePtr()
6678                  ->getPointeeType()
6679                  .withoutLocalFastQualifiers() == Context.CharTy;
6680 
6681     // In C, allow aliasing through `char *`, this is required for AArch64 at
6682     // least.
6683     return true;
6684   };
6685 
6686   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6687   //                 const char *named_addr);
6688 
6689   Expr *Func = Call->getCallee();
6690 
6691   if (Call->getNumArgs() < 3)
6692     return Diag(Call->getEndLoc(),
6693                 diag::err_typecheck_call_too_few_args_at_least)
6694            << 0 /*function call*/ << 3 << Call->getNumArgs();
6695 
6696   // Type-check the first argument normally.
6697   if (checkBuiltinArgument(*this, Call, 0))
6698     return true;
6699 
6700   // Check that the current function is variadic.
6701   if (checkVAStartIsInVariadicFunction(*this, Func))
6702     return true;
6703 
6704   // __va_start on Windows does not validate the parameter qualifiers
6705 
6706   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6707   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6708 
6709   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6710   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6711 
6712   const QualType &ConstCharPtrTy =
6713       Context.getPointerType(Context.CharTy.withConst());
6714   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6715     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6716         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6717         << 0                                      /* qualifier difference */
6718         << 3                                      /* parameter mismatch */
6719         << 2 << Arg1->getType() << ConstCharPtrTy;
6720 
6721   const QualType SizeTy = Context.getSizeType();
6722   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6723     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6724         << Arg2->getType() << SizeTy << 1 /* different class */
6725         << 0                              /* qualifier difference */
6726         << 3                              /* parameter mismatch */
6727         << 3 << Arg2->getType() << SizeTy;
6728 
6729   return false;
6730 }
6731 
6732 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6733 /// friends.  This is declared to take (...), so we have to check everything.
6734 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6735   if (checkArgCount(*this, TheCall, 2))
6736     return true;
6737 
6738   ExprResult OrigArg0 = TheCall->getArg(0);
6739   ExprResult OrigArg1 = TheCall->getArg(1);
6740 
6741   // Do standard promotions between the two arguments, returning their common
6742   // type.
6743   QualType Res = UsualArithmeticConversions(
6744       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6745   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6746     return true;
6747 
6748   // Make sure any conversions are pushed back into the call; this is
6749   // type safe since unordered compare builtins are declared as "_Bool
6750   // foo(...)".
6751   TheCall->setArg(0, OrigArg0.get());
6752   TheCall->setArg(1, OrigArg1.get());
6753 
6754   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6755     return false;
6756 
6757   // If the common type isn't a real floating type, then the arguments were
6758   // invalid for this operation.
6759   if (Res.isNull() || !Res->isRealFloatingType())
6760     return Diag(OrigArg0.get()->getBeginLoc(),
6761                 diag::err_typecheck_call_invalid_ordered_compare)
6762            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6763            << SourceRange(OrigArg0.get()->getBeginLoc(),
6764                           OrigArg1.get()->getEndLoc());
6765 
6766   return false;
6767 }
6768 
6769 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6770 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6771 /// to check everything. We expect the last argument to be a floating point
6772 /// value.
6773 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6774   if (checkArgCount(*this, TheCall, NumArgs))
6775     return true;
6776 
6777   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6778   // on all preceding parameters just being int.  Try all of those.
6779   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6780     Expr *Arg = TheCall->getArg(i);
6781 
6782     if (Arg->isTypeDependent())
6783       return false;
6784 
6785     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6786 
6787     if (Res.isInvalid())
6788       return true;
6789     TheCall->setArg(i, Res.get());
6790   }
6791 
6792   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6793 
6794   if (OrigArg->isTypeDependent())
6795     return false;
6796 
6797   // Usual Unary Conversions will convert half to float, which we want for
6798   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6799   // type how it is, but do normal L->Rvalue conversions.
6800   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6801     OrigArg = UsualUnaryConversions(OrigArg).get();
6802   else
6803     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6804   TheCall->setArg(NumArgs - 1, OrigArg);
6805 
6806   // This operation requires a non-_Complex floating-point number.
6807   if (!OrigArg->getType()->isRealFloatingType())
6808     return Diag(OrigArg->getBeginLoc(),
6809                 diag::err_typecheck_call_invalid_unary_fp)
6810            << OrigArg->getType() << OrigArg->getSourceRange();
6811 
6812   return false;
6813 }
6814 
6815 /// Perform semantic analysis for a call to __builtin_complex.
6816 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6817   if (checkArgCount(*this, TheCall, 2))
6818     return true;
6819 
6820   bool Dependent = false;
6821   for (unsigned I = 0; I != 2; ++I) {
6822     Expr *Arg = TheCall->getArg(I);
6823     QualType T = Arg->getType();
6824     if (T->isDependentType()) {
6825       Dependent = true;
6826       continue;
6827     }
6828 
6829     // Despite supporting _Complex int, GCC requires a real floating point type
6830     // for the operands of __builtin_complex.
6831     if (!T->isRealFloatingType()) {
6832       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6833              << Arg->getType() << Arg->getSourceRange();
6834     }
6835 
6836     ExprResult Converted = DefaultLvalueConversion(Arg);
6837     if (Converted.isInvalid())
6838       return true;
6839     TheCall->setArg(I, Converted.get());
6840   }
6841 
6842   if (Dependent) {
6843     TheCall->setType(Context.DependentTy);
6844     return false;
6845   }
6846 
6847   Expr *Real = TheCall->getArg(0);
6848   Expr *Imag = TheCall->getArg(1);
6849   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6850     return Diag(Real->getBeginLoc(),
6851                 diag::err_typecheck_call_different_arg_types)
6852            << Real->getType() << Imag->getType()
6853            << Real->getSourceRange() << Imag->getSourceRange();
6854   }
6855 
6856   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6857   // don't allow this builtin to form those types either.
6858   // FIXME: Should we allow these types?
6859   if (Real->getType()->isFloat16Type())
6860     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6861            << "_Float16";
6862   if (Real->getType()->isHalfType())
6863     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6864            << "half";
6865 
6866   TheCall->setType(Context.getComplexType(Real->getType()));
6867   return false;
6868 }
6869 
6870 // Customized Sema Checking for VSX builtins that have the following signature:
6871 // vector [...] builtinName(vector [...], vector [...], const int);
6872 // Which takes the same type of vectors (any legal vector type) for the first
6873 // two arguments and takes compile time constant for the third argument.
6874 // Example builtins are :
6875 // vector double vec_xxpermdi(vector double, vector double, int);
6876 // vector short vec_xxsldwi(vector short, vector short, int);
6877 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6878   unsigned ExpectedNumArgs = 3;
6879   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6880     return true;
6881 
6882   // Check the third argument is a compile time constant
6883   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6884     return Diag(TheCall->getBeginLoc(),
6885                 diag::err_vsx_builtin_nonconstant_argument)
6886            << 3 /* argument index */ << TheCall->getDirectCallee()
6887            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6888                           TheCall->getArg(2)->getEndLoc());
6889 
6890   QualType Arg1Ty = TheCall->getArg(0)->getType();
6891   QualType Arg2Ty = TheCall->getArg(1)->getType();
6892 
6893   // Check the type of argument 1 and argument 2 are vectors.
6894   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6895   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6896       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6897     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6898            << TheCall->getDirectCallee()
6899            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6900                           TheCall->getArg(1)->getEndLoc());
6901   }
6902 
6903   // Check the first two arguments are the same type.
6904   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6905     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6906            << TheCall->getDirectCallee()
6907            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6908                           TheCall->getArg(1)->getEndLoc());
6909   }
6910 
6911   // When default clang type checking is turned off and the customized type
6912   // checking is used, the returning type of the function must be explicitly
6913   // set. Otherwise it is _Bool by default.
6914   TheCall->setType(Arg1Ty);
6915 
6916   return false;
6917 }
6918 
6919 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6920 // This is declared to take (...), so we have to check everything.
6921 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6922   if (TheCall->getNumArgs() < 2)
6923     return ExprError(Diag(TheCall->getEndLoc(),
6924                           diag::err_typecheck_call_too_few_args_at_least)
6925                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6926                      << TheCall->getSourceRange());
6927 
6928   // Determine which of the following types of shufflevector we're checking:
6929   // 1) unary, vector mask: (lhs, mask)
6930   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6931   QualType resType = TheCall->getArg(0)->getType();
6932   unsigned numElements = 0;
6933 
6934   if (!TheCall->getArg(0)->isTypeDependent() &&
6935       !TheCall->getArg(1)->isTypeDependent()) {
6936     QualType LHSType = TheCall->getArg(0)->getType();
6937     QualType RHSType = TheCall->getArg(1)->getType();
6938 
6939     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6940       return ExprError(
6941           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6942           << TheCall->getDirectCallee()
6943           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6944                          TheCall->getArg(1)->getEndLoc()));
6945 
6946     numElements = LHSType->castAs<VectorType>()->getNumElements();
6947     unsigned numResElements = TheCall->getNumArgs() - 2;
6948 
6949     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6950     // with mask.  If so, verify that RHS is an integer vector type with the
6951     // same number of elts as lhs.
6952     if (TheCall->getNumArgs() == 2) {
6953       if (!RHSType->hasIntegerRepresentation() ||
6954           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6955         return ExprError(Diag(TheCall->getBeginLoc(),
6956                               diag::err_vec_builtin_incompatible_vector)
6957                          << TheCall->getDirectCallee()
6958                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6959                                         TheCall->getArg(1)->getEndLoc()));
6960     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6961       return ExprError(Diag(TheCall->getBeginLoc(),
6962                             diag::err_vec_builtin_incompatible_vector)
6963                        << TheCall->getDirectCallee()
6964                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6965                                       TheCall->getArg(1)->getEndLoc()));
6966     } else if (numElements != numResElements) {
6967       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6968       resType = Context.getVectorType(eltType, numResElements,
6969                                       VectorType::GenericVector);
6970     }
6971   }
6972 
6973   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6974     if (TheCall->getArg(i)->isTypeDependent() ||
6975         TheCall->getArg(i)->isValueDependent())
6976       continue;
6977 
6978     Optional<llvm::APSInt> Result;
6979     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6980       return ExprError(Diag(TheCall->getBeginLoc(),
6981                             diag::err_shufflevector_nonconstant_argument)
6982                        << TheCall->getArg(i)->getSourceRange());
6983 
6984     // Allow -1 which will be translated to undef in the IR.
6985     if (Result->isSigned() && Result->isAllOnes())
6986       continue;
6987 
6988     if (Result->getActiveBits() > 64 ||
6989         Result->getZExtValue() >= numElements * 2)
6990       return ExprError(Diag(TheCall->getBeginLoc(),
6991                             diag::err_shufflevector_argument_too_large)
6992                        << TheCall->getArg(i)->getSourceRange());
6993   }
6994 
6995   SmallVector<Expr*, 32> exprs;
6996 
6997   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6998     exprs.push_back(TheCall->getArg(i));
6999     TheCall->setArg(i, nullptr);
7000   }
7001 
7002   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7003                                          TheCall->getCallee()->getBeginLoc(),
7004                                          TheCall->getRParenLoc());
7005 }
7006 
7007 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7008 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7009                                        SourceLocation BuiltinLoc,
7010                                        SourceLocation RParenLoc) {
7011   ExprValueKind VK = VK_PRValue;
7012   ExprObjectKind OK = OK_Ordinary;
7013   QualType DstTy = TInfo->getType();
7014   QualType SrcTy = E->getType();
7015 
7016   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7017     return ExprError(Diag(BuiltinLoc,
7018                           diag::err_convertvector_non_vector)
7019                      << E->getSourceRange());
7020   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7021     return ExprError(Diag(BuiltinLoc,
7022                           diag::err_convertvector_non_vector_type));
7023 
7024   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7025     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7026     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7027     if (SrcElts != DstElts)
7028       return ExprError(Diag(BuiltinLoc,
7029                             diag::err_convertvector_incompatible_vector)
7030                        << E->getSourceRange());
7031   }
7032 
7033   return new (Context)
7034       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7035 }
7036 
7037 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7038 // This is declared to take (const void*, ...) and can take two
7039 // optional constant int args.
7040 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7041   unsigned NumArgs = TheCall->getNumArgs();
7042 
7043   if (NumArgs > 3)
7044     return Diag(TheCall->getEndLoc(),
7045                 diag::err_typecheck_call_too_many_args_at_most)
7046            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7047 
7048   // Argument 0 is checked for us and the remaining arguments must be
7049   // constant integers.
7050   for (unsigned i = 1; i != NumArgs; ++i)
7051     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7052       return true;
7053 
7054   return false;
7055 }
7056 
7057 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7058 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7059   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7060     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7061            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7062   if (checkArgCount(*this, TheCall, 1))
7063     return true;
7064   Expr *Arg = TheCall->getArg(0);
7065   if (Arg->isInstantiationDependent())
7066     return false;
7067 
7068   QualType ArgTy = Arg->getType();
7069   if (!ArgTy->hasFloatingRepresentation())
7070     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7071            << ArgTy;
7072   if (Arg->isLValue()) {
7073     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7074     TheCall->setArg(0, FirstArg.get());
7075   }
7076   TheCall->setType(TheCall->getArg(0)->getType());
7077   return false;
7078 }
7079 
7080 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7081 // __assume does not evaluate its arguments, and should warn if its argument
7082 // has side effects.
7083 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7084   Expr *Arg = TheCall->getArg(0);
7085   if (Arg->isInstantiationDependent()) return false;
7086 
7087   if (Arg->HasSideEffects(Context))
7088     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7089         << Arg->getSourceRange()
7090         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7091 
7092   return false;
7093 }
7094 
7095 /// Handle __builtin_alloca_with_align. This is declared
7096 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7097 /// than 8.
7098 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7099   // The alignment must be a constant integer.
7100   Expr *Arg = TheCall->getArg(1);
7101 
7102   // We can't check the value of a dependent argument.
7103   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7104     if (const auto *UE =
7105             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7106       if (UE->getKind() == UETT_AlignOf ||
7107           UE->getKind() == UETT_PreferredAlignOf)
7108         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7109             << Arg->getSourceRange();
7110 
7111     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7112 
7113     if (!Result.isPowerOf2())
7114       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7115              << Arg->getSourceRange();
7116 
7117     if (Result < Context.getCharWidth())
7118       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7119              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7120 
7121     if (Result > std::numeric_limits<int32_t>::max())
7122       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7123              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7124   }
7125 
7126   return false;
7127 }
7128 
7129 /// Handle __builtin_assume_aligned. This is declared
7130 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7131 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7132   unsigned NumArgs = TheCall->getNumArgs();
7133 
7134   if (NumArgs > 3)
7135     return Diag(TheCall->getEndLoc(),
7136                 diag::err_typecheck_call_too_many_args_at_most)
7137            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7138 
7139   // The alignment must be a constant integer.
7140   Expr *Arg = TheCall->getArg(1);
7141 
7142   // We can't check the value of a dependent argument.
7143   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7144     llvm::APSInt Result;
7145     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7146       return true;
7147 
7148     if (!Result.isPowerOf2())
7149       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7150              << Arg->getSourceRange();
7151 
7152     if (Result > Sema::MaximumAlignment)
7153       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7154           << Arg->getSourceRange() << Sema::MaximumAlignment;
7155   }
7156 
7157   if (NumArgs > 2) {
7158     ExprResult Arg(TheCall->getArg(2));
7159     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7160       Context.getSizeType(), false);
7161     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7162     if (Arg.isInvalid()) return true;
7163     TheCall->setArg(2, Arg.get());
7164   }
7165 
7166   return false;
7167 }
7168 
7169 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7170   unsigned BuiltinID =
7171       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7172   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7173 
7174   unsigned NumArgs = TheCall->getNumArgs();
7175   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7176   if (NumArgs < NumRequiredArgs) {
7177     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7178            << 0 /* function call */ << NumRequiredArgs << NumArgs
7179            << TheCall->getSourceRange();
7180   }
7181   if (NumArgs >= NumRequiredArgs + 0x100) {
7182     return Diag(TheCall->getEndLoc(),
7183                 diag::err_typecheck_call_too_many_args_at_most)
7184            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7185            << TheCall->getSourceRange();
7186   }
7187   unsigned i = 0;
7188 
7189   // For formatting call, check buffer arg.
7190   if (!IsSizeCall) {
7191     ExprResult Arg(TheCall->getArg(i));
7192     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7193         Context, Context.VoidPtrTy, false);
7194     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7195     if (Arg.isInvalid())
7196       return true;
7197     TheCall->setArg(i, Arg.get());
7198     i++;
7199   }
7200 
7201   // Check string literal arg.
7202   unsigned FormatIdx = i;
7203   {
7204     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7205     if (Arg.isInvalid())
7206       return true;
7207     TheCall->setArg(i, Arg.get());
7208     i++;
7209   }
7210 
7211   // Make sure variadic args are scalar.
7212   unsigned FirstDataArg = i;
7213   while (i < NumArgs) {
7214     ExprResult Arg = DefaultVariadicArgumentPromotion(
7215         TheCall->getArg(i), VariadicFunction, nullptr);
7216     if (Arg.isInvalid())
7217       return true;
7218     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7219     if (ArgSize.getQuantity() >= 0x100) {
7220       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7221              << i << (int)ArgSize.getQuantity() << 0xff
7222              << TheCall->getSourceRange();
7223     }
7224     TheCall->setArg(i, Arg.get());
7225     i++;
7226   }
7227 
7228   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7229   // call to avoid duplicate diagnostics.
7230   if (!IsSizeCall) {
7231     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7232     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7233     bool Success = CheckFormatArguments(
7234         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7235         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7236         CheckedVarArgs);
7237     if (!Success)
7238       return true;
7239   }
7240 
7241   if (IsSizeCall) {
7242     TheCall->setType(Context.getSizeType());
7243   } else {
7244     TheCall->setType(Context.VoidPtrTy);
7245   }
7246   return false;
7247 }
7248 
7249 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7250 /// TheCall is a constant expression.
7251 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7252                                   llvm::APSInt &Result) {
7253   Expr *Arg = TheCall->getArg(ArgNum);
7254   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7255   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7256 
7257   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7258 
7259   Optional<llvm::APSInt> R;
7260   if (!(R = Arg->getIntegerConstantExpr(Context)))
7261     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7262            << FDecl->getDeclName() << Arg->getSourceRange();
7263   Result = *R;
7264   return false;
7265 }
7266 
7267 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7268 /// TheCall is a constant expression in the range [Low, High].
7269 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7270                                        int Low, int High, bool RangeIsError) {
7271   if (isConstantEvaluated())
7272     return false;
7273   llvm::APSInt Result;
7274 
7275   // We can't check the value of a dependent argument.
7276   Expr *Arg = TheCall->getArg(ArgNum);
7277   if (Arg->isTypeDependent() || Arg->isValueDependent())
7278     return false;
7279 
7280   // Check constant-ness first.
7281   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7282     return true;
7283 
7284   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7285     if (RangeIsError)
7286       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7287              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7288     else
7289       // Defer the warning until we know if the code will be emitted so that
7290       // dead code can ignore this.
7291       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7292                           PDiag(diag::warn_argument_invalid_range)
7293                               << toString(Result, 10) << Low << High
7294                               << Arg->getSourceRange());
7295   }
7296 
7297   return false;
7298 }
7299 
7300 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7301 /// TheCall is a constant expression is a multiple of Num..
7302 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7303                                           unsigned Num) {
7304   llvm::APSInt Result;
7305 
7306   // We can't check the value of a dependent argument.
7307   Expr *Arg = TheCall->getArg(ArgNum);
7308   if (Arg->isTypeDependent() || Arg->isValueDependent())
7309     return false;
7310 
7311   // Check constant-ness first.
7312   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7313     return true;
7314 
7315   if (Result.getSExtValue() % Num != 0)
7316     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7317            << Num << Arg->getSourceRange();
7318 
7319   return false;
7320 }
7321 
7322 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7323 /// constant expression representing a power of 2.
7324 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7325   llvm::APSInt Result;
7326 
7327   // We can't check the value of a dependent argument.
7328   Expr *Arg = TheCall->getArg(ArgNum);
7329   if (Arg->isTypeDependent() || Arg->isValueDependent())
7330     return false;
7331 
7332   // Check constant-ness first.
7333   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7334     return true;
7335 
7336   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7337   // and only if x is a power of 2.
7338   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7339     return false;
7340 
7341   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7342          << Arg->getSourceRange();
7343 }
7344 
7345 static bool IsShiftedByte(llvm::APSInt Value) {
7346   if (Value.isNegative())
7347     return false;
7348 
7349   // Check if it's a shifted byte, by shifting it down
7350   while (true) {
7351     // If the value fits in the bottom byte, the check passes.
7352     if (Value < 0x100)
7353       return true;
7354 
7355     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7356     // fails.
7357     if ((Value & 0xFF) != 0)
7358       return false;
7359 
7360     // If the bottom 8 bits are all 0, but something above that is nonzero,
7361     // then shifting the value right by 8 bits won't affect whether it's a
7362     // shifted byte or not. So do that, and go round again.
7363     Value >>= 8;
7364   }
7365 }
7366 
7367 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7368 /// a constant expression representing an arbitrary byte value shifted left by
7369 /// a multiple of 8 bits.
7370 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7371                                              unsigned ArgBits) {
7372   llvm::APSInt Result;
7373 
7374   // We can't check the value of a dependent argument.
7375   Expr *Arg = TheCall->getArg(ArgNum);
7376   if (Arg->isTypeDependent() || Arg->isValueDependent())
7377     return false;
7378 
7379   // Check constant-ness first.
7380   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7381     return true;
7382 
7383   // Truncate to the given size.
7384   Result = Result.getLoBits(ArgBits);
7385   Result.setIsUnsigned(true);
7386 
7387   if (IsShiftedByte(Result))
7388     return false;
7389 
7390   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7391          << Arg->getSourceRange();
7392 }
7393 
7394 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7395 /// TheCall is a constant expression representing either a shifted byte value,
7396 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7397 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7398 /// Arm MVE intrinsics.
7399 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7400                                                    int ArgNum,
7401                                                    unsigned ArgBits) {
7402   llvm::APSInt Result;
7403 
7404   // We can't check the value of a dependent argument.
7405   Expr *Arg = TheCall->getArg(ArgNum);
7406   if (Arg->isTypeDependent() || Arg->isValueDependent())
7407     return false;
7408 
7409   // Check constant-ness first.
7410   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7411     return true;
7412 
7413   // Truncate to the given size.
7414   Result = Result.getLoBits(ArgBits);
7415   Result.setIsUnsigned(true);
7416 
7417   // Check to see if it's in either of the required forms.
7418   if (IsShiftedByte(Result) ||
7419       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7420     return false;
7421 
7422   return Diag(TheCall->getBeginLoc(),
7423               diag::err_argument_not_shifted_byte_or_xxff)
7424          << Arg->getSourceRange();
7425 }
7426 
7427 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7428 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7429   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7430     if (checkArgCount(*this, TheCall, 2))
7431       return true;
7432     Expr *Arg0 = TheCall->getArg(0);
7433     Expr *Arg1 = TheCall->getArg(1);
7434 
7435     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7436     if (FirstArg.isInvalid())
7437       return true;
7438     QualType FirstArgType = FirstArg.get()->getType();
7439     if (!FirstArgType->isAnyPointerType())
7440       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7441                << "first" << FirstArgType << Arg0->getSourceRange();
7442     TheCall->setArg(0, FirstArg.get());
7443 
7444     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7445     if (SecArg.isInvalid())
7446       return true;
7447     QualType SecArgType = SecArg.get()->getType();
7448     if (!SecArgType->isIntegerType())
7449       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7450                << "second" << SecArgType << Arg1->getSourceRange();
7451 
7452     // Derive the return type from the pointer argument.
7453     TheCall->setType(FirstArgType);
7454     return false;
7455   }
7456 
7457   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7458     if (checkArgCount(*this, TheCall, 2))
7459       return true;
7460 
7461     Expr *Arg0 = TheCall->getArg(0);
7462     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7463     if (FirstArg.isInvalid())
7464       return true;
7465     QualType FirstArgType = FirstArg.get()->getType();
7466     if (!FirstArgType->isAnyPointerType())
7467       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7468                << "first" << FirstArgType << Arg0->getSourceRange();
7469     TheCall->setArg(0, FirstArg.get());
7470 
7471     // Derive the return type from the pointer argument.
7472     TheCall->setType(FirstArgType);
7473 
7474     // Second arg must be an constant in range [0,15]
7475     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7476   }
7477 
7478   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7479     if (checkArgCount(*this, TheCall, 2))
7480       return true;
7481     Expr *Arg0 = TheCall->getArg(0);
7482     Expr *Arg1 = TheCall->getArg(1);
7483 
7484     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7485     if (FirstArg.isInvalid())
7486       return true;
7487     QualType FirstArgType = FirstArg.get()->getType();
7488     if (!FirstArgType->isAnyPointerType())
7489       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7490                << "first" << FirstArgType << Arg0->getSourceRange();
7491 
7492     QualType SecArgType = Arg1->getType();
7493     if (!SecArgType->isIntegerType())
7494       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7495                << "second" << SecArgType << Arg1->getSourceRange();
7496     TheCall->setType(Context.IntTy);
7497     return false;
7498   }
7499 
7500   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7501       BuiltinID == AArch64::BI__builtin_arm_stg) {
7502     if (checkArgCount(*this, TheCall, 1))
7503       return true;
7504     Expr *Arg0 = TheCall->getArg(0);
7505     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7506     if (FirstArg.isInvalid())
7507       return true;
7508 
7509     QualType FirstArgType = FirstArg.get()->getType();
7510     if (!FirstArgType->isAnyPointerType())
7511       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7512                << "first" << FirstArgType << Arg0->getSourceRange();
7513     TheCall->setArg(0, FirstArg.get());
7514 
7515     // Derive the return type from the pointer argument.
7516     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7517       TheCall->setType(FirstArgType);
7518     return false;
7519   }
7520 
7521   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7522     Expr *ArgA = TheCall->getArg(0);
7523     Expr *ArgB = TheCall->getArg(1);
7524 
7525     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7526     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7527 
7528     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7529       return true;
7530 
7531     QualType ArgTypeA = ArgExprA.get()->getType();
7532     QualType ArgTypeB = ArgExprB.get()->getType();
7533 
7534     auto isNull = [&] (Expr *E) -> bool {
7535       return E->isNullPointerConstant(
7536                         Context, Expr::NPC_ValueDependentIsNotNull); };
7537 
7538     // argument should be either a pointer or null
7539     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7540       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7541         << "first" << ArgTypeA << ArgA->getSourceRange();
7542 
7543     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7544       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7545         << "second" << ArgTypeB << ArgB->getSourceRange();
7546 
7547     // Ensure Pointee types are compatible
7548     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7549         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7550       QualType pointeeA = ArgTypeA->getPointeeType();
7551       QualType pointeeB = ArgTypeB->getPointeeType();
7552       if (!Context.typesAreCompatible(
7553              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7554              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7555         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7556           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7557           << ArgB->getSourceRange();
7558       }
7559     }
7560 
7561     // at least one argument should be pointer type
7562     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7563       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7564         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7565 
7566     if (isNull(ArgA)) // adopt type of the other pointer
7567       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7568 
7569     if (isNull(ArgB))
7570       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7571 
7572     TheCall->setArg(0, ArgExprA.get());
7573     TheCall->setArg(1, ArgExprB.get());
7574     TheCall->setType(Context.LongLongTy);
7575     return false;
7576   }
7577   assert(false && "Unhandled ARM MTE intrinsic");
7578   return true;
7579 }
7580 
7581 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7582 /// TheCall is an ARM/AArch64 special register string literal.
7583 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7584                                     int ArgNum, unsigned ExpectedFieldNum,
7585                                     bool AllowName) {
7586   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7587                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7588                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7589                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7590                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7591                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7592   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7593                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7594                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7595                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7596                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7597                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7598   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7599 
7600   // We can't check the value of a dependent argument.
7601   Expr *Arg = TheCall->getArg(ArgNum);
7602   if (Arg->isTypeDependent() || Arg->isValueDependent())
7603     return false;
7604 
7605   // Check if the argument is a string literal.
7606   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7607     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7608            << Arg->getSourceRange();
7609 
7610   // Check the type of special register given.
7611   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7612   SmallVector<StringRef, 6> Fields;
7613   Reg.split(Fields, ":");
7614 
7615   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7616     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7617            << Arg->getSourceRange();
7618 
7619   // If the string is the name of a register then we cannot check that it is
7620   // valid here but if the string is of one the forms described in ACLE then we
7621   // can check that the supplied fields are integers and within the valid
7622   // ranges.
7623   if (Fields.size() > 1) {
7624     bool FiveFields = Fields.size() == 5;
7625 
7626     bool ValidString = true;
7627     if (IsARMBuiltin) {
7628       ValidString &= Fields[0].startswith_insensitive("cp") ||
7629                      Fields[0].startswith_insensitive("p");
7630       if (ValidString)
7631         Fields[0] = Fields[0].drop_front(
7632             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7633 
7634       ValidString &= Fields[2].startswith_insensitive("c");
7635       if (ValidString)
7636         Fields[2] = Fields[2].drop_front(1);
7637 
7638       if (FiveFields) {
7639         ValidString &= Fields[3].startswith_insensitive("c");
7640         if (ValidString)
7641           Fields[3] = Fields[3].drop_front(1);
7642       }
7643     }
7644 
7645     SmallVector<int, 5> Ranges;
7646     if (FiveFields)
7647       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7648     else
7649       Ranges.append({15, 7, 15});
7650 
7651     for (unsigned i=0; i<Fields.size(); ++i) {
7652       int IntField;
7653       ValidString &= !Fields[i].getAsInteger(10, IntField);
7654       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7655     }
7656 
7657     if (!ValidString)
7658       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7659              << Arg->getSourceRange();
7660   } else if (IsAArch64Builtin && Fields.size() == 1) {
7661     // If the register name is one of those that appear in the condition below
7662     // and the special register builtin being used is one of the write builtins,
7663     // then we require that the argument provided for writing to the register
7664     // is an integer constant expression. This is because it will be lowered to
7665     // an MSR (immediate) instruction, so we need to know the immediate at
7666     // compile time.
7667     if (TheCall->getNumArgs() != 2)
7668       return false;
7669 
7670     std::string RegLower = Reg.lower();
7671     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7672         RegLower != "pan" && RegLower != "uao")
7673       return false;
7674 
7675     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7676   }
7677 
7678   return false;
7679 }
7680 
7681 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7682 /// Emit an error and return true on failure; return false on success.
7683 /// TypeStr is a string containing the type descriptor of the value returned by
7684 /// the builtin and the descriptors of the expected type of the arguments.
7685 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7686                                  const char *TypeStr) {
7687 
7688   assert((TypeStr[0] != '\0') &&
7689          "Invalid types in PPC MMA builtin declaration");
7690 
7691   switch (BuiltinID) {
7692   default:
7693     // This function is called in CheckPPCBuiltinFunctionCall where the
7694     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7695     // we are isolating the pair vector memop builtins that can be used with mma
7696     // off so the default case is every builtin that requires mma and paired
7697     // vector memops.
7698     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7699                          diag::err_ppc_builtin_only_on_arch, "10") ||
7700         SemaFeatureCheck(*this, TheCall, "mma",
7701                          diag::err_ppc_builtin_only_on_arch, "10"))
7702       return true;
7703     break;
7704   case PPC::BI__builtin_vsx_lxvp:
7705   case PPC::BI__builtin_vsx_stxvp:
7706   case PPC::BI__builtin_vsx_assemble_pair:
7707   case PPC::BI__builtin_vsx_disassemble_pair:
7708     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7709                          diag::err_ppc_builtin_only_on_arch, "10"))
7710       return true;
7711     break;
7712   }
7713 
7714   unsigned Mask = 0;
7715   unsigned ArgNum = 0;
7716 
7717   // The first type in TypeStr is the type of the value returned by the
7718   // builtin. So we first read that type and change the type of TheCall.
7719   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7720   TheCall->setType(type);
7721 
7722   while (*TypeStr != '\0') {
7723     Mask = 0;
7724     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7725     if (ArgNum >= TheCall->getNumArgs()) {
7726       ArgNum++;
7727       break;
7728     }
7729 
7730     Expr *Arg = TheCall->getArg(ArgNum);
7731     QualType PassedType = Arg->getType();
7732     QualType StrippedRVType = PassedType.getCanonicalType();
7733 
7734     // Strip Restrict/Volatile qualifiers.
7735     if (StrippedRVType.isRestrictQualified() ||
7736         StrippedRVType.isVolatileQualified())
7737       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7738 
7739     // The only case where the argument type and expected type are allowed to
7740     // mismatch is if the argument type is a non-void pointer (or array) and
7741     // expected type is a void pointer.
7742     if (StrippedRVType != ExpectedType)
7743       if (!(ExpectedType->isVoidPointerType() &&
7744             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7745         return Diag(Arg->getBeginLoc(),
7746                     diag::err_typecheck_convert_incompatible)
7747                << PassedType << ExpectedType << 1 << 0 << 0;
7748 
7749     // If the value of the Mask is not 0, we have a constraint in the size of
7750     // the integer argument so here we ensure the argument is a constant that
7751     // is in the valid range.
7752     if (Mask != 0 &&
7753         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7754       return true;
7755 
7756     ArgNum++;
7757   }
7758 
7759   // In case we exited early from the previous loop, there are other types to
7760   // read from TypeStr. So we need to read them all to ensure we have the right
7761   // number of arguments in TheCall and if it is not the case, to display a
7762   // better error message.
7763   while (*TypeStr != '\0') {
7764     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7765     ArgNum++;
7766   }
7767   if (checkArgCount(*this, TheCall, ArgNum))
7768     return true;
7769 
7770   return false;
7771 }
7772 
7773 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7774 /// This checks that the target supports __builtin_longjmp and
7775 /// that val is a constant 1.
7776 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7777   if (!Context.getTargetInfo().hasSjLjLowering())
7778     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7779            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7780 
7781   Expr *Arg = TheCall->getArg(1);
7782   llvm::APSInt Result;
7783 
7784   // TODO: This is less than ideal. Overload this to take a value.
7785   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7786     return true;
7787 
7788   if (Result != 1)
7789     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7790            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7791 
7792   return false;
7793 }
7794 
7795 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7796 /// This checks that the target supports __builtin_setjmp.
7797 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7798   if (!Context.getTargetInfo().hasSjLjLowering())
7799     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7800            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7801   return false;
7802 }
7803 
7804 namespace {
7805 
7806 class UncoveredArgHandler {
7807   enum { Unknown = -1, AllCovered = -2 };
7808 
7809   signed FirstUncoveredArg = Unknown;
7810   SmallVector<const Expr *, 4> DiagnosticExprs;
7811 
7812 public:
7813   UncoveredArgHandler() = default;
7814 
7815   bool hasUncoveredArg() const {
7816     return (FirstUncoveredArg >= 0);
7817   }
7818 
7819   unsigned getUncoveredArg() const {
7820     assert(hasUncoveredArg() && "no uncovered argument");
7821     return FirstUncoveredArg;
7822   }
7823 
7824   void setAllCovered() {
7825     // A string has been found with all arguments covered, so clear out
7826     // the diagnostics.
7827     DiagnosticExprs.clear();
7828     FirstUncoveredArg = AllCovered;
7829   }
7830 
7831   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7832     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7833 
7834     // Don't update if a previous string covers all arguments.
7835     if (FirstUncoveredArg == AllCovered)
7836       return;
7837 
7838     // UncoveredArgHandler tracks the highest uncovered argument index
7839     // and with it all the strings that match this index.
7840     if (NewFirstUncoveredArg == FirstUncoveredArg)
7841       DiagnosticExprs.push_back(StrExpr);
7842     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7843       DiagnosticExprs.clear();
7844       DiagnosticExprs.push_back(StrExpr);
7845       FirstUncoveredArg = NewFirstUncoveredArg;
7846     }
7847   }
7848 
7849   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7850 };
7851 
7852 enum StringLiteralCheckType {
7853   SLCT_NotALiteral,
7854   SLCT_UncheckedLiteral,
7855   SLCT_CheckedLiteral
7856 };
7857 
7858 } // namespace
7859 
7860 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7861                                      BinaryOperatorKind BinOpKind,
7862                                      bool AddendIsRight) {
7863   unsigned BitWidth = Offset.getBitWidth();
7864   unsigned AddendBitWidth = Addend.getBitWidth();
7865   // There might be negative interim results.
7866   if (Addend.isUnsigned()) {
7867     Addend = Addend.zext(++AddendBitWidth);
7868     Addend.setIsSigned(true);
7869   }
7870   // Adjust the bit width of the APSInts.
7871   if (AddendBitWidth > BitWidth) {
7872     Offset = Offset.sext(AddendBitWidth);
7873     BitWidth = AddendBitWidth;
7874   } else if (BitWidth > AddendBitWidth) {
7875     Addend = Addend.sext(BitWidth);
7876   }
7877 
7878   bool Ov = false;
7879   llvm::APSInt ResOffset = Offset;
7880   if (BinOpKind == BO_Add)
7881     ResOffset = Offset.sadd_ov(Addend, Ov);
7882   else {
7883     assert(AddendIsRight && BinOpKind == BO_Sub &&
7884            "operator must be add or sub with addend on the right");
7885     ResOffset = Offset.ssub_ov(Addend, Ov);
7886   }
7887 
7888   // We add an offset to a pointer here so we should support an offset as big as
7889   // possible.
7890   if (Ov) {
7891     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7892            "index (intermediate) result too big");
7893     Offset = Offset.sext(2 * BitWidth);
7894     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7895     return;
7896   }
7897 
7898   Offset = ResOffset;
7899 }
7900 
7901 namespace {
7902 
7903 // This is a wrapper class around StringLiteral to support offsetted string
7904 // literals as format strings. It takes the offset into account when returning
7905 // the string and its length or the source locations to display notes correctly.
7906 class FormatStringLiteral {
7907   const StringLiteral *FExpr;
7908   int64_t Offset;
7909 
7910  public:
7911   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7912       : FExpr(fexpr), Offset(Offset) {}
7913 
7914   StringRef getString() const {
7915     return FExpr->getString().drop_front(Offset);
7916   }
7917 
7918   unsigned getByteLength() const {
7919     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7920   }
7921 
7922   unsigned getLength() const { return FExpr->getLength() - Offset; }
7923   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7924 
7925   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7926 
7927   QualType getType() const { return FExpr->getType(); }
7928 
7929   bool isAscii() const { return FExpr->isAscii(); }
7930   bool isWide() const { return FExpr->isWide(); }
7931   bool isUTF8() const { return FExpr->isUTF8(); }
7932   bool isUTF16() const { return FExpr->isUTF16(); }
7933   bool isUTF32() const { return FExpr->isUTF32(); }
7934   bool isPascal() const { return FExpr->isPascal(); }
7935 
7936   SourceLocation getLocationOfByte(
7937       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7938       const TargetInfo &Target, unsigned *StartToken = nullptr,
7939       unsigned *StartTokenByteOffset = nullptr) const {
7940     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7941                                     StartToken, StartTokenByteOffset);
7942   }
7943 
7944   SourceLocation getBeginLoc() const LLVM_READONLY {
7945     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7946   }
7947 
7948   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7949 };
7950 
7951 }  // namespace
7952 
7953 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7954                               const Expr *OrigFormatExpr,
7955                               ArrayRef<const Expr *> Args,
7956                               bool HasVAListArg, unsigned format_idx,
7957                               unsigned firstDataArg,
7958                               Sema::FormatStringType Type,
7959                               bool inFunctionCall,
7960                               Sema::VariadicCallType CallType,
7961                               llvm::SmallBitVector &CheckedVarArgs,
7962                               UncoveredArgHandler &UncoveredArg,
7963                               bool IgnoreStringsWithoutSpecifiers);
7964 
7965 // Determine if an expression is a string literal or constant string.
7966 // If this function returns false on the arguments to a function expecting a
7967 // format string, we will usually need to emit a warning.
7968 // True string literals are then checked by CheckFormatString.
7969 static StringLiteralCheckType
7970 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7971                       bool HasVAListArg, unsigned format_idx,
7972                       unsigned firstDataArg, Sema::FormatStringType Type,
7973                       Sema::VariadicCallType CallType, bool InFunctionCall,
7974                       llvm::SmallBitVector &CheckedVarArgs,
7975                       UncoveredArgHandler &UncoveredArg,
7976                       llvm::APSInt Offset,
7977                       bool IgnoreStringsWithoutSpecifiers = false) {
7978   if (S.isConstantEvaluated())
7979     return SLCT_NotALiteral;
7980  tryAgain:
7981   assert(Offset.isSigned() && "invalid offset");
7982 
7983   if (E->isTypeDependent() || E->isValueDependent())
7984     return SLCT_NotALiteral;
7985 
7986   E = E->IgnoreParenCasts();
7987 
7988   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7989     // Technically -Wformat-nonliteral does not warn about this case.
7990     // The behavior of printf and friends in this case is implementation
7991     // dependent.  Ideally if the format string cannot be null then
7992     // it should have a 'nonnull' attribute in the function prototype.
7993     return SLCT_UncheckedLiteral;
7994 
7995   switch (E->getStmtClass()) {
7996   case Stmt::BinaryConditionalOperatorClass:
7997   case Stmt::ConditionalOperatorClass: {
7998     // The expression is a literal if both sub-expressions were, and it was
7999     // completely checked only if both sub-expressions were checked.
8000     const AbstractConditionalOperator *C =
8001         cast<AbstractConditionalOperator>(E);
8002 
8003     // Determine whether it is necessary to check both sub-expressions, for
8004     // example, because the condition expression is a constant that can be
8005     // evaluated at compile time.
8006     bool CheckLeft = true, CheckRight = true;
8007 
8008     bool Cond;
8009     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8010                                                  S.isConstantEvaluated())) {
8011       if (Cond)
8012         CheckRight = false;
8013       else
8014         CheckLeft = false;
8015     }
8016 
8017     // We need to maintain the offsets for the right and the left hand side
8018     // separately to check if every possible indexed expression is a valid
8019     // string literal. They might have different offsets for different string
8020     // literals in the end.
8021     StringLiteralCheckType Left;
8022     if (!CheckLeft)
8023       Left = SLCT_UncheckedLiteral;
8024     else {
8025       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8026                                    HasVAListArg, format_idx, firstDataArg,
8027                                    Type, CallType, InFunctionCall,
8028                                    CheckedVarArgs, UncoveredArg, Offset,
8029                                    IgnoreStringsWithoutSpecifiers);
8030       if (Left == SLCT_NotALiteral || !CheckRight) {
8031         return Left;
8032       }
8033     }
8034 
8035     StringLiteralCheckType Right = checkFormatStringExpr(
8036         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8037         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8038         IgnoreStringsWithoutSpecifiers);
8039 
8040     return (CheckLeft && Left < Right) ? Left : Right;
8041   }
8042 
8043   case Stmt::ImplicitCastExprClass:
8044     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8045     goto tryAgain;
8046 
8047   case Stmt::OpaqueValueExprClass:
8048     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8049       E = src;
8050       goto tryAgain;
8051     }
8052     return SLCT_NotALiteral;
8053 
8054   case Stmt::PredefinedExprClass:
8055     // While __func__, etc., are technically not string literals, they
8056     // cannot contain format specifiers and thus are not a security
8057     // liability.
8058     return SLCT_UncheckedLiteral;
8059 
8060   case Stmt::DeclRefExprClass: {
8061     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8062 
8063     // As an exception, do not flag errors for variables binding to
8064     // const string literals.
8065     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8066       bool isConstant = false;
8067       QualType T = DR->getType();
8068 
8069       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8070         isConstant = AT->getElementType().isConstant(S.Context);
8071       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8072         isConstant = T.isConstant(S.Context) &&
8073                      PT->getPointeeType().isConstant(S.Context);
8074       } else if (T->isObjCObjectPointerType()) {
8075         // In ObjC, there is usually no "const ObjectPointer" type,
8076         // so don't check if the pointee type is constant.
8077         isConstant = T.isConstant(S.Context);
8078       }
8079 
8080       if (isConstant) {
8081         if (const Expr *Init = VD->getAnyInitializer()) {
8082           // Look through initializers like const char c[] = { "foo" }
8083           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8084             if (InitList->isStringLiteralInit())
8085               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8086           }
8087           return checkFormatStringExpr(S, Init, Args,
8088                                        HasVAListArg, format_idx,
8089                                        firstDataArg, Type, CallType,
8090                                        /*InFunctionCall*/ false, CheckedVarArgs,
8091                                        UncoveredArg, Offset);
8092         }
8093       }
8094 
8095       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8096       // special check to see if the format string is a function parameter
8097       // of the function calling the printf function.  If the function
8098       // has an attribute indicating it is a printf-like function, then we
8099       // should suppress warnings concerning non-literals being used in a call
8100       // to a vprintf function.  For example:
8101       //
8102       // void
8103       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8104       //      va_list ap;
8105       //      va_start(ap, fmt);
8106       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8107       //      ...
8108       // }
8109       if (HasVAListArg) {
8110         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8111           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8112             int PVIndex = PV->getFunctionScopeIndex() + 1;
8113             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8114               // adjust for implicit parameter
8115               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8116                 if (MD->isInstance())
8117                   ++PVIndex;
8118               // We also check if the formats are compatible.
8119               // We can't pass a 'scanf' string to a 'printf' function.
8120               if (PVIndex == PVFormat->getFormatIdx() &&
8121                   Type == S.GetFormatStringType(PVFormat))
8122                 return SLCT_UncheckedLiteral;
8123             }
8124           }
8125         }
8126       }
8127     }
8128 
8129     return SLCT_NotALiteral;
8130   }
8131 
8132   case Stmt::CallExprClass:
8133   case Stmt::CXXMemberCallExprClass: {
8134     const CallExpr *CE = cast<CallExpr>(E);
8135     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8136       bool IsFirst = true;
8137       StringLiteralCheckType CommonResult;
8138       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8139         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8140         StringLiteralCheckType Result = checkFormatStringExpr(
8141             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8142             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8143             IgnoreStringsWithoutSpecifiers);
8144         if (IsFirst) {
8145           CommonResult = Result;
8146           IsFirst = false;
8147         }
8148       }
8149       if (!IsFirst)
8150         return CommonResult;
8151 
8152       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8153         unsigned BuiltinID = FD->getBuiltinID();
8154         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8155             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8156           const Expr *Arg = CE->getArg(0);
8157           return checkFormatStringExpr(S, Arg, Args,
8158                                        HasVAListArg, format_idx,
8159                                        firstDataArg, Type, CallType,
8160                                        InFunctionCall, CheckedVarArgs,
8161                                        UncoveredArg, Offset,
8162                                        IgnoreStringsWithoutSpecifiers);
8163         }
8164       }
8165     }
8166 
8167     return SLCT_NotALiteral;
8168   }
8169   case Stmt::ObjCMessageExprClass: {
8170     const auto *ME = cast<ObjCMessageExpr>(E);
8171     if (const auto *MD = ME->getMethodDecl()) {
8172       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8173         // As a special case heuristic, if we're using the method -[NSBundle
8174         // localizedStringForKey:value:table:], ignore any key strings that lack
8175         // format specifiers. The idea is that if the key doesn't have any
8176         // format specifiers then its probably just a key to map to the
8177         // localized strings. If it does have format specifiers though, then its
8178         // likely that the text of the key is the format string in the
8179         // programmer's language, and should be checked.
8180         const ObjCInterfaceDecl *IFace;
8181         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8182             IFace->getIdentifier()->isStr("NSBundle") &&
8183             MD->getSelector().isKeywordSelector(
8184                 {"localizedStringForKey", "value", "table"})) {
8185           IgnoreStringsWithoutSpecifiers = true;
8186         }
8187 
8188         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8189         return checkFormatStringExpr(
8190             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8191             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8192             IgnoreStringsWithoutSpecifiers);
8193       }
8194     }
8195 
8196     return SLCT_NotALiteral;
8197   }
8198   case Stmt::ObjCStringLiteralClass:
8199   case Stmt::StringLiteralClass: {
8200     const StringLiteral *StrE = nullptr;
8201 
8202     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8203       StrE = ObjCFExpr->getString();
8204     else
8205       StrE = cast<StringLiteral>(E);
8206 
8207     if (StrE) {
8208       if (Offset.isNegative() || Offset > StrE->getLength()) {
8209         // TODO: It would be better to have an explicit warning for out of
8210         // bounds literals.
8211         return SLCT_NotALiteral;
8212       }
8213       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8214       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8215                         firstDataArg, Type, InFunctionCall, CallType,
8216                         CheckedVarArgs, UncoveredArg,
8217                         IgnoreStringsWithoutSpecifiers);
8218       return SLCT_CheckedLiteral;
8219     }
8220 
8221     return SLCT_NotALiteral;
8222   }
8223   case Stmt::BinaryOperatorClass: {
8224     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8225 
8226     // A string literal + an int offset is still a string literal.
8227     if (BinOp->isAdditiveOp()) {
8228       Expr::EvalResult LResult, RResult;
8229 
8230       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8231           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8232       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8233           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8234 
8235       if (LIsInt != RIsInt) {
8236         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8237 
8238         if (LIsInt) {
8239           if (BinOpKind == BO_Add) {
8240             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8241             E = BinOp->getRHS();
8242             goto tryAgain;
8243           }
8244         } else {
8245           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8246           E = BinOp->getLHS();
8247           goto tryAgain;
8248         }
8249       }
8250     }
8251 
8252     return SLCT_NotALiteral;
8253   }
8254   case Stmt::UnaryOperatorClass: {
8255     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8256     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8257     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8258       Expr::EvalResult IndexResult;
8259       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8260                                        Expr::SE_NoSideEffects,
8261                                        S.isConstantEvaluated())) {
8262         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8263                    /*RHS is int*/ true);
8264         E = ASE->getBase();
8265         goto tryAgain;
8266       }
8267     }
8268 
8269     return SLCT_NotALiteral;
8270   }
8271 
8272   default:
8273     return SLCT_NotALiteral;
8274   }
8275 }
8276 
8277 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8278   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8279       .Case("scanf", FST_Scanf)
8280       .Cases("printf", "printf0", FST_Printf)
8281       .Cases("NSString", "CFString", FST_NSString)
8282       .Case("strftime", FST_Strftime)
8283       .Case("strfmon", FST_Strfmon)
8284       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8285       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8286       .Case("os_trace", FST_OSLog)
8287       .Case("os_log", FST_OSLog)
8288       .Default(FST_Unknown);
8289 }
8290 
8291 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8292 /// functions) for correct use of format strings.
8293 /// Returns true if a format string has been fully checked.
8294 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8295                                 ArrayRef<const Expr *> Args,
8296                                 bool IsCXXMember,
8297                                 VariadicCallType CallType,
8298                                 SourceLocation Loc, SourceRange Range,
8299                                 llvm::SmallBitVector &CheckedVarArgs) {
8300   FormatStringInfo FSI;
8301   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8302     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8303                                 FSI.FirstDataArg, GetFormatStringType(Format),
8304                                 CallType, Loc, Range, CheckedVarArgs);
8305   return false;
8306 }
8307 
8308 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8309                                 bool HasVAListArg, unsigned format_idx,
8310                                 unsigned firstDataArg, FormatStringType Type,
8311                                 VariadicCallType CallType,
8312                                 SourceLocation Loc, SourceRange Range,
8313                                 llvm::SmallBitVector &CheckedVarArgs) {
8314   // CHECK: printf/scanf-like function is called with no format string.
8315   if (format_idx >= Args.size()) {
8316     Diag(Loc, diag::warn_missing_format_string) << Range;
8317     return false;
8318   }
8319 
8320   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8321 
8322   // CHECK: format string is not a string literal.
8323   //
8324   // Dynamically generated format strings are difficult to
8325   // automatically vet at compile time.  Requiring that format strings
8326   // are string literals: (1) permits the checking of format strings by
8327   // the compiler and thereby (2) can practically remove the source of
8328   // many format string exploits.
8329 
8330   // Format string can be either ObjC string (e.g. @"%d") or
8331   // C string (e.g. "%d")
8332   // ObjC string uses the same format specifiers as C string, so we can use
8333   // the same format string checking logic for both ObjC and C strings.
8334   UncoveredArgHandler UncoveredArg;
8335   StringLiteralCheckType CT =
8336       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8337                             format_idx, firstDataArg, Type, CallType,
8338                             /*IsFunctionCall*/ true, CheckedVarArgs,
8339                             UncoveredArg,
8340                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8341 
8342   // Generate a diagnostic where an uncovered argument is detected.
8343   if (UncoveredArg.hasUncoveredArg()) {
8344     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8345     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8346     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8347   }
8348 
8349   if (CT != SLCT_NotALiteral)
8350     // Literal format string found, check done!
8351     return CT == SLCT_CheckedLiteral;
8352 
8353   // Strftime is particular as it always uses a single 'time' argument,
8354   // so it is safe to pass a non-literal string.
8355   if (Type == FST_Strftime)
8356     return false;
8357 
8358   // Do not emit diag when the string param is a macro expansion and the
8359   // format is either NSString or CFString. This is a hack to prevent
8360   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8361   // which are usually used in place of NS and CF string literals.
8362   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8363   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8364     return false;
8365 
8366   // If there are no arguments specified, warn with -Wformat-security, otherwise
8367   // warn only with -Wformat-nonliteral.
8368   if (Args.size() == firstDataArg) {
8369     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8370       << OrigFormatExpr->getSourceRange();
8371     switch (Type) {
8372     default:
8373       break;
8374     case FST_Kprintf:
8375     case FST_FreeBSDKPrintf:
8376     case FST_Printf:
8377       Diag(FormatLoc, diag::note_format_security_fixit)
8378         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8379       break;
8380     case FST_NSString:
8381       Diag(FormatLoc, diag::note_format_security_fixit)
8382         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8383       break;
8384     }
8385   } else {
8386     Diag(FormatLoc, diag::warn_format_nonliteral)
8387       << OrigFormatExpr->getSourceRange();
8388   }
8389   return false;
8390 }
8391 
8392 namespace {
8393 
8394 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8395 protected:
8396   Sema &S;
8397   const FormatStringLiteral *FExpr;
8398   const Expr *OrigFormatExpr;
8399   const Sema::FormatStringType FSType;
8400   const unsigned FirstDataArg;
8401   const unsigned NumDataArgs;
8402   const char *Beg; // Start of format string.
8403   const bool HasVAListArg;
8404   ArrayRef<const Expr *> Args;
8405   unsigned FormatIdx;
8406   llvm::SmallBitVector CoveredArgs;
8407   bool usesPositionalArgs = false;
8408   bool atFirstArg = true;
8409   bool inFunctionCall;
8410   Sema::VariadicCallType CallType;
8411   llvm::SmallBitVector &CheckedVarArgs;
8412   UncoveredArgHandler &UncoveredArg;
8413 
8414 public:
8415   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8416                      const Expr *origFormatExpr,
8417                      const Sema::FormatStringType type, unsigned firstDataArg,
8418                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8419                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8420                      bool inFunctionCall, Sema::VariadicCallType callType,
8421                      llvm::SmallBitVector &CheckedVarArgs,
8422                      UncoveredArgHandler &UncoveredArg)
8423       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8424         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8425         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8426         inFunctionCall(inFunctionCall), CallType(callType),
8427         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8428     CoveredArgs.resize(numDataArgs);
8429     CoveredArgs.reset();
8430   }
8431 
8432   void DoneProcessing();
8433 
8434   void HandleIncompleteSpecifier(const char *startSpecifier,
8435                                  unsigned specifierLen) override;
8436 
8437   void HandleInvalidLengthModifier(
8438                            const analyze_format_string::FormatSpecifier &FS,
8439                            const analyze_format_string::ConversionSpecifier &CS,
8440                            const char *startSpecifier, unsigned specifierLen,
8441                            unsigned DiagID);
8442 
8443   void HandleNonStandardLengthModifier(
8444                     const analyze_format_string::FormatSpecifier &FS,
8445                     const char *startSpecifier, unsigned specifierLen);
8446 
8447   void HandleNonStandardConversionSpecifier(
8448                     const analyze_format_string::ConversionSpecifier &CS,
8449                     const char *startSpecifier, unsigned specifierLen);
8450 
8451   void HandlePosition(const char *startPos, unsigned posLen) override;
8452 
8453   void HandleInvalidPosition(const char *startSpecifier,
8454                              unsigned specifierLen,
8455                              analyze_format_string::PositionContext p) override;
8456 
8457   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8458 
8459   void HandleNullChar(const char *nullCharacter) override;
8460 
8461   template <typename Range>
8462   static void
8463   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8464                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8465                        bool IsStringLocation, Range StringRange,
8466                        ArrayRef<FixItHint> Fixit = None);
8467 
8468 protected:
8469   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8470                                         const char *startSpec,
8471                                         unsigned specifierLen,
8472                                         const char *csStart, unsigned csLen);
8473 
8474   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8475                                          const char *startSpec,
8476                                          unsigned specifierLen);
8477 
8478   SourceRange getFormatStringRange();
8479   CharSourceRange getSpecifierRange(const char *startSpecifier,
8480                                     unsigned specifierLen);
8481   SourceLocation getLocationOfByte(const char *x);
8482 
8483   const Expr *getDataArg(unsigned i) const;
8484 
8485   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8486                     const analyze_format_string::ConversionSpecifier &CS,
8487                     const char *startSpecifier, unsigned specifierLen,
8488                     unsigned argIndex);
8489 
8490   template <typename Range>
8491   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8492                             bool IsStringLocation, Range StringRange,
8493                             ArrayRef<FixItHint> Fixit = None);
8494 };
8495 
8496 } // namespace
8497 
8498 SourceRange CheckFormatHandler::getFormatStringRange() {
8499   return OrigFormatExpr->getSourceRange();
8500 }
8501 
8502 CharSourceRange CheckFormatHandler::
8503 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8504   SourceLocation Start = getLocationOfByte(startSpecifier);
8505   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8506 
8507   // Advance the end SourceLocation by one due to half-open ranges.
8508   End = End.getLocWithOffset(1);
8509 
8510   return CharSourceRange::getCharRange(Start, End);
8511 }
8512 
8513 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8514   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8515                                   S.getLangOpts(), S.Context.getTargetInfo());
8516 }
8517 
8518 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8519                                                    unsigned specifierLen){
8520   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8521                        getLocationOfByte(startSpecifier),
8522                        /*IsStringLocation*/true,
8523                        getSpecifierRange(startSpecifier, specifierLen));
8524 }
8525 
8526 void CheckFormatHandler::HandleInvalidLengthModifier(
8527     const analyze_format_string::FormatSpecifier &FS,
8528     const analyze_format_string::ConversionSpecifier &CS,
8529     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8530   using namespace analyze_format_string;
8531 
8532   const LengthModifier &LM = FS.getLengthModifier();
8533   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8534 
8535   // See if we know how to fix this length modifier.
8536   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8537   if (FixedLM) {
8538     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8539                          getLocationOfByte(LM.getStart()),
8540                          /*IsStringLocation*/true,
8541                          getSpecifierRange(startSpecifier, specifierLen));
8542 
8543     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8544       << FixedLM->toString()
8545       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8546 
8547   } else {
8548     FixItHint Hint;
8549     if (DiagID == diag::warn_format_nonsensical_length)
8550       Hint = FixItHint::CreateRemoval(LMRange);
8551 
8552     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8553                          getLocationOfByte(LM.getStart()),
8554                          /*IsStringLocation*/true,
8555                          getSpecifierRange(startSpecifier, specifierLen),
8556                          Hint);
8557   }
8558 }
8559 
8560 void CheckFormatHandler::HandleNonStandardLengthModifier(
8561     const analyze_format_string::FormatSpecifier &FS,
8562     const char *startSpecifier, unsigned specifierLen) {
8563   using namespace analyze_format_string;
8564 
8565   const LengthModifier &LM = FS.getLengthModifier();
8566   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8567 
8568   // See if we know how to fix this length modifier.
8569   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8570   if (FixedLM) {
8571     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8572                            << LM.toString() << 0,
8573                          getLocationOfByte(LM.getStart()),
8574                          /*IsStringLocation*/true,
8575                          getSpecifierRange(startSpecifier, specifierLen));
8576 
8577     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8578       << FixedLM->toString()
8579       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8580 
8581   } else {
8582     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8583                            << LM.toString() << 0,
8584                          getLocationOfByte(LM.getStart()),
8585                          /*IsStringLocation*/true,
8586                          getSpecifierRange(startSpecifier, specifierLen));
8587   }
8588 }
8589 
8590 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8591     const analyze_format_string::ConversionSpecifier &CS,
8592     const char *startSpecifier, unsigned specifierLen) {
8593   using namespace analyze_format_string;
8594 
8595   // See if we know how to fix this conversion specifier.
8596   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8597   if (FixedCS) {
8598     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8599                           << CS.toString() << /*conversion specifier*/1,
8600                          getLocationOfByte(CS.getStart()),
8601                          /*IsStringLocation*/true,
8602                          getSpecifierRange(startSpecifier, specifierLen));
8603 
8604     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8605     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8606       << FixedCS->toString()
8607       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8608   } else {
8609     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8610                           << CS.toString() << /*conversion specifier*/1,
8611                          getLocationOfByte(CS.getStart()),
8612                          /*IsStringLocation*/true,
8613                          getSpecifierRange(startSpecifier, specifierLen));
8614   }
8615 }
8616 
8617 void CheckFormatHandler::HandlePosition(const char *startPos,
8618                                         unsigned posLen) {
8619   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8620                                getLocationOfByte(startPos),
8621                                /*IsStringLocation*/true,
8622                                getSpecifierRange(startPos, posLen));
8623 }
8624 
8625 void
8626 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8627                                      analyze_format_string::PositionContext p) {
8628   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8629                          << (unsigned) p,
8630                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8631                        getSpecifierRange(startPos, posLen));
8632 }
8633 
8634 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8635                                             unsigned posLen) {
8636   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8637                                getLocationOfByte(startPos),
8638                                /*IsStringLocation*/true,
8639                                getSpecifierRange(startPos, posLen));
8640 }
8641 
8642 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8643   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8644     // The presence of a null character is likely an error.
8645     EmitFormatDiagnostic(
8646       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8647       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8648       getFormatStringRange());
8649   }
8650 }
8651 
8652 // Note that this may return NULL if there was an error parsing or building
8653 // one of the argument expressions.
8654 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8655   return Args[FirstDataArg + i];
8656 }
8657 
8658 void CheckFormatHandler::DoneProcessing() {
8659   // Does the number of data arguments exceed the number of
8660   // format conversions in the format string?
8661   if (!HasVAListArg) {
8662       // Find any arguments that weren't covered.
8663     CoveredArgs.flip();
8664     signed notCoveredArg = CoveredArgs.find_first();
8665     if (notCoveredArg >= 0) {
8666       assert((unsigned)notCoveredArg < NumDataArgs);
8667       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8668     } else {
8669       UncoveredArg.setAllCovered();
8670     }
8671   }
8672 }
8673 
8674 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8675                                    const Expr *ArgExpr) {
8676   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8677          "Invalid state");
8678 
8679   if (!ArgExpr)
8680     return;
8681 
8682   SourceLocation Loc = ArgExpr->getBeginLoc();
8683 
8684   if (S.getSourceManager().isInSystemMacro(Loc))
8685     return;
8686 
8687   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8688   for (auto E : DiagnosticExprs)
8689     PDiag << E->getSourceRange();
8690 
8691   CheckFormatHandler::EmitFormatDiagnostic(
8692                                   S, IsFunctionCall, DiagnosticExprs[0],
8693                                   PDiag, Loc, /*IsStringLocation*/false,
8694                                   DiagnosticExprs[0]->getSourceRange());
8695 }
8696 
8697 bool
8698 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8699                                                      SourceLocation Loc,
8700                                                      const char *startSpec,
8701                                                      unsigned specifierLen,
8702                                                      const char *csStart,
8703                                                      unsigned csLen) {
8704   bool keepGoing = true;
8705   if (argIndex < NumDataArgs) {
8706     // Consider the argument coverered, even though the specifier doesn't
8707     // make sense.
8708     CoveredArgs.set(argIndex);
8709   }
8710   else {
8711     // If argIndex exceeds the number of data arguments we
8712     // don't issue a warning because that is just a cascade of warnings (and
8713     // they may have intended '%%' anyway). We don't want to continue processing
8714     // the format string after this point, however, as we will like just get
8715     // gibberish when trying to match arguments.
8716     keepGoing = false;
8717   }
8718 
8719   StringRef Specifier(csStart, csLen);
8720 
8721   // If the specifier in non-printable, it could be the first byte of a UTF-8
8722   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8723   // hex value.
8724   std::string CodePointStr;
8725   if (!llvm::sys::locale::isPrint(*csStart)) {
8726     llvm::UTF32 CodePoint;
8727     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8728     const llvm::UTF8 *E =
8729         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8730     llvm::ConversionResult Result =
8731         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8732 
8733     if (Result != llvm::conversionOK) {
8734       unsigned char FirstChar = *csStart;
8735       CodePoint = (llvm::UTF32)FirstChar;
8736     }
8737 
8738     llvm::raw_string_ostream OS(CodePointStr);
8739     if (CodePoint < 256)
8740       OS << "\\x" << llvm::format("%02x", CodePoint);
8741     else if (CodePoint <= 0xFFFF)
8742       OS << "\\u" << llvm::format("%04x", CodePoint);
8743     else
8744       OS << "\\U" << llvm::format("%08x", CodePoint);
8745     OS.flush();
8746     Specifier = CodePointStr;
8747   }
8748 
8749   EmitFormatDiagnostic(
8750       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8751       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8752 
8753   return keepGoing;
8754 }
8755 
8756 void
8757 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8758                                                       const char *startSpec,
8759                                                       unsigned specifierLen) {
8760   EmitFormatDiagnostic(
8761     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8762     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8763 }
8764 
8765 bool
8766 CheckFormatHandler::CheckNumArgs(
8767   const analyze_format_string::FormatSpecifier &FS,
8768   const analyze_format_string::ConversionSpecifier &CS,
8769   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8770 
8771   if (argIndex >= NumDataArgs) {
8772     PartialDiagnostic PDiag = FS.usesPositionalArg()
8773       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8774            << (argIndex+1) << NumDataArgs)
8775       : S.PDiag(diag::warn_printf_insufficient_data_args);
8776     EmitFormatDiagnostic(
8777       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8778       getSpecifierRange(startSpecifier, specifierLen));
8779 
8780     // Since more arguments than conversion tokens are given, by extension
8781     // all arguments are covered, so mark this as so.
8782     UncoveredArg.setAllCovered();
8783     return false;
8784   }
8785   return true;
8786 }
8787 
8788 template<typename Range>
8789 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8790                                               SourceLocation Loc,
8791                                               bool IsStringLocation,
8792                                               Range StringRange,
8793                                               ArrayRef<FixItHint> FixIt) {
8794   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8795                        Loc, IsStringLocation, StringRange, FixIt);
8796 }
8797 
8798 /// If the format string is not within the function call, emit a note
8799 /// so that the function call and string are in diagnostic messages.
8800 ///
8801 /// \param InFunctionCall if true, the format string is within the function
8802 /// call and only one diagnostic message will be produced.  Otherwise, an
8803 /// extra note will be emitted pointing to location of the format string.
8804 ///
8805 /// \param ArgumentExpr the expression that is passed as the format string
8806 /// argument in the function call.  Used for getting locations when two
8807 /// diagnostics are emitted.
8808 ///
8809 /// \param PDiag the callee should already have provided any strings for the
8810 /// diagnostic message.  This function only adds locations and fixits
8811 /// to diagnostics.
8812 ///
8813 /// \param Loc primary location for diagnostic.  If two diagnostics are
8814 /// required, one will be at Loc and a new SourceLocation will be created for
8815 /// the other one.
8816 ///
8817 /// \param IsStringLocation if true, Loc points to the format string should be
8818 /// used for the note.  Otherwise, Loc points to the argument list and will
8819 /// be used with PDiag.
8820 ///
8821 /// \param StringRange some or all of the string to highlight.  This is
8822 /// templated so it can accept either a CharSourceRange or a SourceRange.
8823 ///
8824 /// \param FixIt optional fix it hint for the format string.
8825 template <typename Range>
8826 void CheckFormatHandler::EmitFormatDiagnostic(
8827     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8828     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8829     Range StringRange, ArrayRef<FixItHint> FixIt) {
8830   if (InFunctionCall) {
8831     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8832     D << StringRange;
8833     D << FixIt;
8834   } else {
8835     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8836       << ArgumentExpr->getSourceRange();
8837 
8838     const Sema::SemaDiagnosticBuilder &Note =
8839       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8840              diag::note_format_string_defined);
8841 
8842     Note << StringRange;
8843     Note << FixIt;
8844   }
8845 }
8846 
8847 //===--- CHECK: Printf format string checking ------------------------------===//
8848 
8849 namespace {
8850 
8851 class CheckPrintfHandler : public CheckFormatHandler {
8852 public:
8853   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8854                      const Expr *origFormatExpr,
8855                      const Sema::FormatStringType type, unsigned firstDataArg,
8856                      unsigned numDataArgs, bool isObjC, const char *beg,
8857                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8858                      unsigned formatIdx, bool inFunctionCall,
8859                      Sema::VariadicCallType CallType,
8860                      llvm::SmallBitVector &CheckedVarArgs,
8861                      UncoveredArgHandler &UncoveredArg)
8862       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8863                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8864                            inFunctionCall, CallType, CheckedVarArgs,
8865                            UncoveredArg) {}
8866 
8867   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8868 
8869   /// Returns true if '%@' specifiers are allowed in the format string.
8870   bool allowsObjCArg() const {
8871     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8872            FSType == Sema::FST_OSTrace;
8873   }
8874 
8875   bool HandleInvalidPrintfConversionSpecifier(
8876                                       const analyze_printf::PrintfSpecifier &FS,
8877                                       const char *startSpecifier,
8878                                       unsigned specifierLen) override;
8879 
8880   void handleInvalidMaskType(StringRef MaskType) override;
8881 
8882   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8883                              const char *startSpecifier,
8884                              unsigned specifierLen) override;
8885   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8886                        const char *StartSpecifier,
8887                        unsigned SpecifierLen,
8888                        const Expr *E);
8889 
8890   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8891                     const char *startSpecifier, unsigned specifierLen);
8892   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8893                            const analyze_printf::OptionalAmount &Amt,
8894                            unsigned type,
8895                            const char *startSpecifier, unsigned specifierLen);
8896   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8897                   const analyze_printf::OptionalFlag &flag,
8898                   const char *startSpecifier, unsigned specifierLen);
8899   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8900                          const analyze_printf::OptionalFlag &ignoredFlag,
8901                          const analyze_printf::OptionalFlag &flag,
8902                          const char *startSpecifier, unsigned specifierLen);
8903   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8904                            const Expr *E);
8905 
8906   void HandleEmptyObjCModifierFlag(const char *startFlag,
8907                                    unsigned flagLen) override;
8908 
8909   void HandleInvalidObjCModifierFlag(const char *startFlag,
8910                                             unsigned flagLen) override;
8911 
8912   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8913                                            const char *flagsEnd,
8914                                            const char *conversionPosition)
8915                                              override;
8916 };
8917 
8918 } // namespace
8919 
8920 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8921                                       const analyze_printf::PrintfSpecifier &FS,
8922                                       const char *startSpecifier,
8923                                       unsigned specifierLen) {
8924   const analyze_printf::PrintfConversionSpecifier &CS =
8925     FS.getConversionSpecifier();
8926 
8927   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8928                                           getLocationOfByte(CS.getStart()),
8929                                           startSpecifier, specifierLen,
8930                                           CS.getStart(), CS.getLength());
8931 }
8932 
8933 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8934   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8935 }
8936 
8937 bool CheckPrintfHandler::HandleAmount(
8938                                const analyze_format_string::OptionalAmount &Amt,
8939                                unsigned k, const char *startSpecifier,
8940                                unsigned specifierLen) {
8941   if (Amt.hasDataArgument()) {
8942     if (!HasVAListArg) {
8943       unsigned argIndex = Amt.getArgIndex();
8944       if (argIndex >= NumDataArgs) {
8945         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8946                                << k,
8947                              getLocationOfByte(Amt.getStart()),
8948                              /*IsStringLocation*/true,
8949                              getSpecifierRange(startSpecifier, specifierLen));
8950         // Don't do any more checking.  We will just emit
8951         // spurious errors.
8952         return false;
8953       }
8954 
8955       // Type check the data argument.  It should be an 'int'.
8956       // Although not in conformance with C99, we also allow the argument to be
8957       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8958       // doesn't emit a warning for that case.
8959       CoveredArgs.set(argIndex);
8960       const Expr *Arg = getDataArg(argIndex);
8961       if (!Arg)
8962         return false;
8963 
8964       QualType T = Arg->getType();
8965 
8966       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8967       assert(AT.isValid());
8968 
8969       if (!AT.matchesType(S.Context, T)) {
8970         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8971                                << k << AT.getRepresentativeTypeName(S.Context)
8972                                << T << Arg->getSourceRange(),
8973                              getLocationOfByte(Amt.getStart()),
8974                              /*IsStringLocation*/true,
8975                              getSpecifierRange(startSpecifier, specifierLen));
8976         // Don't do any more checking.  We will just emit
8977         // spurious errors.
8978         return false;
8979       }
8980     }
8981   }
8982   return true;
8983 }
8984 
8985 void CheckPrintfHandler::HandleInvalidAmount(
8986                                       const analyze_printf::PrintfSpecifier &FS,
8987                                       const analyze_printf::OptionalAmount &Amt,
8988                                       unsigned type,
8989                                       const char *startSpecifier,
8990                                       unsigned specifierLen) {
8991   const analyze_printf::PrintfConversionSpecifier &CS =
8992     FS.getConversionSpecifier();
8993 
8994   FixItHint fixit =
8995     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8996       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8997                                  Amt.getConstantLength()))
8998       : FixItHint();
8999 
9000   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9001                          << type << CS.toString(),
9002                        getLocationOfByte(Amt.getStart()),
9003                        /*IsStringLocation*/true,
9004                        getSpecifierRange(startSpecifier, specifierLen),
9005                        fixit);
9006 }
9007 
9008 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9009                                     const analyze_printf::OptionalFlag &flag,
9010                                     const char *startSpecifier,
9011                                     unsigned specifierLen) {
9012   // Warn about pointless flag with a fixit removal.
9013   const analyze_printf::PrintfConversionSpecifier &CS =
9014     FS.getConversionSpecifier();
9015   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9016                          << flag.toString() << CS.toString(),
9017                        getLocationOfByte(flag.getPosition()),
9018                        /*IsStringLocation*/true,
9019                        getSpecifierRange(startSpecifier, specifierLen),
9020                        FixItHint::CreateRemoval(
9021                          getSpecifierRange(flag.getPosition(), 1)));
9022 }
9023 
9024 void CheckPrintfHandler::HandleIgnoredFlag(
9025                                 const analyze_printf::PrintfSpecifier &FS,
9026                                 const analyze_printf::OptionalFlag &ignoredFlag,
9027                                 const analyze_printf::OptionalFlag &flag,
9028                                 const char *startSpecifier,
9029                                 unsigned specifierLen) {
9030   // Warn about ignored flag with a fixit removal.
9031   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9032                          << ignoredFlag.toString() << flag.toString(),
9033                        getLocationOfByte(ignoredFlag.getPosition()),
9034                        /*IsStringLocation*/true,
9035                        getSpecifierRange(startSpecifier, specifierLen),
9036                        FixItHint::CreateRemoval(
9037                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9038 }
9039 
9040 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9041                                                      unsigned flagLen) {
9042   // Warn about an empty flag.
9043   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9044                        getLocationOfByte(startFlag),
9045                        /*IsStringLocation*/true,
9046                        getSpecifierRange(startFlag, flagLen));
9047 }
9048 
9049 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9050                                                        unsigned flagLen) {
9051   // Warn about an invalid flag.
9052   auto Range = getSpecifierRange(startFlag, flagLen);
9053   StringRef flag(startFlag, flagLen);
9054   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9055                       getLocationOfByte(startFlag),
9056                       /*IsStringLocation*/true,
9057                       Range, FixItHint::CreateRemoval(Range));
9058 }
9059 
9060 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9061     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9062     // Warn about using '[...]' without a '@' conversion.
9063     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9064     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9065     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9066                          getLocationOfByte(conversionPosition),
9067                          /*IsStringLocation*/true,
9068                          Range, FixItHint::CreateRemoval(Range));
9069 }
9070 
9071 // Determines if the specified is a C++ class or struct containing
9072 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9073 // "c_str()").
9074 template<typename MemberKind>
9075 static llvm::SmallPtrSet<MemberKind*, 1>
9076 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9077   const RecordType *RT = Ty->getAs<RecordType>();
9078   llvm::SmallPtrSet<MemberKind*, 1> Results;
9079 
9080   if (!RT)
9081     return Results;
9082   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9083   if (!RD || !RD->getDefinition())
9084     return Results;
9085 
9086   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9087                  Sema::LookupMemberName);
9088   R.suppressDiagnostics();
9089 
9090   // We just need to include all members of the right kind turned up by the
9091   // filter, at this point.
9092   if (S.LookupQualifiedName(R, RT->getDecl()))
9093     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9094       NamedDecl *decl = (*I)->getUnderlyingDecl();
9095       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9096         Results.insert(FK);
9097     }
9098   return Results;
9099 }
9100 
9101 /// Check if we could call '.c_str()' on an object.
9102 ///
9103 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9104 /// allow the call, or if it would be ambiguous).
9105 bool Sema::hasCStrMethod(const Expr *E) {
9106   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9107 
9108   MethodSet Results =
9109       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9110   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9111        MI != ME; ++MI)
9112     if ((*MI)->getMinRequiredArguments() == 0)
9113       return true;
9114   return false;
9115 }
9116 
9117 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9118 // better diagnostic if so. AT is assumed to be valid.
9119 // Returns true when a c_str() conversion method is found.
9120 bool CheckPrintfHandler::checkForCStrMembers(
9121     const analyze_printf::ArgType &AT, const Expr *E) {
9122   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9123 
9124   MethodSet Results =
9125       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9126 
9127   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9128        MI != ME; ++MI) {
9129     const CXXMethodDecl *Method = *MI;
9130     if (Method->getMinRequiredArguments() == 0 &&
9131         AT.matchesType(S.Context, Method->getReturnType())) {
9132       // FIXME: Suggest parens if the expression needs them.
9133       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9134       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9135           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9136       return true;
9137     }
9138   }
9139 
9140   return false;
9141 }
9142 
9143 bool
9144 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
9145                                             &FS,
9146                                           const char *startSpecifier,
9147                                           unsigned specifierLen) {
9148   using namespace analyze_format_string;
9149   using namespace analyze_printf;
9150 
9151   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9152 
9153   if (FS.consumesDataArgument()) {
9154     if (atFirstArg) {
9155         atFirstArg = false;
9156         usesPositionalArgs = FS.usesPositionalArg();
9157     }
9158     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9159       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9160                                         startSpecifier, specifierLen);
9161       return false;
9162     }
9163   }
9164 
9165   // First check if the field width, precision, and conversion specifier
9166   // have matching data arguments.
9167   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9168                     startSpecifier, specifierLen)) {
9169     return false;
9170   }
9171 
9172   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9173                     startSpecifier, specifierLen)) {
9174     return false;
9175   }
9176 
9177   if (!CS.consumesDataArgument()) {
9178     // FIXME: Technically specifying a precision or field width here
9179     // makes no sense.  Worth issuing a warning at some point.
9180     return true;
9181   }
9182 
9183   // Consume the argument.
9184   unsigned argIndex = FS.getArgIndex();
9185   if (argIndex < NumDataArgs) {
9186     // The check to see if the argIndex is valid will come later.
9187     // We set the bit here because we may exit early from this
9188     // function if we encounter some other error.
9189     CoveredArgs.set(argIndex);
9190   }
9191 
9192   // FreeBSD kernel extensions.
9193   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9194       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9195     // We need at least two arguments.
9196     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9197       return false;
9198 
9199     // Claim the second argument.
9200     CoveredArgs.set(argIndex + 1);
9201 
9202     // Type check the first argument (int for %b, pointer for %D)
9203     const Expr *Ex = getDataArg(argIndex);
9204     const analyze_printf::ArgType &AT =
9205       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9206         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9207     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9208       EmitFormatDiagnostic(
9209           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9210               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9211               << false << Ex->getSourceRange(),
9212           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9213           getSpecifierRange(startSpecifier, specifierLen));
9214 
9215     // Type check the second argument (char * for both %b and %D)
9216     Ex = getDataArg(argIndex + 1);
9217     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9218     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9219       EmitFormatDiagnostic(
9220           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9221               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9222               << false << Ex->getSourceRange(),
9223           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9224           getSpecifierRange(startSpecifier, specifierLen));
9225 
9226      return true;
9227   }
9228 
9229   // Check for using an Objective-C specific conversion specifier
9230   // in a non-ObjC literal.
9231   if (!allowsObjCArg() && CS.isObjCArg()) {
9232     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9233                                                   specifierLen);
9234   }
9235 
9236   // %P can only be used with os_log.
9237   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9238     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9239                                                   specifierLen);
9240   }
9241 
9242   // %n is not allowed with os_log.
9243   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9244     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9245                          getLocationOfByte(CS.getStart()),
9246                          /*IsStringLocation*/ false,
9247                          getSpecifierRange(startSpecifier, specifierLen));
9248 
9249     return true;
9250   }
9251 
9252   // Only scalars are allowed for os_trace.
9253   if (FSType == Sema::FST_OSTrace &&
9254       (CS.getKind() == ConversionSpecifier::PArg ||
9255        CS.getKind() == ConversionSpecifier::sArg ||
9256        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9257     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9258                                                   specifierLen);
9259   }
9260 
9261   // Check for use of public/private annotation outside of os_log().
9262   if (FSType != Sema::FST_OSLog) {
9263     if (FS.isPublic().isSet()) {
9264       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9265                                << "public",
9266                            getLocationOfByte(FS.isPublic().getPosition()),
9267                            /*IsStringLocation*/ false,
9268                            getSpecifierRange(startSpecifier, specifierLen));
9269     }
9270     if (FS.isPrivate().isSet()) {
9271       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9272                                << "private",
9273                            getLocationOfByte(FS.isPrivate().getPosition()),
9274                            /*IsStringLocation*/ false,
9275                            getSpecifierRange(startSpecifier, specifierLen));
9276     }
9277   }
9278 
9279   // Check for invalid use of field width
9280   if (!FS.hasValidFieldWidth()) {
9281     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9282         startSpecifier, specifierLen);
9283   }
9284 
9285   // Check for invalid use of precision
9286   if (!FS.hasValidPrecision()) {
9287     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9288         startSpecifier, specifierLen);
9289   }
9290 
9291   // Precision is mandatory for %P specifier.
9292   if (CS.getKind() == ConversionSpecifier::PArg &&
9293       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9294     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9295                          getLocationOfByte(startSpecifier),
9296                          /*IsStringLocation*/ false,
9297                          getSpecifierRange(startSpecifier, specifierLen));
9298   }
9299 
9300   // Check each flag does not conflict with any other component.
9301   if (!FS.hasValidThousandsGroupingPrefix())
9302     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9303   if (!FS.hasValidLeadingZeros())
9304     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9305   if (!FS.hasValidPlusPrefix())
9306     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9307   if (!FS.hasValidSpacePrefix())
9308     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9309   if (!FS.hasValidAlternativeForm())
9310     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9311   if (!FS.hasValidLeftJustified())
9312     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9313 
9314   // Check that flags are not ignored by another flag
9315   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9316     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9317         startSpecifier, specifierLen);
9318   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9319     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9320             startSpecifier, specifierLen);
9321 
9322   // Check the length modifier is valid with the given conversion specifier.
9323   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9324                                  S.getLangOpts()))
9325     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9326                                 diag::warn_format_nonsensical_length);
9327   else if (!FS.hasStandardLengthModifier())
9328     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9329   else if (!FS.hasStandardLengthConversionCombination())
9330     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9331                                 diag::warn_format_non_standard_conversion_spec);
9332 
9333   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9334     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9335 
9336   // The remaining checks depend on the data arguments.
9337   if (HasVAListArg)
9338     return true;
9339 
9340   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9341     return false;
9342 
9343   const Expr *Arg = getDataArg(argIndex);
9344   if (!Arg)
9345     return true;
9346 
9347   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9348 }
9349 
9350 static bool requiresParensToAddCast(const Expr *E) {
9351   // FIXME: We should have a general way to reason about operator
9352   // precedence and whether parens are actually needed here.
9353   // Take care of a few common cases where they aren't.
9354   const Expr *Inside = E->IgnoreImpCasts();
9355   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9356     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9357 
9358   switch (Inside->getStmtClass()) {
9359   case Stmt::ArraySubscriptExprClass:
9360   case Stmt::CallExprClass:
9361   case Stmt::CharacterLiteralClass:
9362   case Stmt::CXXBoolLiteralExprClass:
9363   case Stmt::DeclRefExprClass:
9364   case Stmt::FloatingLiteralClass:
9365   case Stmt::IntegerLiteralClass:
9366   case Stmt::MemberExprClass:
9367   case Stmt::ObjCArrayLiteralClass:
9368   case Stmt::ObjCBoolLiteralExprClass:
9369   case Stmt::ObjCBoxedExprClass:
9370   case Stmt::ObjCDictionaryLiteralClass:
9371   case Stmt::ObjCEncodeExprClass:
9372   case Stmt::ObjCIvarRefExprClass:
9373   case Stmt::ObjCMessageExprClass:
9374   case Stmt::ObjCPropertyRefExprClass:
9375   case Stmt::ObjCStringLiteralClass:
9376   case Stmt::ObjCSubscriptRefExprClass:
9377   case Stmt::ParenExprClass:
9378   case Stmt::StringLiteralClass:
9379   case Stmt::UnaryOperatorClass:
9380     return false;
9381   default:
9382     return true;
9383   }
9384 }
9385 
9386 static std::pair<QualType, StringRef>
9387 shouldNotPrintDirectly(const ASTContext &Context,
9388                        QualType IntendedTy,
9389                        const Expr *E) {
9390   // Use a 'while' to peel off layers of typedefs.
9391   QualType TyTy = IntendedTy;
9392   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9393     StringRef Name = UserTy->getDecl()->getName();
9394     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9395       .Case("CFIndex", Context.getNSIntegerType())
9396       .Case("NSInteger", Context.getNSIntegerType())
9397       .Case("NSUInteger", Context.getNSUIntegerType())
9398       .Case("SInt32", Context.IntTy)
9399       .Case("UInt32", Context.UnsignedIntTy)
9400       .Default(QualType());
9401 
9402     if (!CastTy.isNull())
9403       return std::make_pair(CastTy, Name);
9404 
9405     TyTy = UserTy->desugar();
9406   }
9407 
9408   // Strip parens if necessary.
9409   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9410     return shouldNotPrintDirectly(Context,
9411                                   PE->getSubExpr()->getType(),
9412                                   PE->getSubExpr());
9413 
9414   // If this is a conditional expression, then its result type is constructed
9415   // via usual arithmetic conversions and thus there might be no necessary
9416   // typedef sugar there.  Recurse to operands to check for NSInteger &
9417   // Co. usage condition.
9418   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9419     QualType TrueTy, FalseTy;
9420     StringRef TrueName, FalseName;
9421 
9422     std::tie(TrueTy, TrueName) =
9423       shouldNotPrintDirectly(Context,
9424                              CO->getTrueExpr()->getType(),
9425                              CO->getTrueExpr());
9426     std::tie(FalseTy, FalseName) =
9427       shouldNotPrintDirectly(Context,
9428                              CO->getFalseExpr()->getType(),
9429                              CO->getFalseExpr());
9430 
9431     if (TrueTy == FalseTy)
9432       return std::make_pair(TrueTy, TrueName);
9433     else if (TrueTy.isNull())
9434       return std::make_pair(FalseTy, FalseName);
9435     else if (FalseTy.isNull())
9436       return std::make_pair(TrueTy, TrueName);
9437   }
9438 
9439   return std::make_pair(QualType(), StringRef());
9440 }
9441 
9442 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9443 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9444 /// type do not count.
9445 static bool
9446 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9447   QualType From = ICE->getSubExpr()->getType();
9448   QualType To = ICE->getType();
9449   // It's an integer promotion if the destination type is the promoted
9450   // source type.
9451   if (ICE->getCastKind() == CK_IntegralCast &&
9452       From->isPromotableIntegerType() &&
9453       S.Context.getPromotedIntegerType(From) == To)
9454     return true;
9455   // Look through vector types, since we do default argument promotion for
9456   // those in OpenCL.
9457   if (const auto *VecTy = From->getAs<ExtVectorType>())
9458     From = VecTy->getElementType();
9459   if (const auto *VecTy = To->getAs<ExtVectorType>())
9460     To = VecTy->getElementType();
9461   // It's a floating promotion if the source type is a lower rank.
9462   return ICE->getCastKind() == CK_FloatingCast &&
9463          S.Context.getFloatingTypeOrder(From, To) < 0;
9464 }
9465 
9466 bool
9467 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9468                                     const char *StartSpecifier,
9469                                     unsigned SpecifierLen,
9470                                     const Expr *E) {
9471   using namespace analyze_format_string;
9472   using namespace analyze_printf;
9473 
9474   // Now type check the data expression that matches the
9475   // format specifier.
9476   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9477   if (!AT.isValid())
9478     return true;
9479 
9480   QualType ExprTy = E->getType();
9481   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9482     ExprTy = TET->getUnderlyingExpr()->getType();
9483   }
9484 
9485   // Diagnose attempts to print a boolean value as a character. Unlike other
9486   // -Wformat diagnostics, this is fine from a type perspective, but it still
9487   // doesn't make sense.
9488   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9489       E->isKnownToHaveBooleanValue()) {
9490     const CharSourceRange &CSR =
9491         getSpecifierRange(StartSpecifier, SpecifierLen);
9492     SmallString<4> FSString;
9493     llvm::raw_svector_ostream os(FSString);
9494     FS.toString(os);
9495     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9496                              << FSString,
9497                          E->getExprLoc(), false, CSR);
9498     return true;
9499   }
9500 
9501   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9502   if (Match == analyze_printf::ArgType::Match)
9503     return true;
9504 
9505   // Look through argument promotions for our error message's reported type.
9506   // This includes the integral and floating promotions, but excludes array
9507   // and function pointer decay (seeing that an argument intended to be a
9508   // string has type 'char [6]' is probably more confusing than 'char *') and
9509   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9510   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9511     if (isArithmeticArgumentPromotion(S, ICE)) {
9512       E = ICE->getSubExpr();
9513       ExprTy = E->getType();
9514 
9515       // Check if we didn't match because of an implicit cast from a 'char'
9516       // or 'short' to an 'int'.  This is done because printf is a varargs
9517       // function.
9518       if (ICE->getType() == S.Context.IntTy ||
9519           ICE->getType() == S.Context.UnsignedIntTy) {
9520         // All further checking is done on the subexpression
9521         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9522             AT.matchesType(S.Context, ExprTy);
9523         if (ImplicitMatch == analyze_printf::ArgType::Match)
9524           return true;
9525         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9526             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9527           Match = ImplicitMatch;
9528       }
9529     }
9530   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9531     // Special case for 'a', which has type 'int' in C.
9532     // Note, however, that we do /not/ want to treat multibyte constants like
9533     // 'MooV' as characters! This form is deprecated but still exists. In
9534     // addition, don't treat expressions as of type 'char' if one byte length
9535     // modifier is provided.
9536     if (ExprTy == S.Context.IntTy &&
9537         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9538       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9539         ExprTy = S.Context.CharTy;
9540   }
9541 
9542   // Look through enums to their underlying type.
9543   bool IsEnum = false;
9544   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9545     ExprTy = EnumTy->getDecl()->getIntegerType();
9546     IsEnum = true;
9547   }
9548 
9549   // %C in an Objective-C context prints a unichar, not a wchar_t.
9550   // If the argument is an integer of some kind, believe the %C and suggest
9551   // a cast instead of changing the conversion specifier.
9552   QualType IntendedTy = ExprTy;
9553   if (isObjCContext() &&
9554       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9555     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9556         !ExprTy->isCharType()) {
9557       // 'unichar' is defined as a typedef of unsigned short, but we should
9558       // prefer using the typedef if it is visible.
9559       IntendedTy = S.Context.UnsignedShortTy;
9560 
9561       // While we are here, check if the value is an IntegerLiteral that happens
9562       // to be within the valid range.
9563       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9564         const llvm::APInt &V = IL->getValue();
9565         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9566           return true;
9567       }
9568 
9569       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9570                           Sema::LookupOrdinaryName);
9571       if (S.LookupName(Result, S.getCurScope())) {
9572         NamedDecl *ND = Result.getFoundDecl();
9573         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9574           if (TD->getUnderlyingType() == IntendedTy)
9575             IntendedTy = S.Context.getTypedefType(TD);
9576       }
9577     }
9578   }
9579 
9580   // Special-case some of Darwin's platform-independence types by suggesting
9581   // casts to primitive types that are known to be large enough.
9582   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9583   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9584     QualType CastTy;
9585     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9586     if (!CastTy.isNull()) {
9587       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9588       // (long in ASTContext). Only complain to pedants.
9589       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9590           (AT.isSizeT() || AT.isPtrdiffT()) &&
9591           AT.matchesType(S.Context, CastTy))
9592         Match = ArgType::NoMatchPedantic;
9593       IntendedTy = CastTy;
9594       ShouldNotPrintDirectly = true;
9595     }
9596   }
9597 
9598   // We may be able to offer a FixItHint if it is a supported type.
9599   PrintfSpecifier fixedFS = FS;
9600   bool Success =
9601       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9602 
9603   if (Success) {
9604     // Get the fix string from the fixed format specifier
9605     SmallString<16> buf;
9606     llvm::raw_svector_ostream os(buf);
9607     fixedFS.toString(os);
9608 
9609     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9610 
9611     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9612       unsigned Diag;
9613       switch (Match) {
9614       case ArgType::Match: llvm_unreachable("expected non-matching");
9615       case ArgType::NoMatchPedantic:
9616         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9617         break;
9618       case ArgType::NoMatchTypeConfusion:
9619         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9620         break;
9621       case ArgType::NoMatch:
9622         Diag = diag::warn_format_conversion_argument_type_mismatch;
9623         break;
9624       }
9625 
9626       // In this case, the specifier is wrong and should be changed to match
9627       // the argument.
9628       EmitFormatDiagnostic(S.PDiag(Diag)
9629                                << AT.getRepresentativeTypeName(S.Context)
9630                                << IntendedTy << IsEnum << E->getSourceRange(),
9631                            E->getBeginLoc(),
9632                            /*IsStringLocation*/ false, SpecRange,
9633                            FixItHint::CreateReplacement(SpecRange, os.str()));
9634     } else {
9635       // The canonical type for formatting this value is different from the
9636       // actual type of the expression. (This occurs, for example, with Darwin's
9637       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9638       // should be printed as 'long' for 64-bit compatibility.)
9639       // Rather than emitting a normal format/argument mismatch, we want to
9640       // add a cast to the recommended type (and correct the format string
9641       // if necessary).
9642       SmallString<16> CastBuf;
9643       llvm::raw_svector_ostream CastFix(CastBuf);
9644       CastFix << "(";
9645       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9646       CastFix << ")";
9647 
9648       SmallVector<FixItHint,4> Hints;
9649       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9650         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9651 
9652       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9653         // If there's already a cast present, just replace it.
9654         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9655         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9656 
9657       } else if (!requiresParensToAddCast(E)) {
9658         // If the expression has high enough precedence,
9659         // just write the C-style cast.
9660         Hints.push_back(
9661             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9662       } else {
9663         // Otherwise, add parens around the expression as well as the cast.
9664         CastFix << "(";
9665         Hints.push_back(
9666             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9667 
9668         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9669         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9670       }
9671 
9672       if (ShouldNotPrintDirectly) {
9673         // The expression has a type that should not be printed directly.
9674         // We extract the name from the typedef because we don't want to show
9675         // the underlying type in the diagnostic.
9676         StringRef Name;
9677         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9678           Name = TypedefTy->getDecl()->getName();
9679         else
9680           Name = CastTyName;
9681         unsigned Diag = Match == ArgType::NoMatchPedantic
9682                             ? diag::warn_format_argument_needs_cast_pedantic
9683                             : diag::warn_format_argument_needs_cast;
9684         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9685                                            << E->getSourceRange(),
9686                              E->getBeginLoc(), /*IsStringLocation=*/false,
9687                              SpecRange, Hints);
9688       } else {
9689         // In this case, the expression could be printed using a different
9690         // specifier, but we've decided that the specifier is probably correct
9691         // and we should cast instead. Just use the normal warning message.
9692         EmitFormatDiagnostic(
9693             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9694                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9695                 << E->getSourceRange(),
9696             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9697       }
9698     }
9699   } else {
9700     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9701                                                    SpecifierLen);
9702     // Since the warning for passing non-POD types to variadic functions
9703     // was deferred until now, we emit a warning for non-POD
9704     // arguments here.
9705     switch (S.isValidVarArgType(ExprTy)) {
9706     case Sema::VAK_Valid:
9707     case Sema::VAK_ValidInCXX11: {
9708       unsigned Diag;
9709       switch (Match) {
9710       case ArgType::Match: llvm_unreachable("expected non-matching");
9711       case ArgType::NoMatchPedantic:
9712         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9713         break;
9714       case ArgType::NoMatchTypeConfusion:
9715         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9716         break;
9717       case ArgType::NoMatch:
9718         Diag = diag::warn_format_conversion_argument_type_mismatch;
9719         break;
9720       }
9721 
9722       EmitFormatDiagnostic(
9723           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9724                         << IsEnum << CSR << E->getSourceRange(),
9725           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9726       break;
9727     }
9728     case Sema::VAK_Undefined:
9729     case Sema::VAK_MSVCUndefined:
9730       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9731                                << S.getLangOpts().CPlusPlus11 << ExprTy
9732                                << CallType
9733                                << AT.getRepresentativeTypeName(S.Context) << CSR
9734                                << E->getSourceRange(),
9735                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9736       checkForCStrMembers(AT, E);
9737       break;
9738 
9739     case Sema::VAK_Invalid:
9740       if (ExprTy->isObjCObjectType())
9741         EmitFormatDiagnostic(
9742             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9743                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9744                 << AT.getRepresentativeTypeName(S.Context) << CSR
9745                 << E->getSourceRange(),
9746             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9747       else
9748         // FIXME: If this is an initializer list, suggest removing the braces
9749         // or inserting a cast to the target type.
9750         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9751             << isa<InitListExpr>(E) << ExprTy << CallType
9752             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9753       break;
9754     }
9755 
9756     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9757            "format string specifier index out of range");
9758     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9759   }
9760 
9761   return true;
9762 }
9763 
9764 //===--- CHECK: Scanf format string checking ------------------------------===//
9765 
9766 namespace {
9767 
9768 class CheckScanfHandler : public CheckFormatHandler {
9769 public:
9770   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9771                     const Expr *origFormatExpr, Sema::FormatStringType type,
9772                     unsigned firstDataArg, unsigned numDataArgs,
9773                     const char *beg, bool hasVAListArg,
9774                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9775                     bool inFunctionCall, Sema::VariadicCallType CallType,
9776                     llvm::SmallBitVector &CheckedVarArgs,
9777                     UncoveredArgHandler &UncoveredArg)
9778       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9779                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9780                            inFunctionCall, CallType, CheckedVarArgs,
9781                            UncoveredArg) {}
9782 
9783   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9784                             const char *startSpecifier,
9785                             unsigned specifierLen) override;
9786 
9787   bool HandleInvalidScanfConversionSpecifier(
9788           const analyze_scanf::ScanfSpecifier &FS,
9789           const char *startSpecifier,
9790           unsigned specifierLen) override;
9791 
9792   void HandleIncompleteScanList(const char *start, const char *end) override;
9793 };
9794 
9795 } // namespace
9796 
9797 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9798                                                  const char *end) {
9799   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9800                        getLocationOfByte(end), /*IsStringLocation*/true,
9801                        getSpecifierRange(start, end - start));
9802 }
9803 
9804 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9805                                         const analyze_scanf::ScanfSpecifier &FS,
9806                                         const char *startSpecifier,
9807                                         unsigned specifierLen) {
9808   const analyze_scanf::ScanfConversionSpecifier &CS =
9809     FS.getConversionSpecifier();
9810 
9811   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9812                                           getLocationOfByte(CS.getStart()),
9813                                           startSpecifier, specifierLen,
9814                                           CS.getStart(), CS.getLength());
9815 }
9816 
9817 bool CheckScanfHandler::HandleScanfSpecifier(
9818                                        const analyze_scanf::ScanfSpecifier &FS,
9819                                        const char *startSpecifier,
9820                                        unsigned specifierLen) {
9821   using namespace analyze_scanf;
9822   using namespace analyze_format_string;
9823 
9824   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9825 
9826   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9827   // be used to decide if we are using positional arguments consistently.
9828   if (FS.consumesDataArgument()) {
9829     if (atFirstArg) {
9830       atFirstArg = false;
9831       usesPositionalArgs = FS.usesPositionalArg();
9832     }
9833     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9834       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9835                                         startSpecifier, specifierLen);
9836       return false;
9837     }
9838   }
9839 
9840   // Check if the field with is non-zero.
9841   const OptionalAmount &Amt = FS.getFieldWidth();
9842   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9843     if (Amt.getConstantAmount() == 0) {
9844       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9845                                                    Amt.getConstantLength());
9846       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9847                            getLocationOfByte(Amt.getStart()),
9848                            /*IsStringLocation*/true, R,
9849                            FixItHint::CreateRemoval(R));
9850     }
9851   }
9852 
9853   if (!FS.consumesDataArgument()) {
9854     // FIXME: Technically specifying a precision or field width here
9855     // makes no sense.  Worth issuing a warning at some point.
9856     return true;
9857   }
9858 
9859   // Consume the argument.
9860   unsigned argIndex = FS.getArgIndex();
9861   if (argIndex < NumDataArgs) {
9862       // The check to see if the argIndex is valid will come later.
9863       // We set the bit here because we may exit early from this
9864       // function if we encounter some other error.
9865     CoveredArgs.set(argIndex);
9866   }
9867 
9868   // Check the length modifier is valid with the given conversion specifier.
9869   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9870                                  S.getLangOpts()))
9871     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9872                                 diag::warn_format_nonsensical_length);
9873   else if (!FS.hasStandardLengthModifier())
9874     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9875   else if (!FS.hasStandardLengthConversionCombination())
9876     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9877                                 diag::warn_format_non_standard_conversion_spec);
9878 
9879   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9880     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9881 
9882   // The remaining checks depend on the data arguments.
9883   if (HasVAListArg)
9884     return true;
9885 
9886   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9887     return false;
9888 
9889   // Check that the argument type matches the format specifier.
9890   const Expr *Ex = getDataArg(argIndex);
9891   if (!Ex)
9892     return true;
9893 
9894   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9895 
9896   if (!AT.isValid()) {
9897     return true;
9898   }
9899 
9900   analyze_format_string::ArgType::MatchKind Match =
9901       AT.matchesType(S.Context, Ex->getType());
9902   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9903   if (Match == analyze_format_string::ArgType::Match)
9904     return true;
9905 
9906   ScanfSpecifier fixedFS = FS;
9907   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9908                                  S.getLangOpts(), S.Context);
9909 
9910   unsigned Diag =
9911       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9912                : diag::warn_format_conversion_argument_type_mismatch;
9913 
9914   if (Success) {
9915     // Get the fix string from the fixed format specifier.
9916     SmallString<128> buf;
9917     llvm::raw_svector_ostream os(buf);
9918     fixedFS.toString(os);
9919 
9920     EmitFormatDiagnostic(
9921         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9922                       << Ex->getType() << false << Ex->getSourceRange(),
9923         Ex->getBeginLoc(),
9924         /*IsStringLocation*/ false,
9925         getSpecifierRange(startSpecifier, specifierLen),
9926         FixItHint::CreateReplacement(
9927             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9928   } else {
9929     EmitFormatDiagnostic(S.PDiag(Diag)
9930                              << AT.getRepresentativeTypeName(S.Context)
9931                              << Ex->getType() << false << Ex->getSourceRange(),
9932                          Ex->getBeginLoc(),
9933                          /*IsStringLocation*/ false,
9934                          getSpecifierRange(startSpecifier, specifierLen));
9935   }
9936 
9937   return true;
9938 }
9939 
9940 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9941                               const Expr *OrigFormatExpr,
9942                               ArrayRef<const Expr *> Args,
9943                               bool HasVAListArg, unsigned format_idx,
9944                               unsigned firstDataArg,
9945                               Sema::FormatStringType Type,
9946                               bool inFunctionCall,
9947                               Sema::VariadicCallType CallType,
9948                               llvm::SmallBitVector &CheckedVarArgs,
9949                               UncoveredArgHandler &UncoveredArg,
9950                               bool IgnoreStringsWithoutSpecifiers) {
9951   // CHECK: is the format string a wide literal?
9952   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9953     CheckFormatHandler::EmitFormatDiagnostic(
9954         S, inFunctionCall, Args[format_idx],
9955         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9956         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9957     return;
9958   }
9959 
9960   // Str - The format string.  NOTE: this is NOT null-terminated!
9961   StringRef StrRef = FExpr->getString();
9962   const char *Str = StrRef.data();
9963   // Account for cases where the string literal is truncated in a declaration.
9964   const ConstantArrayType *T =
9965     S.Context.getAsConstantArrayType(FExpr->getType());
9966   assert(T && "String literal not of constant array type!");
9967   size_t TypeSize = T->getSize().getZExtValue();
9968   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9969   const unsigned numDataArgs = Args.size() - firstDataArg;
9970 
9971   if (IgnoreStringsWithoutSpecifiers &&
9972       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9973           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9974     return;
9975 
9976   // Emit a warning if the string literal is truncated and does not contain an
9977   // embedded null character.
9978   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9979     CheckFormatHandler::EmitFormatDiagnostic(
9980         S, inFunctionCall, Args[format_idx],
9981         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9982         FExpr->getBeginLoc(),
9983         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9984     return;
9985   }
9986 
9987   // CHECK: empty format string?
9988   if (StrLen == 0 && numDataArgs > 0) {
9989     CheckFormatHandler::EmitFormatDiagnostic(
9990         S, inFunctionCall, Args[format_idx],
9991         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9992         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9993     return;
9994   }
9995 
9996   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9997       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9998       Type == Sema::FST_OSTrace) {
9999     CheckPrintfHandler H(
10000         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10001         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10002         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10003         CheckedVarArgs, UncoveredArg);
10004 
10005     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10006                                                   S.getLangOpts(),
10007                                                   S.Context.getTargetInfo(),
10008                                             Type == Sema::FST_FreeBSDKPrintf))
10009       H.DoneProcessing();
10010   } else if (Type == Sema::FST_Scanf) {
10011     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10012                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10013                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10014 
10015     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10016                                                  S.getLangOpts(),
10017                                                  S.Context.getTargetInfo()))
10018       H.DoneProcessing();
10019   } // TODO: handle other formats
10020 }
10021 
10022 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10023   // Str - The format string.  NOTE: this is NOT null-terminated!
10024   StringRef StrRef = FExpr->getString();
10025   const char *Str = StrRef.data();
10026   // Account for cases where the string literal is truncated in a declaration.
10027   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10028   assert(T && "String literal not of constant array type!");
10029   size_t TypeSize = T->getSize().getZExtValue();
10030   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10031   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10032                                                          getLangOpts(),
10033                                                          Context.getTargetInfo());
10034 }
10035 
10036 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10037 
10038 // Returns the related absolute value function that is larger, of 0 if one
10039 // does not exist.
10040 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10041   switch (AbsFunction) {
10042   default:
10043     return 0;
10044 
10045   case Builtin::BI__builtin_abs:
10046     return Builtin::BI__builtin_labs;
10047   case Builtin::BI__builtin_labs:
10048     return Builtin::BI__builtin_llabs;
10049   case Builtin::BI__builtin_llabs:
10050     return 0;
10051 
10052   case Builtin::BI__builtin_fabsf:
10053     return Builtin::BI__builtin_fabs;
10054   case Builtin::BI__builtin_fabs:
10055     return Builtin::BI__builtin_fabsl;
10056   case Builtin::BI__builtin_fabsl:
10057     return 0;
10058 
10059   case Builtin::BI__builtin_cabsf:
10060     return Builtin::BI__builtin_cabs;
10061   case Builtin::BI__builtin_cabs:
10062     return Builtin::BI__builtin_cabsl;
10063   case Builtin::BI__builtin_cabsl:
10064     return 0;
10065 
10066   case Builtin::BIabs:
10067     return Builtin::BIlabs;
10068   case Builtin::BIlabs:
10069     return Builtin::BIllabs;
10070   case Builtin::BIllabs:
10071     return 0;
10072 
10073   case Builtin::BIfabsf:
10074     return Builtin::BIfabs;
10075   case Builtin::BIfabs:
10076     return Builtin::BIfabsl;
10077   case Builtin::BIfabsl:
10078     return 0;
10079 
10080   case Builtin::BIcabsf:
10081    return Builtin::BIcabs;
10082   case Builtin::BIcabs:
10083     return Builtin::BIcabsl;
10084   case Builtin::BIcabsl:
10085     return 0;
10086   }
10087 }
10088 
10089 // Returns the argument type of the absolute value function.
10090 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10091                                              unsigned AbsType) {
10092   if (AbsType == 0)
10093     return QualType();
10094 
10095   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10096   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10097   if (Error != ASTContext::GE_None)
10098     return QualType();
10099 
10100   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10101   if (!FT)
10102     return QualType();
10103 
10104   if (FT->getNumParams() != 1)
10105     return QualType();
10106 
10107   return FT->getParamType(0);
10108 }
10109 
10110 // Returns the best absolute value function, or zero, based on type and
10111 // current absolute value function.
10112 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10113                                    unsigned AbsFunctionKind) {
10114   unsigned BestKind = 0;
10115   uint64_t ArgSize = Context.getTypeSize(ArgType);
10116   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10117        Kind = getLargerAbsoluteValueFunction(Kind)) {
10118     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10119     if (Context.getTypeSize(ParamType) >= ArgSize) {
10120       if (BestKind == 0)
10121         BestKind = Kind;
10122       else if (Context.hasSameType(ParamType, ArgType)) {
10123         BestKind = Kind;
10124         break;
10125       }
10126     }
10127   }
10128   return BestKind;
10129 }
10130 
10131 enum AbsoluteValueKind {
10132   AVK_Integer,
10133   AVK_Floating,
10134   AVK_Complex
10135 };
10136 
10137 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10138   if (T->isIntegralOrEnumerationType())
10139     return AVK_Integer;
10140   if (T->isRealFloatingType())
10141     return AVK_Floating;
10142   if (T->isAnyComplexType())
10143     return AVK_Complex;
10144 
10145   llvm_unreachable("Type not integer, floating, or complex");
10146 }
10147 
10148 // Changes the absolute value function to a different type.  Preserves whether
10149 // the function is a builtin.
10150 static unsigned changeAbsFunction(unsigned AbsKind,
10151                                   AbsoluteValueKind ValueKind) {
10152   switch (ValueKind) {
10153   case AVK_Integer:
10154     switch (AbsKind) {
10155     default:
10156       return 0;
10157     case Builtin::BI__builtin_fabsf:
10158     case Builtin::BI__builtin_fabs:
10159     case Builtin::BI__builtin_fabsl:
10160     case Builtin::BI__builtin_cabsf:
10161     case Builtin::BI__builtin_cabs:
10162     case Builtin::BI__builtin_cabsl:
10163       return Builtin::BI__builtin_abs;
10164     case Builtin::BIfabsf:
10165     case Builtin::BIfabs:
10166     case Builtin::BIfabsl:
10167     case Builtin::BIcabsf:
10168     case Builtin::BIcabs:
10169     case Builtin::BIcabsl:
10170       return Builtin::BIabs;
10171     }
10172   case AVK_Floating:
10173     switch (AbsKind) {
10174     default:
10175       return 0;
10176     case Builtin::BI__builtin_abs:
10177     case Builtin::BI__builtin_labs:
10178     case Builtin::BI__builtin_llabs:
10179     case Builtin::BI__builtin_cabsf:
10180     case Builtin::BI__builtin_cabs:
10181     case Builtin::BI__builtin_cabsl:
10182       return Builtin::BI__builtin_fabsf;
10183     case Builtin::BIabs:
10184     case Builtin::BIlabs:
10185     case Builtin::BIllabs:
10186     case Builtin::BIcabsf:
10187     case Builtin::BIcabs:
10188     case Builtin::BIcabsl:
10189       return Builtin::BIfabsf;
10190     }
10191   case AVK_Complex:
10192     switch (AbsKind) {
10193     default:
10194       return 0;
10195     case Builtin::BI__builtin_abs:
10196     case Builtin::BI__builtin_labs:
10197     case Builtin::BI__builtin_llabs:
10198     case Builtin::BI__builtin_fabsf:
10199     case Builtin::BI__builtin_fabs:
10200     case Builtin::BI__builtin_fabsl:
10201       return Builtin::BI__builtin_cabsf;
10202     case Builtin::BIabs:
10203     case Builtin::BIlabs:
10204     case Builtin::BIllabs:
10205     case Builtin::BIfabsf:
10206     case Builtin::BIfabs:
10207     case Builtin::BIfabsl:
10208       return Builtin::BIcabsf;
10209     }
10210   }
10211   llvm_unreachable("Unable to convert function");
10212 }
10213 
10214 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10215   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10216   if (!FnInfo)
10217     return 0;
10218 
10219   switch (FDecl->getBuiltinID()) {
10220   default:
10221     return 0;
10222   case Builtin::BI__builtin_abs:
10223   case Builtin::BI__builtin_fabs:
10224   case Builtin::BI__builtin_fabsf:
10225   case Builtin::BI__builtin_fabsl:
10226   case Builtin::BI__builtin_labs:
10227   case Builtin::BI__builtin_llabs:
10228   case Builtin::BI__builtin_cabs:
10229   case Builtin::BI__builtin_cabsf:
10230   case Builtin::BI__builtin_cabsl:
10231   case Builtin::BIabs:
10232   case Builtin::BIlabs:
10233   case Builtin::BIllabs:
10234   case Builtin::BIfabs:
10235   case Builtin::BIfabsf:
10236   case Builtin::BIfabsl:
10237   case Builtin::BIcabs:
10238   case Builtin::BIcabsf:
10239   case Builtin::BIcabsl:
10240     return FDecl->getBuiltinID();
10241   }
10242   llvm_unreachable("Unknown Builtin type");
10243 }
10244 
10245 // If the replacement is valid, emit a note with replacement function.
10246 // Additionally, suggest including the proper header if not already included.
10247 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10248                             unsigned AbsKind, QualType ArgType) {
10249   bool EmitHeaderHint = true;
10250   const char *HeaderName = nullptr;
10251   const char *FunctionName = nullptr;
10252   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10253     FunctionName = "std::abs";
10254     if (ArgType->isIntegralOrEnumerationType()) {
10255       HeaderName = "cstdlib";
10256     } else if (ArgType->isRealFloatingType()) {
10257       HeaderName = "cmath";
10258     } else {
10259       llvm_unreachable("Invalid Type");
10260     }
10261 
10262     // Lookup all std::abs
10263     if (NamespaceDecl *Std = S.getStdNamespace()) {
10264       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10265       R.suppressDiagnostics();
10266       S.LookupQualifiedName(R, Std);
10267 
10268       for (const auto *I : R) {
10269         const FunctionDecl *FDecl = nullptr;
10270         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10271           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10272         } else {
10273           FDecl = dyn_cast<FunctionDecl>(I);
10274         }
10275         if (!FDecl)
10276           continue;
10277 
10278         // Found std::abs(), check that they are the right ones.
10279         if (FDecl->getNumParams() != 1)
10280           continue;
10281 
10282         // Check that the parameter type can handle the argument.
10283         QualType ParamType = FDecl->getParamDecl(0)->getType();
10284         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10285             S.Context.getTypeSize(ArgType) <=
10286                 S.Context.getTypeSize(ParamType)) {
10287           // Found a function, don't need the header hint.
10288           EmitHeaderHint = false;
10289           break;
10290         }
10291       }
10292     }
10293   } else {
10294     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10295     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10296 
10297     if (HeaderName) {
10298       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10299       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10300       R.suppressDiagnostics();
10301       S.LookupName(R, S.getCurScope());
10302 
10303       if (R.isSingleResult()) {
10304         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10305         if (FD && FD->getBuiltinID() == AbsKind) {
10306           EmitHeaderHint = false;
10307         } else {
10308           return;
10309         }
10310       } else if (!R.empty()) {
10311         return;
10312       }
10313     }
10314   }
10315 
10316   S.Diag(Loc, diag::note_replace_abs_function)
10317       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10318 
10319   if (!HeaderName)
10320     return;
10321 
10322   if (!EmitHeaderHint)
10323     return;
10324 
10325   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10326                                                     << FunctionName;
10327 }
10328 
10329 template <std::size_t StrLen>
10330 static bool IsStdFunction(const FunctionDecl *FDecl,
10331                           const char (&Str)[StrLen]) {
10332   if (!FDecl)
10333     return false;
10334   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10335     return false;
10336   if (!FDecl->isInStdNamespace())
10337     return false;
10338 
10339   return true;
10340 }
10341 
10342 // Warn when using the wrong abs() function.
10343 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10344                                       const FunctionDecl *FDecl) {
10345   if (Call->getNumArgs() != 1)
10346     return;
10347 
10348   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10349   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10350   if (AbsKind == 0 && !IsStdAbs)
10351     return;
10352 
10353   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10354   QualType ParamType = Call->getArg(0)->getType();
10355 
10356   // Unsigned types cannot be negative.  Suggest removing the absolute value
10357   // function call.
10358   if (ArgType->isUnsignedIntegerType()) {
10359     const char *FunctionName =
10360         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10361     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10362     Diag(Call->getExprLoc(), diag::note_remove_abs)
10363         << FunctionName
10364         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10365     return;
10366   }
10367 
10368   // Taking the absolute value of a pointer is very suspicious, they probably
10369   // wanted to index into an array, dereference a pointer, call a function, etc.
10370   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10371     unsigned DiagType = 0;
10372     if (ArgType->isFunctionType())
10373       DiagType = 1;
10374     else if (ArgType->isArrayType())
10375       DiagType = 2;
10376 
10377     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10378     return;
10379   }
10380 
10381   // std::abs has overloads which prevent most of the absolute value problems
10382   // from occurring.
10383   if (IsStdAbs)
10384     return;
10385 
10386   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10387   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10388 
10389   // The argument and parameter are the same kind.  Check if they are the right
10390   // size.
10391   if (ArgValueKind == ParamValueKind) {
10392     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10393       return;
10394 
10395     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10396     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10397         << FDecl << ArgType << ParamType;
10398 
10399     if (NewAbsKind == 0)
10400       return;
10401 
10402     emitReplacement(*this, Call->getExprLoc(),
10403                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10404     return;
10405   }
10406 
10407   // ArgValueKind != ParamValueKind
10408   // The wrong type of absolute value function was used.  Attempt to find the
10409   // proper one.
10410   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10411   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10412   if (NewAbsKind == 0)
10413     return;
10414 
10415   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10416       << FDecl << ParamValueKind << ArgValueKind;
10417 
10418   emitReplacement(*this, Call->getExprLoc(),
10419                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10420 }
10421 
10422 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10423 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10424                                 const FunctionDecl *FDecl) {
10425   if (!Call || !FDecl) return;
10426 
10427   // Ignore template specializations and macros.
10428   if (inTemplateInstantiation()) return;
10429   if (Call->getExprLoc().isMacroID()) return;
10430 
10431   // Only care about the one template argument, two function parameter std::max
10432   if (Call->getNumArgs() != 2) return;
10433   if (!IsStdFunction(FDecl, "max")) return;
10434   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10435   if (!ArgList) return;
10436   if (ArgList->size() != 1) return;
10437 
10438   // Check that template type argument is unsigned integer.
10439   const auto& TA = ArgList->get(0);
10440   if (TA.getKind() != TemplateArgument::Type) return;
10441   QualType ArgType = TA.getAsType();
10442   if (!ArgType->isUnsignedIntegerType()) return;
10443 
10444   // See if either argument is a literal zero.
10445   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10446     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10447     if (!MTE) return false;
10448     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10449     if (!Num) return false;
10450     if (Num->getValue() != 0) return false;
10451     return true;
10452   };
10453 
10454   const Expr *FirstArg = Call->getArg(0);
10455   const Expr *SecondArg = Call->getArg(1);
10456   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10457   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10458 
10459   // Only warn when exactly one argument is zero.
10460   if (IsFirstArgZero == IsSecondArgZero) return;
10461 
10462   SourceRange FirstRange = FirstArg->getSourceRange();
10463   SourceRange SecondRange = SecondArg->getSourceRange();
10464 
10465   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10466 
10467   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10468       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10469 
10470   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10471   SourceRange RemovalRange;
10472   if (IsFirstArgZero) {
10473     RemovalRange = SourceRange(FirstRange.getBegin(),
10474                                SecondRange.getBegin().getLocWithOffset(-1));
10475   } else {
10476     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10477                                SecondRange.getEnd());
10478   }
10479 
10480   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10481         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10482         << FixItHint::CreateRemoval(RemovalRange);
10483 }
10484 
10485 //===--- CHECK: Standard memory functions ---------------------------------===//
10486 
10487 /// Takes the expression passed to the size_t parameter of functions
10488 /// such as memcmp, strncat, etc and warns if it's a comparison.
10489 ///
10490 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10491 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10492                                            IdentifierInfo *FnName,
10493                                            SourceLocation FnLoc,
10494                                            SourceLocation RParenLoc) {
10495   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10496   if (!Size)
10497     return false;
10498 
10499   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10500   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10501     return false;
10502 
10503   SourceRange SizeRange = Size->getSourceRange();
10504   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10505       << SizeRange << FnName;
10506   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10507       << FnName
10508       << FixItHint::CreateInsertion(
10509              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10510       << FixItHint::CreateRemoval(RParenLoc);
10511   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10512       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10513       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10514                                     ")");
10515 
10516   return true;
10517 }
10518 
10519 /// Determine whether the given type is or contains a dynamic class type
10520 /// (e.g., whether it has a vtable).
10521 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10522                                                      bool &IsContained) {
10523   // Look through array types while ignoring qualifiers.
10524   const Type *Ty = T->getBaseElementTypeUnsafe();
10525   IsContained = false;
10526 
10527   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10528   RD = RD ? RD->getDefinition() : nullptr;
10529   if (!RD || RD->isInvalidDecl())
10530     return nullptr;
10531 
10532   if (RD->isDynamicClass())
10533     return RD;
10534 
10535   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10536   // It's impossible for a class to transitively contain itself by value, so
10537   // infinite recursion is impossible.
10538   for (auto *FD : RD->fields()) {
10539     bool SubContained;
10540     if (const CXXRecordDecl *ContainedRD =
10541             getContainedDynamicClass(FD->getType(), SubContained)) {
10542       IsContained = true;
10543       return ContainedRD;
10544     }
10545   }
10546 
10547   return nullptr;
10548 }
10549 
10550 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10551   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10552     if (Unary->getKind() == UETT_SizeOf)
10553       return Unary;
10554   return nullptr;
10555 }
10556 
10557 /// If E is a sizeof expression, returns its argument expression,
10558 /// otherwise returns NULL.
10559 static const Expr *getSizeOfExprArg(const Expr *E) {
10560   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10561     if (!SizeOf->isArgumentType())
10562       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10563   return nullptr;
10564 }
10565 
10566 /// If E is a sizeof expression, returns its argument type.
10567 static QualType getSizeOfArgType(const Expr *E) {
10568   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10569     return SizeOf->getTypeOfArgument();
10570   return QualType();
10571 }
10572 
10573 namespace {
10574 
10575 struct SearchNonTrivialToInitializeField
10576     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10577   using Super =
10578       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10579 
10580   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10581 
10582   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10583                      SourceLocation SL) {
10584     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10585       asDerived().visitArray(PDIK, AT, SL);
10586       return;
10587     }
10588 
10589     Super::visitWithKind(PDIK, FT, SL);
10590   }
10591 
10592   void visitARCStrong(QualType FT, SourceLocation SL) {
10593     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10594   }
10595   void visitARCWeak(QualType FT, SourceLocation SL) {
10596     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10597   }
10598   void visitStruct(QualType FT, SourceLocation SL) {
10599     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10600       visit(FD->getType(), FD->getLocation());
10601   }
10602   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10603                   const ArrayType *AT, SourceLocation SL) {
10604     visit(getContext().getBaseElementType(AT), SL);
10605   }
10606   void visitTrivial(QualType FT, SourceLocation SL) {}
10607 
10608   static void diag(QualType RT, const Expr *E, Sema &S) {
10609     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10610   }
10611 
10612   ASTContext &getContext() { return S.getASTContext(); }
10613 
10614   const Expr *E;
10615   Sema &S;
10616 };
10617 
10618 struct SearchNonTrivialToCopyField
10619     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10620   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10621 
10622   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10623 
10624   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10625                      SourceLocation SL) {
10626     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10627       asDerived().visitArray(PCK, AT, SL);
10628       return;
10629     }
10630 
10631     Super::visitWithKind(PCK, FT, SL);
10632   }
10633 
10634   void visitARCStrong(QualType FT, SourceLocation SL) {
10635     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10636   }
10637   void visitARCWeak(QualType FT, SourceLocation SL) {
10638     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10639   }
10640   void visitStruct(QualType FT, SourceLocation SL) {
10641     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10642       visit(FD->getType(), FD->getLocation());
10643   }
10644   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10645                   SourceLocation SL) {
10646     visit(getContext().getBaseElementType(AT), SL);
10647   }
10648   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10649                 SourceLocation SL) {}
10650   void visitTrivial(QualType FT, SourceLocation SL) {}
10651   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10652 
10653   static void diag(QualType RT, const Expr *E, Sema &S) {
10654     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10655   }
10656 
10657   ASTContext &getContext() { return S.getASTContext(); }
10658 
10659   const Expr *E;
10660   Sema &S;
10661 };
10662 
10663 }
10664 
10665 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10666 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10667   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10668 
10669   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10670     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10671       return false;
10672 
10673     return doesExprLikelyComputeSize(BO->getLHS()) ||
10674            doesExprLikelyComputeSize(BO->getRHS());
10675   }
10676 
10677   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10678 }
10679 
10680 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10681 ///
10682 /// \code
10683 ///   #define MACRO 0
10684 ///   foo(MACRO);
10685 ///   foo(0);
10686 /// \endcode
10687 ///
10688 /// This should return true for the first call to foo, but not for the second
10689 /// (regardless of whether foo is a macro or function).
10690 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10691                                         SourceLocation CallLoc,
10692                                         SourceLocation ArgLoc) {
10693   if (!CallLoc.isMacroID())
10694     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10695 
10696   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10697          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10698 }
10699 
10700 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10701 /// last two arguments transposed.
10702 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10703   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10704     return;
10705 
10706   const Expr *SizeArg =
10707     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10708 
10709   auto isLiteralZero = [](const Expr *E) {
10710     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10711   };
10712 
10713   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10714   SourceLocation CallLoc = Call->getRParenLoc();
10715   SourceManager &SM = S.getSourceManager();
10716   if (isLiteralZero(SizeArg) &&
10717       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10718 
10719     SourceLocation DiagLoc = SizeArg->getExprLoc();
10720 
10721     // Some platforms #define bzero to __builtin_memset. See if this is the
10722     // case, and if so, emit a better diagnostic.
10723     if (BId == Builtin::BIbzero ||
10724         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10725                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10726       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10727       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10728     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10729       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10730       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10731     }
10732     return;
10733   }
10734 
10735   // If the second argument to a memset is a sizeof expression and the third
10736   // isn't, this is also likely an error. This should catch
10737   // 'memset(buf, sizeof(buf), 0xff)'.
10738   if (BId == Builtin::BImemset &&
10739       doesExprLikelyComputeSize(Call->getArg(1)) &&
10740       !doesExprLikelyComputeSize(Call->getArg(2))) {
10741     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10742     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10743     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10744     return;
10745   }
10746 }
10747 
10748 /// Check for dangerous or invalid arguments to memset().
10749 ///
10750 /// This issues warnings on known problematic, dangerous or unspecified
10751 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10752 /// function calls.
10753 ///
10754 /// \param Call The call expression to diagnose.
10755 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10756                                    unsigned BId,
10757                                    IdentifierInfo *FnName) {
10758   assert(BId != 0);
10759 
10760   // It is possible to have a non-standard definition of memset.  Validate
10761   // we have enough arguments, and if not, abort further checking.
10762   unsigned ExpectedNumArgs =
10763       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10764   if (Call->getNumArgs() < ExpectedNumArgs)
10765     return;
10766 
10767   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10768                       BId == Builtin::BIstrndup ? 1 : 2);
10769   unsigned LenArg =
10770       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10771   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10772 
10773   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10774                                      Call->getBeginLoc(), Call->getRParenLoc()))
10775     return;
10776 
10777   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10778   CheckMemaccessSize(*this, BId, Call);
10779 
10780   // We have special checking when the length is a sizeof expression.
10781   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10782   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10783   llvm::FoldingSetNodeID SizeOfArgID;
10784 
10785   // Although widely used, 'bzero' is not a standard function. Be more strict
10786   // with the argument types before allowing diagnostics and only allow the
10787   // form bzero(ptr, sizeof(...)).
10788   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10789   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10790     return;
10791 
10792   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10793     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10794     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10795 
10796     QualType DestTy = Dest->getType();
10797     QualType PointeeTy;
10798     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10799       PointeeTy = DestPtrTy->getPointeeType();
10800 
10801       // Never warn about void type pointers. This can be used to suppress
10802       // false positives.
10803       if (PointeeTy->isVoidType())
10804         continue;
10805 
10806       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10807       // actually comparing the expressions for equality. Because computing the
10808       // expression IDs can be expensive, we only do this if the diagnostic is
10809       // enabled.
10810       if (SizeOfArg &&
10811           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10812                            SizeOfArg->getExprLoc())) {
10813         // We only compute IDs for expressions if the warning is enabled, and
10814         // cache the sizeof arg's ID.
10815         if (SizeOfArgID == llvm::FoldingSetNodeID())
10816           SizeOfArg->Profile(SizeOfArgID, Context, true);
10817         llvm::FoldingSetNodeID DestID;
10818         Dest->Profile(DestID, Context, true);
10819         if (DestID == SizeOfArgID) {
10820           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10821           //       over sizeof(src) as well.
10822           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10823           StringRef ReadableName = FnName->getName();
10824 
10825           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10826             if (UnaryOp->getOpcode() == UO_AddrOf)
10827               ActionIdx = 1; // If its an address-of operator, just remove it.
10828           if (!PointeeTy->isIncompleteType() &&
10829               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10830             ActionIdx = 2; // If the pointee's size is sizeof(char),
10831                            // suggest an explicit length.
10832 
10833           // If the function is defined as a builtin macro, do not show macro
10834           // expansion.
10835           SourceLocation SL = SizeOfArg->getExprLoc();
10836           SourceRange DSR = Dest->getSourceRange();
10837           SourceRange SSR = SizeOfArg->getSourceRange();
10838           SourceManager &SM = getSourceManager();
10839 
10840           if (SM.isMacroArgExpansion(SL)) {
10841             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10842             SL = SM.getSpellingLoc(SL);
10843             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10844                              SM.getSpellingLoc(DSR.getEnd()));
10845             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10846                              SM.getSpellingLoc(SSR.getEnd()));
10847           }
10848 
10849           DiagRuntimeBehavior(SL, SizeOfArg,
10850                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10851                                 << ReadableName
10852                                 << PointeeTy
10853                                 << DestTy
10854                                 << DSR
10855                                 << SSR);
10856           DiagRuntimeBehavior(SL, SizeOfArg,
10857                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10858                                 << ActionIdx
10859                                 << SSR);
10860 
10861           break;
10862         }
10863       }
10864 
10865       // Also check for cases where the sizeof argument is the exact same
10866       // type as the memory argument, and where it points to a user-defined
10867       // record type.
10868       if (SizeOfArgTy != QualType()) {
10869         if (PointeeTy->isRecordType() &&
10870             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10871           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10872                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10873                                 << FnName << SizeOfArgTy << ArgIdx
10874                                 << PointeeTy << Dest->getSourceRange()
10875                                 << LenExpr->getSourceRange());
10876           break;
10877         }
10878       }
10879     } else if (DestTy->isArrayType()) {
10880       PointeeTy = DestTy;
10881     }
10882 
10883     if (PointeeTy == QualType())
10884       continue;
10885 
10886     // Always complain about dynamic classes.
10887     bool IsContained;
10888     if (const CXXRecordDecl *ContainedRD =
10889             getContainedDynamicClass(PointeeTy, IsContained)) {
10890 
10891       unsigned OperationType = 0;
10892       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10893       // "overwritten" if we're warning about the destination for any call
10894       // but memcmp; otherwise a verb appropriate to the call.
10895       if (ArgIdx != 0 || IsCmp) {
10896         if (BId == Builtin::BImemcpy)
10897           OperationType = 1;
10898         else if(BId == Builtin::BImemmove)
10899           OperationType = 2;
10900         else if (IsCmp)
10901           OperationType = 3;
10902       }
10903 
10904       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10905                           PDiag(diag::warn_dyn_class_memaccess)
10906                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10907                               << IsContained << ContainedRD << OperationType
10908                               << Call->getCallee()->getSourceRange());
10909     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10910              BId != Builtin::BImemset)
10911       DiagRuntimeBehavior(
10912         Dest->getExprLoc(), Dest,
10913         PDiag(diag::warn_arc_object_memaccess)
10914           << ArgIdx << FnName << PointeeTy
10915           << Call->getCallee()->getSourceRange());
10916     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10917       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10918           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10919         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10920                             PDiag(diag::warn_cstruct_memaccess)
10921                                 << ArgIdx << FnName << PointeeTy << 0);
10922         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10923       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10924                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10925         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10926                             PDiag(diag::warn_cstruct_memaccess)
10927                                 << ArgIdx << FnName << PointeeTy << 1);
10928         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10929       } else {
10930         continue;
10931       }
10932     } else
10933       continue;
10934 
10935     DiagRuntimeBehavior(
10936       Dest->getExprLoc(), Dest,
10937       PDiag(diag::note_bad_memaccess_silence)
10938         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10939     break;
10940   }
10941 }
10942 
10943 // A little helper routine: ignore addition and subtraction of integer literals.
10944 // This intentionally does not ignore all integer constant expressions because
10945 // we don't want to remove sizeof().
10946 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10947   Ex = Ex->IgnoreParenCasts();
10948 
10949   while (true) {
10950     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10951     if (!BO || !BO->isAdditiveOp())
10952       break;
10953 
10954     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10955     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10956 
10957     if (isa<IntegerLiteral>(RHS))
10958       Ex = LHS;
10959     else if (isa<IntegerLiteral>(LHS))
10960       Ex = RHS;
10961     else
10962       break;
10963   }
10964 
10965   return Ex;
10966 }
10967 
10968 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10969                                                       ASTContext &Context) {
10970   // Only handle constant-sized or VLAs, but not flexible members.
10971   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10972     // Only issue the FIXIT for arrays of size > 1.
10973     if (CAT->getSize().getSExtValue() <= 1)
10974       return false;
10975   } else if (!Ty->isVariableArrayType()) {
10976     return false;
10977   }
10978   return true;
10979 }
10980 
10981 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10982 // be the size of the source, instead of the destination.
10983 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10984                                     IdentifierInfo *FnName) {
10985 
10986   // Don't crash if the user has the wrong number of arguments
10987   unsigned NumArgs = Call->getNumArgs();
10988   if ((NumArgs != 3) && (NumArgs != 4))
10989     return;
10990 
10991   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10992   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10993   const Expr *CompareWithSrc = nullptr;
10994 
10995   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10996                                      Call->getBeginLoc(), Call->getRParenLoc()))
10997     return;
10998 
10999   // Look for 'strlcpy(dst, x, sizeof(x))'
11000   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11001     CompareWithSrc = Ex;
11002   else {
11003     // Look for 'strlcpy(dst, x, strlen(x))'
11004     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11005       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11006           SizeCall->getNumArgs() == 1)
11007         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11008     }
11009   }
11010 
11011   if (!CompareWithSrc)
11012     return;
11013 
11014   // Determine if the argument to sizeof/strlen is equal to the source
11015   // argument.  In principle there's all kinds of things you could do
11016   // here, for instance creating an == expression and evaluating it with
11017   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11018   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11019   if (!SrcArgDRE)
11020     return;
11021 
11022   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11023   if (!CompareWithSrcDRE ||
11024       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11025     return;
11026 
11027   const Expr *OriginalSizeArg = Call->getArg(2);
11028   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11029       << OriginalSizeArg->getSourceRange() << FnName;
11030 
11031   // Output a FIXIT hint if the destination is an array (rather than a
11032   // pointer to an array).  This could be enhanced to handle some
11033   // pointers if we know the actual size, like if DstArg is 'array+2'
11034   // we could say 'sizeof(array)-2'.
11035   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11036   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11037     return;
11038 
11039   SmallString<128> sizeString;
11040   llvm::raw_svector_ostream OS(sizeString);
11041   OS << "sizeof(";
11042   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11043   OS << ")";
11044 
11045   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11046       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11047                                       OS.str());
11048 }
11049 
11050 /// Check if two expressions refer to the same declaration.
11051 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11052   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11053     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11054       return D1->getDecl() == D2->getDecl();
11055   return false;
11056 }
11057 
11058 static const Expr *getStrlenExprArg(const Expr *E) {
11059   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11060     const FunctionDecl *FD = CE->getDirectCallee();
11061     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11062       return nullptr;
11063     return CE->getArg(0)->IgnoreParenCasts();
11064   }
11065   return nullptr;
11066 }
11067 
11068 // Warn on anti-patterns as the 'size' argument to strncat.
11069 // The correct size argument should look like following:
11070 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11071 void Sema::CheckStrncatArguments(const CallExpr *CE,
11072                                  IdentifierInfo *FnName) {
11073   // Don't crash if the user has the wrong number of arguments.
11074   if (CE->getNumArgs() < 3)
11075     return;
11076   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11077   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11078   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11079 
11080   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11081                                      CE->getRParenLoc()))
11082     return;
11083 
11084   // Identify common expressions, which are wrongly used as the size argument
11085   // to strncat and may lead to buffer overflows.
11086   unsigned PatternType = 0;
11087   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11088     // - sizeof(dst)
11089     if (referToTheSameDecl(SizeOfArg, DstArg))
11090       PatternType = 1;
11091     // - sizeof(src)
11092     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11093       PatternType = 2;
11094   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11095     if (BE->getOpcode() == BO_Sub) {
11096       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11097       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11098       // - sizeof(dst) - strlen(dst)
11099       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11100           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11101         PatternType = 1;
11102       // - sizeof(src) - (anything)
11103       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11104         PatternType = 2;
11105     }
11106   }
11107 
11108   if (PatternType == 0)
11109     return;
11110 
11111   // Generate the diagnostic.
11112   SourceLocation SL = LenArg->getBeginLoc();
11113   SourceRange SR = LenArg->getSourceRange();
11114   SourceManager &SM = getSourceManager();
11115 
11116   // If the function is defined as a builtin macro, do not show macro expansion.
11117   if (SM.isMacroArgExpansion(SL)) {
11118     SL = SM.getSpellingLoc(SL);
11119     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11120                      SM.getSpellingLoc(SR.getEnd()));
11121   }
11122 
11123   // Check if the destination is an array (rather than a pointer to an array).
11124   QualType DstTy = DstArg->getType();
11125   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11126                                                                     Context);
11127   if (!isKnownSizeArray) {
11128     if (PatternType == 1)
11129       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11130     else
11131       Diag(SL, diag::warn_strncat_src_size) << SR;
11132     return;
11133   }
11134 
11135   if (PatternType == 1)
11136     Diag(SL, diag::warn_strncat_large_size) << SR;
11137   else
11138     Diag(SL, diag::warn_strncat_src_size) << SR;
11139 
11140   SmallString<128> sizeString;
11141   llvm::raw_svector_ostream OS(sizeString);
11142   OS << "sizeof(";
11143   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11144   OS << ") - ";
11145   OS << "strlen(";
11146   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11147   OS << ") - 1";
11148 
11149   Diag(SL, diag::note_strncat_wrong_size)
11150     << FixItHint::CreateReplacement(SR, OS.str());
11151 }
11152 
11153 namespace {
11154 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11155                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11156   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11157     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11158         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11159     return;
11160   }
11161 }
11162 
11163 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11164                                  const UnaryOperator *UnaryExpr) {
11165   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11166     const Decl *D = Lvalue->getDecl();
11167     if (isa<DeclaratorDecl>(D))
11168       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11169         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11170   }
11171 
11172   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11173     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11174                                       Lvalue->getMemberDecl());
11175 }
11176 
11177 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11178                             const UnaryOperator *UnaryExpr) {
11179   const auto *Lambda = dyn_cast<LambdaExpr>(
11180       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11181   if (!Lambda)
11182     return;
11183 
11184   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11185       << CalleeName << 2 /*object: lambda expression*/;
11186 }
11187 
11188 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11189                                   const DeclRefExpr *Lvalue) {
11190   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11191   if (Var == nullptr)
11192     return;
11193 
11194   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11195       << CalleeName << 0 /*object: */ << Var;
11196 }
11197 
11198 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11199                             const CastExpr *Cast) {
11200   SmallString<128> SizeString;
11201   llvm::raw_svector_ostream OS(SizeString);
11202 
11203   clang::CastKind Kind = Cast->getCastKind();
11204   if (Kind == clang::CK_BitCast &&
11205       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11206     return;
11207   if (Kind == clang::CK_IntegralToPointer &&
11208       !isa<IntegerLiteral>(
11209           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11210     return;
11211 
11212   switch (Cast->getCastKind()) {
11213   case clang::CK_BitCast:
11214   case clang::CK_IntegralToPointer:
11215   case clang::CK_FunctionToPointerDecay:
11216     OS << '\'';
11217     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11218     OS << '\'';
11219     break;
11220   default:
11221     return;
11222   }
11223 
11224   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11225       << CalleeName << 0 /*object: */ << OS.str();
11226 }
11227 } // namespace
11228 
11229 /// Alerts the user that they are attempting to free a non-malloc'd object.
11230 void Sema::CheckFreeArguments(const CallExpr *E) {
11231   const std::string CalleeName =
11232       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11233 
11234   { // Prefer something that doesn't involve a cast to make things simpler.
11235     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11236     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11237       switch (UnaryExpr->getOpcode()) {
11238       case UnaryOperator::Opcode::UO_AddrOf:
11239         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11240       case UnaryOperator::Opcode::UO_Plus:
11241         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11242       default:
11243         break;
11244       }
11245 
11246     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11247       if (Lvalue->getType()->isArrayType())
11248         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11249 
11250     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11251       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11252           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11253       return;
11254     }
11255 
11256     if (isa<BlockExpr>(Arg)) {
11257       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11258           << CalleeName << 1 /*object: block*/;
11259       return;
11260     }
11261   }
11262   // Maybe the cast was important, check after the other cases.
11263   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11264     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11265 }
11266 
11267 void
11268 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11269                          SourceLocation ReturnLoc,
11270                          bool isObjCMethod,
11271                          const AttrVec *Attrs,
11272                          const FunctionDecl *FD) {
11273   // Check if the return value is null but should not be.
11274   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11275        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11276       CheckNonNullExpr(*this, RetValExp))
11277     Diag(ReturnLoc, diag::warn_null_ret)
11278       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11279 
11280   // C++11 [basic.stc.dynamic.allocation]p4:
11281   //   If an allocation function declared with a non-throwing
11282   //   exception-specification fails to allocate storage, it shall return
11283   //   a null pointer. Any other allocation function that fails to allocate
11284   //   storage shall indicate failure only by throwing an exception [...]
11285   if (FD) {
11286     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11287     if (Op == OO_New || Op == OO_Array_New) {
11288       const FunctionProtoType *Proto
11289         = FD->getType()->castAs<FunctionProtoType>();
11290       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11291           CheckNonNullExpr(*this, RetValExp))
11292         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11293           << FD << getLangOpts().CPlusPlus11;
11294     }
11295   }
11296 
11297   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11298   // here prevent the user from using a PPC MMA type as trailing return type.
11299   if (Context.getTargetInfo().getTriple().isPPC64())
11300     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11301 }
11302 
11303 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11304 
11305 /// Check for comparisons of floating point operands using != and ==.
11306 /// Issue a warning if these are no self-comparisons, as they are not likely
11307 /// to do what the programmer intended.
11308 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11309   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11310   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11311 
11312   // Special case: check for x == x (which is OK).
11313   // Do not emit warnings for such cases.
11314   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11315     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11316       if (DRL->getDecl() == DRR->getDecl())
11317         return;
11318 
11319   // Special case: check for comparisons against literals that can be exactly
11320   //  represented by APFloat.  In such cases, do not emit a warning.  This
11321   //  is a heuristic: often comparison against such literals are used to
11322   //  detect if a value in a variable has not changed.  This clearly can
11323   //  lead to false negatives.
11324   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11325     if (FLL->isExact())
11326       return;
11327   } else
11328     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11329       if (FLR->isExact())
11330         return;
11331 
11332   // Check for comparisons with builtin types.
11333   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11334     if (CL->getBuiltinCallee())
11335       return;
11336 
11337   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11338     if (CR->getBuiltinCallee())
11339       return;
11340 
11341   // Emit the diagnostic.
11342   Diag(Loc, diag::warn_floatingpoint_eq)
11343     << LHS->getSourceRange() << RHS->getSourceRange();
11344 }
11345 
11346 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11347 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11348 
11349 namespace {
11350 
11351 /// Structure recording the 'active' range of an integer-valued
11352 /// expression.
11353 struct IntRange {
11354   /// The number of bits active in the int. Note that this includes exactly one
11355   /// sign bit if !NonNegative.
11356   unsigned Width;
11357 
11358   /// True if the int is known not to have negative values. If so, all leading
11359   /// bits before Width are known zero, otherwise they are known to be the
11360   /// same as the MSB within Width.
11361   bool NonNegative;
11362 
11363   IntRange(unsigned Width, bool NonNegative)
11364       : Width(Width), NonNegative(NonNegative) {}
11365 
11366   /// Number of bits excluding the sign bit.
11367   unsigned valueBits() const {
11368     return NonNegative ? Width : Width - 1;
11369   }
11370 
11371   /// Returns the range of the bool type.
11372   static IntRange forBoolType() {
11373     return IntRange(1, true);
11374   }
11375 
11376   /// Returns the range of an opaque value of the given integral type.
11377   static IntRange forValueOfType(ASTContext &C, QualType T) {
11378     return forValueOfCanonicalType(C,
11379                           T->getCanonicalTypeInternal().getTypePtr());
11380   }
11381 
11382   /// Returns the range of an opaque value of a canonical integral type.
11383   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11384     assert(T->isCanonicalUnqualified());
11385 
11386     if (const VectorType *VT = dyn_cast<VectorType>(T))
11387       T = VT->getElementType().getTypePtr();
11388     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11389       T = CT->getElementType().getTypePtr();
11390     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11391       T = AT->getValueType().getTypePtr();
11392 
11393     if (!C.getLangOpts().CPlusPlus) {
11394       // For enum types in C code, use the underlying datatype.
11395       if (const EnumType *ET = dyn_cast<EnumType>(T))
11396         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11397     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11398       // For enum types in C++, use the known bit width of the enumerators.
11399       EnumDecl *Enum = ET->getDecl();
11400       // In C++11, enums can have a fixed underlying type. Use this type to
11401       // compute the range.
11402       if (Enum->isFixed()) {
11403         return IntRange(C.getIntWidth(QualType(T, 0)),
11404                         !ET->isSignedIntegerOrEnumerationType());
11405       }
11406 
11407       unsigned NumPositive = Enum->getNumPositiveBits();
11408       unsigned NumNegative = Enum->getNumNegativeBits();
11409 
11410       if (NumNegative == 0)
11411         return IntRange(NumPositive, true/*NonNegative*/);
11412       else
11413         return IntRange(std::max(NumPositive + 1, NumNegative),
11414                         false/*NonNegative*/);
11415     }
11416 
11417     if (const auto *EIT = dyn_cast<BitIntType>(T))
11418       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11419 
11420     const BuiltinType *BT = cast<BuiltinType>(T);
11421     assert(BT->isInteger());
11422 
11423     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11424   }
11425 
11426   /// Returns the "target" range of a canonical integral type, i.e.
11427   /// the range of values expressible in the type.
11428   ///
11429   /// This matches forValueOfCanonicalType except that enums have the
11430   /// full range of their type, not the range of their enumerators.
11431   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11432     assert(T->isCanonicalUnqualified());
11433 
11434     if (const VectorType *VT = dyn_cast<VectorType>(T))
11435       T = VT->getElementType().getTypePtr();
11436     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11437       T = CT->getElementType().getTypePtr();
11438     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11439       T = AT->getValueType().getTypePtr();
11440     if (const EnumType *ET = dyn_cast<EnumType>(T))
11441       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11442 
11443     if (const auto *EIT = dyn_cast<BitIntType>(T))
11444       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11445 
11446     const BuiltinType *BT = cast<BuiltinType>(T);
11447     assert(BT->isInteger());
11448 
11449     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11450   }
11451 
11452   /// Returns the supremum of two ranges: i.e. their conservative merge.
11453   static IntRange join(IntRange L, IntRange R) {
11454     bool Unsigned = L.NonNegative && R.NonNegative;
11455     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11456                     L.NonNegative && R.NonNegative);
11457   }
11458 
11459   /// Return the range of a bitwise-AND of the two ranges.
11460   static IntRange bit_and(IntRange L, IntRange R) {
11461     unsigned Bits = std::max(L.Width, R.Width);
11462     bool NonNegative = false;
11463     if (L.NonNegative) {
11464       Bits = std::min(Bits, L.Width);
11465       NonNegative = true;
11466     }
11467     if (R.NonNegative) {
11468       Bits = std::min(Bits, R.Width);
11469       NonNegative = true;
11470     }
11471     return IntRange(Bits, NonNegative);
11472   }
11473 
11474   /// Return the range of a sum of the two ranges.
11475   static IntRange sum(IntRange L, IntRange R) {
11476     bool Unsigned = L.NonNegative && R.NonNegative;
11477     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11478                     Unsigned);
11479   }
11480 
11481   /// Return the range of a difference of the two ranges.
11482   static IntRange difference(IntRange L, IntRange R) {
11483     // We need a 1-bit-wider range if:
11484     //   1) LHS can be negative: least value can be reduced.
11485     //   2) RHS can be negative: greatest value can be increased.
11486     bool CanWiden = !L.NonNegative || !R.NonNegative;
11487     bool Unsigned = L.NonNegative && R.Width == 0;
11488     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11489                         !Unsigned,
11490                     Unsigned);
11491   }
11492 
11493   /// Return the range of a product of the two ranges.
11494   static IntRange product(IntRange L, IntRange R) {
11495     // If both LHS and RHS can be negative, we can form
11496     //   -2^L * -2^R = 2^(L + R)
11497     // which requires L + R + 1 value bits to represent.
11498     bool CanWiden = !L.NonNegative && !R.NonNegative;
11499     bool Unsigned = L.NonNegative && R.NonNegative;
11500     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11501                     Unsigned);
11502   }
11503 
11504   /// Return the range of a remainder operation between the two ranges.
11505   static IntRange rem(IntRange L, IntRange R) {
11506     // The result of a remainder can't be larger than the result of
11507     // either side. The sign of the result is the sign of the LHS.
11508     bool Unsigned = L.NonNegative;
11509     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11510                     Unsigned);
11511   }
11512 };
11513 
11514 } // namespace
11515 
11516 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11517                               unsigned MaxWidth) {
11518   if (value.isSigned() && value.isNegative())
11519     return IntRange(value.getMinSignedBits(), false);
11520 
11521   if (value.getBitWidth() > MaxWidth)
11522     value = value.trunc(MaxWidth);
11523 
11524   // isNonNegative() just checks the sign bit without considering
11525   // signedness.
11526   return IntRange(value.getActiveBits(), true);
11527 }
11528 
11529 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11530                               unsigned MaxWidth) {
11531   if (result.isInt())
11532     return GetValueRange(C, result.getInt(), MaxWidth);
11533 
11534   if (result.isVector()) {
11535     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11536     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11537       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11538       R = IntRange::join(R, El);
11539     }
11540     return R;
11541   }
11542 
11543   if (result.isComplexInt()) {
11544     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11545     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11546     return IntRange::join(R, I);
11547   }
11548 
11549   // This can happen with lossless casts to intptr_t of "based" lvalues.
11550   // Assume it might use arbitrary bits.
11551   // FIXME: The only reason we need to pass the type in here is to get
11552   // the sign right on this one case.  It would be nice if APValue
11553   // preserved this.
11554   assert(result.isLValue() || result.isAddrLabelDiff());
11555   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11556 }
11557 
11558 static QualType GetExprType(const Expr *E) {
11559   QualType Ty = E->getType();
11560   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11561     Ty = AtomicRHS->getValueType();
11562   return Ty;
11563 }
11564 
11565 /// Pseudo-evaluate the given integer expression, estimating the
11566 /// range of values it might take.
11567 ///
11568 /// \param MaxWidth The width to which the value will be truncated.
11569 /// \param Approximate If \c true, return a likely range for the result: in
11570 ///        particular, assume that arithmetic on narrower types doesn't leave
11571 ///        those types. If \c false, return a range including all possible
11572 ///        result values.
11573 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11574                              bool InConstantContext, bool Approximate) {
11575   E = E->IgnoreParens();
11576 
11577   // Try a full evaluation first.
11578   Expr::EvalResult result;
11579   if (E->EvaluateAsRValue(result, C, InConstantContext))
11580     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11581 
11582   // I think we only want to look through implicit casts here; if the
11583   // user has an explicit widening cast, we should treat the value as
11584   // being of the new, wider type.
11585   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11586     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11587       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11588                           Approximate);
11589 
11590     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11591 
11592     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11593                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11594 
11595     // Assume that non-integer casts can span the full range of the type.
11596     if (!isIntegerCast)
11597       return OutputTypeRange;
11598 
11599     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11600                                      std::min(MaxWidth, OutputTypeRange.Width),
11601                                      InConstantContext, Approximate);
11602 
11603     // Bail out if the subexpr's range is as wide as the cast type.
11604     if (SubRange.Width >= OutputTypeRange.Width)
11605       return OutputTypeRange;
11606 
11607     // Otherwise, we take the smaller width, and we're non-negative if
11608     // either the output type or the subexpr is.
11609     return IntRange(SubRange.Width,
11610                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11611   }
11612 
11613   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11614     // If we can fold the condition, just take that operand.
11615     bool CondResult;
11616     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11617       return GetExprRange(C,
11618                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11619                           MaxWidth, InConstantContext, Approximate);
11620 
11621     // Otherwise, conservatively merge.
11622     // GetExprRange requires an integer expression, but a throw expression
11623     // results in a void type.
11624     Expr *E = CO->getTrueExpr();
11625     IntRange L = E->getType()->isVoidType()
11626                      ? IntRange{0, true}
11627                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11628     E = CO->getFalseExpr();
11629     IntRange R = E->getType()->isVoidType()
11630                      ? IntRange{0, true}
11631                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11632     return IntRange::join(L, R);
11633   }
11634 
11635   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11636     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11637 
11638     switch (BO->getOpcode()) {
11639     case BO_Cmp:
11640       llvm_unreachable("builtin <=> should have class type");
11641 
11642     // Boolean-valued operations are single-bit and positive.
11643     case BO_LAnd:
11644     case BO_LOr:
11645     case BO_LT:
11646     case BO_GT:
11647     case BO_LE:
11648     case BO_GE:
11649     case BO_EQ:
11650     case BO_NE:
11651       return IntRange::forBoolType();
11652 
11653     // The type of the assignments is the type of the LHS, so the RHS
11654     // is not necessarily the same type.
11655     case BO_MulAssign:
11656     case BO_DivAssign:
11657     case BO_RemAssign:
11658     case BO_AddAssign:
11659     case BO_SubAssign:
11660     case BO_XorAssign:
11661     case BO_OrAssign:
11662       // TODO: bitfields?
11663       return IntRange::forValueOfType(C, GetExprType(E));
11664 
11665     // Simple assignments just pass through the RHS, which will have
11666     // been coerced to the LHS type.
11667     case BO_Assign:
11668       // TODO: bitfields?
11669       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11670                           Approximate);
11671 
11672     // Operations with opaque sources are black-listed.
11673     case BO_PtrMemD:
11674     case BO_PtrMemI:
11675       return IntRange::forValueOfType(C, GetExprType(E));
11676 
11677     // Bitwise-and uses the *infinum* of the two source ranges.
11678     case BO_And:
11679     case BO_AndAssign:
11680       Combine = IntRange::bit_and;
11681       break;
11682 
11683     // Left shift gets black-listed based on a judgement call.
11684     case BO_Shl:
11685       // ...except that we want to treat '1 << (blah)' as logically
11686       // positive.  It's an important idiom.
11687       if (IntegerLiteral *I
11688             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11689         if (I->getValue() == 1) {
11690           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11691           return IntRange(R.Width, /*NonNegative*/ true);
11692         }
11693       }
11694       LLVM_FALLTHROUGH;
11695 
11696     case BO_ShlAssign:
11697       return IntRange::forValueOfType(C, GetExprType(E));
11698 
11699     // Right shift by a constant can narrow its left argument.
11700     case BO_Shr:
11701     case BO_ShrAssign: {
11702       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11703                                 Approximate);
11704 
11705       // If the shift amount is a positive constant, drop the width by
11706       // that much.
11707       if (Optional<llvm::APSInt> shift =
11708               BO->getRHS()->getIntegerConstantExpr(C)) {
11709         if (shift->isNonNegative()) {
11710           unsigned zext = shift->getZExtValue();
11711           if (zext >= L.Width)
11712             L.Width = (L.NonNegative ? 0 : 1);
11713           else
11714             L.Width -= zext;
11715         }
11716       }
11717 
11718       return L;
11719     }
11720 
11721     // Comma acts as its right operand.
11722     case BO_Comma:
11723       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11724                           Approximate);
11725 
11726     case BO_Add:
11727       if (!Approximate)
11728         Combine = IntRange::sum;
11729       break;
11730 
11731     case BO_Sub:
11732       if (BO->getLHS()->getType()->isPointerType())
11733         return IntRange::forValueOfType(C, GetExprType(E));
11734       if (!Approximate)
11735         Combine = IntRange::difference;
11736       break;
11737 
11738     case BO_Mul:
11739       if (!Approximate)
11740         Combine = IntRange::product;
11741       break;
11742 
11743     // The width of a division result is mostly determined by the size
11744     // of the LHS.
11745     case BO_Div: {
11746       // Don't 'pre-truncate' the operands.
11747       unsigned opWidth = C.getIntWidth(GetExprType(E));
11748       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11749                                 Approximate);
11750 
11751       // If the divisor is constant, use that.
11752       if (Optional<llvm::APSInt> divisor =
11753               BO->getRHS()->getIntegerConstantExpr(C)) {
11754         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11755         if (log2 >= L.Width)
11756           L.Width = (L.NonNegative ? 0 : 1);
11757         else
11758           L.Width = std::min(L.Width - log2, MaxWidth);
11759         return L;
11760       }
11761 
11762       // Otherwise, just use the LHS's width.
11763       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11764       // could be -1.
11765       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11766                                 Approximate);
11767       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11768     }
11769 
11770     case BO_Rem:
11771       Combine = IntRange::rem;
11772       break;
11773 
11774     // The default behavior is okay for these.
11775     case BO_Xor:
11776     case BO_Or:
11777       break;
11778     }
11779 
11780     // Combine the two ranges, but limit the result to the type in which we
11781     // performed the computation.
11782     QualType T = GetExprType(E);
11783     unsigned opWidth = C.getIntWidth(T);
11784     IntRange L =
11785         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11786     IntRange R =
11787         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11788     IntRange C = Combine(L, R);
11789     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11790     C.Width = std::min(C.Width, MaxWidth);
11791     return C;
11792   }
11793 
11794   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11795     switch (UO->getOpcode()) {
11796     // Boolean-valued operations are white-listed.
11797     case UO_LNot:
11798       return IntRange::forBoolType();
11799 
11800     // Operations with opaque sources are black-listed.
11801     case UO_Deref:
11802     case UO_AddrOf: // should be impossible
11803       return IntRange::forValueOfType(C, GetExprType(E));
11804 
11805     default:
11806       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11807                           Approximate);
11808     }
11809   }
11810 
11811   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11812     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11813                         Approximate);
11814 
11815   if (const auto *BitField = E->getSourceBitField())
11816     return IntRange(BitField->getBitWidthValue(C),
11817                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11818 
11819   return IntRange::forValueOfType(C, GetExprType(E));
11820 }
11821 
11822 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11823                              bool InConstantContext, bool Approximate) {
11824   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11825                       Approximate);
11826 }
11827 
11828 /// Checks whether the given value, which currently has the given
11829 /// source semantics, has the same value when coerced through the
11830 /// target semantics.
11831 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11832                                  const llvm::fltSemantics &Src,
11833                                  const llvm::fltSemantics &Tgt) {
11834   llvm::APFloat truncated = value;
11835 
11836   bool ignored;
11837   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11838   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11839 
11840   return truncated.bitwiseIsEqual(value);
11841 }
11842 
11843 /// Checks whether the given value, which currently has the given
11844 /// source semantics, has the same value when coerced through the
11845 /// target semantics.
11846 ///
11847 /// The value might be a vector of floats (or a complex number).
11848 static bool IsSameFloatAfterCast(const APValue &value,
11849                                  const llvm::fltSemantics &Src,
11850                                  const llvm::fltSemantics &Tgt) {
11851   if (value.isFloat())
11852     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11853 
11854   if (value.isVector()) {
11855     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11856       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11857         return false;
11858     return true;
11859   }
11860 
11861   assert(value.isComplexFloat());
11862   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11863           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11864 }
11865 
11866 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11867                                        bool IsListInit = false);
11868 
11869 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11870   // Suppress cases where we are comparing against an enum constant.
11871   if (const DeclRefExpr *DR =
11872       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11873     if (isa<EnumConstantDecl>(DR->getDecl()))
11874       return true;
11875 
11876   // Suppress cases where the value is expanded from a macro, unless that macro
11877   // is how a language represents a boolean literal. This is the case in both C
11878   // and Objective-C.
11879   SourceLocation BeginLoc = E->getBeginLoc();
11880   if (BeginLoc.isMacroID()) {
11881     StringRef MacroName = Lexer::getImmediateMacroName(
11882         BeginLoc, S.getSourceManager(), S.getLangOpts());
11883     return MacroName != "YES" && MacroName != "NO" &&
11884            MacroName != "true" && MacroName != "false";
11885   }
11886 
11887   return false;
11888 }
11889 
11890 static bool isKnownToHaveUnsignedValue(Expr *E) {
11891   return E->getType()->isIntegerType() &&
11892          (!E->getType()->isSignedIntegerType() ||
11893           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11894 }
11895 
11896 namespace {
11897 /// The promoted range of values of a type. In general this has the
11898 /// following structure:
11899 ///
11900 ///     |-----------| . . . |-----------|
11901 ///     ^           ^       ^           ^
11902 ///    Min       HoleMin  HoleMax      Max
11903 ///
11904 /// ... where there is only a hole if a signed type is promoted to unsigned
11905 /// (in which case Min and Max are the smallest and largest representable
11906 /// values).
11907 struct PromotedRange {
11908   // Min, or HoleMax if there is a hole.
11909   llvm::APSInt PromotedMin;
11910   // Max, or HoleMin if there is a hole.
11911   llvm::APSInt PromotedMax;
11912 
11913   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11914     if (R.Width == 0)
11915       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11916     else if (R.Width >= BitWidth && !Unsigned) {
11917       // Promotion made the type *narrower*. This happens when promoting
11918       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11919       // Treat all values of 'signed int' as being in range for now.
11920       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11921       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11922     } else {
11923       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11924                         .extOrTrunc(BitWidth);
11925       PromotedMin.setIsUnsigned(Unsigned);
11926 
11927       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11928                         .extOrTrunc(BitWidth);
11929       PromotedMax.setIsUnsigned(Unsigned);
11930     }
11931   }
11932 
11933   // Determine whether this range is contiguous (has no hole).
11934   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11935 
11936   // Where a constant value is within the range.
11937   enum ComparisonResult {
11938     LT = 0x1,
11939     LE = 0x2,
11940     GT = 0x4,
11941     GE = 0x8,
11942     EQ = 0x10,
11943     NE = 0x20,
11944     InRangeFlag = 0x40,
11945 
11946     Less = LE | LT | NE,
11947     Min = LE | InRangeFlag,
11948     InRange = InRangeFlag,
11949     Max = GE | InRangeFlag,
11950     Greater = GE | GT | NE,
11951 
11952     OnlyValue = LE | GE | EQ | InRangeFlag,
11953     InHole = NE
11954   };
11955 
11956   ComparisonResult compare(const llvm::APSInt &Value) const {
11957     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11958            Value.isUnsigned() == PromotedMin.isUnsigned());
11959     if (!isContiguous()) {
11960       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11961       if (Value.isMinValue()) return Min;
11962       if (Value.isMaxValue()) return Max;
11963       if (Value >= PromotedMin) return InRange;
11964       if (Value <= PromotedMax) return InRange;
11965       return InHole;
11966     }
11967 
11968     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11969     case -1: return Less;
11970     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11971     case 1:
11972       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11973       case -1: return InRange;
11974       case 0: return Max;
11975       case 1: return Greater;
11976       }
11977     }
11978 
11979     llvm_unreachable("impossible compare result");
11980   }
11981 
11982   static llvm::Optional<StringRef>
11983   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11984     if (Op == BO_Cmp) {
11985       ComparisonResult LTFlag = LT, GTFlag = GT;
11986       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11987 
11988       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11989       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11990       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11991       return llvm::None;
11992     }
11993 
11994     ComparisonResult TrueFlag, FalseFlag;
11995     if (Op == BO_EQ) {
11996       TrueFlag = EQ;
11997       FalseFlag = NE;
11998     } else if (Op == BO_NE) {
11999       TrueFlag = NE;
12000       FalseFlag = EQ;
12001     } else {
12002       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12003         TrueFlag = LT;
12004         FalseFlag = GE;
12005       } else {
12006         TrueFlag = GT;
12007         FalseFlag = LE;
12008       }
12009       if (Op == BO_GE || Op == BO_LE)
12010         std::swap(TrueFlag, FalseFlag);
12011     }
12012     if (R & TrueFlag)
12013       return StringRef("true");
12014     if (R & FalseFlag)
12015       return StringRef("false");
12016     return llvm::None;
12017   }
12018 };
12019 }
12020 
12021 static bool HasEnumType(Expr *E) {
12022   // Strip off implicit integral promotions.
12023   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12024     if (ICE->getCastKind() != CK_IntegralCast &&
12025         ICE->getCastKind() != CK_NoOp)
12026       break;
12027     E = ICE->getSubExpr();
12028   }
12029 
12030   return E->getType()->isEnumeralType();
12031 }
12032 
12033 static int classifyConstantValue(Expr *Constant) {
12034   // The values of this enumeration are used in the diagnostics
12035   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12036   enum ConstantValueKind {
12037     Miscellaneous = 0,
12038     LiteralTrue,
12039     LiteralFalse
12040   };
12041   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12042     return BL->getValue() ? ConstantValueKind::LiteralTrue
12043                           : ConstantValueKind::LiteralFalse;
12044   return ConstantValueKind::Miscellaneous;
12045 }
12046 
12047 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12048                                         Expr *Constant, Expr *Other,
12049                                         const llvm::APSInt &Value,
12050                                         bool RhsConstant) {
12051   if (S.inTemplateInstantiation())
12052     return false;
12053 
12054   Expr *OriginalOther = Other;
12055 
12056   Constant = Constant->IgnoreParenImpCasts();
12057   Other = Other->IgnoreParenImpCasts();
12058 
12059   // Suppress warnings on tautological comparisons between values of the same
12060   // enumeration type. There are only two ways we could warn on this:
12061   //  - If the constant is outside the range of representable values of
12062   //    the enumeration. In such a case, we should warn about the cast
12063   //    to enumeration type, not about the comparison.
12064   //  - If the constant is the maximum / minimum in-range value. For an
12065   //    enumeratin type, such comparisons can be meaningful and useful.
12066   if (Constant->getType()->isEnumeralType() &&
12067       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12068     return false;
12069 
12070   IntRange OtherValueRange = GetExprRange(
12071       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12072 
12073   QualType OtherT = Other->getType();
12074   if (const auto *AT = OtherT->getAs<AtomicType>())
12075     OtherT = AT->getValueType();
12076   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12077 
12078   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12079   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12080   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12081                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12082                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12083 
12084   // Whether we're treating Other as being a bool because of the form of
12085   // expression despite it having another type (typically 'int' in C).
12086   bool OtherIsBooleanDespiteType =
12087       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12088   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12089     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12090 
12091   // Check if all values in the range of possible values of this expression
12092   // lead to the same comparison outcome.
12093   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12094                                         Value.isUnsigned());
12095   auto Cmp = OtherPromotedValueRange.compare(Value);
12096   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12097   if (!Result)
12098     return false;
12099 
12100   // Also consider the range determined by the type alone. This allows us to
12101   // classify the warning under the proper diagnostic group.
12102   bool TautologicalTypeCompare = false;
12103   {
12104     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12105                                          Value.isUnsigned());
12106     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12107     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12108                                                        RhsConstant)) {
12109       TautologicalTypeCompare = true;
12110       Cmp = TypeCmp;
12111       Result = TypeResult;
12112     }
12113   }
12114 
12115   // Don't warn if the non-constant operand actually always evaluates to the
12116   // same value.
12117   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12118     return false;
12119 
12120   // Suppress the diagnostic for an in-range comparison if the constant comes
12121   // from a macro or enumerator. We don't want to diagnose
12122   //
12123   //   some_long_value <= INT_MAX
12124   //
12125   // when sizeof(int) == sizeof(long).
12126   bool InRange = Cmp & PromotedRange::InRangeFlag;
12127   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12128     return false;
12129 
12130   // A comparison of an unsigned bit-field against 0 is really a type problem,
12131   // even though at the type level the bit-field might promote to 'signed int'.
12132   if (Other->refersToBitField() && InRange && Value == 0 &&
12133       Other->getType()->isUnsignedIntegerOrEnumerationType())
12134     TautologicalTypeCompare = true;
12135 
12136   // If this is a comparison to an enum constant, include that
12137   // constant in the diagnostic.
12138   const EnumConstantDecl *ED = nullptr;
12139   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12140     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12141 
12142   // Should be enough for uint128 (39 decimal digits)
12143   SmallString<64> PrettySourceValue;
12144   llvm::raw_svector_ostream OS(PrettySourceValue);
12145   if (ED) {
12146     OS << '\'' << *ED << "' (" << Value << ")";
12147   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12148                Constant->IgnoreParenImpCasts())) {
12149     OS << (BL->getValue() ? "YES" : "NO");
12150   } else {
12151     OS << Value;
12152   }
12153 
12154   if (!TautologicalTypeCompare) {
12155     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12156         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12157         << E->getOpcodeStr() << OS.str() << *Result
12158         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12159     return true;
12160   }
12161 
12162   if (IsObjCSignedCharBool) {
12163     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12164                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12165                               << OS.str() << *Result);
12166     return true;
12167   }
12168 
12169   // FIXME: We use a somewhat different formatting for the in-range cases and
12170   // cases involving boolean values for historical reasons. We should pick a
12171   // consistent way of presenting these diagnostics.
12172   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12173 
12174     S.DiagRuntimeBehavior(
12175         E->getOperatorLoc(), E,
12176         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12177                          : diag::warn_tautological_bool_compare)
12178             << OS.str() << classifyConstantValue(Constant) << OtherT
12179             << OtherIsBooleanDespiteType << *Result
12180             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12181   } else {
12182     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12183     unsigned Diag =
12184         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12185             ? (HasEnumType(OriginalOther)
12186                    ? diag::warn_unsigned_enum_always_true_comparison
12187                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12188                               : diag::warn_unsigned_always_true_comparison)
12189             : diag::warn_tautological_constant_compare;
12190 
12191     S.Diag(E->getOperatorLoc(), Diag)
12192         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12193         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12194   }
12195 
12196   return true;
12197 }
12198 
12199 /// Analyze the operands of the given comparison.  Implements the
12200 /// fallback case from AnalyzeComparison.
12201 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12202   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12203   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12204 }
12205 
12206 /// Implements -Wsign-compare.
12207 ///
12208 /// \param E the binary operator to check for warnings
12209 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12210   // The type the comparison is being performed in.
12211   QualType T = E->getLHS()->getType();
12212 
12213   // Only analyze comparison operators where both sides have been converted to
12214   // the same type.
12215   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12216     return AnalyzeImpConvsInComparison(S, E);
12217 
12218   // Don't analyze value-dependent comparisons directly.
12219   if (E->isValueDependent())
12220     return AnalyzeImpConvsInComparison(S, E);
12221 
12222   Expr *LHS = E->getLHS();
12223   Expr *RHS = E->getRHS();
12224 
12225   if (T->isIntegralType(S.Context)) {
12226     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12227     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12228 
12229     // We don't care about expressions whose result is a constant.
12230     if (RHSValue && LHSValue)
12231       return AnalyzeImpConvsInComparison(S, E);
12232 
12233     // We only care about expressions where just one side is literal
12234     if ((bool)RHSValue ^ (bool)LHSValue) {
12235       // Is the constant on the RHS or LHS?
12236       const bool RhsConstant = (bool)RHSValue;
12237       Expr *Const = RhsConstant ? RHS : LHS;
12238       Expr *Other = RhsConstant ? LHS : RHS;
12239       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12240 
12241       // Check whether an integer constant comparison results in a value
12242       // of 'true' or 'false'.
12243       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12244         return AnalyzeImpConvsInComparison(S, E);
12245     }
12246   }
12247 
12248   if (!T->hasUnsignedIntegerRepresentation()) {
12249     // We don't do anything special if this isn't an unsigned integral
12250     // comparison:  we're only interested in integral comparisons, and
12251     // signed comparisons only happen in cases we don't care to warn about.
12252     return AnalyzeImpConvsInComparison(S, E);
12253   }
12254 
12255   LHS = LHS->IgnoreParenImpCasts();
12256   RHS = RHS->IgnoreParenImpCasts();
12257 
12258   if (!S.getLangOpts().CPlusPlus) {
12259     // Avoid warning about comparison of integers with different signs when
12260     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12261     // the type of `E`.
12262     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12263       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12264     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12265       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12266   }
12267 
12268   // Check to see if one of the (unmodified) operands is of different
12269   // signedness.
12270   Expr *signedOperand, *unsignedOperand;
12271   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12272     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12273            "unsigned comparison between two signed integer expressions?");
12274     signedOperand = LHS;
12275     unsignedOperand = RHS;
12276   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12277     signedOperand = RHS;
12278     unsignedOperand = LHS;
12279   } else {
12280     return AnalyzeImpConvsInComparison(S, E);
12281   }
12282 
12283   // Otherwise, calculate the effective range of the signed operand.
12284   IntRange signedRange = GetExprRange(
12285       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12286 
12287   // Go ahead and analyze implicit conversions in the operands.  Note
12288   // that we skip the implicit conversions on both sides.
12289   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12290   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12291 
12292   // If the signed range is non-negative, -Wsign-compare won't fire.
12293   if (signedRange.NonNegative)
12294     return;
12295 
12296   // For (in)equality comparisons, if the unsigned operand is a
12297   // constant which cannot collide with a overflowed signed operand,
12298   // then reinterpreting the signed operand as unsigned will not
12299   // change the result of the comparison.
12300   if (E->isEqualityOp()) {
12301     unsigned comparisonWidth = S.Context.getIntWidth(T);
12302     IntRange unsignedRange =
12303         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12304                      /*Approximate*/ true);
12305 
12306     // We should never be unable to prove that the unsigned operand is
12307     // non-negative.
12308     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12309 
12310     if (unsignedRange.Width < comparisonWidth)
12311       return;
12312   }
12313 
12314   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12315                         S.PDiag(diag::warn_mixed_sign_comparison)
12316                             << LHS->getType() << RHS->getType()
12317                             << LHS->getSourceRange() << RHS->getSourceRange());
12318 }
12319 
12320 /// Analyzes an attempt to assign the given value to a bitfield.
12321 ///
12322 /// Returns true if there was something fishy about the attempt.
12323 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12324                                       SourceLocation InitLoc) {
12325   assert(Bitfield->isBitField());
12326   if (Bitfield->isInvalidDecl())
12327     return false;
12328 
12329   // White-list bool bitfields.
12330   QualType BitfieldType = Bitfield->getType();
12331   if (BitfieldType->isBooleanType())
12332      return false;
12333 
12334   if (BitfieldType->isEnumeralType()) {
12335     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12336     // If the underlying enum type was not explicitly specified as an unsigned
12337     // type and the enum contain only positive values, MSVC++ will cause an
12338     // inconsistency by storing this as a signed type.
12339     if (S.getLangOpts().CPlusPlus11 &&
12340         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12341         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12342         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12343       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12344           << BitfieldEnumDecl;
12345     }
12346   }
12347 
12348   if (Bitfield->getType()->isBooleanType())
12349     return false;
12350 
12351   // Ignore value- or type-dependent expressions.
12352   if (Bitfield->getBitWidth()->isValueDependent() ||
12353       Bitfield->getBitWidth()->isTypeDependent() ||
12354       Init->isValueDependent() ||
12355       Init->isTypeDependent())
12356     return false;
12357 
12358   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12359   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12360 
12361   Expr::EvalResult Result;
12362   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12363                                    Expr::SE_AllowSideEffects)) {
12364     // The RHS is not constant.  If the RHS has an enum type, make sure the
12365     // bitfield is wide enough to hold all the values of the enum without
12366     // truncation.
12367     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12368       EnumDecl *ED = EnumTy->getDecl();
12369       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12370 
12371       // Enum types are implicitly signed on Windows, so check if there are any
12372       // negative enumerators to see if the enum was intended to be signed or
12373       // not.
12374       bool SignedEnum = ED->getNumNegativeBits() > 0;
12375 
12376       // Check for surprising sign changes when assigning enum values to a
12377       // bitfield of different signedness.  If the bitfield is signed and we
12378       // have exactly the right number of bits to store this unsigned enum,
12379       // suggest changing the enum to an unsigned type. This typically happens
12380       // on Windows where unfixed enums always use an underlying type of 'int'.
12381       unsigned DiagID = 0;
12382       if (SignedEnum && !SignedBitfield) {
12383         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12384       } else if (SignedBitfield && !SignedEnum &&
12385                  ED->getNumPositiveBits() == FieldWidth) {
12386         DiagID = diag::warn_signed_bitfield_enum_conversion;
12387       }
12388 
12389       if (DiagID) {
12390         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12391         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12392         SourceRange TypeRange =
12393             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12394         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12395             << SignedEnum << TypeRange;
12396       }
12397 
12398       // Compute the required bitwidth. If the enum has negative values, we need
12399       // one more bit than the normal number of positive bits to represent the
12400       // sign bit.
12401       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12402                                                   ED->getNumNegativeBits())
12403                                        : ED->getNumPositiveBits();
12404 
12405       // Check the bitwidth.
12406       if (BitsNeeded > FieldWidth) {
12407         Expr *WidthExpr = Bitfield->getBitWidth();
12408         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12409             << Bitfield << ED;
12410         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12411             << BitsNeeded << ED << WidthExpr->getSourceRange();
12412       }
12413     }
12414 
12415     return false;
12416   }
12417 
12418   llvm::APSInt Value = Result.Val.getInt();
12419 
12420   unsigned OriginalWidth = Value.getBitWidth();
12421 
12422   if (!Value.isSigned() || Value.isNegative())
12423     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12424       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12425         OriginalWidth = Value.getMinSignedBits();
12426 
12427   if (OriginalWidth <= FieldWidth)
12428     return false;
12429 
12430   // Compute the value which the bitfield will contain.
12431   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12432   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12433 
12434   // Check whether the stored value is equal to the original value.
12435   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12436   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12437     return false;
12438 
12439   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12440   // therefore don't strictly fit into a signed bitfield of width 1.
12441   if (FieldWidth == 1 && Value == 1)
12442     return false;
12443 
12444   std::string PrettyValue = toString(Value, 10);
12445   std::string PrettyTrunc = toString(TruncatedValue, 10);
12446 
12447   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12448     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12449     << Init->getSourceRange();
12450 
12451   return true;
12452 }
12453 
12454 /// Analyze the given simple or compound assignment for warning-worthy
12455 /// operations.
12456 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12457   // Just recurse on the LHS.
12458   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12459 
12460   // We want to recurse on the RHS as normal unless we're assigning to
12461   // a bitfield.
12462   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12463     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12464                                   E->getOperatorLoc())) {
12465       // Recurse, ignoring any implicit conversions on the RHS.
12466       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12467                                         E->getOperatorLoc());
12468     }
12469   }
12470 
12471   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12472 
12473   // Diagnose implicitly sequentially-consistent atomic assignment.
12474   if (E->getLHS()->getType()->isAtomicType())
12475     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12476 }
12477 
12478 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12479 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12480                             SourceLocation CContext, unsigned diag,
12481                             bool pruneControlFlow = false) {
12482   if (pruneControlFlow) {
12483     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12484                           S.PDiag(diag)
12485                               << SourceType << T << E->getSourceRange()
12486                               << SourceRange(CContext));
12487     return;
12488   }
12489   S.Diag(E->getExprLoc(), diag)
12490     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12491 }
12492 
12493 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12494 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12495                             SourceLocation CContext,
12496                             unsigned diag, bool pruneControlFlow = false) {
12497   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12498 }
12499 
12500 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12501   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12502       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12503 }
12504 
12505 static void adornObjCBoolConversionDiagWithTernaryFixit(
12506     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12507   Expr *Ignored = SourceExpr->IgnoreImplicit();
12508   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12509     Ignored = OVE->getSourceExpr();
12510   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12511                      isa<BinaryOperator>(Ignored) ||
12512                      isa<CXXOperatorCallExpr>(Ignored);
12513   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12514   if (NeedsParens)
12515     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12516             << FixItHint::CreateInsertion(EndLoc, ")");
12517   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12518 }
12519 
12520 /// Diagnose an implicit cast from a floating point value to an integer value.
12521 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12522                                     SourceLocation CContext) {
12523   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12524   const bool PruneWarnings = S.inTemplateInstantiation();
12525 
12526   Expr *InnerE = E->IgnoreParenImpCasts();
12527   // We also want to warn on, e.g., "int i = -1.234"
12528   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12529     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12530       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12531 
12532   const bool IsLiteral =
12533       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12534 
12535   llvm::APFloat Value(0.0);
12536   bool IsConstant =
12537     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12538   if (!IsConstant) {
12539     if (isObjCSignedCharBool(S, T)) {
12540       return adornObjCBoolConversionDiagWithTernaryFixit(
12541           S, E,
12542           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12543               << E->getType());
12544     }
12545 
12546     return DiagnoseImpCast(S, E, T, CContext,
12547                            diag::warn_impcast_float_integer, PruneWarnings);
12548   }
12549 
12550   bool isExact = false;
12551 
12552   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12553                             T->hasUnsignedIntegerRepresentation());
12554   llvm::APFloat::opStatus Result = Value.convertToInteger(
12555       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12556 
12557   // FIXME: Force the precision of the source value down so we don't print
12558   // digits which are usually useless (we don't really care here if we
12559   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12560   // would automatically print the shortest representation, but it's a bit
12561   // tricky to implement.
12562   SmallString<16> PrettySourceValue;
12563   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12564   precision = (precision * 59 + 195) / 196;
12565   Value.toString(PrettySourceValue, precision);
12566 
12567   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12568     return adornObjCBoolConversionDiagWithTernaryFixit(
12569         S, E,
12570         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12571             << PrettySourceValue);
12572   }
12573 
12574   if (Result == llvm::APFloat::opOK && isExact) {
12575     if (IsLiteral) return;
12576     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12577                            PruneWarnings);
12578   }
12579 
12580   // Conversion of a floating-point value to a non-bool integer where the
12581   // integral part cannot be represented by the integer type is undefined.
12582   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12583     return DiagnoseImpCast(
12584         S, E, T, CContext,
12585         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12586                   : diag::warn_impcast_float_to_integer_out_of_range,
12587         PruneWarnings);
12588 
12589   unsigned DiagID = 0;
12590   if (IsLiteral) {
12591     // Warn on floating point literal to integer.
12592     DiagID = diag::warn_impcast_literal_float_to_integer;
12593   } else if (IntegerValue == 0) {
12594     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12595       return DiagnoseImpCast(S, E, T, CContext,
12596                              diag::warn_impcast_float_integer, PruneWarnings);
12597     }
12598     // Warn on non-zero to zero conversion.
12599     DiagID = diag::warn_impcast_float_to_integer_zero;
12600   } else {
12601     if (IntegerValue.isUnsigned()) {
12602       if (!IntegerValue.isMaxValue()) {
12603         return DiagnoseImpCast(S, E, T, CContext,
12604                                diag::warn_impcast_float_integer, PruneWarnings);
12605       }
12606     } else {  // IntegerValue.isSigned()
12607       if (!IntegerValue.isMaxSignedValue() &&
12608           !IntegerValue.isMinSignedValue()) {
12609         return DiagnoseImpCast(S, E, T, CContext,
12610                                diag::warn_impcast_float_integer, PruneWarnings);
12611       }
12612     }
12613     // Warn on evaluatable floating point expression to integer conversion.
12614     DiagID = diag::warn_impcast_float_to_integer;
12615   }
12616 
12617   SmallString<16> PrettyTargetValue;
12618   if (IsBool)
12619     PrettyTargetValue = Value.isZero() ? "false" : "true";
12620   else
12621     IntegerValue.toString(PrettyTargetValue);
12622 
12623   if (PruneWarnings) {
12624     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12625                           S.PDiag(DiagID)
12626                               << E->getType() << T.getUnqualifiedType()
12627                               << PrettySourceValue << PrettyTargetValue
12628                               << E->getSourceRange() << SourceRange(CContext));
12629   } else {
12630     S.Diag(E->getExprLoc(), DiagID)
12631         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12632         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12633   }
12634 }
12635 
12636 /// Analyze the given compound assignment for the possible losing of
12637 /// floating-point precision.
12638 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12639   assert(isa<CompoundAssignOperator>(E) &&
12640          "Must be compound assignment operation");
12641   // Recurse on the LHS and RHS in here
12642   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12643   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12644 
12645   if (E->getLHS()->getType()->isAtomicType())
12646     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12647 
12648   // Now check the outermost expression
12649   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12650   const auto *RBT = cast<CompoundAssignOperator>(E)
12651                         ->getComputationResultType()
12652                         ->getAs<BuiltinType>();
12653 
12654   // The below checks assume source is floating point.
12655   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12656 
12657   // If source is floating point but target is an integer.
12658   if (ResultBT->isInteger())
12659     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12660                            E->getExprLoc(), diag::warn_impcast_float_integer);
12661 
12662   if (!ResultBT->isFloatingPoint())
12663     return;
12664 
12665   // If both source and target are floating points, warn about losing precision.
12666   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12667       QualType(ResultBT, 0), QualType(RBT, 0));
12668   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12669     // warn about dropping FP rank.
12670     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12671                     diag::warn_impcast_float_result_precision);
12672 }
12673 
12674 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12675                                       IntRange Range) {
12676   if (!Range.Width) return "0";
12677 
12678   llvm::APSInt ValueInRange = Value;
12679   ValueInRange.setIsSigned(!Range.NonNegative);
12680   ValueInRange = ValueInRange.trunc(Range.Width);
12681   return toString(ValueInRange, 10);
12682 }
12683 
12684 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12685   if (!isa<ImplicitCastExpr>(Ex))
12686     return false;
12687 
12688   Expr *InnerE = Ex->IgnoreParenImpCasts();
12689   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12690   const Type *Source =
12691     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12692   if (Target->isDependentType())
12693     return false;
12694 
12695   const BuiltinType *FloatCandidateBT =
12696     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12697   const Type *BoolCandidateType = ToBool ? Target : Source;
12698 
12699   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12700           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12701 }
12702 
12703 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12704                                              SourceLocation CC) {
12705   unsigned NumArgs = TheCall->getNumArgs();
12706   for (unsigned i = 0; i < NumArgs; ++i) {
12707     Expr *CurrA = TheCall->getArg(i);
12708     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12709       continue;
12710 
12711     bool IsSwapped = ((i > 0) &&
12712         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12713     IsSwapped |= ((i < (NumArgs - 1)) &&
12714         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12715     if (IsSwapped) {
12716       // Warn on this floating-point to bool conversion.
12717       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12718                       CurrA->getType(), CC,
12719                       diag::warn_impcast_floating_point_to_bool);
12720     }
12721   }
12722 }
12723 
12724 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12725                                    SourceLocation CC) {
12726   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12727                         E->getExprLoc()))
12728     return;
12729 
12730   // Don't warn on functions which have return type nullptr_t.
12731   if (isa<CallExpr>(E))
12732     return;
12733 
12734   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12735   const Expr::NullPointerConstantKind NullKind =
12736       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12737   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12738     return;
12739 
12740   // Return if target type is a safe conversion.
12741   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12742       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12743     return;
12744 
12745   SourceLocation Loc = E->getSourceRange().getBegin();
12746 
12747   // Venture through the macro stacks to get to the source of macro arguments.
12748   // The new location is a better location than the complete location that was
12749   // passed in.
12750   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12751   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12752 
12753   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12754   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12755     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12756         Loc, S.SourceMgr, S.getLangOpts());
12757     if (MacroName == "NULL")
12758       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12759   }
12760 
12761   // Only warn if the null and context location are in the same macro expansion.
12762   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12763     return;
12764 
12765   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12766       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12767       << FixItHint::CreateReplacement(Loc,
12768                                       S.getFixItZeroLiteralForType(T, Loc));
12769 }
12770 
12771 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12772                                   ObjCArrayLiteral *ArrayLiteral);
12773 
12774 static void
12775 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12776                            ObjCDictionaryLiteral *DictionaryLiteral);
12777 
12778 /// Check a single element within a collection literal against the
12779 /// target element type.
12780 static void checkObjCCollectionLiteralElement(Sema &S,
12781                                               QualType TargetElementType,
12782                                               Expr *Element,
12783                                               unsigned ElementKind) {
12784   // Skip a bitcast to 'id' or qualified 'id'.
12785   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12786     if (ICE->getCastKind() == CK_BitCast &&
12787         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12788       Element = ICE->getSubExpr();
12789   }
12790 
12791   QualType ElementType = Element->getType();
12792   ExprResult ElementResult(Element);
12793   if (ElementType->getAs<ObjCObjectPointerType>() &&
12794       S.CheckSingleAssignmentConstraints(TargetElementType,
12795                                          ElementResult,
12796                                          false, false)
12797         != Sema::Compatible) {
12798     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12799         << ElementType << ElementKind << TargetElementType
12800         << Element->getSourceRange();
12801   }
12802 
12803   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12804     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12805   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12806     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12807 }
12808 
12809 /// Check an Objective-C array literal being converted to the given
12810 /// target type.
12811 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12812                                   ObjCArrayLiteral *ArrayLiteral) {
12813   if (!S.NSArrayDecl)
12814     return;
12815 
12816   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12817   if (!TargetObjCPtr)
12818     return;
12819 
12820   if (TargetObjCPtr->isUnspecialized() ||
12821       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12822         != S.NSArrayDecl->getCanonicalDecl())
12823     return;
12824 
12825   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12826   if (TypeArgs.size() != 1)
12827     return;
12828 
12829   QualType TargetElementType = TypeArgs[0];
12830   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12831     checkObjCCollectionLiteralElement(S, TargetElementType,
12832                                       ArrayLiteral->getElement(I),
12833                                       0);
12834   }
12835 }
12836 
12837 /// Check an Objective-C dictionary literal being converted to the given
12838 /// target type.
12839 static void
12840 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12841                            ObjCDictionaryLiteral *DictionaryLiteral) {
12842   if (!S.NSDictionaryDecl)
12843     return;
12844 
12845   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12846   if (!TargetObjCPtr)
12847     return;
12848 
12849   if (TargetObjCPtr->isUnspecialized() ||
12850       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12851         != S.NSDictionaryDecl->getCanonicalDecl())
12852     return;
12853 
12854   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12855   if (TypeArgs.size() != 2)
12856     return;
12857 
12858   QualType TargetKeyType = TypeArgs[0];
12859   QualType TargetObjectType = TypeArgs[1];
12860   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12861     auto Element = DictionaryLiteral->getKeyValueElement(I);
12862     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12863     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12864   }
12865 }
12866 
12867 // Helper function to filter out cases for constant width constant conversion.
12868 // Don't warn on char array initialization or for non-decimal values.
12869 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12870                                           SourceLocation CC) {
12871   // If initializing from a constant, and the constant starts with '0',
12872   // then it is a binary, octal, or hexadecimal.  Allow these constants
12873   // to fill all the bits, even if there is a sign change.
12874   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12875     const char FirstLiteralCharacter =
12876         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12877     if (FirstLiteralCharacter == '0')
12878       return false;
12879   }
12880 
12881   // If the CC location points to a '{', and the type is char, then assume
12882   // assume it is an array initialization.
12883   if (CC.isValid() && T->isCharType()) {
12884     const char FirstContextCharacter =
12885         S.getSourceManager().getCharacterData(CC)[0];
12886     if (FirstContextCharacter == '{')
12887       return false;
12888   }
12889 
12890   return true;
12891 }
12892 
12893 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12894   const auto *IL = dyn_cast<IntegerLiteral>(E);
12895   if (!IL) {
12896     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12897       if (UO->getOpcode() == UO_Minus)
12898         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12899     }
12900   }
12901 
12902   return IL;
12903 }
12904 
12905 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12906   E = E->IgnoreParenImpCasts();
12907   SourceLocation ExprLoc = E->getExprLoc();
12908 
12909   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12910     BinaryOperator::Opcode Opc = BO->getOpcode();
12911     Expr::EvalResult Result;
12912     // Do not diagnose unsigned shifts.
12913     if (Opc == BO_Shl) {
12914       const auto *LHS = getIntegerLiteral(BO->getLHS());
12915       const auto *RHS = getIntegerLiteral(BO->getRHS());
12916       if (LHS && LHS->getValue() == 0)
12917         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12918       else if (!E->isValueDependent() && LHS && RHS &&
12919                RHS->getValue().isNonNegative() &&
12920                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12921         S.Diag(ExprLoc, diag::warn_left_shift_always)
12922             << (Result.Val.getInt() != 0);
12923       else if (E->getType()->isSignedIntegerType())
12924         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12925     }
12926   }
12927 
12928   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12929     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12930     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12931     if (!LHS || !RHS)
12932       return;
12933     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12934         (RHS->getValue() == 0 || RHS->getValue() == 1))
12935       // Do not diagnose common idioms.
12936       return;
12937     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12938       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12939   }
12940 }
12941 
12942 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12943                                     SourceLocation CC,
12944                                     bool *ICContext = nullptr,
12945                                     bool IsListInit = false) {
12946   if (E->isTypeDependent() || E->isValueDependent()) return;
12947 
12948   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12949   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12950   if (Source == Target) return;
12951   if (Target->isDependentType()) return;
12952 
12953   // If the conversion context location is invalid don't complain. We also
12954   // don't want to emit a warning if the issue occurs from the expansion of
12955   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12956   // delay this check as long as possible. Once we detect we are in that
12957   // scenario, we just return.
12958   if (CC.isInvalid())
12959     return;
12960 
12961   if (Source->isAtomicType())
12962     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12963 
12964   // Diagnose implicit casts to bool.
12965   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12966     if (isa<StringLiteral>(E))
12967       // Warn on string literal to bool.  Checks for string literals in logical
12968       // and expressions, for instance, assert(0 && "error here"), are
12969       // prevented by a check in AnalyzeImplicitConversions().
12970       return DiagnoseImpCast(S, E, T, CC,
12971                              diag::warn_impcast_string_literal_to_bool);
12972     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12973         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12974       // This covers the literal expressions that evaluate to Objective-C
12975       // objects.
12976       return DiagnoseImpCast(S, E, T, CC,
12977                              diag::warn_impcast_objective_c_literal_to_bool);
12978     }
12979     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12980       // Warn on pointer to bool conversion that is always true.
12981       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12982                                      SourceRange(CC));
12983     }
12984   }
12985 
12986   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12987   // is a typedef for signed char (macOS), then that constant value has to be 1
12988   // or 0.
12989   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12990     Expr::EvalResult Result;
12991     if (E->EvaluateAsInt(Result, S.getASTContext(),
12992                          Expr::SE_AllowSideEffects)) {
12993       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12994         adornObjCBoolConversionDiagWithTernaryFixit(
12995             S, E,
12996             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12997                 << toString(Result.Val.getInt(), 10));
12998       }
12999       return;
13000     }
13001   }
13002 
13003   // Check implicit casts from Objective-C collection literals to specialized
13004   // collection types, e.g., NSArray<NSString *> *.
13005   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13006     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13007   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13008     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13009 
13010   // Strip vector types.
13011   if (isa<VectorType>(Source)) {
13012     if (Target->isVLSTBuiltinType() &&
13013         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13014                                          QualType(Source, 0)) ||
13015          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13016                                             QualType(Source, 0))))
13017       return;
13018 
13019     if (!isa<VectorType>(Target)) {
13020       if (S.SourceMgr.isInSystemMacro(CC))
13021         return;
13022       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13023     }
13024 
13025     // If the vector cast is cast between two vectors of the same size, it is
13026     // a bitcast, not a conversion.
13027     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13028       return;
13029 
13030     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13031     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13032   }
13033   if (auto VecTy = dyn_cast<VectorType>(Target))
13034     Target = VecTy->getElementType().getTypePtr();
13035 
13036   // Strip complex types.
13037   if (isa<ComplexType>(Source)) {
13038     if (!isa<ComplexType>(Target)) {
13039       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13040         return;
13041 
13042       return DiagnoseImpCast(S, E, T, CC,
13043                              S.getLangOpts().CPlusPlus
13044                                  ? diag::err_impcast_complex_scalar
13045                                  : diag::warn_impcast_complex_scalar);
13046     }
13047 
13048     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13049     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13050   }
13051 
13052   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13053   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13054 
13055   // If the source is floating point...
13056   if (SourceBT && SourceBT->isFloatingPoint()) {
13057     // ...and the target is floating point...
13058     if (TargetBT && TargetBT->isFloatingPoint()) {
13059       // ...then warn if we're dropping FP rank.
13060 
13061       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13062           QualType(SourceBT, 0), QualType(TargetBT, 0));
13063       if (Order > 0) {
13064         // Don't warn about float constants that are precisely
13065         // representable in the target type.
13066         Expr::EvalResult result;
13067         if (E->EvaluateAsRValue(result, S.Context)) {
13068           // Value might be a float, a float vector, or a float complex.
13069           if (IsSameFloatAfterCast(result.Val,
13070                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13071                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13072             return;
13073         }
13074 
13075         if (S.SourceMgr.isInSystemMacro(CC))
13076           return;
13077 
13078         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13079       }
13080       // ... or possibly if we're increasing rank, too
13081       else if (Order < 0) {
13082         if (S.SourceMgr.isInSystemMacro(CC))
13083           return;
13084 
13085         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13086       }
13087       return;
13088     }
13089 
13090     // If the target is integral, always warn.
13091     if (TargetBT && TargetBT->isInteger()) {
13092       if (S.SourceMgr.isInSystemMacro(CC))
13093         return;
13094 
13095       DiagnoseFloatingImpCast(S, E, T, CC);
13096     }
13097 
13098     // Detect the case where a call result is converted from floating-point to
13099     // to bool, and the final argument to the call is converted from bool, to
13100     // discover this typo:
13101     //
13102     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13103     //
13104     // FIXME: This is an incredibly special case; is there some more general
13105     // way to detect this class of misplaced-parentheses bug?
13106     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13107       // Check last argument of function call to see if it is an
13108       // implicit cast from a type matching the type the result
13109       // is being cast to.
13110       CallExpr *CEx = cast<CallExpr>(E);
13111       if (unsigned NumArgs = CEx->getNumArgs()) {
13112         Expr *LastA = CEx->getArg(NumArgs - 1);
13113         Expr *InnerE = LastA->IgnoreParenImpCasts();
13114         if (isa<ImplicitCastExpr>(LastA) &&
13115             InnerE->getType()->isBooleanType()) {
13116           // Warn on this floating-point to bool conversion
13117           DiagnoseImpCast(S, E, T, CC,
13118                           diag::warn_impcast_floating_point_to_bool);
13119         }
13120       }
13121     }
13122     return;
13123   }
13124 
13125   // Valid casts involving fixed point types should be accounted for here.
13126   if (Source->isFixedPointType()) {
13127     if (Target->isUnsaturatedFixedPointType()) {
13128       Expr::EvalResult Result;
13129       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13130                                   S.isConstantEvaluated())) {
13131         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13132         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13133         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13134         if (Value > MaxVal || Value < MinVal) {
13135           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13136                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13137                                     << Value.toString() << T
13138                                     << E->getSourceRange()
13139                                     << clang::SourceRange(CC));
13140           return;
13141         }
13142       }
13143     } else if (Target->isIntegerType()) {
13144       Expr::EvalResult Result;
13145       if (!S.isConstantEvaluated() &&
13146           E->EvaluateAsFixedPoint(Result, S.Context,
13147                                   Expr::SE_AllowSideEffects)) {
13148         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13149 
13150         bool Overflowed;
13151         llvm::APSInt IntResult = FXResult.convertToInt(
13152             S.Context.getIntWidth(T),
13153             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13154 
13155         if (Overflowed) {
13156           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13157                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13158                                     << FXResult.toString() << T
13159                                     << E->getSourceRange()
13160                                     << clang::SourceRange(CC));
13161           return;
13162         }
13163       }
13164     }
13165   } else if (Target->isUnsaturatedFixedPointType()) {
13166     if (Source->isIntegerType()) {
13167       Expr::EvalResult Result;
13168       if (!S.isConstantEvaluated() &&
13169           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13170         llvm::APSInt Value = Result.Val.getInt();
13171 
13172         bool Overflowed;
13173         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13174             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13175 
13176         if (Overflowed) {
13177           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13178                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13179                                     << toString(Value, /*Radix=*/10) << T
13180                                     << E->getSourceRange()
13181                                     << clang::SourceRange(CC));
13182           return;
13183         }
13184       }
13185     }
13186   }
13187 
13188   // If we are casting an integer type to a floating point type without
13189   // initialization-list syntax, we might lose accuracy if the floating
13190   // point type has a narrower significand than the integer type.
13191   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13192       TargetBT->isFloatingType() && !IsListInit) {
13193     // Determine the number of precision bits in the source integer type.
13194     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13195                                         /*Approximate*/ true);
13196     unsigned int SourcePrecision = SourceRange.Width;
13197 
13198     // Determine the number of precision bits in the
13199     // target floating point type.
13200     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13201         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13202 
13203     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13204         SourcePrecision > TargetPrecision) {
13205 
13206       if (Optional<llvm::APSInt> SourceInt =
13207               E->getIntegerConstantExpr(S.Context)) {
13208         // If the source integer is a constant, convert it to the target
13209         // floating point type. Issue a warning if the value changes
13210         // during the whole conversion.
13211         llvm::APFloat TargetFloatValue(
13212             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13213         llvm::APFloat::opStatus ConversionStatus =
13214             TargetFloatValue.convertFromAPInt(
13215                 *SourceInt, SourceBT->isSignedInteger(),
13216                 llvm::APFloat::rmNearestTiesToEven);
13217 
13218         if (ConversionStatus != llvm::APFloat::opOK) {
13219           SmallString<32> PrettySourceValue;
13220           SourceInt->toString(PrettySourceValue, 10);
13221           SmallString<32> PrettyTargetValue;
13222           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13223 
13224           S.DiagRuntimeBehavior(
13225               E->getExprLoc(), E,
13226               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13227                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13228                   << E->getSourceRange() << clang::SourceRange(CC));
13229         }
13230       } else {
13231         // Otherwise, the implicit conversion may lose precision.
13232         DiagnoseImpCast(S, E, T, CC,
13233                         diag::warn_impcast_integer_float_precision);
13234       }
13235     }
13236   }
13237 
13238   DiagnoseNullConversion(S, E, T, CC);
13239 
13240   S.DiscardMisalignedMemberAddress(Target, E);
13241 
13242   if (Target->isBooleanType())
13243     DiagnoseIntInBoolContext(S, E);
13244 
13245   if (!Source->isIntegerType() || !Target->isIntegerType())
13246     return;
13247 
13248   // TODO: remove this early return once the false positives for constant->bool
13249   // in templates, macros, etc, are reduced or removed.
13250   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13251     return;
13252 
13253   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13254       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13255     return adornObjCBoolConversionDiagWithTernaryFixit(
13256         S, E,
13257         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13258             << E->getType());
13259   }
13260 
13261   IntRange SourceTypeRange =
13262       IntRange::forTargetOfCanonicalType(S.Context, Source);
13263   IntRange LikelySourceRange =
13264       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13265   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13266 
13267   if (LikelySourceRange.Width > TargetRange.Width) {
13268     // If the source is a constant, use a default-on diagnostic.
13269     // TODO: this should happen for bitfield stores, too.
13270     Expr::EvalResult Result;
13271     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13272                          S.isConstantEvaluated())) {
13273       llvm::APSInt Value(32);
13274       Value = Result.Val.getInt();
13275 
13276       if (S.SourceMgr.isInSystemMacro(CC))
13277         return;
13278 
13279       std::string PrettySourceValue = toString(Value, 10);
13280       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13281 
13282       S.DiagRuntimeBehavior(
13283           E->getExprLoc(), E,
13284           S.PDiag(diag::warn_impcast_integer_precision_constant)
13285               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13286               << E->getSourceRange() << SourceRange(CC));
13287       return;
13288     }
13289 
13290     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13291     if (S.SourceMgr.isInSystemMacro(CC))
13292       return;
13293 
13294     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13295       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13296                              /* pruneControlFlow */ true);
13297     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13298   }
13299 
13300   if (TargetRange.Width > SourceTypeRange.Width) {
13301     if (auto *UO = dyn_cast<UnaryOperator>(E))
13302       if (UO->getOpcode() == UO_Minus)
13303         if (Source->isUnsignedIntegerType()) {
13304           if (Target->isUnsignedIntegerType())
13305             return DiagnoseImpCast(S, E, T, CC,
13306                                    diag::warn_impcast_high_order_zero_bits);
13307           if (Target->isSignedIntegerType())
13308             return DiagnoseImpCast(S, E, T, CC,
13309                                    diag::warn_impcast_nonnegative_result);
13310         }
13311   }
13312 
13313   if (TargetRange.Width == LikelySourceRange.Width &&
13314       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13315       Source->isSignedIntegerType()) {
13316     // Warn when doing a signed to signed conversion, warn if the positive
13317     // source value is exactly the width of the target type, which will
13318     // cause a negative value to be stored.
13319 
13320     Expr::EvalResult Result;
13321     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13322         !S.SourceMgr.isInSystemMacro(CC)) {
13323       llvm::APSInt Value = Result.Val.getInt();
13324       if (isSameWidthConstantConversion(S, E, T, CC)) {
13325         std::string PrettySourceValue = toString(Value, 10);
13326         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13327 
13328         S.DiagRuntimeBehavior(
13329             E->getExprLoc(), E,
13330             S.PDiag(diag::warn_impcast_integer_precision_constant)
13331                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13332                 << E->getSourceRange() << SourceRange(CC));
13333         return;
13334       }
13335     }
13336 
13337     // Fall through for non-constants to give a sign conversion warning.
13338   }
13339 
13340   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13341       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13342        LikelySourceRange.Width == TargetRange.Width)) {
13343     if (S.SourceMgr.isInSystemMacro(CC))
13344       return;
13345 
13346     unsigned DiagID = diag::warn_impcast_integer_sign;
13347 
13348     // Traditionally, gcc has warned about this under -Wsign-compare.
13349     // We also want to warn about it in -Wconversion.
13350     // So if -Wconversion is off, use a completely identical diagnostic
13351     // in the sign-compare group.
13352     // The conditional-checking code will
13353     if (ICContext) {
13354       DiagID = diag::warn_impcast_integer_sign_conditional;
13355       *ICContext = true;
13356     }
13357 
13358     return DiagnoseImpCast(S, E, T, CC, DiagID);
13359   }
13360 
13361   // Diagnose conversions between different enumeration types.
13362   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13363   // type, to give us better diagnostics.
13364   QualType SourceType = E->getType();
13365   if (!S.getLangOpts().CPlusPlus) {
13366     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13367       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13368         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13369         SourceType = S.Context.getTypeDeclType(Enum);
13370         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13371       }
13372   }
13373 
13374   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13375     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13376       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13377           TargetEnum->getDecl()->hasNameForLinkage() &&
13378           SourceEnum != TargetEnum) {
13379         if (S.SourceMgr.isInSystemMacro(CC))
13380           return;
13381 
13382         return DiagnoseImpCast(S, E, SourceType, T, CC,
13383                                diag::warn_impcast_different_enum_types);
13384       }
13385 }
13386 
13387 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13388                                      SourceLocation CC, QualType T);
13389 
13390 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13391                                     SourceLocation CC, bool &ICContext) {
13392   E = E->IgnoreParenImpCasts();
13393 
13394   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13395     return CheckConditionalOperator(S, CO, CC, T);
13396 
13397   AnalyzeImplicitConversions(S, E, CC);
13398   if (E->getType() != T)
13399     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13400 }
13401 
13402 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13403                                      SourceLocation CC, QualType T) {
13404   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13405 
13406   Expr *TrueExpr = E->getTrueExpr();
13407   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13408     TrueExpr = BCO->getCommon();
13409 
13410   bool Suspicious = false;
13411   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13412   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13413 
13414   if (T->isBooleanType())
13415     DiagnoseIntInBoolContext(S, E);
13416 
13417   // If -Wconversion would have warned about either of the candidates
13418   // for a signedness conversion to the context type...
13419   if (!Suspicious) return;
13420 
13421   // ...but it's currently ignored...
13422   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13423     return;
13424 
13425   // ...then check whether it would have warned about either of the
13426   // candidates for a signedness conversion to the condition type.
13427   if (E->getType() == T) return;
13428 
13429   Suspicious = false;
13430   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13431                           E->getType(), CC, &Suspicious);
13432   if (!Suspicious)
13433     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13434                             E->getType(), CC, &Suspicious);
13435 }
13436 
13437 /// Check conversion of given expression to boolean.
13438 /// Input argument E is a logical expression.
13439 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13440   if (S.getLangOpts().Bool)
13441     return;
13442   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13443     return;
13444   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13445 }
13446 
13447 namespace {
13448 struct AnalyzeImplicitConversionsWorkItem {
13449   Expr *E;
13450   SourceLocation CC;
13451   bool IsListInit;
13452 };
13453 }
13454 
13455 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13456 /// that should be visited are added to WorkList.
13457 static void AnalyzeImplicitConversions(
13458     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13459     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13460   Expr *OrigE = Item.E;
13461   SourceLocation CC = Item.CC;
13462 
13463   QualType T = OrigE->getType();
13464   Expr *E = OrigE->IgnoreParenImpCasts();
13465 
13466   // Propagate whether we are in a C++ list initialization expression.
13467   // If so, we do not issue warnings for implicit int-float conversion
13468   // precision loss, because C++11 narrowing already handles it.
13469   bool IsListInit = Item.IsListInit ||
13470                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13471 
13472   if (E->isTypeDependent() || E->isValueDependent())
13473     return;
13474 
13475   Expr *SourceExpr = E;
13476   // Examine, but don't traverse into the source expression of an
13477   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13478   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13479   // evaluate it in the context of checking the specific conversion to T though.
13480   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13481     if (auto *Src = OVE->getSourceExpr())
13482       SourceExpr = Src;
13483 
13484   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13485     if (UO->getOpcode() == UO_Not &&
13486         UO->getSubExpr()->isKnownToHaveBooleanValue())
13487       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13488           << OrigE->getSourceRange() << T->isBooleanType()
13489           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13490 
13491   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13492     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13493         BO->getLHS()->isKnownToHaveBooleanValue() &&
13494         BO->getRHS()->isKnownToHaveBooleanValue() &&
13495         BO->getLHS()->HasSideEffects(S.Context) &&
13496         BO->getRHS()->HasSideEffects(S.Context)) {
13497       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13498           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13499           << FixItHint::CreateReplacement(
13500                  BO->getOperatorLoc(),
13501                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13502       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13503     }
13504 
13505   // For conditional operators, we analyze the arguments as if they
13506   // were being fed directly into the output.
13507   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13508     CheckConditionalOperator(S, CO, CC, T);
13509     return;
13510   }
13511 
13512   // Check implicit argument conversions for function calls.
13513   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13514     CheckImplicitArgumentConversions(S, Call, CC);
13515 
13516   // Go ahead and check any implicit conversions we might have skipped.
13517   // The non-canonical typecheck is just an optimization;
13518   // CheckImplicitConversion will filter out dead implicit conversions.
13519   if (SourceExpr->getType() != T)
13520     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13521 
13522   // Now continue drilling into this expression.
13523 
13524   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13525     // The bound subexpressions in a PseudoObjectExpr are not reachable
13526     // as transitive children.
13527     // FIXME: Use a more uniform representation for this.
13528     for (auto *SE : POE->semantics())
13529       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13530         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13531   }
13532 
13533   // Skip past explicit casts.
13534   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13535     E = CE->getSubExpr()->IgnoreParenImpCasts();
13536     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13537       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13538     WorkList.push_back({E, CC, IsListInit});
13539     return;
13540   }
13541 
13542   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13543     // Do a somewhat different check with comparison operators.
13544     if (BO->isComparisonOp())
13545       return AnalyzeComparison(S, BO);
13546 
13547     // And with simple assignments.
13548     if (BO->getOpcode() == BO_Assign)
13549       return AnalyzeAssignment(S, BO);
13550     // And with compound assignments.
13551     if (BO->isAssignmentOp())
13552       return AnalyzeCompoundAssignment(S, BO);
13553   }
13554 
13555   // These break the otherwise-useful invariant below.  Fortunately,
13556   // we don't really need to recurse into them, because any internal
13557   // expressions should have been analyzed already when they were
13558   // built into statements.
13559   if (isa<StmtExpr>(E)) return;
13560 
13561   // Don't descend into unevaluated contexts.
13562   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13563 
13564   // Now just recurse over the expression's children.
13565   CC = E->getExprLoc();
13566   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13567   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13568   for (Stmt *SubStmt : E->children()) {
13569     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13570     if (!ChildExpr)
13571       continue;
13572 
13573     if (IsLogicalAndOperator &&
13574         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13575       // Ignore checking string literals that are in logical and operators.
13576       // This is a common pattern for asserts.
13577       continue;
13578     WorkList.push_back({ChildExpr, CC, IsListInit});
13579   }
13580 
13581   if (BO && BO->isLogicalOp()) {
13582     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13583     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13584       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13585 
13586     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13587     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13588       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13589   }
13590 
13591   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13592     if (U->getOpcode() == UO_LNot) {
13593       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13594     } else if (U->getOpcode() != UO_AddrOf) {
13595       if (U->getSubExpr()->getType()->isAtomicType())
13596         S.Diag(U->getSubExpr()->getBeginLoc(),
13597                diag::warn_atomic_implicit_seq_cst);
13598     }
13599   }
13600 }
13601 
13602 /// AnalyzeImplicitConversions - Find and report any interesting
13603 /// implicit conversions in the given expression.  There are a couple
13604 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13605 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13606                                        bool IsListInit/*= false*/) {
13607   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13608   WorkList.push_back({OrigE, CC, IsListInit});
13609   while (!WorkList.empty())
13610     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13611 }
13612 
13613 /// Diagnose integer type and any valid implicit conversion to it.
13614 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13615   // Taking into account implicit conversions,
13616   // allow any integer.
13617   if (!E->getType()->isIntegerType()) {
13618     S.Diag(E->getBeginLoc(),
13619            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13620     return true;
13621   }
13622   // Potentially emit standard warnings for implicit conversions if enabled
13623   // using -Wconversion.
13624   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13625   return false;
13626 }
13627 
13628 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13629 // Returns true when emitting a warning about taking the address of a reference.
13630 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13631                               const PartialDiagnostic &PD) {
13632   E = E->IgnoreParenImpCasts();
13633 
13634   const FunctionDecl *FD = nullptr;
13635 
13636   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13637     if (!DRE->getDecl()->getType()->isReferenceType())
13638       return false;
13639   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13640     if (!M->getMemberDecl()->getType()->isReferenceType())
13641       return false;
13642   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13643     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13644       return false;
13645     FD = Call->getDirectCallee();
13646   } else {
13647     return false;
13648   }
13649 
13650   SemaRef.Diag(E->getExprLoc(), PD);
13651 
13652   // If possible, point to location of function.
13653   if (FD) {
13654     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13655   }
13656 
13657   return true;
13658 }
13659 
13660 // Returns true if the SourceLocation is expanded from any macro body.
13661 // Returns false if the SourceLocation is invalid, is from not in a macro
13662 // expansion, or is from expanded from a top-level macro argument.
13663 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13664   if (Loc.isInvalid())
13665     return false;
13666 
13667   while (Loc.isMacroID()) {
13668     if (SM.isMacroBodyExpansion(Loc))
13669       return true;
13670     Loc = SM.getImmediateMacroCallerLoc(Loc);
13671   }
13672 
13673   return false;
13674 }
13675 
13676 /// Diagnose pointers that are always non-null.
13677 /// \param E the expression containing the pointer
13678 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13679 /// compared to a null pointer
13680 /// \param IsEqual True when the comparison is equal to a null pointer
13681 /// \param Range Extra SourceRange to highlight in the diagnostic
13682 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13683                                         Expr::NullPointerConstantKind NullKind,
13684                                         bool IsEqual, SourceRange Range) {
13685   if (!E)
13686     return;
13687 
13688   // Don't warn inside macros.
13689   if (E->getExprLoc().isMacroID()) {
13690     const SourceManager &SM = getSourceManager();
13691     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13692         IsInAnyMacroBody(SM, Range.getBegin()))
13693       return;
13694   }
13695   E = E->IgnoreImpCasts();
13696 
13697   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13698 
13699   if (isa<CXXThisExpr>(E)) {
13700     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13701                                 : diag::warn_this_bool_conversion;
13702     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13703     return;
13704   }
13705 
13706   bool IsAddressOf = false;
13707 
13708   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13709     if (UO->getOpcode() != UO_AddrOf)
13710       return;
13711     IsAddressOf = true;
13712     E = UO->getSubExpr();
13713   }
13714 
13715   if (IsAddressOf) {
13716     unsigned DiagID = IsCompare
13717                           ? diag::warn_address_of_reference_null_compare
13718                           : diag::warn_address_of_reference_bool_conversion;
13719     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13720                                          << IsEqual;
13721     if (CheckForReference(*this, E, PD)) {
13722       return;
13723     }
13724   }
13725 
13726   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13727     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13728     std::string Str;
13729     llvm::raw_string_ostream S(Str);
13730     E->printPretty(S, nullptr, getPrintingPolicy());
13731     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13732                                 : diag::warn_cast_nonnull_to_bool;
13733     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13734       << E->getSourceRange() << Range << IsEqual;
13735     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13736   };
13737 
13738   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13739   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13740     if (auto *Callee = Call->getDirectCallee()) {
13741       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13742         ComplainAboutNonnullParamOrCall(A);
13743         return;
13744       }
13745     }
13746   }
13747 
13748   // Expect to find a single Decl.  Skip anything more complicated.
13749   ValueDecl *D = nullptr;
13750   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13751     D = R->getDecl();
13752   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13753     D = M->getMemberDecl();
13754   }
13755 
13756   // Weak Decls can be null.
13757   if (!D || D->isWeak())
13758     return;
13759 
13760   // Check for parameter decl with nonnull attribute
13761   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13762     if (getCurFunction() &&
13763         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13764       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13765         ComplainAboutNonnullParamOrCall(A);
13766         return;
13767       }
13768 
13769       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13770         // Skip function template not specialized yet.
13771         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13772           return;
13773         auto ParamIter = llvm::find(FD->parameters(), PV);
13774         assert(ParamIter != FD->param_end());
13775         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13776 
13777         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13778           if (!NonNull->args_size()) {
13779               ComplainAboutNonnullParamOrCall(NonNull);
13780               return;
13781           }
13782 
13783           for (const ParamIdx &ArgNo : NonNull->args()) {
13784             if (ArgNo.getASTIndex() == ParamNo) {
13785               ComplainAboutNonnullParamOrCall(NonNull);
13786               return;
13787             }
13788           }
13789         }
13790       }
13791     }
13792   }
13793 
13794   QualType T = D->getType();
13795   const bool IsArray = T->isArrayType();
13796   const bool IsFunction = T->isFunctionType();
13797 
13798   // Address of function is used to silence the function warning.
13799   if (IsAddressOf && IsFunction) {
13800     return;
13801   }
13802 
13803   // Found nothing.
13804   if (!IsAddressOf && !IsFunction && !IsArray)
13805     return;
13806 
13807   // Pretty print the expression for the diagnostic.
13808   std::string Str;
13809   llvm::raw_string_ostream S(Str);
13810   E->printPretty(S, nullptr, getPrintingPolicy());
13811 
13812   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13813                               : diag::warn_impcast_pointer_to_bool;
13814   enum {
13815     AddressOf,
13816     FunctionPointer,
13817     ArrayPointer
13818   } DiagType;
13819   if (IsAddressOf)
13820     DiagType = AddressOf;
13821   else if (IsFunction)
13822     DiagType = FunctionPointer;
13823   else if (IsArray)
13824     DiagType = ArrayPointer;
13825   else
13826     llvm_unreachable("Could not determine diagnostic.");
13827   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13828                                 << Range << IsEqual;
13829 
13830   if (!IsFunction)
13831     return;
13832 
13833   // Suggest '&' to silence the function warning.
13834   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13835       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13836 
13837   // Check to see if '()' fixit should be emitted.
13838   QualType ReturnType;
13839   UnresolvedSet<4> NonTemplateOverloads;
13840   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13841   if (ReturnType.isNull())
13842     return;
13843 
13844   if (IsCompare) {
13845     // There are two cases here.  If there is null constant, the only suggest
13846     // for a pointer return type.  If the null is 0, then suggest if the return
13847     // type is a pointer or an integer type.
13848     if (!ReturnType->isPointerType()) {
13849       if (NullKind == Expr::NPCK_ZeroExpression ||
13850           NullKind == Expr::NPCK_ZeroLiteral) {
13851         if (!ReturnType->isIntegerType())
13852           return;
13853       } else {
13854         return;
13855       }
13856     }
13857   } else { // !IsCompare
13858     // For function to bool, only suggest if the function pointer has bool
13859     // return type.
13860     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13861       return;
13862   }
13863   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13864       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13865 }
13866 
13867 /// Diagnoses "dangerous" implicit conversions within the given
13868 /// expression (which is a full expression).  Implements -Wconversion
13869 /// and -Wsign-compare.
13870 ///
13871 /// \param CC the "context" location of the implicit conversion, i.e.
13872 ///   the most location of the syntactic entity requiring the implicit
13873 ///   conversion
13874 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13875   // Don't diagnose in unevaluated contexts.
13876   if (isUnevaluatedContext())
13877     return;
13878 
13879   // Don't diagnose for value- or type-dependent expressions.
13880   if (E->isTypeDependent() || E->isValueDependent())
13881     return;
13882 
13883   // Check for array bounds violations in cases where the check isn't triggered
13884   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13885   // ArraySubscriptExpr is on the RHS of a variable initialization.
13886   CheckArrayAccess(E);
13887 
13888   // This is not the right CC for (e.g.) a variable initialization.
13889   AnalyzeImplicitConversions(*this, E, CC);
13890 }
13891 
13892 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13893 /// Input argument E is a logical expression.
13894 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13895   ::CheckBoolLikeConversion(*this, E, CC);
13896 }
13897 
13898 /// Diagnose when expression is an integer constant expression and its evaluation
13899 /// results in integer overflow
13900 void Sema::CheckForIntOverflow (Expr *E) {
13901   // Use a work list to deal with nested struct initializers.
13902   SmallVector<Expr *, 2> Exprs(1, E);
13903 
13904   do {
13905     Expr *OriginalE = Exprs.pop_back_val();
13906     Expr *E = OriginalE->IgnoreParenCasts();
13907 
13908     if (isa<BinaryOperator>(E)) {
13909       E->EvaluateForOverflow(Context);
13910       continue;
13911     }
13912 
13913     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13914       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13915     else if (isa<ObjCBoxedExpr>(OriginalE))
13916       E->EvaluateForOverflow(Context);
13917     else if (auto Call = dyn_cast<CallExpr>(E))
13918       Exprs.append(Call->arg_begin(), Call->arg_end());
13919     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13920       Exprs.append(Message->arg_begin(), Message->arg_end());
13921   } while (!Exprs.empty());
13922 }
13923 
13924 namespace {
13925 
13926 /// Visitor for expressions which looks for unsequenced operations on the
13927 /// same object.
13928 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13929   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13930 
13931   /// A tree of sequenced regions within an expression. Two regions are
13932   /// unsequenced if one is an ancestor or a descendent of the other. When we
13933   /// finish processing an expression with sequencing, such as a comma
13934   /// expression, we fold its tree nodes into its parent, since they are
13935   /// unsequenced with respect to nodes we will visit later.
13936   class SequenceTree {
13937     struct Value {
13938       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13939       unsigned Parent : 31;
13940       unsigned Merged : 1;
13941     };
13942     SmallVector<Value, 8> Values;
13943 
13944   public:
13945     /// A region within an expression which may be sequenced with respect
13946     /// to some other region.
13947     class Seq {
13948       friend class SequenceTree;
13949 
13950       unsigned Index;
13951 
13952       explicit Seq(unsigned N) : Index(N) {}
13953 
13954     public:
13955       Seq() : Index(0) {}
13956     };
13957 
13958     SequenceTree() { Values.push_back(Value(0)); }
13959     Seq root() const { return Seq(0); }
13960 
13961     /// Create a new sequence of operations, which is an unsequenced
13962     /// subset of \p Parent. This sequence of operations is sequenced with
13963     /// respect to other children of \p Parent.
13964     Seq allocate(Seq Parent) {
13965       Values.push_back(Value(Parent.Index));
13966       return Seq(Values.size() - 1);
13967     }
13968 
13969     /// Merge a sequence of operations into its parent.
13970     void merge(Seq S) {
13971       Values[S.Index].Merged = true;
13972     }
13973 
13974     /// Determine whether two operations are unsequenced. This operation
13975     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13976     /// should have been merged into its parent as appropriate.
13977     bool isUnsequenced(Seq Cur, Seq Old) {
13978       unsigned C = representative(Cur.Index);
13979       unsigned Target = representative(Old.Index);
13980       while (C >= Target) {
13981         if (C == Target)
13982           return true;
13983         C = Values[C].Parent;
13984       }
13985       return false;
13986     }
13987 
13988   private:
13989     /// Pick a representative for a sequence.
13990     unsigned representative(unsigned K) {
13991       if (Values[K].Merged)
13992         // Perform path compression as we go.
13993         return Values[K].Parent = representative(Values[K].Parent);
13994       return K;
13995     }
13996   };
13997 
13998   /// An object for which we can track unsequenced uses.
13999   using Object = const NamedDecl *;
14000 
14001   /// Different flavors of object usage which we track. We only track the
14002   /// least-sequenced usage of each kind.
14003   enum UsageKind {
14004     /// A read of an object. Multiple unsequenced reads are OK.
14005     UK_Use,
14006 
14007     /// A modification of an object which is sequenced before the value
14008     /// computation of the expression, such as ++n in C++.
14009     UK_ModAsValue,
14010 
14011     /// A modification of an object which is not sequenced before the value
14012     /// computation of the expression, such as n++.
14013     UK_ModAsSideEffect,
14014 
14015     UK_Count = UK_ModAsSideEffect + 1
14016   };
14017 
14018   /// Bundle together a sequencing region and the expression corresponding
14019   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14020   struct Usage {
14021     const Expr *UsageExpr;
14022     SequenceTree::Seq Seq;
14023 
14024     Usage() : UsageExpr(nullptr), Seq() {}
14025   };
14026 
14027   struct UsageInfo {
14028     Usage Uses[UK_Count];
14029 
14030     /// Have we issued a diagnostic for this object already?
14031     bool Diagnosed;
14032 
14033     UsageInfo() : Uses(), Diagnosed(false) {}
14034   };
14035   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14036 
14037   Sema &SemaRef;
14038 
14039   /// Sequenced regions within the expression.
14040   SequenceTree Tree;
14041 
14042   /// Declaration modifications and references which we have seen.
14043   UsageInfoMap UsageMap;
14044 
14045   /// The region we are currently within.
14046   SequenceTree::Seq Region;
14047 
14048   /// Filled in with declarations which were modified as a side-effect
14049   /// (that is, post-increment operations).
14050   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14051 
14052   /// Expressions to check later. We defer checking these to reduce
14053   /// stack usage.
14054   SmallVectorImpl<const Expr *> &WorkList;
14055 
14056   /// RAII object wrapping the visitation of a sequenced subexpression of an
14057   /// expression. At the end of this process, the side-effects of the evaluation
14058   /// become sequenced with respect to the value computation of the result, so
14059   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14060   /// UK_ModAsValue.
14061   struct SequencedSubexpression {
14062     SequencedSubexpression(SequenceChecker &Self)
14063       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14064       Self.ModAsSideEffect = &ModAsSideEffect;
14065     }
14066 
14067     ~SequencedSubexpression() {
14068       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14069         // Add a new usage with usage kind UK_ModAsValue, and then restore
14070         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14071         // the previous one was empty).
14072         UsageInfo &UI = Self.UsageMap[M.first];
14073         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14074         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14075         SideEffectUsage = M.second;
14076       }
14077       Self.ModAsSideEffect = OldModAsSideEffect;
14078     }
14079 
14080     SequenceChecker &Self;
14081     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14082     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14083   };
14084 
14085   /// RAII object wrapping the visitation of a subexpression which we might
14086   /// choose to evaluate as a constant. If any subexpression is evaluated and
14087   /// found to be non-constant, this allows us to suppress the evaluation of
14088   /// the outer expression.
14089   class EvaluationTracker {
14090   public:
14091     EvaluationTracker(SequenceChecker &Self)
14092         : Self(Self), Prev(Self.EvalTracker) {
14093       Self.EvalTracker = this;
14094     }
14095 
14096     ~EvaluationTracker() {
14097       Self.EvalTracker = Prev;
14098       if (Prev)
14099         Prev->EvalOK &= EvalOK;
14100     }
14101 
14102     bool evaluate(const Expr *E, bool &Result) {
14103       if (!EvalOK || E->isValueDependent())
14104         return false;
14105       EvalOK = E->EvaluateAsBooleanCondition(
14106           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14107       return EvalOK;
14108     }
14109 
14110   private:
14111     SequenceChecker &Self;
14112     EvaluationTracker *Prev;
14113     bool EvalOK = true;
14114   } *EvalTracker = nullptr;
14115 
14116   /// Find the object which is produced by the specified expression,
14117   /// if any.
14118   Object getObject(const Expr *E, bool Mod) const {
14119     E = E->IgnoreParenCasts();
14120     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14121       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14122         return getObject(UO->getSubExpr(), Mod);
14123     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14124       if (BO->getOpcode() == BO_Comma)
14125         return getObject(BO->getRHS(), Mod);
14126       if (Mod && BO->isAssignmentOp())
14127         return getObject(BO->getLHS(), Mod);
14128     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14129       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14130       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14131         return ME->getMemberDecl();
14132     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14133       // FIXME: If this is a reference, map through to its value.
14134       return DRE->getDecl();
14135     return nullptr;
14136   }
14137 
14138   /// Note that an object \p O was modified or used by an expression
14139   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14140   /// the object \p O as obtained via the \p UsageMap.
14141   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14142     // Get the old usage for the given object and usage kind.
14143     Usage &U = UI.Uses[UK];
14144     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14145       // If we have a modification as side effect and are in a sequenced
14146       // subexpression, save the old Usage so that we can restore it later
14147       // in SequencedSubexpression::~SequencedSubexpression.
14148       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14149         ModAsSideEffect->push_back(std::make_pair(O, U));
14150       // Then record the new usage with the current sequencing region.
14151       U.UsageExpr = UsageExpr;
14152       U.Seq = Region;
14153     }
14154   }
14155 
14156   /// Check whether a modification or use of an object \p O in an expression
14157   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14158   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14159   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14160   /// usage and false we are checking for a mod-use unsequenced usage.
14161   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14162                   UsageKind OtherKind, bool IsModMod) {
14163     if (UI.Diagnosed)
14164       return;
14165 
14166     const Usage &U = UI.Uses[OtherKind];
14167     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14168       return;
14169 
14170     const Expr *Mod = U.UsageExpr;
14171     const Expr *ModOrUse = UsageExpr;
14172     if (OtherKind == UK_Use)
14173       std::swap(Mod, ModOrUse);
14174 
14175     SemaRef.DiagRuntimeBehavior(
14176         Mod->getExprLoc(), {Mod, ModOrUse},
14177         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14178                                : diag::warn_unsequenced_mod_use)
14179             << O << SourceRange(ModOrUse->getExprLoc()));
14180     UI.Diagnosed = true;
14181   }
14182 
14183   // A note on note{Pre, Post}{Use, Mod}:
14184   //
14185   // (It helps to follow the algorithm with an expression such as
14186   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14187   //  operations before C++17 and both are well-defined in C++17).
14188   //
14189   // When visiting a node which uses/modify an object we first call notePreUse
14190   // or notePreMod before visiting its sub-expression(s). At this point the
14191   // children of the current node have not yet been visited and so the eventual
14192   // uses/modifications resulting from the children of the current node have not
14193   // been recorded yet.
14194   //
14195   // We then visit the children of the current node. After that notePostUse or
14196   // notePostMod is called. These will 1) detect an unsequenced modification
14197   // as side effect (as in "k++ + k") and 2) add a new usage with the
14198   // appropriate usage kind.
14199   //
14200   // We also have to be careful that some operation sequences modification as
14201   // side effect as well (for example: || or ,). To account for this we wrap
14202   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14203   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14204   // which record usages which are modifications as side effect, and then
14205   // downgrade them (or more accurately restore the previous usage which was a
14206   // modification as side effect) when exiting the scope of the sequenced
14207   // subexpression.
14208 
14209   void notePreUse(Object O, const Expr *UseExpr) {
14210     UsageInfo &UI = UsageMap[O];
14211     // Uses conflict with other modifications.
14212     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14213   }
14214 
14215   void notePostUse(Object O, const Expr *UseExpr) {
14216     UsageInfo &UI = UsageMap[O];
14217     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14218                /*IsModMod=*/false);
14219     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14220   }
14221 
14222   void notePreMod(Object O, const Expr *ModExpr) {
14223     UsageInfo &UI = UsageMap[O];
14224     // Modifications conflict with other modifications and with uses.
14225     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14226     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14227   }
14228 
14229   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14230     UsageInfo &UI = UsageMap[O];
14231     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14232                /*IsModMod=*/true);
14233     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14234   }
14235 
14236 public:
14237   SequenceChecker(Sema &S, const Expr *E,
14238                   SmallVectorImpl<const Expr *> &WorkList)
14239       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14240     Visit(E);
14241     // Silence a -Wunused-private-field since WorkList is now unused.
14242     // TODO: Evaluate if it can be used, and if not remove it.
14243     (void)this->WorkList;
14244   }
14245 
14246   void VisitStmt(const Stmt *S) {
14247     // Skip all statements which aren't expressions for now.
14248   }
14249 
14250   void VisitExpr(const Expr *E) {
14251     // By default, just recurse to evaluated subexpressions.
14252     Base::VisitStmt(E);
14253   }
14254 
14255   void VisitCastExpr(const CastExpr *E) {
14256     Object O = Object();
14257     if (E->getCastKind() == CK_LValueToRValue)
14258       O = getObject(E->getSubExpr(), false);
14259 
14260     if (O)
14261       notePreUse(O, E);
14262     VisitExpr(E);
14263     if (O)
14264       notePostUse(O, E);
14265   }
14266 
14267   void VisitSequencedExpressions(const Expr *SequencedBefore,
14268                                  const Expr *SequencedAfter) {
14269     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14270     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14271     SequenceTree::Seq OldRegion = Region;
14272 
14273     {
14274       SequencedSubexpression SeqBefore(*this);
14275       Region = BeforeRegion;
14276       Visit(SequencedBefore);
14277     }
14278 
14279     Region = AfterRegion;
14280     Visit(SequencedAfter);
14281 
14282     Region = OldRegion;
14283 
14284     Tree.merge(BeforeRegion);
14285     Tree.merge(AfterRegion);
14286   }
14287 
14288   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14289     // C++17 [expr.sub]p1:
14290     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14291     //   expression E1 is sequenced before the expression E2.
14292     if (SemaRef.getLangOpts().CPlusPlus17)
14293       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14294     else {
14295       Visit(ASE->getLHS());
14296       Visit(ASE->getRHS());
14297     }
14298   }
14299 
14300   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14301   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14302   void VisitBinPtrMem(const BinaryOperator *BO) {
14303     // C++17 [expr.mptr.oper]p4:
14304     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14305     //  the expression E1 is sequenced before the expression E2.
14306     if (SemaRef.getLangOpts().CPlusPlus17)
14307       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14308     else {
14309       Visit(BO->getLHS());
14310       Visit(BO->getRHS());
14311     }
14312   }
14313 
14314   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14315   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14316   void VisitBinShlShr(const BinaryOperator *BO) {
14317     // C++17 [expr.shift]p4:
14318     //  The expression E1 is sequenced before the expression E2.
14319     if (SemaRef.getLangOpts().CPlusPlus17)
14320       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14321     else {
14322       Visit(BO->getLHS());
14323       Visit(BO->getRHS());
14324     }
14325   }
14326 
14327   void VisitBinComma(const BinaryOperator *BO) {
14328     // C++11 [expr.comma]p1:
14329     //   Every value computation and side effect associated with the left
14330     //   expression is sequenced before every value computation and side
14331     //   effect associated with the right expression.
14332     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14333   }
14334 
14335   void VisitBinAssign(const BinaryOperator *BO) {
14336     SequenceTree::Seq RHSRegion;
14337     SequenceTree::Seq LHSRegion;
14338     if (SemaRef.getLangOpts().CPlusPlus17) {
14339       RHSRegion = Tree.allocate(Region);
14340       LHSRegion = Tree.allocate(Region);
14341     } else {
14342       RHSRegion = Region;
14343       LHSRegion = Region;
14344     }
14345     SequenceTree::Seq OldRegion = Region;
14346 
14347     // C++11 [expr.ass]p1:
14348     //  [...] the assignment is sequenced after the value computation
14349     //  of the right and left operands, [...]
14350     //
14351     // so check it before inspecting the operands and update the
14352     // map afterwards.
14353     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14354     if (O)
14355       notePreMod(O, BO);
14356 
14357     if (SemaRef.getLangOpts().CPlusPlus17) {
14358       // C++17 [expr.ass]p1:
14359       //  [...] The right operand is sequenced before the left operand. [...]
14360       {
14361         SequencedSubexpression SeqBefore(*this);
14362         Region = RHSRegion;
14363         Visit(BO->getRHS());
14364       }
14365 
14366       Region = LHSRegion;
14367       Visit(BO->getLHS());
14368 
14369       if (O && isa<CompoundAssignOperator>(BO))
14370         notePostUse(O, BO);
14371 
14372     } else {
14373       // C++11 does not specify any sequencing between the LHS and RHS.
14374       Region = LHSRegion;
14375       Visit(BO->getLHS());
14376 
14377       if (O && isa<CompoundAssignOperator>(BO))
14378         notePostUse(O, BO);
14379 
14380       Region = RHSRegion;
14381       Visit(BO->getRHS());
14382     }
14383 
14384     // C++11 [expr.ass]p1:
14385     //  the assignment is sequenced [...] before the value computation of the
14386     //  assignment expression.
14387     // C11 6.5.16/3 has no such rule.
14388     Region = OldRegion;
14389     if (O)
14390       notePostMod(O, BO,
14391                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14392                                                   : UK_ModAsSideEffect);
14393     if (SemaRef.getLangOpts().CPlusPlus17) {
14394       Tree.merge(RHSRegion);
14395       Tree.merge(LHSRegion);
14396     }
14397   }
14398 
14399   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14400     VisitBinAssign(CAO);
14401   }
14402 
14403   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14404   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14405   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14406     Object O = getObject(UO->getSubExpr(), true);
14407     if (!O)
14408       return VisitExpr(UO);
14409 
14410     notePreMod(O, UO);
14411     Visit(UO->getSubExpr());
14412     // C++11 [expr.pre.incr]p1:
14413     //   the expression ++x is equivalent to x+=1
14414     notePostMod(O, UO,
14415                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14416                                                 : UK_ModAsSideEffect);
14417   }
14418 
14419   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14420   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14421   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14422     Object O = getObject(UO->getSubExpr(), true);
14423     if (!O)
14424       return VisitExpr(UO);
14425 
14426     notePreMod(O, UO);
14427     Visit(UO->getSubExpr());
14428     notePostMod(O, UO, UK_ModAsSideEffect);
14429   }
14430 
14431   void VisitBinLOr(const BinaryOperator *BO) {
14432     // C++11 [expr.log.or]p2:
14433     //  If the second expression is evaluated, every value computation and
14434     //  side effect associated with the first expression is sequenced before
14435     //  every value computation and side effect associated with the
14436     //  second expression.
14437     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14438     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14439     SequenceTree::Seq OldRegion = Region;
14440 
14441     EvaluationTracker Eval(*this);
14442     {
14443       SequencedSubexpression Sequenced(*this);
14444       Region = LHSRegion;
14445       Visit(BO->getLHS());
14446     }
14447 
14448     // C++11 [expr.log.or]p1:
14449     //  [...] the second operand is not evaluated if the first operand
14450     //  evaluates to true.
14451     bool EvalResult = false;
14452     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14453     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14454     if (ShouldVisitRHS) {
14455       Region = RHSRegion;
14456       Visit(BO->getRHS());
14457     }
14458 
14459     Region = OldRegion;
14460     Tree.merge(LHSRegion);
14461     Tree.merge(RHSRegion);
14462   }
14463 
14464   void VisitBinLAnd(const BinaryOperator *BO) {
14465     // C++11 [expr.log.and]p2:
14466     //  If the second expression is evaluated, every value computation and
14467     //  side effect associated with the first expression is sequenced before
14468     //  every value computation and side effect associated with the
14469     //  second expression.
14470     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14471     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14472     SequenceTree::Seq OldRegion = Region;
14473 
14474     EvaluationTracker Eval(*this);
14475     {
14476       SequencedSubexpression Sequenced(*this);
14477       Region = LHSRegion;
14478       Visit(BO->getLHS());
14479     }
14480 
14481     // C++11 [expr.log.and]p1:
14482     //  [...] the second operand is not evaluated if the first operand is false.
14483     bool EvalResult = false;
14484     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14485     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14486     if (ShouldVisitRHS) {
14487       Region = RHSRegion;
14488       Visit(BO->getRHS());
14489     }
14490 
14491     Region = OldRegion;
14492     Tree.merge(LHSRegion);
14493     Tree.merge(RHSRegion);
14494   }
14495 
14496   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14497     // C++11 [expr.cond]p1:
14498     //  [...] Every value computation and side effect associated with the first
14499     //  expression is sequenced before every value computation and side effect
14500     //  associated with the second or third expression.
14501     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14502 
14503     // No sequencing is specified between the true and false expression.
14504     // However since exactly one of both is going to be evaluated we can
14505     // consider them to be sequenced. This is needed to avoid warning on
14506     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14507     // both the true and false expressions because we can't evaluate x.
14508     // This will still allow us to detect an expression like (pre C++17)
14509     // "(x ? y += 1 : y += 2) = y".
14510     //
14511     // We don't wrap the visitation of the true and false expression with
14512     // SequencedSubexpression because we don't want to downgrade modifications
14513     // as side effect in the true and false expressions after the visition
14514     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14515     // not warn between the two "y++", but we should warn between the "y++"
14516     // and the "y".
14517     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14518     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14519     SequenceTree::Seq OldRegion = Region;
14520 
14521     EvaluationTracker Eval(*this);
14522     {
14523       SequencedSubexpression Sequenced(*this);
14524       Region = ConditionRegion;
14525       Visit(CO->getCond());
14526     }
14527 
14528     // C++11 [expr.cond]p1:
14529     // [...] The first expression is contextually converted to bool (Clause 4).
14530     // It is evaluated and if it is true, the result of the conditional
14531     // expression is the value of the second expression, otherwise that of the
14532     // third expression. Only one of the second and third expressions is
14533     // evaluated. [...]
14534     bool EvalResult = false;
14535     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14536     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14537     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14538     if (ShouldVisitTrueExpr) {
14539       Region = TrueRegion;
14540       Visit(CO->getTrueExpr());
14541     }
14542     if (ShouldVisitFalseExpr) {
14543       Region = FalseRegion;
14544       Visit(CO->getFalseExpr());
14545     }
14546 
14547     Region = OldRegion;
14548     Tree.merge(ConditionRegion);
14549     Tree.merge(TrueRegion);
14550     Tree.merge(FalseRegion);
14551   }
14552 
14553   void VisitCallExpr(const CallExpr *CE) {
14554     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14555 
14556     if (CE->isUnevaluatedBuiltinCall(Context))
14557       return;
14558 
14559     // C++11 [intro.execution]p15:
14560     //   When calling a function [...], every value computation and side effect
14561     //   associated with any argument expression, or with the postfix expression
14562     //   designating the called function, is sequenced before execution of every
14563     //   expression or statement in the body of the function [and thus before
14564     //   the value computation of its result].
14565     SequencedSubexpression Sequenced(*this);
14566     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14567       // C++17 [expr.call]p5
14568       //   The postfix-expression is sequenced before each expression in the
14569       //   expression-list and any default argument. [...]
14570       SequenceTree::Seq CalleeRegion;
14571       SequenceTree::Seq OtherRegion;
14572       if (SemaRef.getLangOpts().CPlusPlus17) {
14573         CalleeRegion = Tree.allocate(Region);
14574         OtherRegion = Tree.allocate(Region);
14575       } else {
14576         CalleeRegion = Region;
14577         OtherRegion = Region;
14578       }
14579       SequenceTree::Seq OldRegion = Region;
14580 
14581       // Visit the callee expression first.
14582       Region = CalleeRegion;
14583       if (SemaRef.getLangOpts().CPlusPlus17) {
14584         SequencedSubexpression Sequenced(*this);
14585         Visit(CE->getCallee());
14586       } else {
14587         Visit(CE->getCallee());
14588       }
14589 
14590       // Then visit the argument expressions.
14591       Region = OtherRegion;
14592       for (const Expr *Argument : CE->arguments())
14593         Visit(Argument);
14594 
14595       Region = OldRegion;
14596       if (SemaRef.getLangOpts().CPlusPlus17) {
14597         Tree.merge(CalleeRegion);
14598         Tree.merge(OtherRegion);
14599       }
14600     });
14601   }
14602 
14603   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14604     // C++17 [over.match.oper]p2:
14605     //   [...] the operator notation is first transformed to the equivalent
14606     //   function-call notation as summarized in Table 12 (where @ denotes one
14607     //   of the operators covered in the specified subclause). However, the
14608     //   operands are sequenced in the order prescribed for the built-in
14609     //   operator (Clause 8).
14610     //
14611     // From the above only overloaded binary operators and overloaded call
14612     // operators have sequencing rules in C++17 that we need to handle
14613     // separately.
14614     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14615         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14616       return VisitCallExpr(CXXOCE);
14617 
14618     enum {
14619       NoSequencing,
14620       LHSBeforeRHS,
14621       RHSBeforeLHS,
14622       LHSBeforeRest
14623     } SequencingKind;
14624     switch (CXXOCE->getOperator()) {
14625     case OO_Equal:
14626     case OO_PlusEqual:
14627     case OO_MinusEqual:
14628     case OO_StarEqual:
14629     case OO_SlashEqual:
14630     case OO_PercentEqual:
14631     case OO_CaretEqual:
14632     case OO_AmpEqual:
14633     case OO_PipeEqual:
14634     case OO_LessLessEqual:
14635     case OO_GreaterGreaterEqual:
14636       SequencingKind = RHSBeforeLHS;
14637       break;
14638 
14639     case OO_LessLess:
14640     case OO_GreaterGreater:
14641     case OO_AmpAmp:
14642     case OO_PipePipe:
14643     case OO_Comma:
14644     case OO_ArrowStar:
14645     case OO_Subscript:
14646       SequencingKind = LHSBeforeRHS;
14647       break;
14648 
14649     case OO_Call:
14650       SequencingKind = LHSBeforeRest;
14651       break;
14652 
14653     default:
14654       SequencingKind = NoSequencing;
14655       break;
14656     }
14657 
14658     if (SequencingKind == NoSequencing)
14659       return VisitCallExpr(CXXOCE);
14660 
14661     // This is a call, so all subexpressions are sequenced before the result.
14662     SequencedSubexpression Sequenced(*this);
14663 
14664     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14665       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14666              "Should only get there with C++17 and above!");
14667       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14668              "Should only get there with an overloaded binary operator"
14669              " or an overloaded call operator!");
14670 
14671       if (SequencingKind == LHSBeforeRest) {
14672         assert(CXXOCE->getOperator() == OO_Call &&
14673                "We should only have an overloaded call operator here!");
14674 
14675         // This is very similar to VisitCallExpr, except that we only have the
14676         // C++17 case. The postfix-expression is the first argument of the
14677         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14678         // are in the following arguments.
14679         //
14680         // Note that we intentionally do not visit the callee expression since
14681         // it is just a decayed reference to a function.
14682         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14683         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14684         SequenceTree::Seq OldRegion = Region;
14685 
14686         assert(CXXOCE->getNumArgs() >= 1 &&
14687                "An overloaded call operator must have at least one argument"
14688                " for the postfix-expression!");
14689         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14690         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14691                                           CXXOCE->getNumArgs() - 1);
14692 
14693         // Visit the postfix-expression first.
14694         {
14695           Region = PostfixExprRegion;
14696           SequencedSubexpression Sequenced(*this);
14697           Visit(PostfixExpr);
14698         }
14699 
14700         // Then visit the argument expressions.
14701         Region = ArgsRegion;
14702         for (const Expr *Arg : Args)
14703           Visit(Arg);
14704 
14705         Region = OldRegion;
14706         Tree.merge(PostfixExprRegion);
14707         Tree.merge(ArgsRegion);
14708       } else {
14709         assert(CXXOCE->getNumArgs() == 2 &&
14710                "Should only have two arguments here!");
14711         assert((SequencingKind == LHSBeforeRHS ||
14712                 SequencingKind == RHSBeforeLHS) &&
14713                "Unexpected sequencing kind!");
14714 
14715         // We do not visit the callee expression since it is just a decayed
14716         // reference to a function.
14717         const Expr *E1 = CXXOCE->getArg(0);
14718         const Expr *E2 = CXXOCE->getArg(1);
14719         if (SequencingKind == RHSBeforeLHS)
14720           std::swap(E1, E2);
14721 
14722         return VisitSequencedExpressions(E1, E2);
14723       }
14724     });
14725   }
14726 
14727   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14728     // This is a call, so all subexpressions are sequenced before the result.
14729     SequencedSubexpression Sequenced(*this);
14730 
14731     if (!CCE->isListInitialization())
14732       return VisitExpr(CCE);
14733 
14734     // In C++11, list initializations are sequenced.
14735     SmallVector<SequenceTree::Seq, 32> Elts;
14736     SequenceTree::Seq Parent = Region;
14737     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14738                                               E = CCE->arg_end();
14739          I != E; ++I) {
14740       Region = Tree.allocate(Parent);
14741       Elts.push_back(Region);
14742       Visit(*I);
14743     }
14744 
14745     // Forget that the initializers are sequenced.
14746     Region = Parent;
14747     for (unsigned I = 0; I < Elts.size(); ++I)
14748       Tree.merge(Elts[I]);
14749   }
14750 
14751   void VisitInitListExpr(const InitListExpr *ILE) {
14752     if (!SemaRef.getLangOpts().CPlusPlus11)
14753       return VisitExpr(ILE);
14754 
14755     // In C++11, list initializations are sequenced.
14756     SmallVector<SequenceTree::Seq, 32> Elts;
14757     SequenceTree::Seq Parent = Region;
14758     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14759       const Expr *E = ILE->getInit(I);
14760       if (!E)
14761         continue;
14762       Region = Tree.allocate(Parent);
14763       Elts.push_back(Region);
14764       Visit(E);
14765     }
14766 
14767     // Forget that the initializers are sequenced.
14768     Region = Parent;
14769     for (unsigned I = 0; I < Elts.size(); ++I)
14770       Tree.merge(Elts[I]);
14771   }
14772 };
14773 
14774 } // namespace
14775 
14776 void Sema::CheckUnsequencedOperations(const Expr *E) {
14777   SmallVector<const Expr *, 8> WorkList;
14778   WorkList.push_back(E);
14779   while (!WorkList.empty()) {
14780     const Expr *Item = WorkList.pop_back_val();
14781     SequenceChecker(*this, Item, WorkList);
14782   }
14783 }
14784 
14785 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14786                               bool IsConstexpr) {
14787   llvm::SaveAndRestore<bool> ConstantContext(
14788       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14789   CheckImplicitConversions(E, CheckLoc);
14790   if (!E->isInstantiationDependent())
14791     CheckUnsequencedOperations(E);
14792   if (!IsConstexpr && !E->isValueDependent())
14793     CheckForIntOverflow(E);
14794   DiagnoseMisalignedMembers();
14795 }
14796 
14797 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14798                                        FieldDecl *BitField,
14799                                        Expr *Init) {
14800   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14801 }
14802 
14803 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14804                                          SourceLocation Loc) {
14805   if (!PType->isVariablyModifiedType())
14806     return;
14807   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14808     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14809     return;
14810   }
14811   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14812     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14813     return;
14814   }
14815   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14816     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14817     return;
14818   }
14819 
14820   const ArrayType *AT = S.Context.getAsArrayType(PType);
14821   if (!AT)
14822     return;
14823 
14824   if (AT->getSizeModifier() != ArrayType::Star) {
14825     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14826     return;
14827   }
14828 
14829   S.Diag(Loc, diag::err_array_star_in_function_definition);
14830 }
14831 
14832 /// CheckParmsForFunctionDef - Check that the parameters of the given
14833 /// function are appropriate for the definition of a function. This
14834 /// takes care of any checks that cannot be performed on the
14835 /// declaration itself, e.g., that the types of each of the function
14836 /// parameters are complete.
14837 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14838                                     bool CheckParameterNames) {
14839   bool HasInvalidParm = false;
14840   for (ParmVarDecl *Param : Parameters) {
14841     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14842     // function declarator that is part of a function definition of
14843     // that function shall not have incomplete type.
14844     //
14845     // This is also C++ [dcl.fct]p6.
14846     if (!Param->isInvalidDecl() &&
14847         RequireCompleteType(Param->getLocation(), Param->getType(),
14848                             diag::err_typecheck_decl_incomplete_type)) {
14849       Param->setInvalidDecl();
14850       HasInvalidParm = true;
14851     }
14852 
14853     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14854     // declaration of each parameter shall include an identifier.
14855     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14856         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14857       // Diagnose this as an extension in C17 and earlier.
14858       if (!getLangOpts().C2x)
14859         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14860     }
14861 
14862     // C99 6.7.5.3p12:
14863     //   If the function declarator is not part of a definition of that
14864     //   function, parameters may have incomplete type and may use the [*]
14865     //   notation in their sequences of declarator specifiers to specify
14866     //   variable length array types.
14867     QualType PType = Param->getOriginalType();
14868     // FIXME: This diagnostic should point the '[*]' if source-location
14869     // information is added for it.
14870     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14871 
14872     // If the parameter is a c++ class type and it has to be destructed in the
14873     // callee function, declare the destructor so that it can be called by the
14874     // callee function. Do not perform any direct access check on the dtor here.
14875     if (!Param->isInvalidDecl()) {
14876       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14877         if (!ClassDecl->isInvalidDecl() &&
14878             !ClassDecl->hasIrrelevantDestructor() &&
14879             !ClassDecl->isDependentContext() &&
14880             ClassDecl->isParamDestroyedInCallee()) {
14881           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14882           MarkFunctionReferenced(Param->getLocation(), Destructor);
14883           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14884         }
14885       }
14886     }
14887 
14888     // Parameters with the pass_object_size attribute only need to be marked
14889     // constant at function definitions. Because we lack information about
14890     // whether we're on a declaration or definition when we're instantiating the
14891     // attribute, we need to check for constness here.
14892     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14893       if (!Param->getType().isConstQualified())
14894         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14895             << Attr->getSpelling() << 1;
14896 
14897     // Check for parameter names shadowing fields from the class.
14898     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14899       // The owning context for the parameter should be the function, but we
14900       // want to see if this function's declaration context is a record.
14901       DeclContext *DC = Param->getDeclContext();
14902       if (DC && DC->isFunctionOrMethod()) {
14903         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14904           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14905                                      RD, /*DeclIsField*/ false);
14906       }
14907     }
14908   }
14909 
14910   return HasInvalidParm;
14911 }
14912 
14913 Optional<std::pair<CharUnits, CharUnits>>
14914 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14915 
14916 /// Compute the alignment and offset of the base class object given the
14917 /// derived-to-base cast expression and the alignment and offset of the derived
14918 /// class object.
14919 static std::pair<CharUnits, CharUnits>
14920 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14921                                    CharUnits BaseAlignment, CharUnits Offset,
14922                                    ASTContext &Ctx) {
14923   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14924        ++PathI) {
14925     const CXXBaseSpecifier *Base = *PathI;
14926     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14927     if (Base->isVirtual()) {
14928       // The complete object may have a lower alignment than the non-virtual
14929       // alignment of the base, in which case the base may be misaligned. Choose
14930       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14931       // conservative lower bound of the complete object alignment.
14932       CharUnits NonVirtualAlignment =
14933           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14934       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14935       Offset = CharUnits::Zero();
14936     } else {
14937       const ASTRecordLayout &RL =
14938           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14939       Offset += RL.getBaseClassOffset(BaseDecl);
14940     }
14941     DerivedType = Base->getType();
14942   }
14943 
14944   return std::make_pair(BaseAlignment, Offset);
14945 }
14946 
14947 /// Compute the alignment and offset of a binary additive operator.
14948 static Optional<std::pair<CharUnits, CharUnits>>
14949 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14950                                      bool IsSub, ASTContext &Ctx) {
14951   QualType PointeeType = PtrE->getType()->getPointeeType();
14952 
14953   if (!PointeeType->isConstantSizeType())
14954     return llvm::None;
14955 
14956   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14957 
14958   if (!P)
14959     return llvm::None;
14960 
14961   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14962   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14963     CharUnits Offset = EltSize * IdxRes->getExtValue();
14964     if (IsSub)
14965       Offset = -Offset;
14966     return std::make_pair(P->first, P->second + Offset);
14967   }
14968 
14969   // If the integer expression isn't a constant expression, compute the lower
14970   // bound of the alignment using the alignment and offset of the pointer
14971   // expression and the element size.
14972   return std::make_pair(
14973       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14974       CharUnits::Zero());
14975 }
14976 
14977 /// This helper function takes an lvalue expression and returns the alignment of
14978 /// a VarDecl and a constant offset from the VarDecl.
14979 Optional<std::pair<CharUnits, CharUnits>>
14980 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14981   E = E->IgnoreParens();
14982   switch (E->getStmtClass()) {
14983   default:
14984     break;
14985   case Stmt::CStyleCastExprClass:
14986   case Stmt::CXXStaticCastExprClass:
14987   case Stmt::ImplicitCastExprClass: {
14988     auto *CE = cast<CastExpr>(E);
14989     const Expr *From = CE->getSubExpr();
14990     switch (CE->getCastKind()) {
14991     default:
14992       break;
14993     case CK_NoOp:
14994       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14995     case CK_UncheckedDerivedToBase:
14996     case CK_DerivedToBase: {
14997       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14998       if (!P)
14999         break;
15000       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15001                                                 P->second, Ctx);
15002     }
15003     }
15004     break;
15005   }
15006   case Stmt::ArraySubscriptExprClass: {
15007     auto *ASE = cast<ArraySubscriptExpr>(E);
15008     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15009                                                 false, Ctx);
15010   }
15011   case Stmt::DeclRefExprClass: {
15012     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15013       // FIXME: If VD is captured by copy or is an escaping __block variable,
15014       // use the alignment of VD's type.
15015       if (!VD->getType()->isReferenceType())
15016         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15017       if (VD->hasInit())
15018         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15019     }
15020     break;
15021   }
15022   case Stmt::MemberExprClass: {
15023     auto *ME = cast<MemberExpr>(E);
15024     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15025     if (!FD || FD->getType()->isReferenceType() ||
15026         FD->getParent()->isInvalidDecl())
15027       break;
15028     Optional<std::pair<CharUnits, CharUnits>> P;
15029     if (ME->isArrow())
15030       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15031     else
15032       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15033     if (!P)
15034       break;
15035     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15036     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15037     return std::make_pair(P->first,
15038                           P->second + CharUnits::fromQuantity(Offset));
15039   }
15040   case Stmt::UnaryOperatorClass: {
15041     auto *UO = cast<UnaryOperator>(E);
15042     switch (UO->getOpcode()) {
15043     default:
15044       break;
15045     case UO_Deref:
15046       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15047     }
15048     break;
15049   }
15050   case Stmt::BinaryOperatorClass: {
15051     auto *BO = cast<BinaryOperator>(E);
15052     auto Opcode = BO->getOpcode();
15053     switch (Opcode) {
15054     default:
15055       break;
15056     case BO_Comma:
15057       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15058     }
15059     break;
15060   }
15061   }
15062   return llvm::None;
15063 }
15064 
15065 /// This helper function takes a pointer expression and returns the alignment of
15066 /// a VarDecl and a constant offset from the VarDecl.
15067 Optional<std::pair<CharUnits, CharUnits>>
15068 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15069   E = E->IgnoreParens();
15070   switch (E->getStmtClass()) {
15071   default:
15072     break;
15073   case Stmt::CStyleCastExprClass:
15074   case Stmt::CXXStaticCastExprClass:
15075   case Stmt::ImplicitCastExprClass: {
15076     auto *CE = cast<CastExpr>(E);
15077     const Expr *From = CE->getSubExpr();
15078     switch (CE->getCastKind()) {
15079     default:
15080       break;
15081     case CK_NoOp:
15082       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15083     case CK_ArrayToPointerDecay:
15084       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15085     case CK_UncheckedDerivedToBase:
15086     case CK_DerivedToBase: {
15087       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15088       if (!P)
15089         break;
15090       return getDerivedToBaseAlignmentAndOffset(
15091           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15092     }
15093     }
15094     break;
15095   }
15096   case Stmt::CXXThisExprClass: {
15097     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15098     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15099     return std::make_pair(Alignment, CharUnits::Zero());
15100   }
15101   case Stmt::UnaryOperatorClass: {
15102     auto *UO = cast<UnaryOperator>(E);
15103     if (UO->getOpcode() == UO_AddrOf)
15104       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15105     break;
15106   }
15107   case Stmt::BinaryOperatorClass: {
15108     auto *BO = cast<BinaryOperator>(E);
15109     auto Opcode = BO->getOpcode();
15110     switch (Opcode) {
15111     default:
15112       break;
15113     case BO_Add:
15114     case BO_Sub: {
15115       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15116       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15117         std::swap(LHS, RHS);
15118       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15119                                                   Ctx);
15120     }
15121     case BO_Comma:
15122       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15123     }
15124     break;
15125   }
15126   }
15127   return llvm::None;
15128 }
15129 
15130 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15131   // See if we can compute the alignment of a VarDecl and an offset from it.
15132   Optional<std::pair<CharUnits, CharUnits>> P =
15133       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15134 
15135   if (P)
15136     return P->first.alignmentAtOffset(P->second);
15137 
15138   // If that failed, return the type's alignment.
15139   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15140 }
15141 
15142 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15143 /// pointer cast increases the alignment requirements.
15144 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15145   // This is actually a lot of work to potentially be doing on every
15146   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15147   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15148     return;
15149 
15150   // Ignore dependent types.
15151   if (T->isDependentType() || Op->getType()->isDependentType())
15152     return;
15153 
15154   // Require that the destination be a pointer type.
15155   const PointerType *DestPtr = T->getAs<PointerType>();
15156   if (!DestPtr) return;
15157 
15158   // If the destination has alignment 1, we're done.
15159   QualType DestPointee = DestPtr->getPointeeType();
15160   if (DestPointee->isIncompleteType()) return;
15161   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15162   if (DestAlign.isOne()) return;
15163 
15164   // Require that the source be a pointer type.
15165   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15166   if (!SrcPtr) return;
15167   QualType SrcPointee = SrcPtr->getPointeeType();
15168 
15169   // Explicitly allow casts from cv void*.  We already implicitly
15170   // allowed casts to cv void*, since they have alignment 1.
15171   // Also allow casts involving incomplete types, which implicitly
15172   // includes 'void'.
15173   if (SrcPointee->isIncompleteType()) return;
15174 
15175   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15176 
15177   if (SrcAlign >= DestAlign) return;
15178 
15179   Diag(TRange.getBegin(), diag::warn_cast_align)
15180     << Op->getType() << T
15181     << static_cast<unsigned>(SrcAlign.getQuantity())
15182     << static_cast<unsigned>(DestAlign.getQuantity())
15183     << TRange << Op->getSourceRange();
15184 }
15185 
15186 /// Check whether this array fits the idiom of a size-one tail padded
15187 /// array member of a struct.
15188 ///
15189 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15190 /// commonly used to emulate flexible arrays in C89 code.
15191 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15192                                     const NamedDecl *ND) {
15193   if (Size != 1 || !ND) return false;
15194 
15195   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15196   if (!FD) return false;
15197 
15198   // Don't consider sizes resulting from macro expansions or template argument
15199   // substitution to form C89 tail-padded arrays.
15200 
15201   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15202   while (TInfo) {
15203     TypeLoc TL = TInfo->getTypeLoc();
15204     // Look through typedefs.
15205     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15206       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15207       TInfo = TDL->getTypeSourceInfo();
15208       continue;
15209     }
15210     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15211       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15212       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15213         return false;
15214     }
15215     break;
15216   }
15217 
15218   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15219   if (!RD) return false;
15220   if (RD->isUnion()) return false;
15221   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15222     if (!CRD->isStandardLayout()) return false;
15223   }
15224 
15225   // See if this is the last field decl in the record.
15226   const Decl *D = FD;
15227   while ((D = D->getNextDeclInContext()))
15228     if (isa<FieldDecl>(D))
15229       return false;
15230   return true;
15231 }
15232 
15233 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15234                             const ArraySubscriptExpr *ASE,
15235                             bool AllowOnePastEnd, bool IndexNegated) {
15236   // Already diagnosed by the constant evaluator.
15237   if (isConstantEvaluated())
15238     return;
15239 
15240   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15241   if (IndexExpr->isValueDependent())
15242     return;
15243 
15244   const Type *EffectiveType =
15245       BaseExpr->getType()->getPointeeOrArrayElementType();
15246   BaseExpr = BaseExpr->IgnoreParenCasts();
15247   const ConstantArrayType *ArrayTy =
15248       Context.getAsConstantArrayType(BaseExpr->getType());
15249 
15250   const Type *BaseType =
15251       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15252   bool IsUnboundedArray = (BaseType == nullptr);
15253   if (EffectiveType->isDependentType() ||
15254       (!IsUnboundedArray && BaseType->isDependentType()))
15255     return;
15256 
15257   Expr::EvalResult Result;
15258   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15259     return;
15260 
15261   llvm::APSInt index = Result.Val.getInt();
15262   if (IndexNegated) {
15263     index.setIsUnsigned(false);
15264     index = -index;
15265   }
15266 
15267   const NamedDecl *ND = nullptr;
15268   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15269     ND = DRE->getDecl();
15270   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15271     ND = ME->getMemberDecl();
15272 
15273   if (IsUnboundedArray) {
15274     if (index.isUnsigned() || !index.isNegative()) {
15275       const auto &ASTC = getASTContext();
15276       unsigned AddrBits =
15277           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15278               EffectiveType->getCanonicalTypeInternal()));
15279       if (index.getBitWidth() < AddrBits)
15280         index = index.zext(AddrBits);
15281       Optional<CharUnits> ElemCharUnits =
15282           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15283       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15284       // pointer) bounds-checking isn't meaningful.
15285       if (!ElemCharUnits)
15286         return;
15287       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15288       // If index has more active bits than address space, we already know
15289       // we have a bounds violation to warn about.  Otherwise, compute
15290       // address of (index + 1)th element, and warn about bounds violation
15291       // only if that address exceeds address space.
15292       if (index.getActiveBits() <= AddrBits) {
15293         bool Overflow;
15294         llvm::APInt Product(index);
15295         Product += 1;
15296         Product = Product.umul_ov(ElemBytes, Overflow);
15297         if (!Overflow && Product.getActiveBits() <= AddrBits)
15298           return;
15299       }
15300 
15301       // Need to compute max possible elements in address space, since that
15302       // is included in diag message.
15303       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15304       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15305       MaxElems += 1;
15306       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15307       MaxElems = MaxElems.udiv(ElemBytes);
15308 
15309       unsigned DiagID =
15310           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15311               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15312 
15313       // Diag message shows element size in bits and in "bytes" (platform-
15314       // dependent CharUnits)
15315       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15316                           PDiag(DiagID)
15317                               << toString(index, 10, true) << AddrBits
15318                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15319                               << toString(ElemBytes, 10, false)
15320                               << toString(MaxElems, 10, false)
15321                               << (unsigned)MaxElems.getLimitedValue(~0U)
15322                               << IndexExpr->getSourceRange());
15323 
15324       if (!ND) {
15325         // Try harder to find a NamedDecl to point at in the note.
15326         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15327           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15328         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15329           ND = DRE->getDecl();
15330         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15331           ND = ME->getMemberDecl();
15332       }
15333 
15334       if (ND)
15335         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15336                             PDiag(diag::note_array_declared_here) << ND);
15337     }
15338     return;
15339   }
15340 
15341   if (index.isUnsigned() || !index.isNegative()) {
15342     // It is possible that the type of the base expression after
15343     // IgnoreParenCasts is incomplete, even though the type of the base
15344     // expression before IgnoreParenCasts is complete (see PR39746 for an
15345     // example). In this case we have no information about whether the array
15346     // access exceeds the array bounds. However we can still diagnose an array
15347     // access which precedes the array bounds.
15348     if (BaseType->isIncompleteType())
15349       return;
15350 
15351     llvm::APInt size = ArrayTy->getSize();
15352     if (!size.isStrictlyPositive())
15353       return;
15354 
15355     if (BaseType != EffectiveType) {
15356       // Make sure we're comparing apples to apples when comparing index to size
15357       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15358       uint64_t array_typesize = Context.getTypeSize(BaseType);
15359       // Handle ptrarith_typesize being zero, such as when casting to void*
15360       if (!ptrarith_typesize) ptrarith_typesize = 1;
15361       if (ptrarith_typesize != array_typesize) {
15362         // There's a cast to a different size type involved
15363         uint64_t ratio = array_typesize / ptrarith_typesize;
15364         // TODO: Be smarter about handling cases where array_typesize is not a
15365         // multiple of ptrarith_typesize
15366         if (ptrarith_typesize * ratio == array_typesize)
15367           size *= llvm::APInt(size.getBitWidth(), ratio);
15368       }
15369     }
15370 
15371     if (size.getBitWidth() > index.getBitWidth())
15372       index = index.zext(size.getBitWidth());
15373     else if (size.getBitWidth() < index.getBitWidth())
15374       size = size.zext(index.getBitWidth());
15375 
15376     // For array subscripting the index must be less than size, but for pointer
15377     // arithmetic also allow the index (offset) to be equal to size since
15378     // computing the next address after the end of the array is legal and
15379     // commonly done e.g. in C++ iterators and range-based for loops.
15380     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15381       return;
15382 
15383     // Also don't warn for arrays of size 1 which are members of some
15384     // structure. These are often used to approximate flexible arrays in C89
15385     // code.
15386     if (IsTailPaddedMemberArray(*this, size, ND))
15387       return;
15388 
15389     // Suppress the warning if the subscript expression (as identified by the
15390     // ']' location) and the index expression are both from macro expansions
15391     // within a system header.
15392     if (ASE) {
15393       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15394           ASE->getRBracketLoc());
15395       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15396         SourceLocation IndexLoc =
15397             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15398         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15399           return;
15400       }
15401     }
15402 
15403     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15404                           : diag::warn_ptr_arith_exceeds_bounds;
15405 
15406     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15407                         PDiag(DiagID) << toString(index, 10, true)
15408                                       << toString(size, 10, true)
15409                                       << (unsigned)size.getLimitedValue(~0U)
15410                                       << IndexExpr->getSourceRange());
15411   } else {
15412     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15413     if (!ASE) {
15414       DiagID = diag::warn_ptr_arith_precedes_bounds;
15415       if (index.isNegative()) index = -index;
15416     }
15417 
15418     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15419                         PDiag(DiagID) << toString(index, 10, true)
15420                                       << IndexExpr->getSourceRange());
15421   }
15422 
15423   if (!ND) {
15424     // Try harder to find a NamedDecl to point at in the note.
15425     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15426       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15427     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15428       ND = DRE->getDecl();
15429     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15430       ND = ME->getMemberDecl();
15431   }
15432 
15433   if (ND)
15434     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15435                         PDiag(diag::note_array_declared_here) << ND);
15436 }
15437 
15438 void Sema::CheckArrayAccess(const Expr *expr) {
15439   int AllowOnePastEnd = 0;
15440   while (expr) {
15441     expr = expr->IgnoreParenImpCasts();
15442     switch (expr->getStmtClass()) {
15443       case Stmt::ArraySubscriptExprClass: {
15444         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15445         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15446                          AllowOnePastEnd > 0);
15447         expr = ASE->getBase();
15448         break;
15449       }
15450       case Stmt::MemberExprClass: {
15451         expr = cast<MemberExpr>(expr)->getBase();
15452         break;
15453       }
15454       case Stmt::OMPArraySectionExprClass: {
15455         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15456         if (ASE->getLowerBound())
15457           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15458                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15459         return;
15460       }
15461       case Stmt::UnaryOperatorClass: {
15462         // Only unwrap the * and & unary operators
15463         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15464         expr = UO->getSubExpr();
15465         switch (UO->getOpcode()) {
15466           case UO_AddrOf:
15467             AllowOnePastEnd++;
15468             break;
15469           case UO_Deref:
15470             AllowOnePastEnd--;
15471             break;
15472           default:
15473             return;
15474         }
15475         break;
15476       }
15477       case Stmt::ConditionalOperatorClass: {
15478         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15479         if (const Expr *lhs = cond->getLHS())
15480           CheckArrayAccess(lhs);
15481         if (const Expr *rhs = cond->getRHS())
15482           CheckArrayAccess(rhs);
15483         return;
15484       }
15485       case Stmt::CXXOperatorCallExprClass: {
15486         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15487         for (const auto *Arg : OCE->arguments())
15488           CheckArrayAccess(Arg);
15489         return;
15490       }
15491       default:
15492         return;
15493     }
15494   }
15495 }
15496 
15497 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15498 
15499 namespace {
15500 
15501 struct RetainCycleOwner {
15502   VarDecl *Variable = nullptr;
15503   SourceRange Range;
15504   SourceLocation Loc;
15505   bool Indirect = false;
15506 
15507   RetainCycleOwner() = default;
15508 
15509   void setLocsFrom(Expr *e) {
15510     Loc = e->getExprLoc();
15511     Range = e->getSourceRange();
15512   }
15513 };
15514 
15515 } // namespace
15516 
15517 /// Consider whether capturing the given variable can possibly lead to
15518 /// a retain cycle.
15519 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15520   // In ARC, it's captured strongly iff the variable has __strong
15521   // lifetime.  In MRR, it's captured strongly if the variable is
15522   // __block and has an appropriate type.
15523   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15524     return false;
15525 
15526   owner.Variable = var;
15527   if (ref)
15528     owner.setLocsFrom(ref);
15529   return true;
15530 }
15531 
15532 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15533   while (true) {
15534     e = e->IgnoreParens();
15535     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15536       switch (cast->getCastKind()) {
15537       case CK_BitCast:
15538       case CK_LValueBitCast:
15539       case CK_LValueToRValue:
15540       case CK_ARCReclaimReturnedObject:
15541         e = cast->getSubExpr();
15542         continue;
15543 
15544       default:
15545         return false;
15546       }
15547     }
15548 
15549     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15550       ObjCIvarDecl *ivar = ref->getDecl();
15551       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15552         return false;
15553 
15554       // Try to find a retain cycle in the base.
15555       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15556         return false;
15557 
15558       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15559       owner.Indirect = true;
15560       return true;
15561     }
15562 
15563     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15564       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15565       if (!var) return false;
15566       return considerVariable(var, ref, owner);
15567     }
15568 
15569     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15570       if (member->isArrow()) return false;
15571 
15572       // Don't count this as an indirect ownership.
15573       e = member->getBase();
15574       continue;
15575     }
15576 
15577     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15578       // Only pay attention to pseudo-objects on property references.
15579       ObjCPropertyRefExpr *pre
15580         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15581                                               ->IgnoreParens());
15582       if (!pre) return false;
15583       if (pre->isImplicitProperty()) return false;
15584       ObjCPropertyDecl *property = pre->getExplicitProperty();
15585       if (!property->isRetaining() &&
15586           !(property->getPropertyIvarDecl() &&
15587             property->getPropertyIvarDecl()->getType()
15588               .getObjCLifetime() == Qualifiers::OCL_Strong))
15589           return false;
15590 
15591       owner.Indirect = true;
15592       if (pre->isSuperReceiver()) {
15593         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15594         if (!owner.Variable)
15595           return false;
15596         owner.Loc = pre->getLocation();
15597         owner.Range = pre->getSourceRange();
15598         return true;
15599       }
15600       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15601                               ->getSourceExpr());
15602       continue;
15603     }
15604 
15605     // Array ivars?
15606 
15607     return false;
15608   }
15609 }
15610 
15611 namespace {
15612 
15613   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15614     ASTContext &Context;
15615     VarDecl *Variable;
15616     Expr *Capturer = nullptr;
15617     bool VarWillBeReased = false;
15618 
15619     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15620         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15621           Context(Context), Variable(variable) {}
15622 
15623     void VisitDeclRefExpr(DeclRefExpr *ref) {
15624       if (ref->getDecl() == Variable && !Capturer)
15625         Capturer = ref;
15626     }
15627 
15628     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15629       if (Capturer) return;
15630       Visit(ref->getBase());
15631       if (Capturer && ref->isFreeIvar())
15632         Capturer = ref;
15633     }
15634 
15635     void VisitBlockExpr(BlockExpr *block) {
15636       // Look inside nested blocks
15637       if (block->getBlockDecl()->capturesVariable(Variable))
15638         Visit(block->getBlockDecl()->getBody());
15639     }
15640 
15641     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15642       if (Capturer) return;
15643       if (OVE->getSourceExpr())
15644         Visit(OVE->getSourceExpr());
15645     }
15646 
15647     void VisitBinaryOperator(BinaryOperator *BinOp) {
15648       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15649         return;
15650       Expr *LHS = BinOp->getLHS();
15651       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15652         if (DRE->getDecl() != Variable)
15653           return;
15654         if (Expr *RHS = BinOp->getRHS()) {
15655           RHS = RHS->IgnoreParenCasts();
15656           Optional<llvm::APSInt> Value;
15657           VarWillBeReased =
15658               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15659                *Value == 0);
15660         }
15661       }
15662     }
15663   };
15664 
15665 } // namespace
15666 
15667 /// Check whether the given argument is a block which captures a
15668 /// variable.
15669 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15670   assert(owner.Variable && owner.Loc.isValid());
15671 
15672   e = e->IgnoreParenCasts();
15673 
15674   // Look through [^{...} copy] and Block_copy(^{...}).
15675   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15676     Selector Cmd = ME->getSelector();
15677     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15678       e = ME->getInstanceReceiver();
15679       if (!e)
15680         return nullptr;
15681       e = e->IgnoreParenCasts();
15682     }
15683   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15684     if (CE->getNumArgs() == 1) {
15685       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15686       if (Fn) {
15687         const IdentifierInfo *FnI = Fn->getIdentifier();
15688         if (FnI && FnI->isStr("_Block_copy")) {
15689           e = CE->getArg(0)->IgnoreParenCasts();
15690         }
15691       }
15692     }
15693   }
15694 
15695   BlockExpr *block = dyn_cast<BlockExpr>(e);
15696   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15697     return nullptr;
15698 
15699   FindCaptureVisitor visitor(S.Context, owner.Variable);
15700   visitor.Visit(block->getBlockDecl()->getBody());
15701   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15702 }
15703 
15704 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15705                                 RetainCycleOwner &owner) {
15706   assert(capturer);
15707   assert(owner.Variable && owner.Loc.isValid());
15708 
15709   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15710     << owner.Variable << capturer->getSourceRange();
15711   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15712     << owner.Indirect << owner.Range;
15713 }
15714 
15715 /// Check for a keyword selector that starts with the word 'add' or
15716 /// 'set'.
15717 static bool isSetterLikeSelector(Selector sel) {
15718   if (sel.isUnarySelector()) return false;
15719 
15720   StringRef str = sel.getNameForSlot(0);
15721   while (!str.empty() && str.front() == '_') str = str.substr(1);
15722   if (str.startswith("set"))
15723     str = str.substr(3);
15724   else if (str.startswith("add")) {
15725     // Specially allow 'addOperationWithBlock:'.
15726     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15727       return false;
15728     str = str.substr(3);
15729   }
15730   else
15731     return false;
15732 
15733   if (str.empty()) return true;
15734   return !isLowercase(str.front());
15735 }
15736 
15737 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15738                                                     ObjCMessageExpr *Message) {
15739   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15740                                                 Message->getReceiverInterface(),
15741                                                 NSAPI::ClassId_NSMutableArray);
15742   if (!IsMutableArray) {
15743     return None;
15744   }
15745 
15746   Selector Sel = Message->getSelector();
15747 
15748   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15749     S.NSAPIObj->getNSArrayMethodKind(Sel);
15750   if (!MKOpt) {
15751     return None;
15752   }
15753 
15754   NSAPI::NSArrayMethodKind MK = *MKOpt;
15755 
15756   switch (MK) {
15757     case NSAPI::NSMutableArr_addObject:
15758     case NSAPI::NSMutableArr_insertObjectAtIndex:
15759     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15760       return 0;
15761     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15762       return 1;
15763 
15764     default:
15765       return None;
15766   }
15767 
15768   return None;
15769 }
15770 
15771 static
15772 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15773                                                   ObjCMessageExpr *Message) {
15774   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15775                                             Message->getReceiverInterface(),
15776                                             NSAPI::ClassId_NSMutableDictionary);
15777   if (!IsMutableDictionary) {
15778     return None;
15779   }
15780 
15781   Selector Sel = Message->getSelector();
15782 
15783   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15784     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15785   if (!MKOpt) {
15786     return None;
15787   }
15788 
15789   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15790 
15791   switch (MK) {
15792     case NSAPI::NSMutableDict_setObjectForKey:
15793     case NSAPI::NSMutableDict_setValueForKey:
15794     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15795       return 0;
15796 
15797     default:
15798       return None;
15799   }
15800 
15801   return None;
15802 }
15803 
15804 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15805   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15806                                                 Message->getReceiverInterface(),
15807                                                 NSAPI::ClassId_NSMutableSet);
15808 
15809   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15810                                             Message->getReceiverInterface(),
15811                                             NSAPI::ClassId_NSMutableOrderedSet);
15812   if (!IsMutableSet && !IsMutableOrderedSet) {
15813     return None;
15814   }
15815 
15816   Selector Sel = Message->getSelector();
15817 
15818   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15819   if (!MKOpt) {
15820     return None;
15821   }
15822 
15823   NSAPI::NSSetMethodKind MK = *MKOpt;
15824 
15825   switch (MK) {
15826     case NSAPI::NSMutableSet_addObject:
15827     case NSAPI::NSOrderedSet_setObjectAtIndex:
15828     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15829     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15830       return 0;
15831     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15832       return 1;
15833   }
15834 
15835   return None;
15836 }
15837 
15838 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15839   if (!Message->isInstanceMessage()) {
15840     return;
15841   }
15842 
15843   Optional<int> ArgOpt;
15844 
15845   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15846       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15847       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15848     return;
15849   }
15850 
15851   int ArgIndex = *ArgOpt;
15852 
15853   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15854   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15855     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15856   }
15857 
15858   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15859     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15860       if (ArgRE->isObjCSelfExpr()) {
15861         Diag(Message->getSourceRange().getBegin(),
15862              diag::warn_objc_circular_container)
15863           << ArgRE->getDecl() << StringRef("'super'");
15864       }
15865     }
15866   } else {
15867     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15868 
15869     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15870       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15871     }
15872 
15873     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15874       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15875         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15876           ValueDecl *Decl = ReceiverRE->getDecl();
15877           Diag(Message->getSourceRange().getBegin(),
15878                diag::warn_objc_circular_container)
15879             << Decl << Decl;
15880           if (!ArgRE->isObjCSelfExpr()) {
15881             Diag(Decl->getLocation(),
15882                  diag::note_objc_circular_container_declared_here)
15883               << Decl;
15884           }
15885         }
15886       }
15887     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15888       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15889         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15890           ObjCIvarDecl *Decl = IvarRE->getDecl();
15891           Diag(Message->getSourceRange().getBegin(),
15892                diag::warn_objc_circular_container)
15893             << Decl << Decl;
15894           Diag(Decl->getLocation(),
15895                diag::note_objc_circular_container_declared_here)
15896             << Decl;
15897         }
15898       }
15899     }
15900   }
15901 }
15902 
15903 /// Check a message send to see if it's likely to cause a retain cycle.
15904 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15905   // Only check instance methods whose selector looks like a setter.
15906   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15907     return;
15908 
15909   // Try to find a variable that the receiver is strongly owned by.
15910   RetainCycleOwner owner;
15911   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15912     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15913       return;
15914   } else {
15915     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15916     owner.Variable = getCurMethodDecl()->getSelfDecl();
15917     owner.Loc = msg->getSuperLoc();
15918     owner.Range = msg->getSuperLoc();
15919   }
15920 
15921   // Check whether the receiver is captured by any of the arguments.
15922   const ObjCMethodDecl *MD = msg->getMethodDecl();
15923   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15924     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15925       // noescape blocks should not be retained by the method.
15926       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15927         continue;
15928       return diagnoseRetainCycle(*this, capturer, owner);
15929     }
15930   }
15931 }
15932 
15933 /// Check a property assign to see if it's likely to cause a retain cycle.
15934 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15935   RetainCycleOwner owner;
15936   if (!findRetainCycleOwner(*this, receiver, owner))
15937     return;
15938 
15939   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15940     diagnoseRetainCycle(*this, capturer, owner);
15941 }
15942 
15943 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15944   RetainCycleOwner Owner;
15945   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15946     return;
15947 
15948   // Because we don't have an expression for the variable, we have to set the
15949   // location explicitly here.
15950   Owner.Loc = Var->getLocation();
15951   Owner.Range = Var->getSourceRange();
15952 
15953   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15954     diagnoseRetainCycle(*this, Capturer, Owner);
15955 }
15956 
15957 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15958                                      Expr *RHS, bool isProperty) {
15959   // Check if RHS is an Objective-C object literal, which also can get
15960   // immediately zapped in a weak reference.  Note that we explicitly
15961   // allow ObjCStringLiterals, since those are designed to never really die.
15962   RHS = RHS->IgnoreParenImpCasts();
15963 
15964   // This enum needs to match with the 'select' in
15965   // warn_objc_arc_literal_assign (off-by-1).
15966   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15967   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15968     return false;
15969 
15970   S.Diag(Loc, diag::warn_arc_literal_assign)
15971     << (unsigned) Kind
15972     << (isProperty ? 0 : 1)
15973     << RHS->getSourceRange();
15974 
15975   return true;
15976 }
15977 
15978 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15979                                     Qualifiers::ObjCLifetime LT,
15980                                     Expr *RHS, bool isProperty) {
15981   // Strip off any implicit cast added to get to the one ARC-specific.
15982   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15983     if (cast->getCastKind() == CK_ARCConsumeObject) {
15984       S.Diag(Loc, diag::warn_arc_retained_assign)
15985         << (LT == Qualifiers::OCL_ExplicitNone)
15986         << (isProperty ? 0 : 1)
15987         << RHS->getSourceRange();
15988       return true;
15989     }
15990     RHS = cast->getSubExpr();
15991   }
15992 
15993   if (LT == Qualifiers::OCL_Weak &&
15994       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15995     return true;
15996 
15997   return false;
15998 }
15999 
16000 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16001                               QualType LHS, Expr *RHS) {
16002   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16003 
16004   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16005     return false;
16006 
16007   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16008     return true;
16009 
16010   return false;
16011 }
16012 
16013 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16014                               Expr *LHS, Expr *RHS) {
16015   QualType LHSType;
16016   // PropertyRef on LHS type need be directly obtained from
16017   // its declaration as it has a PseudoType.
16018   ObjCPropertyRefExpr *PRE
16019     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16020   if (PRE && !PRE->isImplicitProperty()) {
16021     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16022     if (PD)
16023       LHSType = PD->getType();
16024   }
16025 
16026   if (LHSType.isNull())
16027     LHSType = LHS->getType();
16028 
16029   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16030 
16031   if (LT == Qualifiers::OCL_Weak) {
16032     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16033       getCurFunction()->markSafeWeakUse(LHS);
16034   }
16035 
16036   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16037     return;
16038 
16039   // FIXME. Check for other life times.
16040   if (LT != Qualifiers::OCL_None)
16041     return;
16042 
16043   if (PRE) {
16044     if (PRE->isImplicitProperty())
16045       return;
16046     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16047     if (!PD)
16048       return;
16049 
16050     unsigned Attributes = PD->getPropertyAttributes();
16051     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16052       // when 'assign' attribute was not explicitly specified
16053       // by user, ignore it and rely on property type itself
16054       // for lifetime info.
16055       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16056       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16057           LHSType->isObjCRetainableType())
16058         return;
16059 
16060       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16061         if (cast->getCastKind() == CK_ARCConsumeObject) {
16062           Diag(Loc, diag::warn_arc_retained_property_assign)
16063           << RHS->getSourceRange();
16064           return;
16065         }
16066         RHS = cast->getSubExpr();
16067       }
16068     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16069       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16070         return;
16071     }
16072   }
16073 }
16074 
16075 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16076 
16077 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16078                                         SourceLocation StmtLoc,
16079                                         const NullStmt *Body) {
16080   // Do not warn if the body is a macro that expands to nothing, e.g:
16081   //
16082   // #define CALL(x)
16083   // if (condition)
16084   //   CALL(0);
16085   if (Body->hasLeadingEmptyMacro())
16086     return false;
16087 
16088   // Get line numbers of statement and body.
16089   bool StmtLineInvalid;
16090   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16091                                                       &StmtLineInvalid);
16092   if (StmtLineInvalid)
16093     return false;
16094 
16095   bool BodyLineInvalid;
16096   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16097                                                       &BodyLineInvalid);
16098   if (BodyLineInvalid)
16099     return false;
16100 
16101   // Warn if null statement and body are on the same line.
16102   if (StmtLine != BodyLine)
16103     return false;
16104 
16105   return true;
16106 }
16107 
16108 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16109                                  const Stmt *Body,
16110                                  unsigned DiagID) {
16111   // Since this is a syntactic check, don't emit diagnostic for template
16112   // instantiations, this just adds noise.
16113   if (CurrentInstantiationScope)
16114     return;
16115 
16116   // The body should be a null statement.
16117   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16118   if (!NBody)
16119     return;
16120 
16121   // Do the usual checks.
16122   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16123     return;
16124 
16125   Diag(NBody->getSemiLoc(), DiagID);
16126   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16127 }
16128 
16129 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16130                                  const Stmt *PossibleBody) {
16131   assert(!CurrentInstantiationScope); // Ensured by caller
16132 
16133   SourceLocation StmtLoc;
16134   const Stmt *Body;
16135   unsigned DiagID;
16136   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16137     StmtLoc = FS->getRParenLoc();
16138     Body = FS->getBody();
16139     DiagID = diag::warn_empty_for_body;
16140   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16141     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16142     Body = WS->getBody();
16143     DiagID = diag::warn_empty_while_body;
16144   } else
16145     return; // Neither `for' nor `while'.
16146 
16147   // The body should be a null statement.
16148   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16149   if (!NBody)
16150     return;
16151 
16152   // Skip expensive checks if diagnostic is disabled.
16153   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16154     return;
16155 
16156   // Do the usual checks.
16157   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16158     return;
16159 
16160   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16161   // noise level low, emit diagnostics only if for/while is followed by a
16162   // CompoundStmt, e.g.:
16163   //    for (int i = 0; i < n; i++);
16164   //    {
16165   //      a(i);
16166   //    }
16167   // or if for/while is followed by a statement with more indentation
16168   // than for/while itself:
16169   //    for (int i = 0; i < n; i++);
16170   //      a(i);
16171   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16172   if (!ProbableTypo) {
16173     bool BodyColInvalid;
16174     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16175         PossibleBody->getBeginLoc(), &BodyColInvalid);
16176     if (BodyColInvalid)
16177       return;
16178 
16179     bool StmtColInvalid;
16180     unsigned StmtCol =
16181         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16182     if (StmtColInvalid)
16183       return;
16184 
16185     if (BodyCol > StmtCol)
16186       ProbableTypo = true;
16187   }
16188 
16189   if (ProbableTypo) {
16190     Diag(NBody->getSemiLoc(), DiagID);
16191     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16192   }
16193 }
16194 
16195 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16196 
16197 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16198 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16199                              SourceLocation OpLoc) {
16200   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16201     return;
16202 
16203   if (inTemplateInstantiation())
16204     return;
16205 
16206   // Strip parens and casts away.
16207   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16208   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16209 
16210   // Check for a call expression
16211   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16212   if (!CE || CE->getNumArgs() != 1)
16213     return;
16214 
16215   // Check for a call to std::move
16216   if (!CE->isCallToStdMove())
16217     return;
16218 
16219   // Get argument from std::move
16220   RHSExpr = CE->getArg(0);
16221 
16222   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16223   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16224 
16225   // Two DeclRefExpr's, check that the decls are the same.
16226   if (LHSDeclRef && RHSDeclRef) {
16227     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16228       return;
16229     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16230         RHSDeclRef->getDecl()->getCanonicalDecl())
16231       return;
16232 
16233     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16234                                         << LHSExpr->getSourceRange()
16235                                         << RHSExpr->getSourceRange();
16236     return;
16237   }
16238 
16239   // Member variables require a different approach to check for self moves.
16240   // MemberExpr's are the same if every nested MemberExpr refers to the same
16241   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16242   // the base Expr's are CXXThisExpr's.
16243   const Expr *LHSBase = LHSExpr;
16244   const Expr *RHSBase = RHSExpr;
16245   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16246   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16247   if (!LHSME || !RHSME)
16248     return;
16249 
16250   while (LHSME && RHSME) {
16251     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16252         RHSME->getMemberDecl()->getCanonicalDecl())
16253       return;
16254 
16255     LHSBase = LHSME->getBase();
16256     RHSBase = RHSME->getBase();
16257     LHSME = dyn_cast<MemberExpr>(LHSBase);
16258     RHSME = dyn_cast<MemberExpr>(RHSBase);
16259   }
16260 
16261   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16262   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16263   if (LHSDeclRef && RHSDeclRef) {
16264     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16265       return;
16266     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16267         RHSDeclRef->getDecl()->getCanonicalDecl())
16268       return;
16269 
16270     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16271                                         << LHSExpr->getSourceRange()
16272                                         << RHSExpr->getSourceRange();
16273     return;
16274   }
16275 
16276   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16277     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16278                                         << LHSExpr->getSourceRange()
16279                                         << RHSExpr->getSourceRange();
16280 }
16281 
16282 //===--- Layout compatibility ----------------------------------------------//
16283 
16284 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16285 
16286 /// Check if two enumeration types are layout-compatible.
16287 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16288   // C++11 [dcl.enum] p8:
16289   // Two enumeration types are layout-compatible if they have the same
16290   // underlying type.
16291   return ED1->isComplete() && ED2->isComplete() &&
16292          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16293 }
16294 
16295 /// Check if two fields are layout-compatible.
16296 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16297                                FieldDecl *Field2) {
16298   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16299     return false;
16300 
16301   if (Field1->isBitField() != Field2->isBitField())
16302     return false;
16303 
16304   if (Field1->isBitField()) {
16305     // Make sure that the bit-fields are the same length.
16306     unsigned Bits1 = Field1->getBitWidthValue(C);
16307     unsigned Bits2 = Field2->getBitWidthValue(C);
16308 
16309     if (Bits1 != Bits2)
16310       return false;
16311   }
16312 
16313   return true;
16314 }
16315 
16316 /// Check if two standard-layout structs are layout-compatible.
16317 /// (C++11 [class.mem] p17)
16318 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16319                                      RecordDecl *RD2) {
16320   // If both records are C++ classes, check that base classes match.
16321   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16322     // If one of records is a CXXRecordDecl we are in C++ mode,
16323     // thus the other one is a CXXRecordDecl, too.
16324     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16325     // Check number of base classes.
16326     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16327       return false;
16328 
16329     // Check the base classes.
16330     for (CXXRecordDecl::base_class_const_iterator
16331                Base1 = D1CXX->bases_begin(),
16332            BaseEnd1 = D1CXX->bases_end(),
16333               Base2 = D2CXX->bases_begin();
16334          Base1 != BaseEnd1;
16335          ++Base1, ++Base2) {
16336       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16337         return false;
16338     }
16339   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16340     // If only RD2 is a C++ class, it should have zero base classes.
16341     if (D2CXX->getNumBases() > 0)
16342       return false;
16343   }
16344 
16345   // Check the fields.
16346   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16347                              Field2End = RD2->field_end(),
16348                              Field1 = RD1->field_begin(),
16349                              Field1End = RD1->field_end();
16350   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16351     if (!isLayoutCompatible(C, *Field1, *Field2))
16352       return false;
16353   }
16354   if (Field1 != Field1End || Field2 != Field2End)
16355     return false;
16356 
16357   return true;
16358 }
16359 
16360 /// Check if two standard-layout unions are layout-compatible.
16361 /// (C++11 [class.mem] p18)
16362 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16363                                     RecordDecl *RD2) {
16364   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16365   for (auto *Field2 : RD2->fields())
16366     UnmatchedFields.insert(Field2);
16367 
16368   for (auto *Field1 : RD1->fields()) {
16369     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16370         I = UnmatchedFields.begin(),
16371         E = UnmatchedFields.end();
16372 
16373     for ( ; I != E; ++I) {
16374       if (isLayoutCompatible(C, Field1, *I)) {
16375         bool Result = UnmatchedFields.erase(*I);
16376         (void) Result;
16377         assert(Result);
16378         break;
16379       }
16380     }
16381     if (I == E)
16382       return false;
16383   }
16384 
16385   return UnmatchedFields.empty();
16386 }
16387 
16388 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16389                                RecordDecl *RD2) {
16390   if (RD1->isUnion() != RD2->isUnion())
16391     return false;
16392 
16393   if (RD1->isUnion())
16394     return isLayoutCompatibleUnion(C, RD1, RD2);
16395   else
16396     return isLayoutCompatibleStruct(C, RD1, RD2);
16397 }
16398 
16399 /// Check if two types are layout-compatible in C++11 sense.
16400 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16401   if (T1.isNull() || T2.isNull())
16402     return false;
16403 
16404   // C++11 [basic.types] p11:
16405   // If two types T1 and T2 are the same type, then T1 and T2 are
16406   // layout-compatible types.
16407   if (C.hasSameType(T1, T2))
16408     return true;
16409 
16410   T1 = T1.getCanonicalType().getUnqualifiedType();
16411   T2 = T2.getCanonicalType().getUnqualifiedType();
16412 
16413   const Type::TypeClass TC1 = T1->getTypeClass();
16414   const Type::TypeClass TC2 = T2->getTypeClass();
16415 
16416   if (TC1 != TC2)
16417     return false;
16418 
16419   if (TC1 == Type::Enum) {
16420     return isLayoutCompatible(C,
16421                               cast<EnumType>(T1)->getDecl(),
16422                               cast<EnumType>(T2)->getDecl());
16423   } else if (TC1 == Type::Record) {
16424     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16425       return false;
16426 
16427     return isLayoutCompatible(C,
16428                               cast<RecordType>(T1)->getDecl(),
16429                               cast<RecordType>(T2)->getDecl());
16430   }
16431 
16432   return false;
16433 }
16434 
16435 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16436 
16437 /// Given a type tag expression find the type tag itself.
16438 ///
16439 /// \param TypeExpr Type tag expression, as it appears in user's code.
16440 ///
16441 /// \param VD Declaration of an identifier that appears in a type tag.
16442 ///
16443 /// \param MagicValue Type tag magic value.
16444 ///
16445 /// \param isConstantEvaluated whether the evalaution should be performed in
16446 
16447 /// constant context.
16448 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16449                             const ValueDecl **VD, uint64_t *MagicValue,
16450                             bool isConstantEvaluated) {
16451   while(true) {
16452     if (!TypeExpr)
16453       return false;
16454 
16455     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16456 
16457     switch (TypeExpr->getStmtClass()) {
16458     case Stmt::UnaryOperatorClass: {
16459       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16460       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16461         TypeExpr = UO->getSubExpr();
16462         continue;
16463       }
16464       return false;
16465     }
16466 
16467     case Stmt::DeclRefExprClass: {
16468       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16469       *VD = DRE->getDecl();
16470       return true;
16471     }
16472 
16473     case Stmt::IntegerLiteralClass: {
16474       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16475       llvm::APInt MagicValueAPInt = IL->getValue();
16476       if (MagicValueAPInt.getActiveBits() <= 64) {
16477         *MagicValue = MagicValueAPInt.getZExtValue();
16478         return true;
16479       } else
16480         return false;
16481     }
16482 
16483     case Stmt::BinaryConditionalOperatorClass:
16484     case Stmt::ConditionalOperatorClass: {
16485       const AbstractConditionalOperator *ACO =
16486           cast<AbstractConditionalOperator>(TypeExpr);
16487       bool Result;
16488       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16489                                                      isConstantEvaluated)) {
16490         if (Result)
16491           TypeExpr = ACO->getTrueExpr();
16492         else
16493           TypeExpr = ACO->getFalseExpr();
16494         continue;
16495       }
16496       return false;
16497     }
16498 
16499     case Stmt::BinaryOperatorClass: {
16500       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16501       if (BO->getOpcode() == BO_Comma) {
16502         TypeExpr = BO->getRHS();
16503         continue;
16504       }
16505       return false;
16506     }
16507 
16508     default:
16509       return false;
16510     }
16511   }
16512 }
16513 
16514 /// Retrieve the C type corresponding to type tag TypeExpr.
16515 ///
16516 /// \param TypeExpr Expression that specifies a type tag.
16517 ///
16518 /// \param MagicValues Registered magic values.
16519 ///
16520 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16521 ///        kind.
16522 ///
16523 /// \param TypeInfo Information about the corresponding C type.
16524 ///
16525 /// \param isConstantEvaluated whether the evalaution should be performed in
16526 /// constant context.
16527 ///
16528 /// \returns true if the corresponding C type was found.
16529 static bool GetMatchingCType(
16530     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16531     const ASTContext &Ctx,
16532     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16533         *MagicValues,
16534     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16535     bool isConstantEvaluated) {
16536   FoundWrongKind = false;
16537 
16538   // Variable declaration that has type_tag_for_datatype attribute.
16539   const ValueDecl *VD = nullptr;
16540 
16541   uint64_t MagicValue;
16542 
16543   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16544     return false;
16545 
16546   if (VD) {
16547     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16548       if (I->getArgumentKind() != ArgumentKind) {
16549         FoundWrongKind = true;
16550         return false;
16551       }
16552       TypeInfo.Type = I->getMatchingCType();
16553       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16554       TypeInfo.MustBeNull = I->getMustBeNull();
16555       return true;
16556     }
16557     return false;
16558   }
16559 
16560   if (!MagicValues)
16561     return false;
16562 
16563   llvm::DenseMap<Sema::TypeTagMagicValue,
16564                  Sema::TypeTagData>::const_iterator I =
16565       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16566   if (I == MagicValues->end())
16567     return false;
16568 
16569   TypeInfo = I->second;
16570   return true;
16571 }
16572 
16573 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16574                                       uint64_t MagicValue, QualType Type,
16575                                       bool LayoutCompatible,
16576                                       bool MustBeNull) {
16577   if (!TypeTagForDatatypeMagicValues)
16578     TypeTagForDatatypeMagicValues.reset(
16579         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16580 
16581   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16582   (*TypeTagForDatatypeMagicValues)[Magic] =
16583       TypeTagData(Type, LayoutCompatible, MustBeNull);
16584 }
16585 
16586 static bool IsSameCharType(QualType T1, QualType T2) {
16587   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16588   if (!BT1)
16589     return false;
16590 
16591   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16592   if (!BT2)
16593     return false;
16594 
16595   BuiltinType::Kind T1Kind = BT1->getKind();
16596   BuiltinType::Kind T2Kind = BT2->getKind();
16597 
16598   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16599          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16600          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16601          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16602 }
16603 
16604 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16605                                     const ArrayRef<const Expr *> ExprArgs,
16606                                     SourceLocation CallSiteLoc) {
16607   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16608   bool IsPointerAttr = Attr->getIsPointer();
16609 
16610   // Retrieve the argument representing the 'type_tag'.
16611   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16612   if (TypeTagIdxAST >= ExprArgs.size()) {
16613     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16614         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16615     return;
16616   }
16617   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16618   bool FoundWrongKind;
16619   TypeTagData TypeInfo;
16620   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16621                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16622                         TypeInfo, isConstantEvaluated())) {
16623     if (FoundWrongKind)
16624       Diag(TypeTagExpr->getExprLoc(),
16625            diag::warn_type_tag_for_datatype_wrong_kind)
16626         << TypeTagExpr->getSourceRange();
16627     return;
16628   }
16629 
16630   // Retrieve the argument representing the 'arg_idx'.
16631   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16632   if (ArgumentIdxAST >= ExprArgs.size()) {
16633     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16634         << 1 << Attr->getArgumentIdx().getSourceIndex();
16635     return;
16636   }
16637   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16638   if (IsPointerAttr) {
16639     // Skip implicit cast of pointer to `void *' (as a function argument).
16640     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16641       if (ICE->getType()->isVoidPointerType() &&
16642           ICE->getCastKind() == CK_BitCast)
16643         ArgumentExpr = ICE->getSubExpr();
16644   }
16645   QualType ArgumentType = ArgumentExpr->getType();
16646 
16647   // Passing a `void*' pointer shouldn't trigger a warning.
16648   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16649     return;
16650 
16651   if (TypeInfo.MustBeNull) {
16652     // Type tag with matching void type requires a null pointer.
16653     if (!ArgumentExpr->isNullPointerConstant(Context,
16654                                              Expr::NPC_ValueDependentIsNotNull)) {
16655       Diag(ArgumentExpr->getExprLoc(),
16656            diag::warn_type_safety_null_pointer_required)
16657           << ArgumentKind->getName()
16658           << ArgumentExpr->getSourceRange()
16659           << TypeTagExpr->getSourceRange();
16660     }
16661     return;
16662   }
16663 
16664   QualType RequiredType = TypeInfo.Type;
16665   if (IsPointerAttr)
16666     RequiredType = Context.getPointerType(RequiredType);
16667 
16668   bool mismatch = false;
16669   if (!TypeInfo.LayoutCompatible) {
16670     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16671 
16672     // C++11 [basic.fundamental] p1:
16673     // Plain char, signed char, and unsigned char are three distinct types.
16674     //
16675     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16676     // char' depending on the current char signedness mode.
16677     if (mismatch)
16678       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16679                                            RequiredType->getPointeeType())) ||
16680           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16681         mismatch = false;
16682   } else
16683     if (IsPointerAttr)
16684       mismatch = !isLayoutCompatible(Context,
16685                                      ArgumentType->getPointeeType(),
16686                                      RequiredType->getPointeeType());
16687     else
16688       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16689 
16690   if (mismatch)
16691     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16692         << ArgumentType << ArgumentKind
16693         << TypeInfo.LayoutCompatible << RequiredType
16694         << ArgumentExpr->getSourceRange()
16695         << TypeTagExpr->getSourceRange();
16696 }
16697 
16698 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16699                                          CharUnits Alignment) {
16700   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16701 }
16702 
16703 void Sema::DiagnoseMisalignedMembers() {
16704   for (MisalignedMember &m : MisalignedMembers) {
16705     const NamedDecl *ND = m.RD;
16706     if (ND->getName().empty()) {
16707       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16708         ND = TD;
16709     }
16710     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16711         << m.MD << ND << m.E->getSourceRange();
16712   }
16713   MisalignedMembers.clear();
16714 }
16715 
16716 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16717   E = E->IgnoreParens();
16718   if (!T->isPointerType() && !T->isIntegerType())
16719     return;
16720   if (isa<UnaryOperator>(E) &&
16721       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16722     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16723     if (isa<MemberExpr>(Op)) {
16724       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16725       if (MA != MisalignedMembers.end() &&
16726           (T->isIntegerType() ||
16727            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16728                                    Context.getTypeAlignInChars(
16729                                        T->getPointeeType()) <= MA->Alignment))))
16730         MisalignedMembers.erase(MA);
16731     }
16732   }
16733 }
16734 
16735 void Sema::RefersToMemberWithReducedAlignment(
16736     Expr *E,
16737     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16738         Action) {
16739   const auto *ME = dyn_cast<MemberExpr>(E);
16740   if (!ME)
16741     return;
16742 
16743   // No need to check expressions with an __unaligned-qualified type.
16744   if (E->getType().getQualifiers().hasUnaligned())
16745     return;
16746 
16747   // For a chain of MemberExpr like "a.b.c.d" this list
16748   // will keep FieldDecl's like [d, c, b].
16749   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16750   const MemberExpr *TopME = nullptr;
16751   bool AnyIsPacked = false;
16752   do {
16753     QualType BaseType = ME->getBase()->getType();
16754     if (BaseType->isDependentType())
16755       return;
16756     if (ME->isArrow())
16757       BaseType = BaseType->getPointeeType();
16758     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16759     if (RD->isInvalidDecl())
16760       return;
16761 
16762     ValueDecl *MD = ME->getMemberDecl();
16763     auto *FD = dyn_cast<FieldDecl>(MD);
16764     // We do not care about non-data members.
16765     if (!FD || FD->isInvalidDecl())
16766       return;
16767 
16768     AnyIsPacked =
16769         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16770     ReverseMemberChain.push_back(FD);
16771 
16772     TopME = ME;
16773     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16774   } while (ME);
16775   assert(TopME && "We did not compute a topmost MemberExpr!");
16776 
16777   // Not the scope of this diagnostic.
16778   if (!AnyIsPacked)
16779     return;
16780 
16781   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16782   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16783   // TODO: The innermost base of the member expression may be too complicated.
16784   // For now, just disregard these cases. This is left for future
16785   // improvement.
16786   if (!DRE && !isa<CXXThisExpr>(TopBase))
16787       return;
16788 
16789   // Alignment expected by the whole expression.
16790   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16791 
16792   // No need to do anything else with this case.
16793   if (ExpectedAlignment.isOne())
16794     return;
16795 
16796   // Synthesize offset of the whole access.
16797   CharUnits Offset;
16798   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16799     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16800 
16801   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16802   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16803       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16804 
16805   // The base expression of the innermost MemberExpr may give
16806   // stronger guarantees than the class containing the member.
16807   if (DRE && !TopME->isArrow()) {
16808     const ValueDecl *VD = DRE->getDecl();
16809     if (!VD->getType()->isReferenceType())
16810       CompleteObjectAlignment =
16811           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16812   }
16813 
16814   // Check if the synthesized offset fulfills the alignment.
16815   if (Offset % ExpectedAlignment != 0 ||
16816       // It may fulfill the offset it but the effective alignment may still be
16817       // lower than the expected expression alignment.
16818       CompleteObjectAlignment < ExpectedAlignment) {
16819     // If this happens, we want to determine a sensible culprit of this.
16820     // Intuitively, watching the chain of member expressions from right to
16821     // left, we start with the required alignment (as required by the field
16822     // type) but some packed attribute in that chain has reduced the alignment.
16823     // It may happen that another packed structure increases it again. But if
16824     // we are here such increase has not been enough. So pointing the first
16825     // FieldDecl that either is packed or else its RecordDecl is,
16826     // seems reasonable.
16827     FieldDecl *FD = nullptr;
16828     CharUnits Alignment;
16829     for (FieldDecl *FDI : ReverseMemberChain) {
16830       if (FDI->hasAttr<PackedAttr>() ||
16831           FDI->getParent()->hasAttr<PackedAttr>()) {
16832         FD = FDI;
16833         Alignment = std::min(
16834             Context.getTypeAlignInChars(FD->getType()),
16835             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16836         break;
16837       }
16838     }
16839     assert(FD && "We did not find a packed FieldDecl!");
16840     Action(E, FD->getParent(), FD, Alignment);
16841   }
16842 }
16843 
16844 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16845   using namespace std::placeholders;
16846 
16847   RefersToMemberWithReducedAlignment(
16848       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16849                      _2, _3, _4));
16850 }
16851 
16852 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16853 // not a valid type, emit an error message and return true. Otherwise return
16854 // false.
16855 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16856                                         QualType Ty) {
16857   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16858     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16859         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16860     return true;
16861   }
16862   return false;
16863 }
16864 
16865 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16866   if (checkArgCount(*this, TheCall, 1))
16867     return true;
16868 
16869   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16870   if (A.isInvalid())
16871     return true;
16872 
16873   TheCall->setArg(0, A.get());
16874   QualType TyA = A.get()->getType();
16875 
16876   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16877     return true;
16878 
16879   TheCall->setType(TyA);
16880   return false;
16881 }
16882 
16883 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16884   if (checkArgCount(*this, TheCall, 2))
16885     return true;
16886 
16887   ExprResult A = TheCall->getArg(0);
16888   ExprResult B = TheCall->getArg(1);
16889   // Do standard promotions between the two arguments, returning their common
16890   // type.
16891   QualType Res =
16892       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16893   if (A.isInvalid() || B.isInvalid())
16894     return true;
16895 
16896   QualType TyA = A.get()->getType();
16897   QualType TyB = B.get()->getType();
16898 
16899   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16900     return Diag(A.get()->getBeginLoc(),
16901                 diag::err_typecheck_call_different_arg_types)
16902            << TyA << TyB;
16903 
16904   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16905     return true;
16906 
16907   TheCall->setArg(0, A.get());
16908   TheCall->setArg(1, B.get());
16909   TheCall->setType(Res);
16910   return false;
16911 }
16912 
16913 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16914   if (checkArgCount(*this, TheCall, 1))
16915     return true;
16916 
16917   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16918   if (A.isInvalid())
16919     return true;
16920 
16921   TheCall->setArg(0, A.get());
16922   return false;
16923 }
16924 
16925 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16926                                             ExprResult CallResult) {
16927   if (checkArgCount(*this, TheCall, 1))
16928     return ExprError();
16929 
16930   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16931   if (MatrixArg.isInvalid())
16932     return MatrixArg;
16933   Expr *Matrix = MatrixArg.get();
16934 
16935   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16936   if (!MType) {
16937     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16938         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16939     return ExprError();
16940   }
16941 
16942   // Create returned matrix type by swapping rows and columns of the argument
16943   // matrix type.
16944   QualType ResultType = Context.getConstantMatrixType(
16945       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16946 
16947   // Change the return type to the type of the returned matrix.
16948   TheCall->setType(ResultType);
16949 
16950   // Update call argument to use the possibly converted matrix argument.
16951   TheCall->setArg(0, Matrix);
16952   return CallResult;
16953 }
16954 
16955 // Get and verify the matrix dimensions.
16956 static llvm::Optional<unsigned>
16957 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16958   SourceLocation ErrorPos;
16959   Optional<llvm::APSInt> Value =
16960       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16961   if (!Value) {
16962     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16963         << Name;
16964     return {};
16965   }
16966   uint64_t Dim = Value->getZExtValue();
16967   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16968     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16969         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16970     return {};
16971   }
16972   return Dim;
16973 }
16974 
16975 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16976                                                   ExprResult CallResult) {
16977   if (!getLangOpts().MatrixTypes) {
16978     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16979     return ExprError();
16980   }
16981 
16982   if (checkArgCount(*this, TheCall, 4))
16983     return ExprError();
16984 
16985   unsigned PtrArgIdx = 0;
16986   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16987   Expr *RowsExpr = TheCall->getArg(1);
16988   Expr *ColumnsExpr = TheCall->getArg(2);
16989   Expr *StrideExpr = TheCall->getArg(3);
16990 
16991   bool ArgError = false;
16992 
16993   // Check pointer argument.
16994   {
16995     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16996     if (PtrConv.isInvalid())
16997       return PtrConv;
16998     PtrExpr = PtrConv.get();
16999     TheCall->setArg(0, PtrExpr);
17000     if (PtrExpr->isTypeDependent()) {
17001       TheCall->setType(Context.DependentTy);
17002       return TheCall;
17003     }
17004   }
17005 
17006   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17007   QualType ElementTy;
17008   if (!PtrTy) {
17009     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17010         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17011     ArgError = true;
17012   } else {
17013     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17014 
17015     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17016       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17017           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17018           << PtrExpr->getType();
17019       ArgError = true;
17020     }
17021   }
17022 
17023   // Apply default Lvalue conversions and convert the expression to size_t.
17024   auto ApplyArgumentConversions = [this](Expr *E) {
17025     ExprResult Conv = DefaultLvalueConversion(E);
17026     if (Conv.isInvalid())
17027       return Conv;
17028 
17029     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17030   };
17031 
17032   // Apply conversion to row and column expressions.
17033   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17034   if (!RowsConv.isInvalid()) {
17035     RowsExpr = RowsConv.get();
17036     TheCall->setArg(1, RowsExpr);
17037   } else
17038     RowsExpr = nullptr;
17039 
17040   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17041   if (!ColumnsConv.isInvalid()) {
17042     ColumnsExpr = ColumnsConv.get();
17043     TheCall->setArg(2, ColumnsExpr);
17044   } else
17045     ColumnsExpr = nullptr;
17046 
17047   // If any any part of the result matrix type is still pending, just use
17048   // Context.DependentTy, until all parts are resolved.
17049   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17050       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17051     TheCall->setType(Context.DependentTy);
17052     return CallResult;
17053   }
17054 
17055   // Check row and column dimensions.
17056   llvm::Optional<unsigned> MaybeRows;
17057   if (RowsExpr)
17058     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17059 
17060   llvm::Optional<unsigned> MaybeColumns;
17061   if (ColumnsExpr)
17062     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17063 
17064   // Check stride argument.
17065   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17066   if (StrideConv.isInvalid())
17067     return ExprError();
17068   StrideExpr = StrideConv.get();
17069   TheCall->setArg(3, StrideExpr);
17070 
17071   if (MaybeRows) {
17072     if (Optional<llvm::APSInt> Value =
17073             StrideExpr->getIntegerConstantExpr(Context)) {
17074       uint64_t Stride = Value->getZExtValue();
17075       if (Stride < *MaybeRows) {
17076         Diag(StrideExpr->getBeginLoc(),
17077              diag::err_builtin_matrix_stride_too_small);
17078         ArgError = true;
17079       }
17080     }
17081   }
17082 
17083   if (ArgError || !MaybeRows || !MaybeColumns)
17084     return ExprError();
17085 
17086   TheCall->setType(
17087       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17088   return CallResult;
17089 }
17090 
17091 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17092                                                    ExprResult CallResult) {
17093   if (checkArgCount(*this, TheCall, 3))
17094     return ExprError();
17095 
17096   unsigned PtrArgIdx = 1;
17097   Expr *MatrixExpr = TheCall->getArg(0);
17098   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17099   Expr *StrideExpr = TheCall->getArg(2);
17100 
17101   bool ArgError = false;
17102 
17103   {
17104     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17105     if (MatrixConv.isInvalid())
17106       return MatrixConv;
17107     MatrixExpr = MatrixConv.get();
17108     TheCall->setArg(0, MatrixExpr);
17109   }
17110   if (MatrixExpr->isTypeDependent()) {
17111     TheCall->setType(Context.DependentTy);
17112     return TheCall;
17113   }
17114 
17115   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17116   if (!MatrixTy) {
17117     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17118         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17119     ArgError = true;
17120   }
17121 
17122   {
17123     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17124     if (PtrConv.isInvalid())
17125       return PtrConv;
17126     PtrExpr = PtrConv.get();
17127     TheCall->setArg(1, PtrExpr);
17128     if (PtrExpr->isTypeDependent()) {
17129       TheCall->setType(Context.DependentTy);
17130       return TheCall;
17131     }
17132   }
17133 
17134   // Check pointer argument.
17135   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17136   if (!PtrTy) {
17137     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17138         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17139     ArgError = true;
17140   } else {
17141     QualType ElementTy = PtrTy->getPointeeType();
17142     if (ElementTy.isConstQualified()) {
17143       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17144       ArgError = true;
17145     }
17146     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17147     if (MatrixTy &&
17148         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17149       Diag(PtrExpr->getBeginLoc(),
17150            diag::err_builtin_matrix_pointer_arg_mismatch)
17151           << ElementTy << MatrixTy->getElementType();
17152       ArgError = true;
17153     }
17154   }
17155 
17156   // Apply default Lvalue conversions and convert the stride expression to
17157   // size_t.
17158   {
17159     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17160     if (StrideConv.isInvalid())
17161       return StrideConv;
17162 
17163     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17164     if (StrideConv.isInvalid())
17165       return StrideConv;
17166     StrideExpr = StrideConv.get();
17167     TheCall->setArg(2, StrideExpr);
17168   }
17169 
17170   // Check stride argument.
17171   if (MatrixTy) {
17172     if (Optional<llvm::APSInt> Value =
17173             StrideExpr->getIntegerConstantExpr(Context)) {
17174       uint64_t Stride = Value->getZExtValue();
17175       if (Stride < MatrixTy->getNumRows()) {
17176         Diag(StrideExpr->getBeginLoc(),
17177              diag::err_builtin_matrix_stride_too_small);
17178         ArgError = true;
17179       }
17180     }
17181   }
17182 
17183   if (ArgError)
17184     return ExprError();
17185 
17186   return CallResult;
17187 }
17188 
17189 /// \brief Enforce the bounds of a TCB
17190 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17191 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17192 /// and enforce_tcb_leaf attributes.
17193 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17194                                const FunctionDecl *Callee) {
17195   const FunctionDecl *Caller = getCurFunctionDecl();
17196 
17197   // Calls to builtins are not enforced.
17198   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17199       Callee->getBuiltinID() != 0)
17200     return;
17201 
17202   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17203   // all TCBs the callee is a part of.
17204   llvm::StringSet<> CalleeTCBs;
17205   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17206            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17207   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17208            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17209 
17210   // Go through the TCBs the caller is a part of and emit warnings if Caller
17211   // is in a TCB that the Callee is not.
17212   for_each(
17213       Caller->specific_attrs<EnforceTCBAttr>(),
17214       [&](const auto *A) {
17215         StringRef CallerTCB = A->getTCBName();
17216         if (CalleeTCBs.count(CallerTCB) == 0) {
17217           this->Diag(TheCall->getExprLoc(),
17218                      diag::warn_tcb_enforcement_violation) << Callee
17219                                                            << CallerTCB;
17220         }
17221       });
17222 }
17223