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,
503                              const TargetInfo &) override {
504 
505     const size_t FieldWidth = computeFieldWidth(FS);
506     const size_t Precision = computePrecision(FS);
507 
508     // The actual format.
509     switch (FS.getConversionSpecifier().getKind()) {
510     // Just a char.
511     case analyze_format_string::ConversionSpecifier::cArg:
512     case analyze_format_string::ConversionSpecifier::CArg:
513       Size += std::max(FieldWidth, (size_t)1);
514       break;
515     // Just an integer.
516     case analyze_format_string::ConversionSpecifier::dArg:
517     case analyze_format_string::ConversionSpecifier::DArg:
518     case analyze_format_string::ConversionSpecifier::iArg:
519     case analyze_format_string::ConversionSpecifier::oArg:
520     case analyze_format_string::ConversionSpecifier::OArg:
521     case analyze_format_string::ConversionSpecifier::uArg:
522     case analyze_format_string::ConversionSpecifier::UArg:
523     case analyze_format_string::ConversionSpecifier::xArg:
524     case analyze_format_string::ConversionSpecifier::XArg:
525       Size += std::max(FieldWidth, Precision);
526       break;
527 
528     // %g style conversion switches between %f or %e style dynamically.
529     // %f always takes less space, so default to it.
530     case analyze_format_string::ConversionSpecifier::gArg:
531     case analyze_format_string::ConversionSpecifier::GArg:
532 
533     // Floating point number in the form '[+]ddd.ddd'.
534     case analyze_format_string::ConversionSpecifier::fArg:
535     case analyze_format_string::ConversionSpecifier::FArg:
536       Size += std::max(FieldWidth, 1 /* integer part */ +
537                                        (Precision ? 1 + Precision
538                                                   : 0) /* period + decimal */);
539       break;
540 
541     // Floating point number in the form '[-]d.ddde[+-]dd'.
542     case analyze_format_string::ConversionSpecifier::eArg:
543     case analyze_format_string::ConversionSpecifier::EArg:
544       Size +=
545           std::max(FieldWidth,
546                    1 /* integer part */ +
547                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
548                        1 /* e or E letter */ + 2 /* exponent */);
549       break;
550 
551     // Floating point number in the form '[-]0xh.hhhhp±dd'.
552     case analyze_format_string::ConversionSpecifier::aArg:
553     case analyze_format_string::ConversionSpecifier::AArg:
554       Size +=
555           std::max(FieldWidth,
556                    2 /* 0x */ + 1 /* integer part */ +
557                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
558                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
559       break;
560 
561     // Just a string.
562     case analyze_format_string::ConversionSpecifier::sArg:
563     case analyze_format_string::ConversionSpecifier::SArg:
564       Size += FieldWidth;
565       break;
566 
567     // Just a pointer in the form '0xddd'.
568     case analyze_format_string::ConversionSpecifier::pArg:
569       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
570       break;
571 
572     // A plain percent.
573     case analyze_format_string::ConversionSpecifier::PercentArg:
574       Size += 1;
575       break;
576 
577     default:
578       break;
579     }
580 
581     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
582 
583     if (FS.hasAlternativeForm()) {
584       switch (FS.getConversionSpecifier().getKind()) {
585       default:
586         break;
587       // Force a leading '0'.
588       case analyze_format_string::ConversionSpecifier::oArg:
589         Size += 1;
590         break;
591       // Force a leading '0x'.
592       case analyze_format_string::ConversionSpecifier::xArg:
593       case analyze_format_string::ConversionSpecifier::XArg:
594         Size += 2;
595         break;
596       // Force a period '.' before decimal, even if precision is 0.
597       case analyze_format_string::ConversionSpecifier::aArg:
598       case analyze_format_string::ConversionSpecifier::AArg:
599       case analyze_format_string::ConversionSpecifier::eArg:
600       case analyze_format_string::ConversionSpecifier::EArg:
601       case analyze_format_string::ConversionSpecifier::fArg:
602       case analyze_format_string::ConversionSpecifier::FArg:
603       case analyze_format_string::ConversionSpecifier::gArg:
604       case analyze_format_string::ConversionSpecifier::GArg:
605         Size += (Precision ? 0 : 1);
606         break;
607       }
608     }
609     assert(SpecifierLen <= Size && "no underflow");
610     Size -= SpecifierLen;
611     return true;
612   }
613 
614   size_t getSizeLowerBound() const { return Size; }
615 
616 private:
617   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
618     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
619     size_t FieldWidth = 0;
620     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
621       FieldWidth = FW.getConstantAmount();
622     return FieldWidth;
623   }
624 
625   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
626     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
627     size_t Precision = 0;
628 
629     // See man 3 printf for default precision value based on the specifier.
630     switch (FW.getHowSpecified()) {
631     case analyze_format_string::OptionalAmount::NotSpecified:
632       switch (FS.getConversionSpecifier().getKind()) {
633       default:
634         break;
635       case analyze_format_string::ConversionSpecifier::dArg: // %d
636       case analyze_format_string::ConversionSpecifier::DArg: // %D
637       case analyze_format_string::ConversionSpecifier::iArg: // %i
638         Precision = 1;
639         break;
640       case analyze_format_string::ConversionSpecifier::oArg: // %d
641       case analyze_format_string::ConversionSpecifier::OArg: // %D
642       case analyze_format_string::ConversionSpecifier::uArg: // %d
643       case analyze_format_string::ConversionSpecifier::UArg: // %D
644       case analyze_format_string::ConversionSpecifier::xArg: // %d
645       case analyze_format_string::ConversionSpecifier::XArg: // %D
646         Precision = 1;
647         break;
648       case analyze_format_string::ConversionSpecifier::fArg: // %f
649       case analyze_format_string::ConversionSpecifier::FArg: // %F
650       case analyze_format_string::ConversionSpecifier::eArg: // %e
651       case analyze_format_string::ConversionSpecifier::EArg: // %E
652       case analyze_format_string::ConversionSpecifier::gArg: // %g
653       case analyze_format_string::ConversionSpecifier::GArg: // %G
654         Precision = 6;
655         break;
656       case analyze_format_string::ConversionSpecifier::pArg: // %d
657         Precision = 1;
658         break;
659       }
660       break;
661     case analyze_format_string::OptionalAmount::Constant:
662       Precision = FW.getConstantAmount();
663       break;
664     default:
665       break;
666     }
667     return Precision;
668   }
669 };
670 
671 } // namespace
672 
673 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
674                                                CallExpr *TheCall) {
675   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
676       isConstantEvaluated())
677     return;
678 
679   bool UseDABAttr = false;
680   const FunctionDecl *UseDecl = FD;
681 
682   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
683   if (DABAttr) {
684     UseDecl = DABAttr->getFunction();
685     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
686     UseDABAttr = true;
687   }
688 
689   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
690 
691   if (!BuiltinID)
692     return;
693 
694   const TargetInfo &TI = getASTContext().getTargetInfo();
695   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
696 
697   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
698     // If we refer to a diagnose_as_builtin attribute, we need to change the
699     // argument index to refer to the arguments of the called function. Unless
700     // the index is out of bounds, which presumably means it's a variadic
701     // function.
702     if (!UseDABAttr)
703       return Index;
704     unsigned DABIndices = DABAttr->argIndices_size();
705     unsigned NewIndex = Index < DABIndices
706                             ? DABAttr->argIndices_begin()[Index]
707                             : Index - DABIndices + FD->getNumParams();
708     if (NewIndex >= TheCall->getNumArgs())
709       return llvm::None;
710     return NewIndex;
711   };
712 
713   auto ComputeExplicitObjectSizeArgument =
714       [&](unsigned Index) -> Optional<llvm::APSInt> {
715     Optional<unsigned> IndexOptional = TranslateIndex(Index);
716     if (!IndexOptional)
717       return llvm::None;
718     unsigned NewIndex = IndexOptional.getValue();
719     Expr::EvalResult Result;
720     Expr *SizeArg = TheCall->getArg(NewIndex);
721     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
722       return llvm::None;
723     llvm::APSInt Integer = Result.Val.getInt();
724     Integer.setIsUnsigned(true);
725     return Integer;
726   };
727 
728   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
729     // If the parameter has a pass_object_size attribute, then we should use its
730     // (potentially) more strict checking mode. Otherwise, conservatively assume
731     // type 0.
732     int BOSType = 0;
733     // This check can fail for variadic functions.
734     if (Index < FD->getNumParams()) {
735       if (const auto *POS =
736               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
737         BOSType = POS->getType();
738     }
739 
740     Optional<unsigned> IndexOptional = TranslateIndex(Index);
741     if (!IndexOptional)
742       return llvm::None;
743     unsigned NewIndex = IndexOptional.getValue();
744 
745     const Expr *ObjArg = TheCall->getArg(NewIndex);
746     uint64_t Result;
747     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
748       return llvm::None;
749 
750     // Get the object size in the target's size_t width.
751     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
752   };
753 
754   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
755     Optional<unsigned> IndexOptional = TranslateIndex(Index);
756     if (!IndexOptional)
757       return llvm::None;
758     unsigned NewIndex = IndexOptional.getValue();
759 
760     const Expr *ObjArg = TheCall->getArg(NewIndex);
761     uint64_t Result;
762     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
763       return llvm::None;
764     // Add 1 for null byte.
765     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
766   };
767 
768   Optional<llvm::APSInt> SourceSize;
769   Optional<llvm::APSInt> DestinationSize;
770   unsigned DiagID = 0;
771   bool IsChkVariant = false;
772 
773   auto GetFunctionName = [&]() {
774     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775     // Skim off the details of whichever builtin was called to produce a better
776     // diagnostic, as it's unlikely that the user wrote the __builtin
777     // explicitly.
778     if (IsChkVariant) {
779       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
780       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
781     } else if (FunctionName.startswith("__builtin_")) {
782       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
783     }
784     return FunctionName;
785   };
786 
787   switch (BuiltinID) {
788   default:
789     return;
790   case Builtin::BI__builtin_strcpy:
791   case Builtin::BIstrcpy: {
792     DiagID = diag::warn_fortify_strlen_overflow;
793     SourceSize = ComputeStrLenArgument(1);
794     DestinationSize = ComputeSizeArgument(0);
795     break;
796   }
797 
798   case Builtin::BI__builtin___strcpy_chk: {
799     DiagID = diag::warn_fortify_strlen_overflow;
800     SourceSize = ComputeStrLenArgument(1);
801     DestinationSize = ComputeExplicitObjectSizeArgument(2);
802     IsChkVariant = true;
803     break;
804   }
805 
806   case Builtin::BIscanf:
807   case Builtin::BIfscanf:
808   case Builtin::BIsscanf: {
809     unsigned FormatIndex = 1;
810     unsigned DataIndex = 2;
811     if (BuiltinID == Builtin::BIscanf) {
812       FormatIndex = 0;
813       DataIndex = 1;
814     }
815 
816     const auto *FormatExpr =
817         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
818 
819     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
820     if (!Format)
821       return;
822 
823     if (!Format->isAscii() && !Format->isUTF8())
824       return;
825 
826     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
827                         unsigned SourceSize) {
828       DiagID = diag::warn_fortify_scanf_overflow;
829       unsigned Index = ArgIndex + DataIndex;
830       StringRef FunctionName = GetFunctionName();
831       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
832                           PDiag(DiagID) << FunctionName << (Index + 1)
833                                         << DestSize << SourceSize);
834     };
835 
836     StringRef FormatStrRef = Format->getString();
837     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
838       return ComputeSizeArgument(Index + DataIndex);
839     };
840     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
841     const char *FormatBytes = FormatStrRef.data();
842     const ConstantArrayType *T =
843         Context.getAsConstantArrayType(Format->getType());
844     assert(T && "String literal not of constant array type!");
845     size_t TypeSize = T->getSize().getZExtValue();
846 
847     // In case there's a null byte somewhere.
848     size_t StrLen =
849         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
850 
851     analyze_format_string::ParseScanfString(H, FormatBytes,
852                                             FormatBytes + StrLen, getLangOpts(),
853                                             Context.getTargetInfo());
854 
855     // Unlike the other cases, in this one we have already issued the diagnostic
856     // here, so no need to continue (because unlike the other cases, here the
857     // diagnostic refers to the argument number).
858     return;
859   }
860 
861   case Builtin::BIsprintf:
862   case Builtin::BI__builtin___sprintf_chk: {
863     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
864     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
865 
866     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
867 
868       if (!Format->isAscii() && !Format->isUTF8())
869         return;
870 
871       StringRef FormatStrRef = Format->getString();
872       EstimateSizeFormatHandler H(FormatStrRef);
873       const char *FormatBytes = FormatStrRef.data();
874       const ConstantArrayType *T =
875           Context.getAsConstantArrayType(Format->getType());
876       assert(T && "String literal not of constant array type!");
877       size_t TypeSize = T->getSize().getZExtValue();
878 
879       // In case there's a null byte somewhere.
880       size_t StrLen =
881           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
882       if (!analyze_format_string::ParsePrintfString(
883               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
884               Context.getTargetInfo(), false)) {
885         DiagID = diag::warn_fortify_source_format_overflow;
886         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
887                          .extOrTrunc(SizeTypeWidth);
888         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
889           DestinationSize = ComputeExplicitObjectSizeArgument(2);
890           IsChkVariant = true;
891         } else {
892           DestinationSize = ComputeSizeArgument(0);
893         }
894         break;
895       }
896     }
897     return;
898   }
899   case Builtin::BI__builtin___memcpy_chk:
900   case Builtin::BI__builtin___memmove_chk:
901   case Builtin::BI__builtin___memset_chk:
902   case Builtin::BI__builtin___strlcat_chk:
903   case Builtin::BI__builtin___strlcpy_chk:
904   case Builtin::BI__builtin___strncat_chk:
905   case Builtin::BI__builtin___strncpy_chk:
906   case Builtin::BI__builtin___stpncpy_chk:
907   case Builtin::BI__builtin___memccpy_chk:
908   case Builtin::BI__builtin___mempcpy_chk: {
909     DiagID = diag::warn_builtin_chk_overflow;
910     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
911     DestinationSize =
912         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
913     IsChkVariant = true;
914     break;
915   }
916 
917   case Builtin::BI__builtin___snprintf_chk:
918   case Builtin::BI__builtin___vsnprintf_chk: {
919     DiagID = diag::warn_builtin_chk_overflow;
920     SourceSize = ComputeExplicitObjectSizeArgument(1);
921     DestinationSize = ComputeExplicitObjectSizeArgument(3);
922     IsChkVariant = true;
923     break;
924   }
925 
926   case Builtin::BIstrncat:
927   case Builtin::BI__builtin_strncat:
928   case Builtin::BIstrncpy:
929   case Builtin::BI__builtin_strncpy:
930   case Builtin::BIstpncpy:
931   case Builtin::BI__builtin_stpncpy: {
932     // Whether these functions overflow depends on the runtime strlen of the
933     // string, not just the buffer size, so emitting the "always overflow"
934     // diagnostic isn't quite right. We should still diagnose passing a buffer
935     // size larger than the destination buffer though; this is a runtime abort
936     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
937     DiagID = diag::warn_fortify_source_size_mismatch;
938     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
939     DestinationSize = ComputeSizeArgument(0);
940     break;
941   }
942 
943   case Builtin::BImemcpy:
944   case Builtin::BI__builtin_memcpy:
945   case Builtin::BImemmove:
946   case Builtin::BI__builtin_memmove:
947   case Builtin::BImemset:
948   case Builtin::BI__builtin_memset:
949   case Builtin::BImempcpy:
950   case Builtin::BI__builtin_mempcpy: {
951     DiagID = diag::warn_fortify_source_overflow;
952     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
953     DestinationSize = ComputeSizeArgument(0);
954     break;
955   }
956   case Builtin::BIsnprintf:
957   case Builtin::BI__builtin_snprintf:
958   case Builtin::BIvsnprintf:
959   case Builtin::BI__builtin_vsnprintf: {
960     DiagID = diag::warn_fortify_source_size_mismatch;
961     SourceSize = ComputeExplicitObjectSizeArgument(1);
962     DestinationSize = ComputeSizeArgument(0);
963     break;
964   }
965   }
966 
967   if (!SourceSize || !DestinationSize ||
968       llvm::APSInt::compareValues(SourceSize.getValue(),
969                                   DestinationSize.getValue()) <= 0)
970     return;
971 
972   StringRef FunctionName = GetFunctionName();
973 
974   SmallString<16> DestinationStr;
975   SmallString<16> SourceStr;
976   DestinationSize->toString(DestinationStr, /*Radix=*/10);
977   SourceSize->toString(SourceStr, /*Radix=*/10);
978   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
979                       PDiag(DiagID)
980                           << FunctionName << DestinationStr << SourceStr);
981 }
982 
983 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
984                                      Scope::ScopeFlags NeededScopeFlags,
985                                      unsigned DiagID) {
986   // Scopes aren't available during instantiation. Fortunately, builtin
987   // functions cannot be template args so they cannot be formed through template
988   // instantiation. Therefore checking once during the parse is sufficient.
989   if (SemaRef.inTemplateInstantiation())
990     return false;
991 
992   Scope *S = SemaRef.getCurScope();
993   while (S && !S->isSEHExceptScope())
994     S = S->getParent();
995   if (!S || !(S->getFlags() & NeededScopeFlags)) {
996     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
997     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
998         << DRE->getDecl()->getIdentifier();
999     return true;
1000   }
1001 
1002   return false;
1003 }
1004 
1005 static inline bool isBlockPointer(Expr *Arg) {
1006   return Arg->getType()->isBlockPointerType();
1007 }
1008 
1009 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1010 /// void*, which is a requirement of device side enqueue.
1011 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1012   const BlockPointerType *BPT =
1013       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1014   ArrayRef<QualType> Params =
1015       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1016   unsigned ArgCounter = 0;
1017   bool IllegalParams = false;
1018   // Iterate through the block parameters until either one is found that is not
1019   // a local void*, or the block is valid.
1020   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1021        I != E; ++I, ++ArgCounter) {
1022     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1023         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1024             LangAS::opencl_local) {
1025       // Get the location of the error. If a block literal has been passed
1026       // (BlockExpr) then we can point straight to the offending argument,
1027       // else we just point to the variable reference.
1028       SourceLocation ErrorLoc;
1029       if (isa<BlockExpr>(BlockArg)) {
1030         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1031         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1032       } else if (isa<DeclRefExpr>(BlockArg)) {
1033         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1034       }
1035       S.Diag(ErrorLoc,
1036              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1037       IllegalParams = true;
1038     }
1039   }
1040 
1041   return IllegalParams;
1042 }
1043 
1044 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1045   // OpenCL device can support extension but not the feature as extension
1046   // requires subgroup independent forward progress, but subgroup independent
1047   // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1048   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1049       !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1050                                         S.getLangOpts())) {
1051     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1052         << 1 << Call->getDirectCallee()
1053         << "cl_khr_subgroups or __opencl_c_subgroups";
1054     return true;
1055   }
1056   return false;
1057 }
1058 
1059 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1060   if (checkArgCount(S, TheCall, 2))
1061     return true;
1062 
1063   if (checkOpenCLSubgroupExt(S, TheCall))
1064     return true;
1065 
1066   // First argument is an ndrange_t type.
1067   Expr *NDRangeArg = TheCall->getArg(0);
1068   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1069     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1070         << TheCall->getDirectCallee() << "'ndrange_t'";
1071     return true;
1072   }
1073 
1074   Expr *BlockArg = TheCall->getArg(1);
1075   if (!isBlockPointer(BlockArg)) {
1076     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1077         << TheCall->getDirectCallee() << "block";
1078     return true;
1079   }
1080   return checkOpenCLBlockArgs(S, BlockArg);
1081 }
1082 
1083 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1084 /// get_kernel_work_group_size
1085 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1086 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1087   if (checkArgCount(S, TheCall, 1))
1088     return true;
1089 
1090   Expr *BlockArg = TheCall->getArg(0);
1091   if (!isBlockPointer(BlockArg)) {
1092     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1093         << TheCall->getDirectCallee() << "block";
1094     return true;
1095   }
1096   return checkOpenCLBlockArgs(S, BlockArg);
1097 }
1098 
1099 /// Diagnose integer type and any valid implicit conversion to it.
1100 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1101                                       const QualType &IntType);
1102 
1103 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1104                                             unsigned Start, unsigned End) {
1105   bool IllegalParams = false;
1106   for (unsigned I = Start; I <= End; ++I)
1107     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1108                                               S.Context.getSizeType());
1109   return IllegalParams;
1110 }
1111 
1112 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1113 /// 'local void*' parameter of passed block.
1114 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1115                                            Expr *BlockArg,
1116                                            unsigned NumNonVarArgs) {
1117   const BlockPointerType *BPT =
1118       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1119   unsigned NumBlockParams =
1120       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1121   unsigned TotalNumArgs = TheCall->getNumArgs();
1122 
1123   // For each argument passed to the block, a corresponding uint needs to
1124   // be passed to describe the size of the local memory.
1125   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1126     S.Diag(TheCall->getBeginLoc(),
1127            diag::err_opencl_enqueue_kernel_local_size_args);
1128     return true;
1129   }
1130 
1131   // Check that the sizes of the local memory are specified by integers.
1132   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1133                                          TotalNumArgs - 1);
1134 }
1135 
1136 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1137 /// overload formats specified in Table 6.13.17.1.
1138 /// int enqueue_kernel(queue_t queue,
1139 ///                    kernel_enqueue_flags_t flags,
1140 ///                    const ndrange_t ndrange,
1141 ///                    void (^block)(void))
1142 /// int enqueue_kernel(queue_t queue,
1143 ///                    kernel_enqueue_flags_t flags,
1144 ///                    const ndrange_t ndrange,
1145 ///                    uint num_events_in_wait_list,
1146 ///                    clk_event_t *event_wait_list,
1147 ///                    clk_event_t *event_ret,
1148 ///                    void (^block)(void))
1149 /// int enqueue_kernel(queue_t queue,
1150 ///                    kernel_enqueue_flags_t flags,
1151 ///                    const ndrange_t ndrange,
1152 ///                    void (^block)(local void*, ...),
1153 ///                    uint size0, ...)
1154 /// int enqueue_kernel(queue_t queue,
1155 ///                    kernel_enqueue_flags_t flags,
1156 ///                    const ndrange_t ndrange,
1157 ///                    uint num_events_in_wait_list,
1158 ///                    clk_event_t *event_wait_list,
1159 ///                    clk_event_t *event_ret,
1160 ///                    void (^block)(local void*, ...),
1161 ///                    uint size0, ...)
1162 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1163   unsigned NumArgs = TheCall->getNumArgs();
1164 
1165   if (NumArgs < 4) {
1166     S.Diag(TheCall->getBeginLoc(),
1167            diag::err_typecheck_call_too_few_args_at_least)
1168         << 0 << 4 << NumArgs;
1169     return true;
1170   }
1171 
1172   Expr *Arg0 = TheCall->getArg(0);
1173   Expr *Arg1 = TheCall->getArg(1);
1174   Expr *Arg2 = TheCall->getArg(2);
1175   Expr *Arg3 = TheCall->getArg(3);
1176 
1177   // First argument always needs to be a queue_t type.
1178   if (!Arg0->getType()->isQueueT()) {
1179     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1180            diag::err_opencl_builtin_expected_type)
1181         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1182     return true;
1183   }
1184 
1185   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1186   if (!Arg1->getType()->isIntegerType()) {
1187     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1188            diag::err_opencl_builtin_expected_type)
1189         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1190     return true;
1191   }
1192 
1193   // Third argument is always an ndrange_t type.
1194   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1195     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1196            diag::err_opencl_builtin_expected_type)
1197         << TheCall->getDirectCallee() << "'ndrange_t'";
1198     return true;
1199   }
1200 
1201   // With four arguments, there is only one form that the function could be
1202   // called in: no events and no variable arguments.
1203   if (NumArgs == 4) {
1204     // check that the last argument is the right block type.
1205     if (!isBlockPointer(Arg3)) {
1206       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1207           << TheCall->getDirectCallee() << "block";
1208       return true;
1209     }
1210     // we have a block type, check the prototype
1211     const BlockPointerType *BPT =
1212         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1213     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1214       S.Diag(Arg3->getBeginLoc(),
1215              diag::err_opencl_enqueue_kernel_blocks_no_args);
1216       return true;
1217     }
1218     return false;
1219   }
1220   // we can have block + varargs.
1221   if (isBlockPointer(Arg3))
1222     return (checkOpenCLBlockArgs(S, Arg3) ||
1223             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1224   // last two cases with either exactly 7 args or 7 args and varargs.
1225   if (NumArgs >= 7) {
1226     // check common block argument.
1227     Expr *Arg6 = TheCall->getArg(6);
1228     if (!isBlockPointer(Arg6)) {
1229       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1230           << TheCall->getDirectCallee() << "block";
1231       return true;
1232     }
1233     if (checkOpenCLBlockArgs(S, Arg6))
1234       return true;
1235 
1236     // Forth argument has to be any integer type.
1237     if (!Arg3->getType()->isIntegerType()) {
1238       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1239              diag::err_opencl_builtin_expected_type)
1240           << TheCall->getDirectCallee() << "integer";
1241       return true;
1242     }
1243     // check remaining common arguments.
1244     Expr *Arg4 = TheCall->getArg(4);
1245     Expr *Arg5 = TheCall->getArg(5);
1246 
1247     // Fifth argument is always passed as a pointer to clk_event_t.
1248     if (!Arg4->isNullPointerConstant(S.Context,
1249                                      Expr::NPC_ValueDependentIsNotNull) &&
1250         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1251       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1252              diag::err_opencl_builtin_expected_type)
1253           << TheCall->getDirectCallee()
1254           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1255       return true;
1256     }
1257 
1258     // Sixth argument is always passed as a pointer to clk_event_t.
1259     if (!Arg5->isNullPointerConstant(S.Context,
1260                                      Expr::NPC_ValueDependentIsNotNull) &&
1261         !(Arg5->getType()->isPointerType() &&
1262           Arg5->getType()->getPointeeType()->isClkEventT())) {
1263       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1264              diag::err_opencl_builtin_expected_type)
1265           << TheCall->getDirectCallee()
1266           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1267       return true;
1268     }
1269 
1270     if (NumArgs == 7)
1271       return false;
1272 
1273     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1274   }
1275 
1276   // None of the specific case has been detected, give generic error
1277   S.Diag(TheCall->getBeginLoc(),
1278          diag::err_opencl_enqueue_kernel_incorrect_args);
1279   return true;
1280 }
1281 
1282 /// Returns OpenCL access qual.
1283 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1284     return D->getAttr<OpenCLAccessAttr>();
1285 }
1286 
1287 /// Returns true if pipe element type is different from the pointer.
1288 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1289   const Expr *Arg0 = Call->getArg(0);
1290   // First argument type should always be pipe.
1291   if (!Arg0->getType()->isPipeType()) {
1292     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1293         << Call->getDirectCallee() << Arg0->getSourceRange();
1294     return true;
1295   }
1296   OpenCLAccessAttr *AccessQual =
1297       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1298   // Validates the access qualifier is compatible with the call.
1299   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1300   // read_only and write_only, and assumed to be read_only if no qualifier is
1301   // specified.
1302   switch (Call->getDirectCallee()->getBuiltinID()) {
1303   case Builtin::BIread_pipe:
1304   case Builtin::BIreserve_read_pipe:
1305   case Builtin::BIcommit_read_pipe:
1306   case Builtin::BIwork_group_reserve_read_pipe:
1307   case Builtin::BIsub_group_reserve_read_pipe:
1308   case Builtin::BIwork_group_commit_read_pipe:
1309   case Builtin::BIsub_group_commit_read_pipe:
1310     if (!(!AccessQual || AccessQual->isReadOnly())) {
1311       S.Diag(Arg0->getBeginLoc(),
1312              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1313           << "read_only" << Arg0->getSourceRange();
1314       return true;
1315     }
1316     break;
1317   case Builtin::BIwrite_pipe:
1318   case Builtin::BIreserve_write_pipe:
1319   case Builtin::BIcommit_write_pipe:
1320   case Builtin::BIwork_group_reserve_write_pipe:
1321   case Builtin::BIsub_group_reserve_write_pipe:
1322   case Builtin::BIwork_group_commit_write_pipe:
1323   case Builtin::BIsub_group_commit_write_pipe:
1324     if (!(AccessQual && AccessQual->isWriteOnly())) {
1325       S.Diag(Arg0->getBeginLoc(),
1326              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1327           << "write_only" << Arg0->getSourceRange();
1328       return true;
1329     }
1330     break;
1331   default:
1332     break;
1333   }
1334   return false;
1335 }
1336 
1337 /// Returns true if pipe element type is different from the pointer.
1338 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1339   const Expr *Arg0 = Call->getArg(0);
1340   const Expr *ArgIdx = Call->getArg(Idx);
1341   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1342   const QualType EltTy = PipeTy->getElementType();
1343   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1344   // The Idx argument should be a pointer and the type of the pointer and
1345   // the type of pipe element should also be the same.
1346   if (!ArgTy ||
1347       !S.Context.hasSameType(
1348           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1349     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1350         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1351         << ArgIdx->getType() << ArgIdx->getSourceRange();
1352     return true;
1353   }
1354   return false;
1355 }
1356 
1357 // Performs semantic analysis for the read/write_pipe call.
1358 // \param S Reference to the semantic analyzer.
1359 // \param Call A pointer to the builtin call.
1360 // \return True if a semantic error has been found, false otherwise.
1361 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1362   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1363   // functions have two forms.
1364   switch (Call->getNumArgs()) {
1365   case 2:
1366     if (checkOpenCLPipeArg(S, Call))
1367       return true;
1368     // The call with 2 arguments should be
1369     // read/write_pipe(pipe T, T*).
1370     // Check packet type T.
1371     if (checkOpenCLPipePacketType(S, Call, 1))
1372       return true;
1373     break;
1374 
1375   case 4: {
1376     if (checkOpenCLPipeArg(S, Call))
1377       return true;
1378     // The call with 4 arguments should be
1379     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1380     // Check reserve_id_t.
1381     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1382       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1383           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1384           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1385       return true;
1386     }
1387 
1388     // Check the index.
1389     const Expr *Arg2 = Call->getArg(2);
1390     if (!Arg2->getType()->isIntegerType() &&
1391         !Arg2->getType()->isUnsignedIntegerType()) {
1392       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1393           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1394           << Arg2->getType() << Arg2->getSourceRange();
1395       return true;
1396     }
1397 
1398     // Check packet type T.
1399     if (checkOpenCLPipePacketType(S, Call, 3))
1400       return true;
1401   } break;
1402   default:
1403     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1404         << Call->getDirectCallee() << Call->getSourceRange();
1405     return true;
1406   }
1407 
1408   return false;
1409 }
1410 
1411 // Performs a semantic analysis on the {work_group_/sub_group_
1412 //        /_}reserve_{read/write}_pipe
1413 // \param S Reference to the semantic analyzer.
1414 // \param Call The call to the builtin function to be analyzed.
1415 // \return True if a semantic error was found, false otherwise.
1416 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1417   if (checkArgCount(S, Call, 2))
1418     return true;
1419 
1420   if (checkOpenCLPipeArg(S, Call))
1421     return true;
1422 
1423   // Check the reserve size.
1424   if (!Call->getArg(1)->getType()->isIntegerType() &&
1425       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1426     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1427         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1428         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1429     return true;
1430   }
1431 
1432   // Since return type of reserve_read/write_pipe built-in function is
1433   // reserve_id_t, which is not defined in the builtin def file , we used int
1434   // as return type and need to override the return type of these functions.
1435   Call->setType(S.Context.OCLReserveIDTy);
1436 
1437   return false;
1438 }
1439 
1440 // Performs a semantic analysis on {work_group_/sub_group_
1441 //        /_}commit_{read/write}_pipe
1442 // \param S Reference to the semantic analyzer.
1443 // \param Call The call to the builtin function to be analyzed.
1444 // \return True if a semantic error was found, false otherwise.
1445 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1446   if (checkArgCount(S, Call, 2))
1447     return true;
1448 
1449   if (checkOpenCLPipeArg(S, Call))
1450     return true;
1451 
1452   // Check reserve_id_t.
1453   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1454     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1455         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1456         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1457     return true;
1458   }
1459 
1460   return false;
1461 }
1462 
1463 // Performs a semantic analysis on the call to built-in Pipe
1464 //        Query Functions.
1465 // \param S Reference to the semantic analyzer.
1466 // \param Call The call to the builtin function to be analyzed.
1467 // \return True if a semantic error was found, false otherwise.
1468 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1469   if (checkArgCount(S, Call, 1))
1470     return true;
1471 
1472   if (!Call->getArg(0)->getType()->isPipeType()) {
1473     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1474         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1475     return true;
1476   }
1477 
1478   return false;
1479 }
1480 
1481 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1482 // Performs semantic analysis for the to_global/local/private call.
1483 // \param S Reference to the semantic analyzer.
1484 // \param BuiltinID ID of the builtin function.
1485 // \param Call A pointer to the builtin call.
1486 // \return True if a semantic error has been found, false otherwise.
1487 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1488                                     CallExpr *Call) {
1489   if (checkArgCount(S, Call, 1))
1490     return true;
1491 
1492   auto RT = Call->getArg(0)->getType();
1493   if (!RT->isPointerType() || RT->getPointeeType()
1494       .getAddressSpace() == LangAS::opencl_constant) {
1495     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1496         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1497     return true;
1498   }
1499 
1500   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1501     S.Diag(Call->getArg(0)->getBeginLoc(),
1502            diag::warn_opencl_generic_address_space_arg)
1503         << Call->getDirectCallee()->getNameInfo().getAsString()
1504         << Call->getArg(0)->getSourceRange();
1505   }
1506 
1507   RT = RT->getPointeeType();
1508   auto Qual = RT.getQualifiers();
1509   switch (BuiltinID) {
1510   case Builtin::BIto_global:
1511     Qual.setAddressSpace(LangAS::opencl_global);
1512     break;
1513   case Builtin::BIto_local:
1514     Qual.setAddressSpace(LangAS::opencl_local);
1515     break;
1516   case Builtin::BIto_private:
1517     Qual.setAddressSpace(LangAS::opencl_private);
1518     break;
1519   default:
1520     llvm_unreachable("Invalid builtin function");
1521   }
1522   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1523       RT.getUnqualifiedType(), Qual)));
1524 
1525   return false;
1526 }
1527 
1528 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1529   if (checkArgCount(S, TheCall, 1))
1530     return ExprError();
1531 
1532   // Compute __builtin_launder's parameter type from the argument.
1533   // The parameter type is:
1534   //  * The type of the argument if it's not an array or function type,
1535   //  Otherwise,
1536   //  * The decayed argument type.
1537   QualType ParamTy = [&]() {
1538     QualType ArgTy = TheCall->getArg(0)->getType();
1539     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1540       return S.Context.getPointerType(Ty->getElementType());
1541     if (ArgTy->isFunctionType()) {
1542       return S.Context.getPointerType(ArgTy);
1543     }
1544     return ArgTy;
1545   }();
1546 
1547   TheCall->setType(ParamTy);
1548 
1549   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1550     if (!ParamTy->isPointerType())
1551       return 0;
1552     if (ParamTy->isFunctionPointerType())
1553       return 1;
1554     if (ParamTy->isVoidPointerType())
1555       return 2;
1556     return llvm::Optional<unsigned>{};
1557   }();
1558   if (DiagSelect.hasValue()) {
1559     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1560         << DiagSelect.getValue() << TheCall->getSourceRange();
1561     return ExprError();
1562   }
1563 
1564   // We either have an incomplete class type, or we have a class template
1565   // whose instantiation has not been forced. Example:
1566   //
1567   //   template <class T> struct Foo { T value; };
1568   //   Foo<int> *p = nullptr;
1569   //   auto *d = __builtin_launder(p);
1570   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1571                             diag::err_incomplete_type))
1572     return ExprError();
1573 
1574   assert(ParamTy->getPointeeType()->isObjectType() &&
1575          "Unhandled non-object pointer case");
1576 
1577   InitializedEntity Entity =
1578       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1579   ExprResult Arg =
1580       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1581   if (Arg.isInvalid())
1582     return ExprError();
1583   TheCall->setArg(0, Arg.get());
1584 
1585   return TheCall;
1586 }
1587 
1588 // Emit an error and return true if the current object format type is in the
1589 // list of unsupported types.
1590 static bool CheckBuiltinTargetNotInUnsupported(
1591     Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1592     ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1593   llvm::Triple::ObjectFormatType CurObjFormat =
1594       S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1595   if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1596     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1597         << TheCall->getSourceRange();
1598     return true;
1599   }
1600   return false;
1601 }
1602 
1603 // Emit an error and return true if the current architecture is not in the list
1604 // of supported architectures.
1605 static bool
1606 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1607                               ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1608   llvm::Triple::ArchType CurArch =
1609       S.getASTContext().getTargetInfo().getTriple().getArch();
1610   if (llvm::is_contained(SupportedArchs, CurArch))
1611     return false;
1612   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1613       << TheCall->getSourceRange();
1614   return true;
1615 }
1616 
1617 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1618                                  SourceLocation CallSiteLoc);
1619 
1620 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1621                                       CallExpr *TheCall) {
1622   switch (TI.getTriple().getArch()) {
1623   default:
1624     // Some builtins don't require additional checking, so just consider these
1625     // acceptable.
1626     return false;
1627   case llvm::Triple::arm:
1628   case llvm::Triple::armeb:
1629   case llvm::Triple::thumb:
1630   case llvm::Triple::thumbeb:
1631     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1632   case llvm::Triple::aarch64:
1633   case llvm::Triple::aarch64_32:
1634   case llvm::Triple::aarch64_be:
1635     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1636   case llvm::Triple::bpfeb:
1637   case llvm::Triple::bpfel:
1638     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1639   case llvm::Triple::hexagon:
1640     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1641   case llvm::Triple::mips:
1642   case llvm::Triple::mipsel:
1643   case llvm::Triple::mips64:
1644   case llvm::Triple::mips64el:
1645     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1646   case llvm::Triple::systemz:
1647     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1648   case llvm::Triple::x86:
1649   case llvm::Triple::x86_64:
1650     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1651   case llvm::Triple::ppc:
1652   case llvm::Triple::ppcle:
1653   case llvm::Triple::ppc64:
1654   case llvm::Triple::ppc64le:
1655     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1656   case llvm::Triple::amdgcn:
1657     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1658   case llvm::Triple::riscv32:
1659   case llvm::Triple::riscv64:
1660     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1661   }
1662 }
1663 
1664 ExprResult
1665 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1666                                CallExpr *TheCall) {
1667   ExprResult TheCallResult(TheCall);
1668 
1669   // Find out if any arguments are required to be integer constant expressions.
1670   unsigned ICEArguments = 0;
1671   ASTContext::GetBuiltinTypeError Error;
1672   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1673   if (Error != ASTContext::GE_None)
1674     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1675 
1676   // If any arguments are required to be ICE's, check and diagnose.
1677   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1678     // Skip arguments not required to be ICE's.
1679     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1680 
1681     llvm::APSInt Result;
1682     // If we don't have enough arguments, continue so we can issue better
1683     // diagnostic in checkArgCount(...)
1684     if (ArgNo < TheCall->getNumArgs() &&
1685         SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1686       return true;
1687     ICEArguments &= ~(1 << ArgNo);
1688   }
1689 
1690   switch (BuiltinID) {
1691   case Builtin::BI__builtin___CFStringMakeConstantString:
1692     // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
1693     // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
1694     if (CheckBuiltinTargetNotInUnsupported(
1695             *this, BuiltinID, TheCall,
1696             {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
1697       return ExprError();
1698     assert(TheCall->getNumArgs() == 1 &&
1699            "Wrong # arguments to builtin CFStringMakeConstantString");
1700     if (CheckObjCString(TheCall->getArg(0)))
1701       return ExprError();
1702     break;
1703   case Builtin::BI__builtin_ms_va_start:
1704   case Builtin::BI__builtin_stdarg_start:
1705   case Builtin::BI__builtin_va_start:
1706     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1707       return ExprError();
1708     break;
1709   case Builtin::BI__va_start: {
1710     switch (Context.getTargetInfo().getTriple().getArch()) {
1711     case llvm::Triple::aarch64:
1712     case llvm::Triple::arm:
1713     case llvm::Triple::thumb:
1714       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1715         return ExprError();
1716       break;
1717     default:
1718       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1719         return ExprError();
1720       break;
1721     }
1722     break;
1723   }
1724 
1725   // The acquire, release, and no fence variants are ARM and AArch64 only.
1726   case Builtin::BI_interlockedbittestandset_acq:
1727   case Builtin::BI_interlockedbittestandset_rel:
1728   case Builtin::BI_interlockedbittestandset_nf:
1729   case Builtin::BI_interlockedbittestandreset_acq:
1730   case Builtin::BI_interlockedbittestandreset_rel:
1731   case Builtin::BI_interlockedbittestandreset_nf:
1732     if (CheckBuiltinTargetInSupported(
1733             *this, BuiltinID, TheCall,
1734             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1735       return ExprError();
1736     break;
1737 
1738   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1739   case Builtin::BI_bittest64:
1740   case Builtin::BI_bittestandcomplement64:
1741   case Builtin::BI_bittestandreset64:
1742   case Builtin::BI_bittestandset64:
1743   case Builtin::BI_interlockedbittestandreset64:
1744   case Builtin::BI_interlockedbittestandset64:
1745     if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
1746                                       {llvm::Triple::x86_64, llvm::Triple::arm,
1747                                        llvm::Triple::thumb,
1748                                        llvm::Triple::aarch64}))
1749       return ExprError();
1750     break;
1751 
1752   case Builtin::BI__builtin_isgreater:
1753   case Builtin::BI__builtin_isgreaterequal:
1754   case Builtin::BI__builtin_isless:
1755   case Builtin::BI__builtin_islessequal:
1756   case Builtin::BI__builtin_islessgreater:
1757   case Builtin::BI__builtin_isunordered:
1758     if (SemaBuiltinUnorderedCompare(TheCall))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__builtin_fpclassify:
1762     if (SemaBuiltinFPClassification(TheCall, 6))
1763       return ExprError();
1764     break;
1765   case Builtin::BI__builtin_isfinite:
1766   case Builtin::BI__builtin_isinf:
1767   case Builtin::BI__builtin_isinf_sign:
1768   case Builtin::BI__builtin_isnan:
1769   case Builtin::BI__builtin_isnormal:
1770   case Builtin::BI__builtin_signbit:
1771   case Builtin::BI__builtin_signbitf:
1772   case Builtin::BI__builtin_signbitl:
1773     if (SemaBuiltinFPClassification(TheCall, 1))
1774       return ExprError();
1775     break;
1776   case Builtin::BI__builtin_shufflevector:
1777     return SemaBuiltinShuffleVector(TheCall);
1778     // TheCall will be freed by the smart pointer here, but that's fine, since
1779     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1780   case Builtin::BI__builtin_prefetch:
1781     if (SemaBuiltinPrefetch(TheCall))
1782       return ExprError();
1783     break;
1784   case Builtin::BI__builtin_alloca_with_align:
1785   case Builtin::BI__builtin_alloca_with_align_uninitialized:
1786     if (SemaBuiltinAllocaWithAlign(TheCall))
1787       return ExprError();
1788     LLVM_FALLTHROUGH;
1789   case Builtin::BI__builtin_alloca:
1790   case Builtin::BI__builtin_alloca_uninitialized:
1791     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1792         << TheCall->getDirectCallee();
1793     break;
1794   case Builtin::BI__arithmetic_fence:
1795     if (SemaBuiltinArithmeticFence(TheCall))
1796       return ExprError();
1797     break;
1798   case Builtin::BI__assume:
1799   case Builtin::BI__builtin_assume:
1800     if (SemaBuiltinAssume(TheCall))
1801       return ExprError();
1802     break;
1803   case Builtin::BI__builtin_assume_aligned:
1804     if (SemaBuiltinAssumeAligned(TheCall))
1805       return ExprError();
1806     break;
1807   case Builtin::BI__builtin_dynamic_object_size:
1808   case Builtin::BI__builtin_object_size:
1809     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1810       return ExprError();
1811     break;
1812   case Builtin::BI__builtin_longjmp:
1813     if (SemaBuiltinLongjmp(TheCall))
1814       return ExprError();
1815     break;
1816   case Builtin::BI__builtin_setjmp:
1817     if (SemaBuiltinSetjmp(TheCall))
1818       return ExprError();
1819     break;
1820   case Builtin::BI__builtin_classify_type:
1821     if (checkArgCount(*this, TheCall, 1)) return true;
1822     TheCall->setType(Context.IntTy);
1823     break;
1824   case Builtin::BI__builtin_complex:
1825     if (SemaBuiltinComplex(TheCall))
1826       return ExprError();
1827     break;
1828   case Builtin::BI__builtin_constant_p: {
1829     if (checkArgCount(*this, TheCall, 1)) return true;
1830     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1831     if (Arg.isInvalid()) return true;
1832     TheCall->setArg(0, Arg.get());
1833     TheCall->setType(Context.IntTy);
1834     break;
1835   }
1836   case Builtin::BI__builtin_launder:
1837     return SemaBuiltinLaunder(*this, TheCall);
1838   case Builtin::BI__sync_fetch_and_add:
1839   case Builtin::BI__sync_fetch_and_add_1:
1840   case Builtin::BI__sync_fetch_and_add_2:
1841   case Builtin::BI__sync_fetch_and_add_4:
1842   case Builtin::BI__sync_fetch_and_add_8:
1843   case Builtin::BI__sync_fetch_and_add_16:
1844   case Builtin::BI__sync_fetch_and_sub:
1845   case Builtin::BI__sync_fetch_and_sub_1:
1846   case Builtin::BI__sync_fetch_and_sub_2:
1847   case Builtin::BI__sync_fetch_and_sub_4:
1848   case Builtin::BI__sync_fetch_and_sub_8:
1849   case Builtin::BI__sync_fetch_and_sub_16:
1850   case Builtin::BI__sync_fetch_and_or:
1851   case Builtin::BI__sync_fetch_and_or_1:
1852   case Builtin::BI__sync_fetch_and_or_2:
1853   case Builtin::BI__sync_fetch_and_or_4:
1854   case Builtin::BI__sync_fetch_and_or_8:
1855   case Builtin::BI__sync_fetch_and_or_16:
1856   case Builtin::BI__sync_fetch_and_and:
1857   case Builtin::BI__sync_fetch_and_and_1:
1858   case Builtin::BI__sync_fetch_and_and_2:
1859   case Builtin::BI__sync_fetch_and_and_4:
1860   case Builtin::BI__sync_fetch_and_and_8:
1861   case Builtin::BI__sync_fetch_and_and_16:
1862   case Builtin::BI__sync_fetch_and_xor:
1863   case Builtin::BI__sync_fetch_and_xor_1:
1864   case Builtin::BI__sync_fetch_and_xor_2:
1865   case Builtin::BI__sync_fetch_and_xor_4:
1866   case Builtin::BI__sync_fetch_and_xor_8:
1867   case Builtin::BI__sync_fetch_and_xor_16:
1868   case Builtin::BI__sync_fetch_and_nand:
1869   case Builtin::BI__sync_fetch_and_nand_1:
1870   case Builtin::BI__sync_fetch_and_nand_2:
1871   case Builtin::BI__sync_fetch_and_nand_4:
1872   case Builtin::BI__sync_fetch_and_nand_8:
1873   case Builtin::BI__sync_fetch_and_nand_16:
1874   case Builtin::BI__sync_add_and_fetch:
1875   case Builtin::BI__sync_add_and_fetch_1:
1876   case Builtin::BI__sync_add_and_fetch_2:
1877   case Builtin::BI__sync_add_and_fetch_4:
1878   case Builtin::BI__sync_add_and_fetch_8:
1879   case Builtin::BI__sync_add_and_fetch_16:
1880   case Builtin::BI__sync_sub_and_fetch:
1881   case Builtin::BI__sync_sub_and_fetch_1:
1882   case Builtin::BI__sync_sub_and_fetch_2:
1883   case Builtin::BI__sync_sub_and_fetch_4:
1884   case Builtin::BI__sync_sub_and_fetch_8:
1885   case Builtin::BI__sync_sub_and_fetch_16:
1886   case Builtin::BI__sync_and_and_fetch:
1887   case Builtin::BI__sync_and_and_fetch_1:
1888   case Builtin::BI__sync_and_and_fetch_2:
1889   case Builtin::BI__sync_and_and_fetch_4:
1890   case Builtin::BI__sync_and_and_fetch_8:
1891   case Builtin::BI__sync_and_and_fetch_16:
1892   case Builtin::BI__sync_or_and_fetch:
1893   case Builtin::BI__sync_or_and_fetch_1:
1894   case Builtin::BI__sync_or_and_fetch_2:
1895   case Builtin::BI__sync_or_and_fetch_4:
1896   case Builtin::BI__sync_or_and_fetch_8:
1897   case Builtin::BI__sync_or_and_fetch_16:
1898   case Builtin::BI__sync_xor_and_fetch:
1899   case Builtin::BI__sync_xor_and_fetch_1:
1900   case Builtin::BI__sync_xor_and_fetch_2:
1901   case Builtin::BI__sync_xor_and_fetch_4:
1902   case Builtin::BI__sync_xor_and_fetch_8:
1903   case Builtin::BI__sync_xor_and_fetch_16:
1904   case Builtin::BI__sync_nand_and_fetch:
1905   case Builtin::BI__sync_nand_and_fetch_1:
1906   case Builtin::BI__sync_nand_and_fetch_2:
1907   case Builtin::BI__sync_nand_and_fetch_4:
1908   case Builtin::BI__sync_nand_and_fetch_8:
1909   case Builtin::BI__sync_nand_and_fetch_16:
1910   case Builtin::BI__sync_val_compare_and_swap:
1911   case Builtin::BI__sync_val_compare_and_swap_1:
1912   case Builtin::BI__sync_val_compare_and_swap_2:
1913   case Builtin::BI__sync_val_compare_and_swap_4:
1914   case Builtin::BI__sync_val_compare_and_swap_8:
1915   case Builtin::BI__sync_val_compare_and_swap_16:
1916   case Builtin::BI__sync_bool_compare_and_swap:
1917   case Builtin::BI__sync_bool_compare_and_swap_1:
1918   case Builtin::BI__sync_bool_compare_and_swap_2:
1919   case Builtin::BI__sync_bool_compare_and_swap_4:
1920   case Builtin::BI__sync_bool_compare_and_swap_8:
1921   case Builtin::BI__sync_bool_compare_and_swap_16:
1922   case Builtin::BI__sync_lock_test_and_set:
1923   case Builtin::BI__sync_lock_test_and_set_1:
1924   case Builtin::BI__sync_lock_test_and_set_2:
1925   case Builtin::BI__sync_lock_test_and_set_4:
1926   case Builtin::BI__sync_lock_test_and_set_8:
1927   case Builtin::BI__sync_lock_test_and_set_16:
1928   case Builtin::BI__sync_lock_release:
1929   case Builtin::BI__sync_lock_release_1:
1930   case Builtin::BI__sync_lock_release_2:
1931   case Builtin::BI__sync_lock_release_4:
1932   case Builtin::BI__sync_lock_release_8:
1933   case Builtin::BI__sync_lock_release_16:
1934   case Builtin::BI__sync_swap:
1935   case Builtin::BI__sync_swap_1:
1936   case Builtin::BI__sync_swap_2:
1937   case Builtin::BI__sync_swap_4:
1938   case Builtin::BI__sync_swap_8:
1939   case Builtin::BI__sync_swap_16:
1940     return SemaBuiltinAtomicOverloaded(TheCallResult);
1941   case Builtin::BI__sync_synchronize:
1942     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1943         << TheCall->getCallee()->getSourceRange();
1944     break;
1945   case Builtin::BI__builtin_nontemporal_load:
1946   case Builtin::BI__builtin_nontemporal_store:
1947     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1948   case Builtin::BI__builtin_memcpy_inline: {
1949     if (checkArgCount(*this, TheCall, 3))
1950       return ExprError();
1951     auto ArgArrayConversionFailed = [&](unsigned Arg) {
1952       ExprResult ArgExpr =
1953           DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
1954       if (ArgExpr.isInvalid())
1955         return true;
1956       TheCall->setArg(Arg, ArgExpr.get());
1957       return false;
1958     };
1959 
1960     if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1))
1961       return true;
1962     clang::Expr *SizeOp = TheCall->getArg(2);
1963     // We warn about copying to or from `nullptr` pointers when `size` is
1964     // greater than 0. When `size` is value dependent we cannot evaluate its
1965     // value so we bail out.
1966     if (SizeOp->isValueDependent())
1967       break;
1968     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1969       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1970       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1971     }
1972     break;
1973   }
1974 #define BUILTIN(ID, TYPE, ATTRS)
1975 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1976   case Builtin::BI##ID: \
1977     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1978 #include "clang/Basic/Builtins.def"
1979   case Builtin::BI__annotation:
1980     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1981       return ExprError();
1982     break;
1983   case Builtin::BI__builtin_annotation:
1984     if (SemaBuiltinAnnotation(*this, TheCall))
1985       return ExprError();
1986     break;
1987   case Builtin::BI__builtin_addressof:
1988     if (SemaBuiltinAddressof(*this, TheCall))
1989       return ExprError();
1990     break;
1991   case Builtin::BI__builtin_function_start:
1992     if (SemaBuiltinFunctionStart(*this, TheCall))
1993       return ExprError();
1994     break;
1995   case Builtin::BI__builtin_is_aligned:
1996   case Builtin::BI__builtin_align_up:
1997   case Builtin::BI__builtin_align_down:
1998     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1999       return ExprError();
2000     break;
2001   case Builtin::BI__builtin_add_overflow:
2002   case Builtin::BI__builtin_sub_overflow:
2003   case Builtin::BI__builtin_mul_overflow:
2004     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
2005       return ExprError();
2006     break;
2007   case Builtin::BI__builtin_operator_new:
2008   case Builtin::BI__builtin_operator_delete: {
2009     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2010     ExprResult Res =
2011         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2012     if (Res.isInvalid())
2013       CorrectDelayedTyposInExpr(TheCallResult.get());
2014     return Res;
2015   }
2016   case Builtin::BI__builtin_dump_struct: {
2017     // We first want to ensure we are called with 2 arguments
2018     if (checkArgCount(*this, TheCall, 2))
2019       return ExprError();
2020     // Ensure that the first argument is of type 'struct XX *'
2021     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
2022     const QualType PtrArgType = PtrArg->getType();
2023     if (!PtrArgType->isPointerType() ||
2024         !PtrArgType->getPointeeType()->isRecordType()) {
2025       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2026           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
2027           << "structure pointer";
2028       return ExprError();
2029     }
2030 
2031     // Ensure that the second argument is of type 'FunctionType'
2032     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
2033     const QualType FnPtrArgType = FnPtrArg->getType();
2034     if (!FnPtrArgType->isPointerType()) {
2035       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2036           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2037           << FnPtrArgType << "'int (*)(const char *, ...)'";
2038       return ExprError();
2039     }
2040 
2041     const auto *FuncType =
2042         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
2043 
2044     if (!FuncType) {
2045       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2046           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2047           << FnPtrArgType << "'int (*)(const char *, ...)'";
2048       return ExprError();
2049     }
2050 
2051     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2052       if (!FT->getNumParams()) {
2053         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2054             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2055             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2056         return ExprError();
2057       }
2058       QualType PT = FT->getParamType(0);
2059       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2060           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2061           !PT->getPointeeType().isConstQualified()) {
2062         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2063             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2064             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2065         return ExprError();
2066       }
2067     }
2068 
2069     TheCall->setType(Context.IntTy);
2070     break;
2071   }
2072   case Builtin::BI__builtin_expect_with_probability: {
2073     // We first want to ensure we are called with 3 arguments
2074     if (checkArgCount(*this, TheCall, 3))
2075       return ExprError();
2076     // then check probability is constant float in range [0.0, 1.0]
2077     const Expr *ProbArg = TheCall->getArg(2);
2078     SmallVector<PartialDiagnosticAt, 8> Notes;
2079     Expr::EvalResult Eval;
2080     Eval.Diag = &Notes;
2081     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2082         !Eval.Val.isFloat()) {
2083       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2084           << ProbArg->getSourceRange();
2085       for (const PartialDiagnosticAt &PDiag : Notes)
2086         Diag(PDiag.first, PDiag.second);
2087       return ExprError();
2088     }
2089     llvm::APFloat Probability = Eval.Val.getFloat();
2090     bool LoseInfo = false;
2091     Probability.convert(llvm::APFloat::IEEEdouble(),
2092                         llvm::RoundingMode::Dynamic, &LoseInfo);
2093     if (!(Probability >= llvm::APFloat(0.0) &&
2094           Probability <= llvm::APFloat(1.0))) {
2095       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2096           << ProbArg->getSourceRange();
2097       return ExprError();
2098     }
2099     break;
2100   }
2101   case Builtin::BI__builtin_preserve_access_index:
2102     if (SemaBuiltinPreserveAI(*this, TheCall))
2103       return ExprError();
2104     break;
2105   case Builtin::BI__builtin_call_with_static_chain:
2106     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2107       return ExprError();
2108     break;
2109   case Builtin::BI__exception_code:
2110   case Builtin::BI_exception_code:
2111     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2112                                  diag::err_seh___except_block))
2113       return ExprError();
2114     break;
2115   case Builtin::BI__exception_info:
2116   case Builtin::BI_exception_info:
2117     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2118                                  diag::err_seh___except_filter))
2119       return ExprError();
2120     break;
2121   case Builtin::BI__GetExceptionInfo:
2122     if (checkArgCount(*this, TheCall, 1))
2123       return ExprError();
2124 
2125     if (CheckCXXThrowOperand(
2126             TheCall->getBeginLoc(),
2127             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2128             TheCall))
2129       return ExprError();
2130 
2131     TheCall->setType(Context.VoidPtrTy);
2132     break;
2133   case Builtin::BIaddressof:
2134   case Builtin::BI__addressof:
2135   case Builtin::BIforward:
2136   case Builtin::BImove:
2137   case Builtin::BImove_if_noexcept:
2138   case Builtin::BIas_const: {
2139     // These are all expected to be of the form
2140     //   T &/&&/* f(U &/&&)
2141     // where T and U only differ in qualification.
2142     if (checkArgCount(*this, TheCall, 1))
2143       return ExprError();
2144     QualType Param = FDecl->getParamDecl(0)->getType();
2145     QualType Result = FDecl->getReturnType();
2146     bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2147                           BuiltinID == Builtin::BI__addressof;
2148     if (!(Param->isReferenceType() &&
2149           (ReturnsPointer ? Result->isPointerType()
2150                           : Result->isReferenceType()) &&
2151           Context.hasSameUnqualifiedType(Param->getPointeeType(),
2152                                          Result->getPointeeType()))) {
2153       Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2154           << FDecl;
2155       return ExprError();
2156     }
2157     break;
2158   }
2159   // OpenCL v2.0, s6.13.16 - Pipe functions
2160   case Builtin::BIread_pipe:
2161   case Builtin::BIwrite_pipe:
2162     // Since those two functions are declared with var args, we need a semantic
2163     // check for the argument.
2164     if (SemaBuiltinRWPipe(*this, TheCall))
2165       return ExprError();
2166     break;
2167   case Builtin::BIreserve_read_pipe:
2168   case Builtin::BIreserve_write_pipe:
2169   case Builtin::BIwork_group_reserve_read_pipe:
2170   case Builtin::BIwork_group_reserve_write_pipe:
2171     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2172       return ExprError();
2173     break;
2174   case Builtin::BIsub_group_reserve_read_pipe:
2175   case Builtin::BIsub_group_reserve_write_pipe:
2176     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2177         SemaBuiltinReserveRWPipe(*this, TheCall))
2178       return ExprError();
2179     break;
2180   case Builtin::BIcommit_read_pipe:
2181   case Builtin::BIcommit_write_pipe:
2182   case Builtin::BIwork_group_commit_read_pipe:
2183   case Builtin::BIwork_group_commit_write_pipe:
2184     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2185       return ExprError();
2186     break;
2187   case Builtin::BIsub_group_commit_read_pipe:
2188   case Builtin::BIsub_group_commit_write_pipe:
2189     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2190         SemaBuiltinCommitRWPipe(*this, TheCall))
2191       return ExprError();
2192     break;
2193   case Builtin::BIget_pipe_num_packets:
2194   case Builtin::BIget_pipe_max_packets:
2195     if (SemaBuiltinPipePackets(*this, TheCall))
2196       return ExprError();
2197     break;
2198   case Builtin::BIto_global:
2199   case Builtin::BIto_local:
2200   case Builtin::BIto_private:
2201     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2202       return ExprError();
2203     break;
2204   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2205   case Builtin::BIenqueue_kernel:
2206     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2207       return ExprError();
2208     break;
2209   case Builtin::BIget_kernel_work_group_size:
2210   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2211     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2212       return ExprError();
2213     break;
2214   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2215   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2216     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2217       return ExprError();
2218     break;
2219   case Builtin::BI__builtin_os_log_format:
2220     Cleanup.setExprNeedsCleanups(true);
2221     LLVM_FALLTHROUGH;
2222   case Builtin::BI__builtin_os_log_format_buffer_size:
2223     if (SemaBuiltinOSLogFormat(TheCall))
2224       return ExprError();
2225     break;
2226   case Builtin::BI__builtin_frame_address:
2227   case Builtin::BI__builtin_return_address: {
2228     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2229       return ExprError();
2230 
2231     // -Wframe-address warning if non-zero passed to builtin
2232     // return/frame address.
2233     Expr::EvalResult Result;
2234     if (!TheCall->getArg(0)->isValueDependent() &&
2235         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2236         Result.Val.getInt() != 0)
2237       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2238           << ((BuiltinID == Builtin::BI__builtin_return_address)
2239                   ? "__builtin_return_address"
2240                   : "__builtin_frame_address")
2241           << TheCall->getSourceRange();
2242     break;
2243   }
2244 
2245   // __builtin_elementwise_abs restricts the element type to signed integers or
2246   // floating point types only.
2247   case Builtin::BI__builtin_elementwise_abs: {
2248     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2249       return ExprError();
2250 
2251     QualType ArgTy = TheCall->getArg(0)->getType();
2252     QualType EltTy = ArgTy;
2253 
2254     if (auto *VecTy = EltTy->getAs<VectorType>())
2255       EltTy = VecTy->getElementType();
2256     if (EltTy->isUnsignedIntegerType()) {
2257       Diag(TheCall->getArg(0)->getBeginLoc(),
2258            diag::err_builtin_invalid_arg_type)
2259           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2260       return ExprError();
2261     }
2262     break;
2263   }
2264 
2265   // These builtins restrict the element type to floating point
2266   // types only.
2267   case Builtin::BI__builtin_elementwise_ceil:
2268   case Builtin::BI__builtin_elementwise_floor:
2269   case Builtin::BI__builtin_elementwise_roundeven:
2270   case Builtin::BI__builtin_elementwise_trunc: {
2271     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2272       return ExprError();
2273 
2274     QualType ArgTy = TheCall->getArg(0)->getType();
2275     QualType EltTy = ArgTy;
2276 
2277     if (auto *VecTy = EltTy->getAs<VectorType>())
2278       EltTy = VecTy->getElementType();
2279     if (!EltTy->isFloatingType()) {
2280       Diag(TheCall->getArg(0)->getBeginLoc(),
2281            diag::err_builtin_invalid_arg_type)
2282           << 1 << /* float ty*/ 5 << ArgTy;
2283 
2284       return ExprError();
2285     }
2286     break;
2287   }
2288 
2289   // These builtins restrict the element type to integer
2290   // types only.
2291   case Builtin::BI__builtin_elementwise_add_sat:
2292   case Builtin::BI__builtin_elementwise_sub_sat: {
2293     if (SemaBuiltinElementwiseMath(TheCall))
2294       return ExprError();
2295 
2296     const Expr *Arg = TheCall->getArg(0);
2297     QualType ArgTy = Arg->getType();
2298     QualType EltTy = ArgTy;
2299 
2300     if (auto *VecTy = EltTy->getAs<VectorType>())
2301       EltTy = VecTy->getElementType();
2302 
2303     if (!EltTy->isIntegerType()) {
2304       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2305           << 1 << /* integer ty */ 6 << ArgTy;
2306       return ExprError();
2307     }
2308     break;
2309   }
2310 
2311   case Builtin::BI__builtin_elementwise_min:
2312   case Builtin::BI__builtin_elementwise_max:
2313     if (SemaBuiltinElementwiseMath(TheCall))
2314       return ExprError();
2315     break;
2316   case Builtin::BI__builtin_reduce_max:
2317   case Builtin::BI__builtin_reduce_min: {
2318     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2319       return ExprError();
2320 
2321     const Expr *Arg = TheCall->getArg(0);
2322     const auto *TyA = Arg->getType()->getAs<VectorType>();
2323     if (!TyA) {
2324       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2325           << 1 << /* vector ty*/ 4 << Arg->getType();
2326       return ExprError();
2327     }
2328 
2329     TheCall->setType(TyA->getElementType());
2330     break;
2331   }
2332 
2333   // These builtins support vectors of integers only.
2334   case Builtin::BI__builtin_reduce_xor:
2335   case Builtin::BI__builtin_reduce_or:
2336   case Builtin::BI__builtin_reduce_and: {
2337     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2338       return ExprError();
2339 
2340     const Expr *Arg = TheCall->getArg(0);
2341     const auto *TyA = Arg->getType()->getAs<VectorType>();
2342     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2343       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2344           << 1  << /* vector of integers */ 6 << Arg->getType();
2345       return ExprError();
2346     }
2347     TheCall->setType(TyA->getElementType());
2348     break;
2349   }
2350 
2351   case Builtin::BI__builtin_matrix_transpose:
2352     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2353 
2354   case Builtin::BI__builtin_matrix_column_major_load:
2355     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2356 
2357   case Builtin::BI__builtin_matrix_column_major_store:
2358     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2359 
2360   case Builtin::BI__builtin_get_device_side_mangled_name: {
2361     auto Check = [](CallExpr *TheCall) {
2362       if (TheCall->getNumArgs() != 1)
2363         return false;
2364       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2365       if (!DRE)
2366         return false;
2367       auto *D = DRE->getDecl();
2368       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2369         return false;
2370       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2371              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2372     };
2373     if (!Check(TheCall)) {
2374       Diag(TheCall->getBeginLoc(),
2375            diag::err_hip_invalid_args_builtin_mangled_name);
2376       return ExprError();
2377     }
2378   }
2379   }
2380 
2381   // Since the target specific builtins for each arch overlap, only check those
2382   // of the arch we are compiling for.
2383   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2384     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2385       assert(Context.getAuxTargetInfo() &&
2386              "Aux Target Builtin, but not an aux target?");
2387 
2388       if (CheckTSBuiltinFunctionCall(
2389               *Context.getAuxTargetInfo(),
2390               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2391         return ExprError();
2392     } else {
2393       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2394                                      TheCall))
2395         return ExprError();
2396     }
2397   }
2398 
2399   return TheCallResult;
2400 }
2401 
2402 // Get the valid immediate range for the specified NEON type code.
2403 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2404   NeonTypeFlags Type(t);
2405   int IsQuad = ForceQuad ? true : Type.isQuad();
2406   switch (Type.getEltType()) {
2407   case NeonTypeFlags::Int8:
2408   case NeonTypeFlags::Poly8:
2409     return shift ? 7 : (8 << IsQuad) - 1;
2410   case NeonTypeFlags::Int16:
2411   case NeonTypeFlags::Poly16:
2412     return shift ? 15 : (4 << IsQuad) - 1;
2413   case NeonTypeFlags::Int32:
2414     return shift ? 31 : (2 << IsQuad) - 1;
2415   case NeonTypeFlags::Int64:
2416   case NeonTypeFlags::Poly64:
2417     return shift ? 63 : (1 << IsQuad) - 1;
2418   case NeonTypeFlags::Poly128:
2419     return shift ? 127 : (1 << IsQuad) - 1;
2420   case NeonTypeFlags::Float16:
2421     assert(!shift && "cannot shift float types!");
2422     return (4 << IsQuad) - 1;
2423   case NeonTypeFlags::Float32:
2424     assert(!shift && "cannot shift float types!");
2425     return (2 << IsQuad) - 1;
2426   case NeonTypeFlags::Float64:
2427     assert(!shift && "cannot shift float types!");
2428     return (1 << IsQuad) - 1;
2429   case NeonTypeFlags::BFloat16:
2430     assert(!shift && "cannot shift float types!");
2431     return (4 << IsQuad) - 1;
2432   }
2433   llvm_unreachable("Invalid NeonTypeFlag!");
2434 }
2435 
2436 /// getNeonEltType - Return the QualType corresponding to the elements of
2437 /// the vector type specified by the NeonTypeFlags.  This is used to check
2438 /// the pointer arguments for Neon load/store intrinsics.
2439 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2440                                bool IsPolyUnsigned, bool IsInt64Long) {
2441   switch (Flags.getEltType()) {
2442   case NeonTypeFlags::Int8:
2443     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2444   case NeonTypeFlags::Int16:
2445     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2446   case NeonTypeFlags::Int32:
2447     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2448   case NeonTypeFlags::Int64:
2449     if (IsInt64Long)
2450       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2451     else
2452       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2453                                 : Context.LongLongTy;
2454   case NeonTypeFlags::Poly8:
2455     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2456   case NeonTypeFlags::Poly16:
2457     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2458   case NeonTypeFlags::Poly64:
2459     if (IsInt64Long)
2460       return Context.UnsignedLongTy;
2461     else
2462       return Context.UnsignedLongLongTy;
2463   case NeonTypeFlags::Poly128:
2464     break;
2465   case NeonTypeFlags::Float16:
2466     return Context.HalfTy;
2467   case NeonTypeFlags::Float32:
2468     return Context.FloatTy;
2469   case NeonTypeFlags::Float64:
2470     return Context.DoubleTy;
2471   case NeonTypeFlags::BFloat16:
2472     return Context.BFloat16Ty;
2473   }
2474   llvm_unreachable("Invalid NeonTypeFlag!");
2475 }
2476 
2477 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2478   // Range check SVE intrinsics that take immediate values.
2479   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2480 
2481   switch (BuiltinID) {
2482   default:
2483     return false;
2484 #define GET_SVE_IMMEDIATE_CHECK
2485 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2486 #undef GET_SVE_IMMEDIATE_CHECK
2487   }
2488 
2489   // Perform all the immediate checks for this builtin call.
2490   bool HasError = false;
2491   for (auto &I : ImmChecks) {
2492     int ArgNum, CheckTy, ElementSizeInBits;
2493     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2494 
2495     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2496 
2497     // Function that checks whether the operand (ArgNum) is an immediate
2498     // that is one of the predefined values.
2499     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2500                                    int ErrDiag) -> bool {
2501       // We can't check the value of a dependent argument.
2502       Expr *Arg = TheCall->getArg(ArgNum);
2503       if (Arg->isTypeDependent() || Arg->isValueDependent())
2504         return false;
2505 
2506       // Check constant-ness first.
2507       llvm::APSInt Imm;
2508       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2509         return true;
2510 
2511       if (!CheckImm(Imm.getSExtValue()))
2512         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2513       return false;
2514     };
2515 
2516     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2517     case SVETypeFlags::ImmCheck0_31:
2518       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2519         HasError = true;
2520       break;
2521     case SVETypeFlags::ImmCheck0_13:
2522       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2523         HasError = true;
2524       break;
2525     case SVETypeFlags::ImmCheck1_16:
2526       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2527         HasError = true;
2528       break;
2529     case SVETypeFlags::ImmCheck0_7:
2530       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2531         HasError = true;
2532       break;
2533     case SVETypeFlags::ImmCheckExtract:
2534       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2535                                       (2048 / ElementSizeInBits) - 1))
2536         HasError = true;
2537       break;
2538     case SVETypeFlags::ImmCheckShiftRight:
2539       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2540         HasError = true;
2541       break;
2542     case SVETypeFlags::ImmCheckShiftRightNarrow:
2543       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2544                                       ElementSizeInBits / 2))
2545         HasError = true;
2546       break;
2547     case SVETypeFlags::ImmCheckShiftLeft:
2548       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2549                                       ElementSizeInBits - 1))
2550         HasError = true;
2551       break;
2552     case SVETypeFlags::ImmCheckLaneIndex:
2553       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2554                                       (128 / (1 * ElementSizeInBits)) - 1))
2555         HasError = true;
2556       break;
2557     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2558       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2559                                       (128 / (2 * ElementSizeInBits)) - 1))
2560         HasError = true;
2561       break;
2562     case SVETypeFlags::ImmCheckLaneIndexDot:
2563       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2564                                       (128 / (4 * ElementSizeInBits)) - 1))
2565         HasError = true;
2566       break;
2567     case SVETypeFlags::ImmCheckComplexRot90_270:
2568       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2569                               diag::err_rotation_argument_to_cadd))
2570         HasError = true;
2571       break;
2572     case SVETypeFlags::ImmCheckComplexRotAll90:
2573       if (CheckImmediateInSet(
2574               [](int64_t V) {
2575                 return V == 0 || V == 90 || V == 180 || V == 270;
2576               },
2577               diag::err_rotation_argument_to_cmla))
2578         HasError = true;
2579       break;
2580     case SVETypeFlags::ImmCheck0_1:
2581       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2582         HasError = true;
2583       break;
2584     case SVETypeFlags::ImmCheck0_2:
2585       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2586         HasError = true;
2587       break;
2588     case SVETypeFlags::ImmCheck0_3:
2589       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2590         HasError = true;
2591       break;
2592     }
2593   }
2594 
2595   return HasError;
2596 }
2597 
2598 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2599                                         unsigned BuiltinID, CallExpr *TheCall) {
2600   llvm::APSInt Result;
2601   uint64_t mask = 0;
2602   unsigned TV = 0;
2603   int PtrArgNum = -1;
2604   bool HasConstPtr = false;
2605   switch (BuiltinID) {
2606 #define GET_NEON_OVERLOAD_CHECK
2607 #include "clang/Basic/arm_neon.inc"
2608 #include "clang/Basic/arm_fp16.inc"
2609 #undef GET_NEON_OVERLOAD_CHECK
2610   }
2611 
2612   // For NEON intrinsics which are overloaded on vector element type, validate
2613   // the immediate which specifies which variant to emit.
2614   unsigned ImmArg = TheCall->getNumArgs()-1;
2615   if (mask) {
2616     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2617       return true;
2618 
2619     TV = Result.getLimitedValue(64);
2620     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2621       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2622              << TheCall->getArg(ImmArg)->getSourceRange();
2623   }
2624 
2625   if (PtrArgNum >= 0) {
2626     // Check that pointer arguments have the specified type.
2627     Expr *Arg = TheCall->getArg(PtrArgNum);
2628     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2629       Arg = ICE->getSubExpr();
2630     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2631     QualType RHSTy = RHS.get()->getType();
2632 
2633     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2634     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2635                           Arch == llvm::Triple::aarch64_32 ||
2636                           Arch == llvm::Triple::aarch64_be;
2637     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2638     QualType EltTy =
2639         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2640     if (HasConstPtr)
2641       EltTy = EltTy.withConst();
2642     QualType LHSTy = Context.getPointerType(EltTy);
2643     AssignConvertType ConvTy;
2644     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2645     if (RHS.isInvalid())
2646       return true;
2647     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2648                                  RHS.get(), AA_Assigning))
2649       return true;
2650   }
2651 
2652   // For NEON intrinsics which take an immediate value as part of the
2653   // instruction, range check them here.
2654   unsigned i = 0, l = 0, u = 0;
2655   switch (BuiltinID) {
2656   default:
2657     return false;
2658   #define GET_NEON_IMMEDIATE_CHECK
2659   #include "clang/Basic/arm_neon.inc"
2660   #include "clang/Basic/arm_fp16.inc"
2661   #undef GET_NEON_IMMEDIATE_CHECK
2662   }
2663 
2664   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2665 }
2666 
2667 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2668   switch (BuiltinID) {
2669   default:
2670     return false;
2671   #include "clang/Basic/arm_mve_builtin_sema.inc"
2672   }
2673 }
2674 
2675 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2676                                        CallExpr *TheCall) {
2677   bool Err = false;
2678   switch (BuiltinID) {
2679   default:
2680     return false;
2681 #include "clang/Basic/arm_cde_builtin_sema.inc"
2682   }
2683 
2684   if (Err)
2685     return true;
2686 
2687   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2688 }
2689 
2690 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2691                                         const Expr *CoprocArg, bool WantCDE) {
2692   if (isConstantEvaluated())
2693     return false;
2694 
2695   // We can't check the value of a dependent argument.
2696   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2697     return false;
2698 
2699   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2700   int64_t CoprocNo = CoprocNoAP.getExtValue();
2701   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2702 
2703   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2704   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2705 
2706   if (IsCDECoproc != WantCDE)
2707     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2708            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2709 
2710   return false;
2711 }
2712 
2713 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2714                                         unsigned MaxWidth) {
2715   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2716           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2717           BuiltinID == ARM::BI__builtin_arm_strex ||
2718           BuiltinID == ARM::BI__builtin_arm_stlex ||
2719           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2720           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2721           BuiltinID == AArch64::BI__builtin_arm_strex ||
2722           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2723          "unexpected ARM builtin");
2724   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2725                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2726                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2727                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2728 
2729   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2730 
2731   // Ensure that we have the proper number of arguments.
2732   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2733     return true;
2734 
2735   // Inspect the pointer argument of the atomic builtin.  This should always be
2736   // a pointer type, whose element is an integral scalar or pointer type.
2737   // Because it is a pointer type, we don't have to worry about any implicit
2738   // casts here.
2739   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2740   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2741   if (PointerArgRes.isInvalid())
2742     return true;
2743   PointerArg = PointerArgRes.get();
2744 
2745   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2746   if (!pointerType) {
2747     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2748         << PointerArg->getType() << PointerArg->getSourceRange();
2749     return true;
2750   }
2751 
2752   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2753   // task is to insert the appropriate casts into the AST. First work out just
2754   // what the appropriate type is.
2755   QualType ValType = pointerType->getPointeeType();
2756   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2757   if (IsLdrex)
2758     AddrType.addConst();
2759 
2760   // Issue a warning if the cast is dodgy.
2761   CastKind CastNeeded = CK_NoOp;
2762   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2763     CastNeeded = CK_BitCast;
2764     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2765         << PointerArg->getType() << Context.getPointerType(AddrType)
2766         << AA_Passing << PointerArg->getSourceRange();
2767   }
2768 
2769   // Finally, do the cast and replace the argument with the corrected version.
2770   AddrType = Context.getPointerType(AddrType);
2771   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2772   if (PointerArgRes.isInvalid())
2773     return true;
2774   PointerArg = PointerArgRes.get();
2775 
2776   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2777 
2778   // In general, we allow ints, floats and pointers to be loaded and stored.
2779   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2780       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2781     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2782         << PointerArg->getType() << PointerArg->getSourceRange();
2783     return true;
2784   }
2785 
2786   // But ARM doesn't have instructions to deal with 128-bit versions.
2787   if (Context.getTypeSize(ValType) > MaxWidth) {
2788     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2789     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2790         << PointerArg->getType() << PointerArg->getSourceRange();
2791     return true;
2792   }
2793 
2794   switch (ValType.getObjCLifetime()) {
2795   case Qualifiers::OCL_None:
2796   case Qualifiers::OCL_ExplicitNone:
2797     // okay
2798     break;
2799 
2800   case Qualifiers::OCL_Weak:
2801   case Qualifiers::OCL_Strong:
2802   case Qualifiers::OCL_Autoreleasing:
2803     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2804         << ValType << PointerArg->getSourceRange();
2805     return true;
2806   }
2807 
2808   if (IsLdrex) {
2809     TheCall->setType(ValType);
2810     return false;
2811   }
2812 
2813   // Initialize the argument to be stored.
2814   ExprResult ValArg = TheCall->getArg(0);
2815   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2816       Context, ValType, /*consume*/ false);
2817   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2818   if (ValArg.isInvalid())
2819     return true;
2820   TheCall->setArg(0, ValArg.get());
2821 
2822   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2823   // but the custom checker bypasses all default analysis.
2824   TheCall->setType(Context.IntTy);
2825   return false;
2826 }
2827 
2828 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2829                                        CallExpr *TheCall) {
2830   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2831       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2832       BuiltinID == ARM::BI__builtin_arm_strex ||
2833       BuiltinID == ARM::BI__builtin_arm_stlex) {
2834     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2835   }
2836 
2837   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2838     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2839       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2840   }
2841 
2842   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2843       BuiltinID == ARM::BI__builtin_arm_wsr64)
2844     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2845 
2846   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2847       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2848       BuiltinID == ARM::BI__builtin_arm_wsr ||
2849       BuiltinID == ARM::BI__builtin_arm_wsrp)
2850     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2851 
2852   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2853     return true;
2854   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2855     return true;
2856   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2857     return true;
2858 
2859   // For intrinsics which take an immediate value as part of the instruction,
2860   // range check them here.
2861   // FIXME: VFP Intrinsics should error if VFP not present.
2862   switch (BuiltinID) {
2863   default: return false;
2864   case ARM::BI__builtin_arm_ssat:
2865     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2866   case ARM::BI__builtin_arm_usat:
2867     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2868   case ARM::BI__builtin_arm_ssat16:
2869     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2870   case ARM::BI__builtin_arm_usat16:
2871     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2872   case ARM::BI__builtin_arm_vcvtr_f:
2873   case ARM::BI__builtin_arm_vcvtr_d:
2874     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2875   case ARM::BI__builtin_arm_dmb:
2876   case ARM::BI__builtin_arm_dsb:
2877   case ARM::BI__builtin_arm_isb:
2878   case ARM::BI__builtin_arm_dbg:
2879     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2880   case ARM::BI__builtin_arm_cdp:
2881   case ARM::BI__builtin_arm_cdp2:
2882   case ARM::BI__builtin_arm_mcr:
2883   case ARM::BI__builtin_arm_mcr2:
2884   case ARM::BI__builtin_arm_mrc:
2885   case ARM::BI__builtin_arm_mrc2:
2886   case ARM::BI__builtin_arm_mcrr:
2887   case ARM::BI__builtin_arm_mcrr2:
2888   case ARM::BI__builtin_arm_mrrc:
2889   case ARM::BI__builtin_arm_mrrc2:
2890   case ARM::BI__builtin_arm_ldc:
2891   case ARM::BI__builtin_arm_ldcl:
2892   case ARM::BI__builtin_arm_ldc2:
2893   case ARM::BI__builtin_arm_ldc2l:
2894   case ARM::BI__builtin_arm_stc:
2895   case ARM::BI__builtin_arm_stcl:
2896   case ARM::BI__builtin_arm_stc2:
2897   case ARM::BI__builtin_arm_stc2l:
2898     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2899            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2900                                         /*WantCDE*/ false);
2901   }
2902 }
2903 
2904 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2905                                            unsigned BuiltinID,
2906                                            CallExpr *TheCall) {
2907   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2908       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2909       BuiltinID == AArch64::BI__builtin_arm_strex ||
2910       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2911     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2912   }
2913 
2914   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2915     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2916       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2917       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2918       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2919   }
2920 
2921   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2922       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2923     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2924 
2925   // Memory Tagging Extensions (MTE) Intrinsics
2926   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2927       BuiltinID == AArch64::BI__builtin_arm_addg ||
2928       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2929       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2930       BuiltinID == AArch64::BI__builtin_arm_stg ||
2931       BuiltinID == AArch64::BI__builtin_arm_subp) {
2932     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2933   }
2934 
2935   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2936       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2937       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2938       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2939     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2940 
2941   // Only check the valid encoding range. Any constant in this range would be
2942   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2943   // an exception for incorrect registers. This matches MSVC behavior.
2944   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2945       BuiltinID == AArch64::BI_WriteStatusReg)
2946     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2947 
2948   if (BuiltinID == AArch64::BI__getReg)
2949     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2950 
2951   if (BuiltinID == AArch64::BI__break)
2952     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xffff);
2953 
2954   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2955     return true;
2956 
2957   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2958     return true;
2959 
2960   // For intrinsics which take an immediate value as part of the instruction,
2961   // range check them here.
2962   unsigned i = 0, l = 0, u = 0;
2963   switch (BuiltinID) {
2964   default: return false;
2965   case AArch64::BI__builtin_arm_dmb:
2966   case AArch64::BI__builtin_arm_dsb:
2967   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2968   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2969   }
2970 
2971   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2972 }
2973 
2974 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2975   if (Arg->getType()->getAsPlaceholderType())
2976     return false;
2977 
2978   // The first argument needs to be a record field access.
2979   // If it is an array element access, we delay decision
2980   // to BPF backend to check whether the access is a
2981   // field access or not.
2982   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2983           isa<MemberExpr>(Arg->IgnoreParens()) ||
2984           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2985 }
2986 
2987 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2988                             QualType VectorTy, QualType EltTy) {
2989   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2990   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2991     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2992         << Call->getSourceRange() << VectorEltTy << EltTy;
2993     return false;
2994   }
2995   return true;
2996 }
2997 
2998 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2999   QualType ArgType = Arg->getType();
3000   if (ArgType->getAsPlaceholderType())
3001     return false;
3002 
3003   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
3004   // format:
3005   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
3006   //   2. <type> var;
3007   //      __builtin_preserve_type_info(var, flag);
3008   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
3009       !isa<UnaryOperator>(Arg->IgnoreParens()))
3010     return false;
3011 
3012   // Typedef type.
3013   if (ArgType->getAs<TypedefType>())
3014     return true;
3015 
3016   // Record type or Enum type.
3017   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3018   if (const auto *RT = Ty->getAs<RecordType>()) {
3019     if (!RT->getDecl()->getDeclName().isEmpty())
3020       return true;
3021   } else if (const auto *ET = Ty->getAs<EnumType>()) {
3022     if (!ET->getDecl()->getDeclName().isEmpty())
3023       return true;
3024   }
3025 
3026   return false;
3027 }
3028 
3029 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
3030   QualType ArgType = Arg->getType();
3031   if (ArgType->getAsPlaceholderType())
3032     return false;
3033 
3034   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
3035   // format:
3036   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
3037   //                                 flag);
3038   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
3039   if (!UO)
3040     return false;
3041 
3042   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
3043   if (!CE)
3044     return false;
3045   if (CE->getCastKind() != CK_IntegralToPointer &&
3046       CE->getCastKind() != CK_NullToPointer)
3047     return false;
3048 
3049   // The integer must be from an EnumConstantDecl.
3050   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3051   if (!DR)
3052     return false;
3053 
3054   const EnumConstantDecl *Enumerator =
3055       dyn_cast<EnumConstantDecl>(DR->getDecl());
3056   if (!Enumerator)
3057     return false;
3058 
3059   // The type must be EnumType.
3060   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3061   const auto *ET = Ty->getAs<EnumType>();
3062   if (!ET)
3063     return false;
3064 
3065   // The enum value must be supported.
3066   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3067 }
3068 
3069 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3070                                        CallExpr *TheCall) {
3071   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3072           BuiltinID == BPF::BI__builtin_btf_type_id ||
3073           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3074           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3075          "unexpected BPF builtin");
3076 
3077   if (checkArgCount(*this, TheCall, 2))
3078     return true;
3079 
3080   // The second argument needs to be a constant int
3081   Expr *Arg = TheCall->getArg(1);
3082   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3083   diag::kind kind;
3084   if (!Value) {
3085     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3086       kind = diag::err_preserve_field_info_not_const;
3087     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3088       kind = diag::err_btf_type_id_not_const;
3089     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3090       kind = diag::err_preserve_type_info_not_const;
3091     else
3092       kind = diag::err_preserve_enum_value_not_const;
3093     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3094     return true;
3095   }
3096 
3097   // The first argument
3098   Arg = TheCall->getArg(0);
3099   bool InvalidArg = false;
3100   bool ReturnUnsignedInt = true;
3101   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3102     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3103       InvalidArg = true;
3104       kind = diag::err_preserve_field_info_not_field;
3105     }
3106   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3107     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3108       InvalidArg = true;
3109       kind = diag::err_preserve_type_info_invalid;
3110     }
3111   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3112     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3113       InvalidArg = true;
3114       kind = diag::err_preserve_enum_value_invalid;
3115     }
3116     ReturnUnsignedInt = false;
3117   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3118     ReturnUnsignedInt = false;
3119   }
3120 
3121   if (InvalidArg) {
3122     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3123     return true;
3124   }
3125 
3126   if (ReturnUnsignedInt)
3127     TheCall->setType(Context.UnsignedIntTy);
3128   else
3129     TheCall->setType(Context.UnsignedLongTy);
3130   return false;
3131 }
3132 
3133 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3134   struct ArgInfo {
3135     uint8_t OpNum;
3136     bool IsSigned;
3137     uint8_t BitWidth;
3138     uint8_t Align;
3139   };
3140   struct BuiltinInfo {
3141     unsigned BuiltinID;
3142     ArgInfo Infos[2];
3143   };
3144 
3145   static BuiltinInfo Infos[] = {
3146     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3147     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3148     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3149     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3150     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3151     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3152     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3153     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3154     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3155     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3156     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3157 
3158     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3160     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3161     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3162     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3163     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3164     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3165     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3166     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3167     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3168     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3169 
3170     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3171     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3177     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3179     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3185     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3186     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3188     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3192     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3194     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3196     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3197     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3198     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3201     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3209     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3210     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3212     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3215     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3216     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3218     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3219     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3221     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3222                                                       {{ 1, false, 6,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3224     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3225     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3226     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3227     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3228     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3229     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3230                                                       {{ 1, false, 5,  0 }} },
3231     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3232     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3233     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3234     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3235     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3236     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3237                                                        { 2, false, 5,  0 }} },
3238     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3239                                                        { 2, false, 6,  0 }} },
3240     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3241                                                        { 3, false, 5,  0 }} },
3242     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3243                                                        { 3, false, 6,  0 }} },
3244     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3245     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3246     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3247     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3248     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3249     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3250     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3251     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3252     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3253     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3254     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3255     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3256     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3257     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3258     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3259     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3260                                                       {{ 2, false, 4,  0 },
3261                                                        { 3, false, 5,  0 }} },
3262     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3263                                                       {{ 2, false, 4,  0 },
3264                                                        { 3, false, 5,  0 }} },
3265     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3266                                                       {{ 2, false, 4,  0 },
3267                                                        { 3, false, 5,  0 }} },
3268     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3269                                                       {{ 2, false, 4,  0 },
3270                                                        { 3, false, 5,  0 }} },
3271     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3272     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3273     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3274     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3275     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3276     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3277     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3278     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3279     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3280     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3281     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3282                                                        { 2, false, 5,  0 }} },
3283     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3284                                                        { 2, false, 6,  0 }} },
3285     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3286     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3287     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3288     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3289     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3290     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3291     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3292     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3293     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3294                                                       {{ 1, false, 4,  0 }} },
3295     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3296     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3297                                                       {{ 1, false, 4,  0 }} },
3298     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3299     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3300     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3301     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3302     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3303     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3304     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3305     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3306     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3307     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3308     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3309     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3310     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3311     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3312     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3313     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3314     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3315     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3316     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3317     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3318                                                       {{ 3, false, 1,  0 }} },
3319     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3320     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3321     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3322     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3323                                                       {{ 3, false, 1,  0 }} },
3324     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3325     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3326     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3327     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3328                                                       {{ 3, false, 1,  0 }} },
3329   };
3330 
3331   // Use a dynamically initialized static to sort the table exactly once on
3332   // first run.
3333   static const bool SortOnce =
3334       (llvm::sort(Infos,
3335                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3336                    return LHS.BuiltinID < RHS.BuiltinID;
3337                  }),
3338        true);
3339   (void)SortOnce;
3340 
3341   const BuiltinInfo *F = llvm::partition_point(
3342       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3343   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3344     return false;
3345 
3346   bool Error = false;
3347 
3348   for (const ArgInfo &A : F->Infos) {
3349     // Ignore empty ArgInfo elements.
3350     if (A.BitWidth == 0)
3351       continue;
3352 
3353     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3354     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3355     if (!A.Align) {
3356       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3357     } else {
3358       unsigned M = 1 << A.Align;
3359       Min *= M;
3360       Max *= M;
3361       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3362       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3363     }
3364   }
3365   return Error;
3366 }
3367 
3368 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3369                                            CallExpr *TheCall) {
3370   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3371 }
3372 
3373 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3374                                         unsigned BuiltinID, CallExpr *TheCall) {
3375   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3376          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3377 }
3378 
3379 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3380                                CallExpr *TheCall) {
3381 
3382   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3383       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3384     if (!TI.hasFeature("dsp"))
3385       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3386   }
3387 
3388   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3389       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3390     if (!TI.hasFeature("dspr2"))
3391       return Diag(TheCall->getBeginLoc(),
3392                   diag::err_mips_builtin_requires_dspr2);
3393   }
3394 
3395   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3396       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3397     if (!TI.hasFeature("msa"))
3398       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3399   }
3400 
3401   return false;
3402 }
3403 
3404 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3405 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3406 // ordering for DSP is unspecified. MSA is ordered by the data format used
3407 // by the underlying instruction i.e., df/m, df/n and then by size.
3408 //
3409 // FIXME: The size tests here should instead be tablegen'd along with the
3410 //        definitions from include/clang/Basic/BuiltinsMips.def.
3411 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3412 //        be too.
3413 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3414   unsigned i = 0, l = 0, u = 0, m = 0;
3415   switch (BuiltinID) {
3416   default: return false;
3417   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3418   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3419   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3420   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3421   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3422   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3423   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3424   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3425   // df/m field.
3426   // These intrinsics take an unsigned 3 bit immediate.
3427   case Mips::BI__builtin_msa_bclri_b:
3428   case Mips::BI__builtin_msa_bnegi_b:
3429   case Mips::BI__builtin_msa_bseti_b:
3430   case Mips::BI__builtin_msa_sat_s_b:
3431   case Mips::BI__builtin_msa_sat_u_b:
3432   case Mips::BI__builtin_msa_slli_b:
3433   case Mips::BI__builtin_msa_srai_b:
3434   case Mips::BI__builtin_msa_srari_b:
3435   case Mips::BI__builtin_msa_srli_b:
3436   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3437   case Mips::BI__builtin_msa_binsli_b:
3438   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3439   // These intrinsics take an unsigned 4 bit immediate.
3440   case Mips::BI__builtin_msa_bclri_h:
3441   case Mips::BI__builtin_msa_bnegi_h:
3442   case Mips::BI__builtin_msa_bseti_h:
3443   case Mips::BI__builtin_msa_sat_s_h:
3444   case Mips::BI__builtin_msa_sat_u_h:
3445   case Mips::BI__builtin_msa_slli_h:
3446   case Mips::BI__builtin_msa_srai_h:
3447   case Mips::BI__builtin_msa_srari_h:
3448   case Mips::BI__builtin_msa_srli_h:
3449   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3450   case Mips::BI__builtin_msa_binsli_h:
3451   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3452   // These intrinsics take an unsigned 5 bit immediate.
3453   // The first block of intrinsics actually have an unsigned 5 bit field,
3454   // not a df/n field.
3455   case Mips::BI__builtin_msa_cfcmsa:
3456   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3457   case Mips::BI__builtin_msa_clei_u_b:
3458   case Mips::BI__builtin_msa_clei_u_h:
3459   case Mips::BI__builtin_msa_clei_u_w:
3460   case Mips::BI__builtin_msa_clei_u_d:
3461   case Mips::BI__builtin_msa_clti_u_b:
3462   case Mips::BI__builtin_msa_clti_u_h:
3463   case Mips::BI__builtin_msa_clti_u_w:
3464   case Mips::BI__builtin_msa_clti_u_d:
3465   case Mips::BI__builtin_msa_maxi_u_b:
3466   case Mips::BI__builtin_msa_maxi_u_h:
3467   case Mips::BI__builtin_msa_maxi_u_w:
3468   case Mips::BI__builtin_msa_maxi_u_d:
3469   case Mips::BI__builtin_msa_mini_u_b:
3470   case Mips::BI__builtin_msa_mini_u_h:
3471   case Mips::BI__builtin_msa_mini_u_w:
3472   case Mips::BI__builtin_msa_mini_u_d:
3473   case Mips::BI__builtin_msa_addvi_b:
3474   case Mips::BI__builtin_msa_addvi_h:
3475   case Mips::BI__builtin_msa_addvi_w:
3476   case Mips::BI__builtin_msa_addvi_d:
3477   case Mips::BI__builtin_msa_bclri_w:
3478   case Mips::BI__builtin_msa_bnegi_w:
3479   case Mips::BI__builtin_msa_bseti_w:
3480   case Mips::BI__builtin_msa_sat_s_w:
3481   case Mips::BI__builtin_msa_sat_u_w:
3482   case Mips::BI__builtin_msa_slli_w:
3483   case Mips::BI__builtin_msa_srai_w:
3484   case Mips::BI__builtin_msa_srari_w:
3485   case Mips::BI__builtin_msa_srli_w:
3486   case Mips::BI__builtin_msa_srlri_w:
3487   case Mips::BI__builtin_msa_subvi_b:
3488   case Mips::BI__builtin_msa_subvi_h:
3489   case Mips::BI__builtin_msa_subvi_w:
3490   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3491   case Mips::BI__builtin_msa_binsli_w:
3492   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3493   // These intrinsics take an unsigned 6 bit immediate.
3494   case Mips::BI__builtin_msa_bclri_d:
3495   case Mips::BI__builtin_msa_bnegi_d:
3496   case Mips::BI__builtin_msa_bseti_d:
3497   case Mips::BI__builtin_msa_sat_s_d:
3498   case Mips::BI__builtin_msa_sat_u_d:
3499   case Mips::BI__builtin_msa_slli_d:
3500   case Mips::BI__builtin_msa_srai_d:
3501   case Mips::BI__builtin_msa_srari_d:
3502   case Mips::BI__builtin_msa_srli_d:
3503   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3504   case Mips::BI__builtin_msa_binsli_d:
3505   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3506   // These intrinsics take a signed 5 bit immediate.
3507   case Mips::BI__builtin_msa_ceqi_b:
3508   case Mips::BI__builtin_msa_ceqi_h:
3509   case Mips::BI__builtin_msa_ceqi_w:
3510   case Mips::BI__builtin_msa_ceqi_d:
3511   case Mips::BI__builtin_msa_clti_s_b:
3512   case Mips::BI__builtin_msa_clti_s_h:
3513   case Mips::BI__builtin_msa_clti_s_w:
3514   case Mips::BI__builtin_msa_clti_s_d:
3515   case Mips::BI__builtin_msa_clei_s_b:
3516   case Mips::BI__builtin_msa_clei_s_h:
3517   case Mips::BI__builtin_msa_clei_s_w:
3518   case Mips::BI__builtin_msa_clei_s_d:
3519   case Mips::BI__builtin_msa_maxi_s_b:
3520   case Mips::BI__builtin_msa_maxi_s_h:
3521   case Mips::BI__builtin_msa_maxi_s_w:
3522   case Mips::BI__builtin_msa_maxi_s_d:
3523   case Mips::BI__builtin_msa_mini_s_b:
3524   case Mips::BI__builtin_msa_mini_s_h:
3525   case Mips::BI__builtin_msa_mini_s_w:
3526   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3527   // These intrinsics take an unsigned 8 bit immediate.
3528   case Mips::BI__builtin_msa_andi_b:
3529   case Mips::BI__builtin_msa_nori_b:
3530   case Mips::BI__builtin_msa_ori_b:
3531   case Mips::BI__builtin_msa_shf_b:
3532   case Mips::BI__builtin_msa_shf_h:
3533   case Mips::BI__builtin_msa_shf_w:
3534   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3535   case Mips::BI__builtin_msa_bseli_b:
3536   case Mips::BI__builtin_msa_bmnzi_b:
3537   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3538   // df/n format
3539   // These intrinsics take an unsigned 4 bit immediate.
3540   case Mips::BI__builtin_msa_copy_s_b:
3541   case Mips::BI__builtin_msa_copy_u_b:
3542   case Mips::BI__builtin_msa_insve_b:
3543   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3544   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3545   // These intrinsics take an unsigned 3 bit immediate.
3546   case Mips::BI__builtin_msa_copy_s_h:
3547   case Mips::BI__builtin_msa_copy_u_h:
3548   case Mips::BI__builtin_msa_insve_h:
3549   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3550   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3551   // These intrinsics take an unsigned 2 bit immediate.
3552   case Mips::BI__builtin_msa_copy_s_w:
3553   case Mips::BI__builtin_msa_copy_u_w:
3554   case Mips::BI__builtin_msa_insve_w:
3555   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3556   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3557   // These intrinsics take an unsigned 1 bit immediate.
3558   case Mips::BI__builtin_msa_copy_s_d:
3559   case Mips::BI__builtin_msa_copy_u_d:
3560   case Mips::BI__builtin_msa_insve_d:
3561   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3562   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3563   // Memory offsets and immediate loads.
3564   // These intrinsics take a signed 10 bit immediate.
3565   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3566   case Mips::BI__builtin_msa_ldi_h:
3567   case Mips::BI__builtin_msa_ldi_w:
3568   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3569   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3570   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3571   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3572   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3573   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3574   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3575   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3576   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3577   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3578   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3579   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3580   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3581   }
3582 
3583   if (!m)
3584     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3585 
3586   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3587          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3588 }
3589 
3590 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3591 /// advancing the pointer over the consumed characters. The decoded type is
3592 /// returned. If the decoded type represents a constant integer with a
3593 /// constraint on its value then Mask is set to that value. The type descriptors
3594 /// used in Str are specific to PPC MMA builtins and are documented in the file
3595 /// defining the PPC builtins.
3596 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3597                                         unsigned &Mask) {
3598   bool RequireICE = false;
3599   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3600   switch (*Str++) {
3601   case 'V':
3602     return Context.getVectorType(Context.UnsignedCharTy, 16,
3603                                  VectorType::VectorKind::AltiVecVector);
3604   case 'i': {
3605     char *End;
3606     unsigned size = strtoul(Str, &End, 10);
3607     assert(End != Str && "Missing constant parameter constraint");
3608     Str = End;
3609     Mask = size;
3610     return Context.IntTy;
3611   }
3612   case 'W': {
3613     char *End;
3614     unsigned size = strtoul(Str, &End, 10);
3615     assert(End != Str && "Missing PowerPC MMA type size");
3616     Str = End;
3617     QualType Type;
3618     switch (size) {
3619   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3620     case size: Type = Context.Id##Ty; break;
3621   #include "clang/Basic/PPCTypes.def"
3622     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3623     }
3624     bool CheckVectorArgs = false;
3625     while (!CheckVectorArgs) {
3626       switch (*Str++) {
3627       case '*':
3628         Type = Context.getPointerType(Type);
3629         break;
3630       case 'C':
3631         Type = Type.withConst();
3632         break;
3633       default:
3634         CheckVectorArgs = true;
3635         --Str;
3636         break;
3637       }
3638     }
3639     return Type;
3640   }
3641   default:
3642     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3643   }
3644 }
3645 
3646 static bool isPPC_64Builtin(unsigned BuiltinID) {
3647   // These builtins only work on PPC 64bit targets.
3648   switch (BuiltinID) {
3649   case PPC::BI__builtin_divde:
3650   case PPC::BI__builtin_divdeu:
3651   case PPC::BI__builtin_bpermd:
3652   case PPC::BI__builtin_pdepd:
3653   case PPC::BI__builtin_pextd:
3654   case PPC::BI__builtin_ppc_ldarx:
3655   case PPC::BI__builtin_ppc_stdcx:
3656   case PPC::BI__builtin_ppc_tdw:
3657   case PPC::BI__builtin_ppc_trapd:
3658   case PPC::BI__builtin_ppc_cmpeqb:
3659   case PPC::BI__builtin_ppc_setb:
3660   case PPC::BI__builtin_ppc_mulhd:
3661   case PPC::BI__builtin_ppc_mulhdu:
3662   case PPC::BI__builtin_ppc_maddhd:
3663   case PPC::BI__builtin_ppc_maddhdu:
3664   case PPC::BI__builtin_ppc_maddld:
3665   case PPC::BI__builtin_ppc_load8r:
3666   case PPC::BI__builtin_ppc_store8r:
3667   case PPC::BI__builtin_ppc_insert_exp:
3668   case PPC::BI__builtin_ppc_extract_sig:
3669   case PPC::BI__builtin_ppc_addex:
3670   case PPC::BI__builtin_darn:
3671   case PPC::BI__builtin_darn_raw:
3672   case PPC::BI__builtin_ppc_compare_and_swaplp:
3673   case PPC::BI__builtin_ppc_fetch_and_addlp:
3674   case PPC::BI__builtin_ppc_fetch_and_andlp:
3675   case PPC::BI__builtin_ppc_fetch_and_orlp:
3676   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3677     return true;
3678   }
3679   return false;
3680 }
3681 
3682 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3683                              StringRef FeatureToCheck, unsigned DiagID,
3684                              StringRef DiagArg = "") {
3685   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3686     return false;
3687 
3688   if (DiagArg.empty())
3689     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3690   else
3691     S.Diag(TheCall->getBeginLoc(), DiagID)
3692         << DiagArg << TheCall->getSourceRange();
3693 
3694   return true;
3695 }
3696 
3697 /// Returns true if the argument consists of one contiguous run of 1s with any
3698 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3699 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3700 /// since all 1s are not contiguous.
3701 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3702   llvm::APSInt Result;
3703   // We can't check the value of a dependent argument.
3704   Expr *Arg = TheCall->getArg(ArgNum);
3705   if (Arg->isTypeDependent() || Arg->isValueDependent())
3706     return false;
3707 
3708   // Check constant-ness first.
3709   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3710     return true;
3711 
3712   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3713   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3714     return false;
3715 
3716   return Diag(TheCall->getBeginLoc(),
3717               diag::err_argument_not_contiguous_bit_field)
3718          << ArgNum << Arg->getSourceRange();
3719 }
3720 
3721 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3722                                        CallExpr *TheCall) {
3723   unsigned i = 0, l = 0, u = 0;
3724   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3725   llvm::APSInt Result;
3726 
3727   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3728     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3729            << TheCall->getSourceRange();
3730 
3731   switch (BuiltinID) {
3732   default: return false;
3733   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3734   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3735     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3736            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3737   case PPC::BI__builtin_altivec_dss:
3738     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3739   case PPC::BI__builtin_tbegin:
3740   case PPC::BI__builtin_tend:
3741     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3742            SemaFeatureCheck(*this, TheCall, "htm",
3743                             diag::err_ppc_builtin_requires_htm);
3744   case PPC::BI__builtin_tsr:
3745     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3746            SemaFeatureCheck(*this, TheCall, "htm",
3747                             diag::err_ppc_builtin_requires_htm);
3748   case PPC::BI__builtin_tabortwc:
3749   case PPC::BI__builtin_tabortdc:
3750     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3751            SemaFeatureCheck(*this, TheCall, "htm",
3752                             diag::err_ppc_builtin_requires_htm);
3753   case PPC::BI__builtin_tabortwci:
3754   case PPC::BI__builtin_tabortdci:
3755     return SemaFeatureCheck(*this, TheCall, "htm",
3756                             diag::err_ppc_builtin_requires_htm) ||
3757            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3758             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3759   case PPC::BI__builtin_tabort:
3760   case PPC::BI__builtin_tcheck:
3761   case PPC::BI__builtin_treclaim:
3762   case PPC::BI__builtin_trechkpt:
3763   case PPC::BI__builtin_tendall:
3764   case PPC::BI__builtin_tresume:
3765   case PPC::BI__builtin_tsuspend:
3766   case PPC::BI__builtin_get_texasr:
3767   case PPC::BI__builtin_get_texasru:
3768   case PPC::BI__builtin_get_tfhar:
3769   case PPC::BI__builtin_get_tfiar:
3770   case PPC::BI__builtin_set_texasr:
3771   case PPC::BI__builtin_set_texasru:
3772   case PPC::BI__builtin_set_tfhar:
3773   case PPC::BI__builtin_set_tfiar:
3774   case PPC::BI__builtin_ttest:
3775     return SemaFeatureCheck(*this, TheCall, "htm",
3776                             diag::err_ppc_builtin_requires_htm);
3777   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3778   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3779   // extended double representation.
3780   case PPC::BI__builtin_unpack_longdouble:
3781     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3782       return true;
3783     LLVM_FALLTHROUGH;
3784   case PPC::BI__builtin_pack_longdouble:
3785     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3786       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3787              << "ibmlongdouble";
3788     return false;
3789   case PPC::BI__builtin_altivec_dst:
3790   case PPC::BI__builtin_altivec_dstt:
3791   case PPC::BI__builtin_altivec_dstst:
3792   case PPC::BI__builtin_altivec_dststt:
3793     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3794   case PPC::BI__builtin_vsx_xxpermdi:
3795   case PPC::BI__builtin_vsx_xxsldwi:
3796     return SemaBuiltinVSX(TheCall);
3797   case PPC::BI__builtin_divwe:
3798   case PPC::BI__builtin_divweu:
3799   case PPC::BI__builtin_divde:
3800   case PPC::BI__builtin_divdeu:
3801     return SemaFeatureCheck(*this, TheCall, "extdiv",
3802                             diag::err_ppc_builtin_only_on_arch, "7");
3803   case PPC::BI__builtin_bpermd:
3804     return SemaFeatureCheck(*this, TheCall, "bpermd",
3805                             diag::err_ppc_builtin_only_on_arch, "7");
3806   case PPC::BI__builtin_unpack_vector_int128:
3807     return SemaFeatureCheck(*this, TheCall, "vsx",
3808                             diag::err_ppc_builtin_only_on_arch, "7") ||
3809            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3810   case PPC::BI__builtin_pack_vector_int128:
3811     return SemaFeatureCheck(*this, TheCall, "vsx",
3812                             diag::err_ppc_builtin_only_on_arch, "7");
3813   case PPC::BI__builtin_pdepd:
3814   case PPC::BI__builtin_pextd:
3815     return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
3816                             diag::err_ppc_builtin_only_on_arch, "10");
3817   case PPC::BI__builtin_altivec_vgnb:
3818      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3819   case PPC::BI__builtin_altivec_vec_replace_elt:
3820   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3821     QualType VecTy = TheCall->getArg(0)->getType();
3822     QualType EltTy = TheCall->getArg(1)->getType();
3823     unsigned Width = Context.getIntWidth(EltTy);
3824     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3825            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3826   }
3827   case PPC::BI__builtin_vsx_xxeval:
3828      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3829   case PPC::BI__builtin_altivec_vsldbi:
3830      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3831   case PPC::BI__builtin_altivec_vsrdbi:
3832      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3833   case PPC::BI__builtin_vsx_xxpermx:
3834      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3835   case PPC::BI__builtin_ppc_tw:
3836   case PPC::BI__builtin_ppc_tdw:
3837     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3838   case PPC::BI__builtin_ppc_cmpeqb:
3839   case PPC::BI__builtin_ppc_setb:
3840   case PPC::BI__builtin_ppc_maddhd:
3841   case PPC::BI__builtin_ppc_maddhdu:
3842   case PPC::BI__builtin_ppc_maddld:
3843     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3844                             diag::err_ppc_builtin_only_on_arch, "9");
3845   case PPC::BI__builtin_ppc_cmprb:
3846     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3847                             diag::err_ppc_builtin_only_on_arch, "9") ||
3848            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3849   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3850   // be a constant that represents a contiguous bit field.
3851   case PPC::BI__builtin_ppc_rlwnm:
3852     return SemaValueIsRunOfOnes(TheCall, 2);
3853   case PPC::BI__builtin_ppc_rlwimi:
3854   case PPC::BI__builtin_ppc_rldimi:
3855     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3856            SemaValueIsRunOfOnes(TheCall, 3);
3857   case PPC::BI__builtin_ppc_extract_exp:
3858   case PPC::BI__builtin_ppc_extract_sig:
3859   case PPC::BI__builtin_ppc_insert_exp:
3860     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3861                             diag::err_ppc_builtin_only_on_arch, "9");
3862   case PPC::BI__builtin_ppc_addex: {
3863     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3864                          diag::err_ppc_builtin_only_on_arch, "9") ||
3865         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3866       return true;
3867     // Output warning for reserved values 1 to 3.
3868     int ArgValue =
3869         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3870     if (ArgValue != 0)
3871       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3872           << ArgValue;
3873     return false;
3874   }
3875   case PPC::BI__builtin_ppc_mtfsb0:
3876   case PPC::BI__builtin_ppc_mtfsb1:
3877     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3878   case PPC::BI__builtin_ppc_mtfsf:
3879     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3880   case PPC::BI__builtin_ppc_mtfsfi:
3881     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3882            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3883   case PPC::BI__builtin_ppc_alignx:
3884     return SemaBuiltinConstantArgPower2(TheCall, 0);
3885   case PPC::BI__builtin_ppc_rdlam:
3886     return SemaValueIsRunOfOnes(TheCall, 2);
3887   case PPC::BI__builtin_ppc_icbt:
3888   case PPC::BI__builtin_ppc_sthcx:
3889   case PPC::BI__builtin_ppc_stbcx:
3890   case PPC::BI__builtin_ppc_lharx:
3891   case PPC::BI__builtin_ppc_lbarx:
3892     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3893                             diag::err_ppc_builtin_only_on_arch, "8");
3894   case PPC::BI__builtin_vsx_ldrmb:
3895   case PPC::BI__builtin_vsx_strmb:
3896     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3897                             diag::err_ppc_builtin_only_on_arch, "8") ||
3898            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3899   case PPC::BI__builtin_altivec_vcntmbb:
3900   case PPC::BI__builtin_altivec_vcntmbh:
3901   case PPC::BI__builtin_altivec_vcntmbw:
3902   case PPC::BI__builtin_altivec_vcntmbd:
3903     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3904   case PPC::BI__builtin_darn:
3905   case PPC::BI__builtin_darn_raw:
3906   case PPC::BI__builtin_darn_32:
3907     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3908                             diag::err_ppc_builtin_only_on_arch, "9");
3909   case PPC::BI__builtin_vsx_xxgenpcvbm:
3910   case PPC::BI__builtin_vsx_xxgenpcvhm:
3911   case PPC::BI__builtin_vsx_xxgenpcvwm:
3912   case PPC::BI__builtin_vsx_xxgenpcvdm:
3913     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3914   case PPC::BI__builtin_ppc_compare_exp_uo:
3915   case PPC::BI__builtin_ppc_compare_exp_lt:
3916   case PPC::BI__builtin_ppc_compare_exp_gt:
3917   case PPC::BI__builtin_ppc_compare_exp_eq:
3918     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3919                             diag::err_ppc_builtin_only_on_arch, "9") ||
3920            SemaFeatureCheck(*this, TheCall, "vsx",
3921                             diag::err_ppc_builtin_requires_vsx);
3922   case PPC::BI__builtin_ppc_test_data_class: {
3923     // Check if the first argument of the __builtin_ppc_test_data_class call is
3924     // valid. The argument must be either a 'float' or a 'double'.
3925     QualType ArgType = TheCall->getArg(0)->getType();
3926     if (ArgType != QualType(Context.FloatTy) &&
3927         ArgType != QualType(Context.DoubleTy))
3928       return Diag(TheCall->getBeginLoc(),
3929                   diag::err_ppc_invalid_test_data_class_type);
3930     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3931                             diag::err_ppc_builtin_only_on_arch, "9") ||
3932            SemaFeatureCheck(*this, TheCall, "vsx",
3933                             diag::err_ppc_builtin_requires_vsx) ||
3934            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3935   }
3936   case PPC::BI__builtin_ppc_maxfe:
3937   case PPC::BI__builtin_ppc_minfe:
3938   case PPC::BI__builtin_ppc_maxfl:
3939   case PPC::BI__builtin_ppc_minfl:
3940   case PPC::BI__builtin_ppc_maxfs:
3941   case PPC::BI__builtin_ppc_minfs: {
3942     if (Context.getTargetInfo().getTriple().isOSAIX() &&
3943         (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
3944          BuiltinID == PPC::BI__builtin_ppc_minfe))
3945       return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
3946              << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
3947              << false << Context.getTargetInfo().getTriple().str();
3948     // Argument type should be exact.
3949     QualType ArgType = QualType(Context.LongDoubleTy);
3950     if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
3951         BuiltinID == PPC::BI__builtin_ppc_minfl)
3952       ArgType = QualType(Context.DoubleTy);
3953     else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
3954              BuiltinID == PPC::BI__builtin_ppc_minfs)
3955       ArgType = QualType(Context.FloatTy);
3956     for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
3957       if (TheCall->getArg(I)->getType() != ArgType)
3958         return Diag(TheCall->getBeginLoc(),
3959                     diag::err_typecheck_convert_incompatible)
3960                << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
3961     return false;
3962   }
3963   case PPC::BI__builtin_ppc_load8r:
3964   case PPC::BI__builtin_ppc_store8r:
3965     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3966                             diag::err_ppc_builtin_only_on_arch, "7");
3967 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3968   case PPC::BI__builtin_##Name:                                                \
3969     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3970 #include "clang/Basic/BuiltinsPPC.def"
3971   }
3972   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3973 }
3974 
3975 // Check if the given type is a non-pointer PPC MMA type. This function is used
3976 // in Sema to prevent invalid uses of restricted PPC MMA types.
3977 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3978   if (Type->isPointerType() || Type->isArrayType())
3979     return false;
3980 
3981   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3982 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3983   if (false
3984 #include "clang/Basic/PPCTypes.def"
3985      ) {
3986     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3987     return true;
3988   }
3989   return false;
3990 }
3991 
3992 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3993                                           CallExpr *TheCall) {
3994   // position of memory order and scope arguments in the builtin
3995   unsigned OrderIndex, ScopeIndex;
3996   switch (BuiltinID) {
3997   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3998   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3999   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
4000   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
4001     OrderIndex = 2;
4002     ScopeIndex = 3;
4003     break;
4004   case AMDGPU::BI__builtin_amdgcn_fence:
4005     OrderIndex = 0;
4006     ScopeIndex = 1;
4007     break;
4008   default:
4009     return false;
4010   }
4011 
4012   ExprResult Arg = TheCall->getArg(OrderIndex);
4013   auto ArgExpr = Arg.get();
4014   Expr::EvalResult ArgResult;
4015 
4016   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
4017     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
4018            << ArgExpr->getType();
4019   auto Ord = ArgResult.Val.getInt().getZExtValue();
4020 
4021   // Check validity of memory ordering as per C11 / C++11's memody model.
4022   // Only fence needs check. Atomic dec/inc allow all memory orders.
4023   if (!llvm::isValidAtomicOrderingCABI(Ord))
4024     return Diag(ArgExpr->getBeginLoc(),
4025                 diag::warn_atomic_op_has_invalid_memory_order)
4026            << ArgExpr->getSourceRange();
4027   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
4028   case llvm::AtomicOrderingCABI::relaxed:
4029   case llvm::AtomicOrderingCABI::consume:
4030     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
4031       return Diag(ArgExpr->getBeginLoc(),
4032                   diag::warn_atomic_op_has_invalid_memory_order)
4033              << ArgExpr->getSourceRange();
4034     break;
4035   case llvm::AtomicOrderingCABI::acquire:
4036   case llvm::AtomicOrderingCABI::release:
4037   case llvm::AtomicOrderingCABI::acq_rel:
4038   case llvm::AtomicOrderingCABI::seq_cst:
4039     break;
4040   }
4041 
4042   Arg = TheCall->getArg(ScopeIndex);
4043   ArgExpr = Arg.get();
4044   Expr::EvalResult ArgResult1;
4045   // Check that sync scope is a constant literal
4046   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
4047     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
4048            << ArgExpr->getType();
4049 
4050   return false;
4051 }
4052 
4053 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
4054   llvm::APSInt Result;
4055 
4056   // We can't check the value of a dependent argument.
4057   Expr *Arg = TheCall->getArg(ArgNum);
4058   if (Arg->isTypeDependent() || Arg->isValueDependent())
4059     return false;
4060 
4061   // Check constant-ness first.
4062   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4063     return true;
4064 
4065   int64_t Val = Result.getSExtValue();
4066   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
4067     return false;
4068 
4069   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
4070          << Arg->getSourceRange();
4071 }
4072 
4073 static bool isRISCV32Builtin(unsigned BuiltinID) {
4074   // These builtins only work on riscv32 targets.
4075   switch (BuiltinID) {
4076   case RISCV::BI__builtin_riscv_zip_32:
4077   case RISCV::BI__builtin_riscv_unzip_32:
4078   case RISCV::BI__builtin_riscv_aes32dsi_32:
4079   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4080   case RISCV::BI__builtin_riscv_aes32esi_32:
4081   case RISCV::BI__builtin_riscv_aes32esmi_32:
4082   case RISCV::BI__builtin_riscv_sha512sig0h_32:
4083   case RISCV::BI__builtin_riscv_sha512sig0l_32:
4084   case RISCV::BI__builtin_riscv_sha512sig1h_32:
4085   case RISCV::BI__builtin_riscv_sha512sig1l_32:
4086   case RISCV::BI__builtin_riscv_sha512sum0r_32:
4087   case RISCV::BI__builtin_riscv_sha512sum1r_32:
4088     return true;
4089   }
4090 
4091   return false;
4092 }
4093 
4094 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
4095                                          unsigned BuiltinID,
4096                                          CallExpr *TheCall) {
4097   // CodeGenFunction can also detect this, but this gives a better error
4098   // message.
4099   bool FeatureMissing = false;
4100   SmallVector<StringRef> ReqFeatures;
4101   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4102   Features.split(ReqFeatures, ',');
4103 
4104   // Check for 32-bit only builtins on a 64-bit target.
4105   const llvm::Triple &TT = TI.getTriple();
4106   if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID))
4107     return Diag(TheCall->getCallee()->getBeginLoc(),
4108                 diag::err_32_bit_builtin_64_bit_tgt);
4109 
4110   // Check if each required feature is included
4111   for (StringRef F : ReqFeatures) {
4112     SmallVector<StringRef> ReqOpFeatures;
4113     F.split(ReqOpFeatures, '|');
4114     bool HasFeature = false;
4115     for (StringRef OF : ReqOpFeatures) {
4116       if (TI.hasFeature(OF)) {
4117         HasFeature = true;
4118         continue;
4119       }
4120     }
4121 
4122     if (!HasFeature) {
4123       std::string FeatureStrs;
4124       for (StringRef OF : ReqOpFeatures) {
4125         // If the feature is 64bit, alter the string so it will print better in
4126         // the diagnostic.
4127         if (OF == "64bit")
4128           OF = "RV64";
4129 
4130         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4131         OF.consume_front("experimental-");
4132         std::string FeatureStr = OF.str();
4133         FeatureStr[0] = std::toupper(FeatureStr[0]);
4134         // Combine strings.
4135         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4136         FeatureStrs += "'";
4137         FeatureStrs += FeatureStr;
4138         FeatureStrs += "'";
4139       }
4140       // Error message
4141       FeatureMissing = true;
4142       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4143           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4144     }
4145   }
4146 
4147   if (FeatureMissing)
4148     return true;
4149 
4150   switch (BuiltinID) {
4151   case RISCVVector::BI__builtin_rvv_vsetvli:
4152     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4153            CheckRISCVLMUL(TheCall, 2);
4154   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4155     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4156            CheckRISCVLMUL(TheCall, 1);
4157   case RISCVVector::BI__builtin_rvv_vget_v: {
4158     ASTContext::BuiltinVectorTypeInfo ResVecInfo =
4159         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4160             TheCall->getType().getCanonicalType().getTypePtr()));
4161     ASTContext::BuiltinVectorTypeInfo VecInfo =
4162         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4163             TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
4164     unsigned MaxIndex =
4165         (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
4166         (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
4167     return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
4168   }
4169   case RISCVVector::BI__builtin_rvv_vset_v: {
4170     ASTContext::BuiltinVectorTypeInfo ResVecInfo =
4171         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4172             TheCall->getType().getCanonicalType().getTypePtr()));
4173     ASTContext::BuiltinVectorTypeInfo VecInfo =
4174         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4175             TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
4176     unsigned MaxIndex =
4177         (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
4178         (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
4179     return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
4180   }
4181   // Check if byteselect is in [0, 3]
4182   case RISCV::BI__builtin_riscv_aes32dsi_32:
4183   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4184   case RISCV::BI__builtin_riscv_aes32esi_32:
4185   case RISCV::BI__builtin_riscv_aes32esmi_32:
4186   case RISCV::BI__builtin_riscv_sm4ks:
4187   case RISCV::BI__builtin_riscv_sm4ed:
4188     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4189   // Check if rnum is in [0, 10]
4190   case RISCV::BI__builtin_riscv_aes64ks1i_64:
4191     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10);
4192   }
4193 
4194   return false;
4195 }
4196 
4197 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4198                                            CallExpr *TheCall) {
4199   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4200     Expr *Arg = TheCall->getArg(0);
4201     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4202       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4203         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4204                << Arg->getSourceRange();
4205   }
4206 
4207   // For intrinsics which take an immediate value as part of the instruction,
4208   // range check them here.
4209   unsigned i = 0, l = 0, u = 0;
4210   switch (BuiltinID) {
4211   default: return false;
4212   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4213   case SystemZ::BI__builtin_s390_verimb:
4214   case SystemZ::BI__builtin_s390_verimh:
4215   case SystemZ::BI__builtin_s390_verimf:
4216   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4217   case SystemZ::BI__builtin_s390_vfaeb:
4218   case SystemZ::BI__builtin_s390_vfaeh:
4219   case SystemZ::BI__builtin_s390_vfaef:
4220   case SystemZ::BI__builtin_s390_vfaebs:
4221   case SystemZ::BI__builtin_s390_vfaehs:
4222   case SystemZ::BI__builtin_s390_vfaefs:
4223   case SystemZ::BI__builtin_s390_vfaezb:
4224   case SystemZ::BI__builtin_s390_vfaezh:
4225   case SystemZ::BI__builtin_s390_vfaezf:
4226   case SystemZ::BI__builtin_s390_vfaezbs:
4227   case SystemZ::BI__builtin_s390_vfaezhs:
4228   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4229   case SystemZ::BI__builtin_s390_vfisb:
4230   case SystemZ::BI__builtin_s390_vfidb:
4231     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4232            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4233   case SystemZ::BI__builtin_s390_vftcisb:
4234   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4235   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4236   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4237   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4238   case SystemZ::BI__builtin_s390_vstrcb:
4239   case SystemZ::BI__builtin_s390_vstrch:
4240   case SystemZ::BI__builtin_s390_vstrcf:
4241   case SystemZ::BI__builtin_s390_vstrczb:
4242   case SystemZ::BI__builtin_s390_vstrczh:
4243   case SystemZ::BI__builtin_s390_vstrczf:
4244   case SystemZ::BI__builtin_s390_vstrcbs:
4245   case SystemZ::BI__builtin_s390_vstrchs:
4246   case SystemZ::BI__builtin_s390_vstrcfs:
4247   case SystemZ::BI__builtin_s390_vstrczbs:
4248   case SystemZ::BI__builtin_s390_vstrczhs:
4249   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4250   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4251   case SystemZ::BI__builtin_s390_vfminsb:
4252   case SystemZ::BI__builtin_s390_vfmaxsb:
4253   case SystemZ::BI__builtin_s390_vfmindb:
4254   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4255   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4256   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4257   case SystemZ::BI__builtin_s390_vclfnhs:
4258   case SystemZ::BI__builtin_s390_vclfnls:
4259   case SystemZ::BI__builtin_s390_vcfn:
4260   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4261   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4262   }
4263   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4264 }
4265 
4266 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4267 /// This checks that the target supports __builtin_cpu_supports and
4268 /// that the string argument is constant and valid.
4269 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4270                                    CallExpr *TheCall) {
4271   Expr *Arg = TheCall->getArg(0);
4272 
4273   // Check if the argument is a string literal.
4274   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4275     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4276            << Arg->getSourceRange();
4277 
4278   // Check the contents of the string.
4279   StringRef Feature =
4280       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4281   if (!TI.validateCpuSupports(Feature))
4282     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4283            << Arg->getSourceRange();
4284   return false;
4285 }
4286 
4287 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4288 /// This checks that the target supports __builtin_cpu_is and
4289 /// that the string argument is constant and valid.
4290 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4291   Expr *Arg = TheCall->getArg(0);
4292 
4293   // Check if the argument is a string literal.
4294   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4295     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4296            << Arg->getSourceRange();
4297 
4298   // Check the contents of the string.
4299   StringRef Feature =
4300       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4301   if (!TI.validateCpuIs(Feature))
4302     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4303            << Arg->getSourceRange();
4304   return false;
4305 }
4306 
4307 // Check if the rounding mode is legal.
4308 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4309   // Indicates if this instruction has rounding control or just SAE.
4310   bool HasRC = false;
4311 
4312   unsigned ArgNum = 0;
4313   switch (BuiltinID) {
4314   default:
4315     return false;
4316   case X86::BI__builtin_ia32_vcvttsd2si32:
4317   case X86::BI__builtin_ia32_vcvttsd2si64:
4318   case X86::BI__builtin_ia32_vcvttsd2usi32:
4319   case X86::BI__builtin_ia32_vcvttsd2usi64:
4320   case X86::BI__builtin_ia32_vcvttss2si32:
4321   case X86::BI__builtin_ia32_vcvttss2si64:
4322   case X86::BI__builtin_ia32_vcvttss2usi32:
4323   case X86::BI__builtin_ia32_vcvttss2usi64:
4324   case X86::BI__builtin_ia32_vcvttsh2si32:
4325   case X86::BI__builtin_ia32_vcvttsh2si64:
4326   case X86::BI__builtin_ia32_vcvttsh2usi32:
4327   case X86::BI__builtin_ia32_vcvttsh2usi64:
4328     ArgNum = 1;
4329     break;
4330   case X86::BI__builtin_ia32_maxpd512:
4331   case X86::BI__builtin_ia32_maxps512:
4332   case X86::BI__builtin_ia32_minpd512:
4333   case X86::BI__builtin_ia32_minps512:
4334   case X86::BI__builtin_ia32_maxph512:
4335   case X86::BI__builtin_ia32_minph512:
4336     ArgNum = 2;
4337     break;
4338   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4339   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4340   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4341   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4342   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4343   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4344   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4345   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4346   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4347   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4348   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4349   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4350   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4351   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4352   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4353   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4354   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4355   case X86::BI__builtin_ia32_exp2pd_mask:
4356   case X86::BI__builtin_ia32_exp2ps_mask:
4357   case X86::BI__builtin_ia32_getexppd512_mask:
4358   case X86::BI__builtin_ia32_getexpps512_mask:
4359   case X86::BI__builtin_ia32_getexpph512_mask:
4360   case X86::BI__builtin_ia32_rcp28pd_mask:
4361   case X86::BI__builtin_ia32_rcp28ps_mask:
4362   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4363   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4364   case X86::BI__builtin_ia32_vcomisd:
4365   case X86::BI__builtin_ia32_vcomiss:
4366   case X86::BI__builtin_ia32_vcomish:
4367   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4368     ArgNum = 3;
4369     break;
4370   case X86::BI__builtin_ia32_cmppd512_mask:
4371   case X86::BI__builtin_ia32_cmpps512_mask:
4372   case X86::BI__builtin_ia32_cmpsd_mask:
4373   case X86::BI__builtin_ia32_cmpss_mask:
4374   case X86::BI__builtin_ia32_cmpsh_mask:
4375   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4376   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4377   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4378   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4379   case X86::BI__builtin_ia32_getexpss128_round_mask:
4380   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4381   case X86::BI__builtin_ia32_getmantpd512_mask:
4382   case X86::BI__builtin_ia32_getmantps512_mask:
4383   case X86::BI__builtin_ia32_getmantph512_mask:
4384   case X86::BI__builtin_ia32_maxsd_round_mask:
4385   case X86::BI__builtin_ia32_maxss_round_mask:
4386   case X86::BI__builtin_ia32_maxsh_round_mask:
4387   case X86::BI__builtin_ia32_minsd_round_mask:
4388   case X86::BI__builtin_ia32_minss_round_mask:
4389   case X86::BI__builtin_ia32_minsh_round_mask:
4390   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4391   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4392   case X86::BI__builtin_ia32_reducepd512_mask:
4393   case X86::BI__builtin_ia32_reduceps512_mask:
4394   case X86::BI__builtin_ia32_reduceph512_mask:
4395   case X86::BI__builtin_ia32_rndscalepd_mask:
4396   case X86::BI__builtin_ia32_rndscaleps_mask:
4397   case X86::BI__builtin_ia32_rndscaleph_mask:
4398   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4399   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4400     ArgNum = 4;
4401     break;
4402   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4403   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4404   case X86::BI__builtin_ia32_fixupimmps512_mask:
4405   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4406   case X86::BI__builtin_ia32_fixupimmsd_mask:
4407   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4408   case X86::BI__builtin_ia32_fixupimmss_mask:
4409   case X86::BI__builtin_ia32_fixupimmss_maskz:
4410   case X86::BI__builtin_ia32_getmantsd_round_mask:
4411   case X86::BI__builtin_ia32_getmantss_round_mask:
4412   case X86::BI__builtin_ia32_getmantsh_round_mask:
4413   case X86::BI__builtin_ia32_rangepd512_mask:
4414   case X86::BI__builtin_ia32_rangeps512_mask:
4415   case X86::BI__builtin_ia32_rangesd128_round_mask:
4416   case X86::BI__builtin_ia32_rangess128_round_mask:
4417   case X86::BI__builtin_ia32_reducesd_mask:
4418   case X86::BI__builtin_ia32_reducess_mask:
4419   case X86::BI__builtin_ia32_reducesh_mask:
4420   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4421   case X86::BI__builtin_ia32_rndscaless_round_mask:
4422   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4423     ArgNum = 5;
4424     break;
4425   case X86::BI__builtin_ia32_vcvtsd2si64:
4426   case X86::BI__builtin_ia32_vcvtsd2si32:
4427   case X86::BI__builtin_ia32_vcvtsd2usi32:
4428   case X86::BI__builtin_ia32_vcvtsd2usi64:
4429   case X86::BI__builtin_ia32_vcvtss2si32:
4430   case X86::BI__builtin_ia32_vcvtss2si64:
4431   case X86::BI__builtin_ia32_vcvtss2usi32:
4432   case X86::BI__builtin_ia32_vcvtss2usi64:
4433   case X86::BI__builtin_ia32_vcvtsh2si32:
4434   case X86::BI__builtin_ia32_vcvtsh2si64:
4435   case X86::BI__builtin_ia32_vcvtsh2usi32:
4436   case X86::BI__builtin_ia32_vcvtsh2usi64:
4437   case X86::BI__builtin_ia32_sqrtpd512:
4438   case X86::BI__builtin_ia32_sqrtps512:
4439   case X86::BI__builtin_ia32_sqrtph512:
4440     ArgNum = 1;
4441     HasRC = true;
4442     break;
4443   case X86::BI__builtin_ia32_addph512:
4444   case X86::BI__builtin_ia32_divph512:
4445   case X86::BI__builtin_ia32_mulph512:
4446   case X86::BI__builtin_ia32_subph512:
4447   case X86::BI__builtin_ia32_addpd512:
4448   case X86::BI__builtin_ia32_addps512:
4449   case X86::BI__builtin_ia32_divpd512:
4450   case X86::BI__builtin_ia32_divps512:
4451   case X86::BI__builtin_ia32_mulpd512:
4452   case X86::BI__builtin_ia32_mulps512:
4453   case X86::BI__builtin_ia32_subpd512:
4454   case X86::BI__builtin_ia32_subps512:
4455   case X86::BI__builtin_ia32_cvtsi2sd64:
4456   case X86::BI__builtin_ia32_cvtsi2ss32:
4457   case X86::BI__builtin_ia32_cvtsi2ss64:
4458   case X86::BI__builtin_ia32_cvtusi2sd64:
4459   case X86::BI__builtin_ia32_cvtusi2ss32:
4460   case X86::BI__builtin_ia32_cvtusi2ss64:
4461   case X86::BI__builtin_ia32_vcvtusi2sh:
4462   case X86::BI__builtin_ia32_vcvtusi642sh:
4463   case X86::BI__builtin_ia32_vcvtsi2sh:
4464   case X86::BI__builtin_ia32_vcvtsi642sh:
4465     ArgNum = 2;
4466     HasRC = true;
4467     break;
4468   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4469   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4470   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4471   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4472   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4473   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4474   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4475   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4476   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4477   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4478   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4479   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4480   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4481   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4482   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4483   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4484   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4485   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4486   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4487   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4488   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4489   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4490   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4491   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4492   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4493   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4494   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4495   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4496   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4497     ArgNum = 3;
4498     HasRC = true;
4499     break;
4500   case X86::BI__builtin_ia32_addsh_round_mask:
4501   case X86::BI__builtin_ia32_addss_round_mask:
4502   case X86::BI__builtin_ia32_addsd_round_mask:
4503   case X86::BI__builtin_ia32_divsh_round_mask:
4504   case X86::BI__builtin_ia32_divss_round_mask:
4505   case X86::BI__builtin_ia32_divsd_round_mask:
4506   case X86::BI__builtin_ia32_mulsh_round_mask:
4507   case X86::BI__builtin_ia32_mulss_round_mask:
4508   case X86::BI__builtin_ia32_mulsd_round_mask:
4509   case X86::BI__builtin_ia32_subsh_round_mask:
4510   case X86::BI__builtin_ia32_subss_round_mask:
4511   case X86::BI__builtin_ia32_subsd_round_mask:
4512   case X86::BI__builtin_ia32_scalefph512_mask:
4513   case X86::BI__builtin_ia32_scalefpd512_mask:
4514   case X86::BI__builtin_ia32_scalefps512_mask:
4515   case X86::BI__builtin_ia32_scalefsd_round_mask:
4516   case X86::BI__builtin_ia32_scalefss_round_mask:
4517   case X86::BI__builtin_ia32_scalefsh_round_mask:
4518   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4519   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4520   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4521   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4522   case X86::BI__builtin_ia32_sqrtss_round_mask:
4523   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4524   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4525   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4526   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4527   case X86::BI__builtin_ia32_vfmaddss3_mask:
4528   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4529   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4530   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4531   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4532   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4533   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4534   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4535   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4536   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4537   case X86::BI__builtin_ia32_vfmaddps512_mask:
4538   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4539   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4540   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4541   case X86::BI__builtin_ia32_vfmaddph512_mask:
4542   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4543   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4544   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4545   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4546   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4547   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4548   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4549   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4550   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4551   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4552   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4553   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4554   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4555   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4556   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4557   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4558   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4559   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4560   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4561   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4562   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4563   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4564   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4565   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4566   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4567   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4568   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4569   case X86::BI__builtin_ia32_vfmulcsh_mask:
4570   case X86::BI__builtin_ia32_vfmulcph512_mask:
4571   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4572   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4573     ArgNum = 4;
4574     HasRC = true;
4575     break;
4576   }
4577 
4578   llvm::APSInt Result;
4579 
4580   // We can't check the value of a dependent argument.
4581   Expr *Arg = TheCall->getArg(ArgNum);
4582   if (Arg->isTypeDependent() || Arg->isValueDependent())
4583     return false;
4584 
4585   // Check constant-ness first.
4586   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4587     return true;
4588 
4589   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4590   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4591   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4592   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4593   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4594       Result == 8/*ROUND_NO_EXC*/ ||
4595       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4596       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4597     return false;
4598 
4599   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4600          << Arg->getSourceRange();
4601 }
4602 
4603 // Check if the gather/scatter scale is legal.
4604 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4605                                              CallExpr *TheCall) {
4606   unsigned ArgNum = 0;
4607   switch (BuiltinID) {
4608   default:
4609     return false;
4610   case X86::BI__builtin_ia32_gatherpfdpd:
4611   case X86::BI__builtin_ia32_gatherpfdps:
4612   case X86::BI__builtin_ia32_gatherpfqpd:
4613   case X86::BI__builtin_ia32_gatherpfqps:
4614   case X86::BI__builtin_ia32_scatterpfdpd:
4615   case X86::BI__builtin_ia32_scatterpfdps:
4616   case X86::BI__builtin_ia32_scatterpfqpd:
4617   case X86::BI__builtin_ia32_scatterpfqps:
4618     ArgNum = 3;
4619     break;
4620   case X86::BI__builtin_ia32_gatherd_pd:
4621   case X86::BI__builtin_ia32_gatherd_pd256:
4622   case X86::BI__builtin_ia32_gatherq_pd:
4623   case X86::BI__builtin_ia32_gatherq_pd256:
4624   case X86::BI__builtin_ia32_gatherd_ps:
4625   case X86::BI__builtin_ia32_gatherd_ps256:
4626   case X86::BI__builtin_ia32_gatherq_ps:
4627   case X86::BI__builtin_ia32_gatherq_ps256:
4628   case X86::BI__builtin_ia32_gatherd_q:
4629   case X86::BI__builtin_ia32_gatherd_q256:
4630   case X86::BI__builtin_ia32_gatherq_q:
4631   case X86::BI__builtin_ia32_gatherq_q256:
4632   case X86::BI__builtin_ia32_gatherd_d:
4633   case X86::BI__builtin_ia32_gatherd_d256:
4634   case X86::BI__builtin_ia32_gatherq_d:
4635   case X86::BI__builtin_ia32_gatherq_d256:
4636   case X86::BI__builtin_ia32_gather3div2df:
4637   case X86::BI__builtin_ia32_gather3div2di:
4638   case X86::BI__builtin_ia32_gather3div4df:
4639   case X86::BI__builtin_ia32_gather3div4di:
4640   case X86::BI__builtin_ia32_gather3div4sf:
4641   case X86::BI__builtin_ia32_gather3div4si:
4642   case X86::BI__builtin_ia32_gather3div8sf:
4643   case X86::BI__builtin_ia32_gather3div8si:
4644   case X86::BI__builtin_ia32_gather3siv2df:
4645   case X86::BI__builtin_ia32_gather3siv2di:
4646   case X86::BI__builtin_ia32_gather3siv4df:
4647   case X86::BI__builtin_ia32_gather3siv4di:
4648   case X86::BI__builtin_ia32_gather3siv4sf:
4649   case X86::BI__builtin_ia32_gather3siv4si:
4650   case X86::BI__builtin_ia32_gather3siv8sf:
4651   case X86::BI__builtin_ia32_gather3siv8si:
4652   case X86::BI__builtin_ia32_gathersiv8df:
4653   case X86::BI__builtin_ia32_gathersiv16sf:
4654   case X86::BI__builtin_ia32_gatherdiv8df:
4655   case X86::BI__builtin_ia32_gatherdiv16sf:
4656   case X86::BI__builtin_ia32_gathersiv8di:
4657   case X86::BI__builtin_ia32_gathersiv16si:
4658   case X86::BI__builtin_ia32_gatherdiv8di:
4659   case X86::BI__builtin_ia32_gatherdiv16si:
4660   case X86::BI__builtin_ia32_scatterdiv2df:
4661   case X86::BI__builtin_ia32_scatterdiv2di:
4662   case X86::BI__builtin_ia32_scatterdiv4df:
4663   case X86::BI__builtin_ia32_scatterdiv4di:
4664   case X86::BI__builtin_ia32_scatterdiv4sf:
4665   case X86::BI__builtin_ia32_scatterdiv4si:
4666   case X86::BI__builtin_ia32_scatterdiv8sf:
4667   case X86::BI__builtin_ia32_scatterdiv8si:
4668   case X86::BI__builtin_ia32_scattersiv2df:
4669   case X86::BI__builtin_ia32_scattersiv2di:
4670   case X86::BI__builtin_ia32_scattersiv4df:
4671   case X86::BI__builtin_ia32_scattersiv4di:
4672   case X86::BI__builtin_ia32_scattersiv4sf:
4673   case X86::BI__builtin_ia32_scattersiv4si:
4674   case X86::BI__builtin_ia32_scattersiv8sf:
4675   case X86::BI__builtin_ia32_scattersiv8si:
4676   case X86::BI__builtin_ia32_scattersiv8df:
4677   case X86::BI__builtin_ia32_scattersiv16sf:
4678   case X86::BI__builtin_ia32_scatterdiv8df:
4679   case X86::BI__builtin_ia32_scatterdiv16sf:
4680   case X86::BI__builtin_ia32_scattersiv8di:
4681   case X86::BI__builtin_ia32_scattersiv16si:
4682   case X86::BI__builtin_ia32_scatterdiv8di:
4683   case X86::BI__builtin_ia32_scatterdiv16si:
4684     ArgNum = 4;
4685     break;
4686   }
4687 
4688   llvm::APSInt Result;
4689 
4690   // We can't check the value of a dependent argument.
4691   Expr *Arg = TheCall->getArg(ArgNum);
4692   if (Arg->isTypeDependent() || Arg->isValueDependent())
4693     return false;
4694 
4695   // Check constant-ness first.
4696   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4697     return true;
4698 
4699   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4700     return false;
4701 
4702   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4703          << Arg->getSourceRange();
4704 }
4705 
4706 enum { TileRegLow = 0, TileRegHigh = 7 };
4707 
4708 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4709                                              ArrayRef<int> ArgNums) {
4710   for (int ArgNum : ArgNums) {
4711     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4712       return true;
4713   }
4714   return false;
4715 }
4716 
4717 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4718                                         ArrayRef<int> ArgNums) {
4719   // Because the max number of tile register is TileRegHigh + 1, so here we use
4720   // each bit to represent the usage of them in bitset.
4721   std::bitset<TileRegHigh + 1> ArgValues;
4722   for (int ArgNum : ArgNums) {
4723     Expr *Arg = TheCall->getArg(ArgNum);
4724     if (Arg->isTypeDependent() || Arg->isValueDependent())
4725       continue;
4726 
4727     llvm::APSInt Result;
4728     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4729       return true;
4730     int ArgExtValue = Result.getExtValue();
4731     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4732            "Incorrect tile register num.");
4733     if (ArgValues.test(ArgExtValue))
4734       return Diag(TheCall->getBeginLoc(),
4735                   diag::err_x86_builtin_tile_arg_duplicate)
4736              << TheCall->getArg(ArgNum)->getSourceRange();
4737     ArgValues.set(ArgExtValue);
4738   }
4739   return false;
4740 }
4741 
4742 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4743                                                 ArrayRef<int> ArgNums) {
4744   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4745          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4746 }
4747 
4748 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4749   switch (BuiltinID) {
4750   default:
4751     return false;
4752   case X86::BI__builtin_ia32_tileloadd64:
4753   case X86::BI__builtin_ia32_tileloaddt164:
4754   case X86::BI__builtin_ia32_tilestored64:
4755   case X86::BI__builtin_ia32_tilezero:
4756     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4757   case X86::BI__builtin_ia32_tdpbssd:
4758   case X86::BI__builtin_ia32_tdpbsud:
4759   case X86::BI__builtin_ia32_tdpbusd:
4760   case X86::BI__builtin_ia32_tdpbuud:
4761   case X86::BI__builtin_ia32_tdpbf16ps:
4762     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4763   }
4764 }
4765 static bool isX86_32Builtin(unsigned BuiltinID) {
4766   // These builtins only work on x86-32 targets.
4767   switch (BuiltinID) {
4768   case X86::BI__builtin_ia32_readeflags_u32:
4769   case X86::BI__builtin_ia32_writeeflags_u32:
4770     return true;
4771   }
4772 
4773   return false;
4774 }
4775 
4776 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4777                                        CallExpr *TheCall) {
4778   if (BuiltinID == X86::BI__builtin_cpu_supports)
4779     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4780 
4781   if (BuiltinID == X86::BI__builtin_cpu_is)
4782     return SemaBuiltinCpuIs(*this, TI, TheCall);
4783 
4784   // Check for 32-bit only builtins on a 64-bit target.
4785   const llvm::Triple &TT = TI.getTriple();
4786   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4787     return Diag(TheCall->getCallee()->getBeginLoc(),
4788                 diag::err_32_bit_builtin_64_bit_tgt);
4789 
4790   // If the intrinsic has rounding or SAE make sure its valid.
4791   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4792     return true;
4793 
4794   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4795   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4796     return true;
4797 
4798   // If the intrinsic has a tile arguments, make sure they are valid.
4799   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4800     return true;
4801 
4802   // For intrinsics which take an immediate value as part of the instruction,
4803   // range check them here.
4804   int i = 0, l = 0, u = 0;
4805   switch (BuiltinID) {
4806   default:
4807     return false;
4808   case X86::BI__builtin_ia32_vec_ext_v2si:
4809   case X86::BI__builtin_ia32_vec_ext_v2di:
4810   case X86::BI__builtin_ia32_vextractf128_pd256:
4811   case X86::BI__builtin_ia32_vextractf128_ps256:
4812   case X86::BI__builtin_ia32_vextractf128_si256:
4813   case X86::BI__builtin_ia32_extract128i256:
4814   case X86::BI__builtin_ia32_extractf64x4_mask:
4815   case X86::BI__builtin_ia32_extracti64x4_mask:
4816   case X86::BI__builtin_ia32_extractf32x8_mask:
4817   case X86::BI__builtin_ia32_extracti32x8_mask:
4818   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4819   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4820   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4821   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4822     i = 1; l = 0; u = 1;
4823     break;
4824   case X86::BI__builtin_ia32_vec_set_v2di:
4825   case X86::BI__builtin_ia32_vinsertf128_pd256:
4826   case X86::BI__builtin_ia32_vinsertf128_ps256:
4827   case X86::BI__builtin_ia32_vinsertf128_si256:
4828   case X86::BI__builtin_ia32_insert128i256:
4829   case X86::BI__builtin_ia32_insertf32x8:
4830   case X86::BI__builtin_ia32_inserti32x8:
4831   case X86::BI__builtin_ia32_insertf64x4:
4832   case X86::BI__builtin_ia32_inserti64x4:
4833   case X86::BI__builtin_ia32_insertf64x2_256:
4834   case X86::BI__builtin_ia32_inserti64x2_256:
4835   case X86::BI__builtin_ia32_insertf32x4_256:
4836   case X86::BI__builtin_ia32_inserti32x4_256:
4837     i = 2; l = 0; u = 1;
4838     break;
4839   case X86::BI__builtin_ia32_vpermilpd:
4840   case X86::BI__builtin_ia32_vec_ext_v4hi:
4841   case X86::BI__builtin_ia32_vec_ext_v4si:
4842   case X86::BI__builtin_ia32_vec_ext_v4sf:
4843   case X86::BI__builtin_ia32_vec_ext_v4di:
4844   case X86::BI__builtin_ia32_extractf32x4_mask:
4845   case X86::BI__builtin_ia32_extracti32x4_mask:
4846   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4847   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4848     i = 1; l = 0; u = 3;
4849     break;
4850   case X86::BI_mm_prefetch:
4851   case X86::BI__builtin_ia32_vec_ext_v8hi:
4852   case X86::BI__builtin_ia32_vec_ext_v8si:
4853     i = 1; l = 0; u = 7;
4854     break;
4855   case X86::BI__builtin_ia32_sha1rnds4:
4856   case X86::BI__builtin_ia32_blendpd:
4857   case X86::BI__builtin_ia32_shufpd:
4858   case X86::BI__builtin_ia32_vec_set_v4hi:
4859   case X86::BI__builtin_ia32_vec_set_v4si:
4860   case X86::BI__builtin_ia32_vec_set_v4di:
4861   case X86::BI__builtin_ia32_shuf_f32x4_256:
4862   case X86::BI__builtin_ia32_shuf_f64x2_256:
4863   case X86::BI__builtin_ia32_shuf_i32x4_256:
4864   case X86::BI__builtin_ia32_shuf_i64x2_256:
4865   case X86::BI__builtin_ia32_insertf64x2_512:
4866   case X86::BI__builtin_ia32_inserti64x2_512:
4867   case X86::BI__builtin_ia32_insertf32x4:
4868   case X86::BI__builtin_ia32_inserti32x4:
4869     i = 2; l = 0; u = 3;
4870     break;
4871   case X86::BI__builtin_ia32_vpermil2pd:
4872   case X86::BI__builtin_ia32_vpermil2pd256:
4873   case X86::BI__builtin_ia32_vpermil2ps:
4874   case X86::BI__builtin_ia32_vpermil2ps256:
4875     i = 3; l = 0; u = 3;
4876     break;
4877   case X86::BI__builtin_ia32_cmpb128_mask:
4878   case X86::BI__builtin_ia32_cmpw128_mask:
4879   case X86::BI__builtin_ia32_cmpd128_mask:
4880   case X86::BI__builtin_ia32_cmpq128_mask:
4881   case X86::BI__builtin_ia32_cmpb256_mask:
4882   case X86::BI__builtin_ia32_cmpw256_mask:
4883   case X86::BI__builtin_ia32_cmpd256_mask:
4884   case X86::BI__builtin_ia32_cmpq256_mask:
4885   case X86::BI__builtin_ia32_cmpb512_mask:
4886   case X86::BI__builtin_ia32_cmpw512_mask:
4887   case X86::BI__builtin_ia32_cmpd512_mask:
4888   case X86::BI__builtin_ia32_cmpq512_mask:
4889   case X86::BI__builtin_ia32_ucmpb128_mask:
4890   case X86::BI__builtin_ia32_ucmpw128_mask:
4891   case X86::BI__builtin_ia32_ucmpd128_mask:
4892   case X86::BI__builtin_ia32_ucmpq128_mask:
4893   case X86::BI__builtin_ia32_ucmpb256_mask:
4894   case X86::BI__builtin_ia32_ucmpw256_mask:
4895   case X86::BI__builtin_ia32_ucmpd256_mask:
4896   case X86::BI__builtin_ia32_ucmpq256_mask:
4897   case X86::BI__builtin_ia32_ucmpb512_mask:
4898   case X86::BI__builtin_ia32_ucmpw512_mask:
4899   case X86::BI__builtin_ia32_ucmpd512_mask:
4900   case X86::BI__builtin_ia32_ucmpq512_mask:
4901   case X86::BI__builtin_ia32_vpcomub:
4902   case X86::BI__builtin_ia32_vpcomuw:
4903   case X86::BI__builtin_ia32_vpcomud:
4904   case X86::BI__builtin_ia32_vpcomuq:
4905   case X86::BI__builtin_ia32_vpcomb:
4906   case X86::BI__builtin_ia32_vpcomw:
4907   case X86::BI__builtin_ia32_vpcomd:
4908   case X86::BI__builtin_ia32_vpcomq:
4909   case X86::BI__builtin_ia32_vec_set_v8hi:
4910   case X86::BI__builtin_ia32_vec_set_v8si:
4911     i = 2; l = 0; u = 7;
4912     break;
4913   case X86::BI__builtin_ia32_vpermilpd256:
4914   case X86::BI__builtin_ia32_roundps:
4915   case X86::BI__builtin_ia32_roundpd:
4916   case X86::BI__builtin_ia32_roundps256:
4917   case X86::BI__builtin_ia32_roundpd256:
4918   case X86::BI__builtin_ia32_getmantpd128_mask:
4919   case X86::BI__builtin_ia32_getmantpd256_mask:
4920   case X86::BI__builtin_ia32_getmantps128_mask:
4921   case X86::BI__builtin_ia32_getmantps256_mask:
4922   case X86::BI__builtin_ia32_getmantpd512_mask:
4923   case X86::BI__builtin_ia32_getmantps512_mask:
4924   case X86::BI__builtin_ia32_getmantph128_mask:
4925   case X86::BI__builtin_ia32_getmantph256_mask:
4926   case X86::BI__builtin_ia32_getmantph512_mask:
4927   case X86::BI__builtin_ia32_vec_ext_v16qi:
4928   case X86::BI__builtin_ia32_vec_ext_v16hi:
4929     i = 1; l = 0; u = 15;
4930     break;
4931   case X86::BI__builtin_ia32_pblendd128:
4932   case X86::BI__builtin_ia32_blendps:
4933   case X86::BI__builtin_ia32_blendpd256:
4934   case X86::BI__builtin_ia32_shufpd256:
4935   case X86::BI__builtin_ia32_roundss:
4936   case X86::BI__builtin_ia32_roundsd:
4937   case X86::BI__builtin_ia32_rangepd128_mask:
4938   case X86::BI__builtin_ia32_rangepd256_mask:
4939   case X86::BI__builtin_ia32_rangepd512_mask:
4940   case X86::BI__builtin_ia32_rangeps128_mask:
4941   case X86::BI__builtin_ia32_rangeps256_mask:
4942   case X86::BI__builtin_ia32_rangeps512_mask:
4943   case X86::BI__builtin_ia32_getmantsd_round_mask:
4944   case X86::BI__builtin_ia32_getmantss_round_mask:
4945   case X86::BI__builtin_ia32_getmantsh_round_mask:
4946   case X86::BI__builtin_ia32_vec_set_v16qi:
4947   case X86::BI__builtin_ia32_vec_set_v16hi:
4948     i = 2; l = 0; u = 15;
4949     break;
4950   case X86::BI__builtin_ia32_vec_ext_v32qi:
4951     i = 1; l = 0; u = 31;
4952     break;
4953   case X86::BI__builtin_ia32_cmpps:
4954   case X86::BI__builtin_ia32_cmpss:
4955   case X86::BI__builtin_ia32_cmppd:
4956   case X86::BI__builtin_ia32_cmpsd:
4957   case X86::BI__builtin_ia32_cmpps256:
4958   case X86::BI__builtin_ia32_cmppd256:
4959   case X86::BI__builtin_ia32_cmpps128_mask:
4960   case X86::BI__builtin_ia32_cmppd128_mask:
4961   case X86::BI__builtin_ia32_cmpps256_mask:
4962   case X86::BI__builtin_ia32_cmppd256_mask:
4963   case X86::BI__builtin_ia32_cmpps512_mask:
4964   case X86::BI__builtin_ia32_cmppd512_mask:
4965   case X86::BI__builtin_ia32_cmpsd_mask:
4966   case X86::BI__builtin_ia32_cmpss_mask:
4967   case X86::BI__builtin_ia32_vec_set_v32qi:
4968     i = 2; l = 0; u = 31;
4969     break;
4970   case X86::BI__builtin_ia32_permdf256:
4971   case X86::BI__builtin_ia32_permdi256:
4972   case X86::BI__builtin_ia32_permdf512:
4973   case X86::BI__builtin_ia32_permdi512:
4974   case X86::BI__builtin_ia32_vpermilps:
4975   case X86::BI__builtin_ia32_vpermilps256:
4976   case X86::BI__builtin_ia32_vpermilpd512:
4977   case X86::BI__builtin_ia32_vpermilps512:
4978   case X86::BI__builtin_ia32_pshufd:
4979   case X86::BI__builtin_ia32_pshufd256:
4980   case X86::BI__builtin_ia32_pshufd512:
4981   case X86::BI__builtin_ia32_pshufhw:
4982   case X86::BI__builtin_ia32_pshufhw256:
4983   case X86::BI__builtin_ia32_pshufhw512:
4984   case X86::BI__builtin_ia32_pshuflw:
4985   case X86::BI__builtin_ia32_pshuflw256:
4986   case X86::BI__builtin_ia32_pshuflw512:
4987   case X86::BI__builtin_ia32_vcvtps2ph:
4988   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4989   case X86::BI__builtin_ia32_vcvtps2ph256:
4990   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4991   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4992   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4993   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4994   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4995   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4996   case X86::BI__builtin_ia32_rndscaleps_mask:
4997   case X86::BI__builtin_ia32_rndscalepd_mask:
4998   case X86::BI__builtin_ia32_rndscaleph_mask:
4999   case X86::BI__builtin_ia32_reducepd128_mask:
5000   case X86::BI__builtin_ia32_reducepd256_mask:
5001   case X86::BI__builtin_ia32_reducepd512_mask:
5002   case X86::BI__builtin_ia32_reduceps128_mask:
5003   case X86::BI__builtin_ia32_reduceps256_mask:
5004   case X86::BI__builtin_ia32_reduceps512_mask:
5005   case X86::BI__builtin_ia32_reduceph128_mask:
5006   case X86::BI__builtin_ia32_reduceph256_mask:
5007   case X86::BI__builtin_ia32_reduceph512_mask:
5008   case X86::BI__builtin_ia32_prold512:
5009   case X86::BI__builtin_ia32_prolq512:
5010   case X86::BI__builtin_ia32_prold128:
5011   case X86::BI__builtin_ia32_prold256:
5012   case X86::BI__builtin_ia32_prolq128:
5013   case X86::BI__builtin_ia32_prolq256:
5014   case X86::BI__builtin_ia32_prord512:
5015   case X86::BI__builtin_ia32_prorq512:
5016   case X86::BI__builtin_ia32_prord128:
5017   case X86::BI__builtin_ia32_prord256:
5018   case X86::BI__builtin_ia32_prorq128:
5019   case X86::BI__builtin_ia32_prorq256:
5020   case X86::BI__builtin_ia32_fpclasspd128_mask:
5021   case X86::BI__builtin_ia32_fpclasspd256_mask:
5022   case X86::BI__builtin_ia32_fpclassps128_mask:
5023   case X86::BI__builtin_ia32_fpclassps256_mask:
5024   case X86::BI__builtin_ia32_fpclassps512_mask:
5025   case X86::BI__builtin_ia32_fpclasspd512_mask:
5026   case X86::BI__builtin_ia32_fpclassph128_mask:
5027   case X86::BI__builtin_ia32_fpclassph256_mask:
5028   case X86::BI__builtin_ia32_fpclassph512_mask:
5029   case X86::BI__builtin_ia32_fpclasssd_mask:
5030   case X86::BI__builtin_ia32_fpclassss_mask:
5031   case X86::BI__builtin_ia32_fpclasssh_mask:
5032   case X86::BI__builtin_ia32_pslldqi128_byteshift:
5033   case X86::BI__builtin_ia32_pslldqi256_byteshift:
5034   case X86::BI__builtin_ia32_pslldqi512_byteshift:
5035   case X86::BI__builtin_ia32_psrldqi128_byteshift:
5036   case X86::BI__builtin_ia32_psrldqi256_byteshift:
5037   case X86::BI__builtin_ia32_psrldqi512_byteshift:
5038   case X86::BI__builtin_ia32_kshiftliqi:
5039   case X86::BI__builtin_ia32_kshiftlihi:
5040   case X86::BI__builtin_ia32_kshiftlisi:
5041   case X86::BI__builtin_ia32_kshiftlidi:
5042   case X86::BI__builtin_ia32_kshiftriqi:
5043   case X86::BI__builtin_ia32_kshiftrihi:
5044   case X86::BI__builtin_ia32_kshiftrisi:
5045   case X86::BI__builtin_ia32_kshiftridi:
5046     i = 1; l = 0; u = 255;
5047     break;
5048   case X86::BI__builtin_ia32_vperm2f128_pd256:
5049   case X86::BI__builtin_ia32_vperm2f128_ps256:
5050   case X86::BI__builtin_ia32_vperm2f128_si256:
5051   case X86::BI__builtin_ia32_permti256:
5052   case X86::BI__builtin_ia32_pblendw128:
5053   case X86::BI__builtin_ia32_pblendw256:
5054   case X86::BI__builtin_ia32_blendps256:
5055   case X86::BI__builtin_ia32_pblendd256:
5056   case X86::BI__builtin_ia32_palignr128:
5057   case X86::BI__builtin_ia32_palignr256:
5058   case X86::BI__builtin_ia32_palignr512:
5059   case X86::BI__builtin_ia32_alignq512:
5060   case X86::BI__builtin_ia32_alignd512:
5061   case X86::BI__builtin_ia32_alignd128:
5062   case X86::BI__builtin_ia32_alignd256:
5063   case X86::BI__builtin_ia32_alignq128:
5064   case X86::BI__builtin_ia32_alignq256:
5065   case X86::BI__builtin_ia32_vcomisd:
5066   case X86::BI__builtin_ia32_vcomiss:
5067   case X86::BI__builtin_ia32_shuf_f32x4:
5068   case X86::BI__builtin_ia32_shuf_f64x2:
5069   case X86::BI__builtin_ia32_shuf_i32x4:
5070   case X86::BI__builtin_ia32_shuf_i64x2:
5071   case X86::BI__builtin_ia32_shufpd512:
5072   case X86::BI__builtin_ia32_shufps:
5073   case X86::BI__builtin_ia32_shufps256:
5074   case X86::BI__builtin_ia32_shufps512:
5075   case X86::BI__builtin_ia32_dbpsadbw128:
5076   case X86::BI__builtin_ia32_dbpsadbw256:
5077   case X86::BI__builtin_ia32_dbpsadbw512:
5078   case X86::BI__builtin_ia32_vpshldd128:
5079   case X86::BI__builtin_ia32_vpshldd256:
5080   case X86::BI__builtin_ia32_vpshldd512:
5081   case X86::BI__builtin_ia32_vpshldq128:
5082   case X86::BI__builtin_ia32_vpshldq256:
5083   case X86::BI__builtin_ia32_vpshldq512:
5084   case X86::BI__builtin_ia32_vpshldw128:
5085   case X86::BI__builtin_ia32_vpshldw256:
5086   case X86::BI__builtin_ia32_vpshldw512:
5087   case X86::BI__builtin_ia32_vpshrdd128:
5088   case X86::BI__builtin_ia32_vpshrdd256:
5089   case X86::BI__builtin_ia32_vpshrdd512:
5090   case X86::BI__builtin_ia32_vpshrdq128:
5091   case X86::BI__builtin_ia32_vpshrdq256:
5092   case X86::BI__builtin_ia32_vpshrdq512:
5093   case X86::BI__builtin_ia32_vpshrdw128:
5094   case X86::BI__builtin_ia32_vpshrdw256:
5095   case X86::BI__builtin_ia32_vpshrdw512:
5096     i = 2; l = 0; u = 255;
5097     break;
5098   case X86::BI__builtin_ia32_fixupimmpd512_mask:
5099   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
5100   case X86::BI__builtin_ia32_fixupimmps512_mask:
5101   case X86::BI__builtin_ia32_fixupimmps512_maskz:
5102   case X86::BI__builtin_ia32_fixupimmsd_mask:
5103   case X86::BI__builtin_ia32_fixupimmsd_maskz:
5104   case X86::BI__builtin_ia32_fixupimmss_mask:
5105   case X86::BI__builtin_ia32_fixupimmss_maskz:
5106   case X86::BI__builtin_ia32_fixupimmpd128_mask:
5107   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
5108   case X86::BI__builtin_ia32_fixupimmpd256_mask:
5109   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
5110   case X86::BI__builtin_ia32_fixupimmps128_mask:
5111   case X86::BI__builtin_ia32_fixupimmps128_maskz:
5112   case X86::BI__builtin_ia32_fixupimmps256_mask:
5113   case X86::BI__builtin_ia32_fixupimmps256_maskz:
5114   case X86::BI__builtin_ia32_pternlogd512_mask:
5115   case X86::BI__builtin_ia32_pternlogd512_maskz:
5116   case X86::BI__builtin_ia32_pternlogq512_mask:
5117   case X86::BI__builtin_ia32_pternlogq512_maskz:
5118   case X86::BI__builtin_ia32_pternlogd128_mask:
5119   case X86::BI__builtin_ia32_pternlogd128_maskz:
5120   case X86::BI__builtin_ia32_pternlogd256_mask:
5121   case X86::BI__builtin_ia32_pternlogd256_maskz:
5122   case X86::BI__builtin_ia32_pternlogq128_mask:
5123   case X86::BI__builtin_ia32_pternlogq128_maskz:
5124   case X86::BI__builtin_ia32_pternlogq256_mask:
5125   case X86::BI__builtin_ia32_pternlogq256_maskz:
5126     i = 3; l = 0; u = 255;
5127     break;
5128   case X86::BI__builtin_ia32_gatherpfdpd:
5129   case X86::BI__builtin_ia32_gatherpfdps:
5130   case X86::BI__builtin_ia32_gatherpfqpd:
5131   case X86::BI__builtin_ia32_gatherpfqps:
5132   case X86::BI__builtin_ia32_scatterpfdpd:
5133   case X86::BI__builtin_ia32_scatterpfdps:
5134   case X86::BI__builtin_ia32_scatterpfqpd:
5135   case X86::BI__builtin_ia32_scatterpfqps:
5136     i = 4; l = 2; u = 3;
5137     break;
5138   case X86::BI__builtin_ia32_reducesd_mask:
5139   case X86::BI__builtin_ia32_reducess_mask:
5140   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5141   case X86::BI__builtin_ia32_rndscaless_round_mask:
5142   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5143   case X86::BI__builtin_ia32_reducesh_mask:
5144     i = 4; l = 0; u = 255;
5145     break;
5146   }
5147 
5148   // Note that we don't force a hard error on the range check here, allowing
5149   // template-generated or macro-generated dead code to potentially have out-of-
5150   // range values. These need to code generate, but don't need to necessarily
5151   // make any sense. We use a warning that defaults to an error.
5152   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5153 }
5154 
5155 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5156 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5157 /// Returns true when the format fits the function and the FormatStringInfo has
5158 /// been populated.
5159 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5160                                FormatStringInfo *FSI) {
5161   FSI->HasVAListArg = Format->getFirstArg() == 0;
5162   FSI->FormatIdx = Format->getFormatIdx() - 1;
5163   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5164 
5165   // The way the format attribute works in GCC, the implicit this argument
5166   // of member functions is counted. However, it doesn't appear in our own
5167   // lists, so decrement format_idx in that case.
5168   if (IsCXXMember) {
5169     if(FSI->FormatIdx == 0)
5170       return false;
5171     --FSI->FormatIdx;
5172     if (FSI->FirstDataArg != 0)
5173       --FSI->FirstDataArg;
5174   }
5175   return true;
5176 }
5177 
5178 /// Checks if a the given expression evaluates to null.
5179 ///
5180 /// Returns true if the value evaluates to null.
5181 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5182   // If the expression has non-null type, it doesn't evaluate to null.
5183   if (auto nullability
5184         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5185     if (*nullability == NullabilityKind::NonNull)
5186       return false;
5187   }
5188 
5189   // As a special case, transparent unions initialized with zero are
5190   // considered null for the purposes of the nonnull attribute.
5191   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5192     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5193       if (const CompoundLiteralExpr *CLE =
5194           dyn_cast<CompoundLiteralExpr>(Expr))
5195         if (const InitListExpr *ILE =
5196             dyn_cast<InitListExpr>(CLE->getInitializer()))
5197           Expr = ILE->getInit(0);
5198   }
5199 
5200   bool Result;
5201   return (!Expr->isValueDependent() &&
5202           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5203           !Result);
5204 }
5205 
5206 static void CheckNonNullArgument(Sema &S,
5207                                  const Expr *ArgExpr,
5208                                  SourceLocation CallSiteLoc) {
5209   if (CheckNonNullExpr(S, ArgExpr))
5210     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5211                           S.PDiag(diag::warn_null_arg)
5212                               << ArgExpr->getSourceRange());
5213 }
5214 
5215 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5216   FormatStringInfo FSI;
5217   if ((GetFormatStringType(Format) == FST_NSString) &&
5218       getFormatStringInfo(Format, false, &FSI)) {
5219     Idx = FSI.FormatIdx;
5220     return true;
5221   }
5222   return false;
5223 }
5224 
5225 /// Diagnose use of %s directive in an NSString which is being passed
5226 /// as formatting string to formatting method.
5227 static void
5228 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5229                                         const NamedDecl *FDecl,
5230                                         Expr **Args,
5231                                         unsigned NumArgs) {
5232   unsigned Idx = 0;
5233   bool Format = false;
5234   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5235   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5236     Idx = 2;
5237     Format = true;
5238   }
5239   else
5240     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5241       if (S.GetFormatNSStringIdx(I, Idx)) {
5242         Format = true;
5243         break;
5244       }
5245     }
5246   if (!Format || NumArgs <= Idx)
5247     return;
5248   const Expr *FormatExpr = Args[Idx];
5249   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5250     FormatExpr = CSCE->getSubExpr();
5251   const StringLiteral *FormatString;
5252   if (const ObjCStringLiteral *OSL =
5253       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5254     FormatString = OSL->getString();
5255   else
5256     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5257   if (!FormatString)
5258     return;
5259   if (S.FormatStringHasSArg(FormatString)) {
5260     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5261       << "%s" << 1 << 1;
5262     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5263       << FDecl->getDeclName();
5264   }
5265 }
5266 
5267 /// Determine whether the given type has a non-null nullability annotation.
5268 static bool isNonNullType(ASTContext &ctx, QualType type) {
5269   if (auto nullability = type->getNullability(ctx))
5270     return *nullability == NullabilityKind::NonNull;
5271 
5272   return false;
5273 }
5274 
5275 static void CheckNonNullArguments(Sema &S,
5276                                   const NamedDecl *FDecl,
5277                                   const FunctionProtoType *Proto,
5278                                   ArrayRef<const Expr *> Args,
5279                                   SourceLocation CallSiteLoc) {
5280   assert((FDecl || Proto) && "Need a function declaration or prototype");
5281 
5282   // Already checked by by constant evaluator.
5283   if (S.isConstantEvaluated())
5284     return;
5285   // Check the attributes attached to the method/function itself.
5286   llvm::SmallBitVector NonNullArgs;
5287   if (FDecl) {
5288     // Handle the nonnull attribute on the function/method declaration itself.
5289     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5290       if (!NonNull->args_size()) {
5291         // Easy case: all pointer arguments are nonnull.
5292         for (const auto *Arg : Args)
5293           if (S.isValidPointerAttrType(Arg->getType()))
5294             CheckNonNullArgument(S, Arg, CallSiteLoc);
5295         return;
5296       }
5297 
5298       for (const ParamIdx &Idx : NonNull->args()) {
5299         unsigned IdxAST = Idx.getASTIndex();
5300         if (IdxAST >= Args.size())
5301           continue;
5302         if (NonNullArgs.empty())
5303           NonNullArgs.resize(Args.size());
5304         NonNullArgs.set(IdxAST);
5305       }
5306     }
5307   }
5308 
5309   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5310     // Handle the nonnull attribute on the parameters of the
5311     // function/method.
5312     ArrayRef<ParmVarDecl*> parms;
5313     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5314       parms = FD->parameters();
5315     else
5316       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5317 
5318     unsigned ParamIndex = 0;
5319     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5320          I != E; ++I, ++ParamIndex) {
5321       const ParmVarDecl *PVD = *I;
5322       if (PVD->hasAttr<NonNullAttr>() ||
5323           isNonNullType(S.Context, PVD->getType())) {
5324         if (NonNullArgs.empty())
5325           NonNullArgs.resize(Args.size());
5326 
5327         NonNullArgs.set(ParamIndex);
5328       }
5329     }
5330   } else {
5331     // If we have a non-function, non-method declaration but no
5332     // function prototype, try to dig out the function prototype.
5333     if (!Proto) {
5334       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5335         QualType type = VD->getType().getNonReferenceType();
5336         if (auto pointerType = type->getAs<PointerType>())
5337           type = pointerType->getPointeeType();
5338         else if (auto blockType = type->getAs<BlockPointerType>())
5339           type = blockType->getPointeeType();
5340         // FIXME: data member pointers?
5341 
5342         // Dig out the function prototype, if there is one.
5343         Proto = type->getAs<FunctionProtoType>();
5344       }
5345     }
5346 
5347     // Fill in non-null argument information from the nullability
5348     // information on the parameter types (if we have them).
5349     if (Proto) {
5350       unsigned Index = 0;
5351       for (auto paramType : Proto->getParamTypes()) {
5352         if (isNonNullType(S.Context, paramType)) {
5353           if (NonNullArgs.empty())
5354             NonNullArgs.resize(Args.size());
5355 
5356           NonNullArgs.set(Index);
5357         }
5358 
5359         ++Index;
5360       }
5361     }
5362   }
5363 
5364   // Check for non-null arguments.
5365   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5366        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5367     if (NonNullArgs[ArgIndex])
5368       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5369   }
5370 }
5371 
5372 /// Warn if a pointer or reference argument passed to a function points to an
5373 /// object that is less aligned than the parameter. This can happen when
5374 /// creating a typedef with a lower alignment than the original type and then
5375 /// calling functions defined in terms of the original type.
5376 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5377                              StringRef ParamName, QualType ArgTy,
5378                              QualType ParamTy) {
5379 
5380   // If a function accepts a pointer or reference type
5381   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5382     return;
5383 
5384   // If the parameter is a pointer type, get the pointee type for the
5385   // argument too. If the parameter is a reference type, don't try to get
5386   // the pointee type for the argument.
5387   if (ParamTy->isPointerType())
5388     ArgTy = ArgTy->getPointeeType();
5389 
5390   // Remove reference or pointer
5391   ParamTy = ParamTy->getPointeeType();
5392 
5393   // Find expected alignment, and the actual alignment of the passed object.
5394   // getTypeAlignInChars requires complete types
5395   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5396       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5397       ArgTy->isUndeducedType())
5398     return;
5399 
5400   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5401   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5402 
5403   // If the argument is less aligned than the parameter, there is a
5404   // potential alignment issue.
5405   if (ArgAlign < ParamAlign)
5406     Diag(Loc, diag::warn_param_mismatched_alignment)
5407         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5408         << ParamName << (FDecl != nullptr) << FDecl;
5409 }
5410 
5411 /// Handles the checks for format strings, non-POD arguments to vararg
5412 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5413 /// attributes.
5414 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5415                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5416                      bool IsMemberFunction, SourceLocation Loc,
5417                      SourceRange Range, VariadicCallType CallType) {
5418   // FIXME: We should check as much as we can in the template definition.
5419   if (CurContext->isDependentContext())
5420     return;
5421 
5422   // Printf and scanf checking.
5423   llvm::SmallBitVector CheckedVarArgs;
5424   if (FDecl) {
5425     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5426       // Only create vector if there are format attributes.
5427       CheckedVarArgs.resize(Args.size());
5428 
5429       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5430                            CheckedVarArgs);
5431     }
5432   }
5433 
5434   // Refuse POD arguments that weren't caught by the format string
5435   // checks above.
5436   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5437   if (CallType != VariadicDoesNotApply &&
5438       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5439     unsigned NumParams = Proto ? Proto->getNumParams()
5440                        : FDecl && isa<FunctionDecl>(FDecl)
5441                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5442                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5443                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5444                        : 0;
5445 
5446     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5447       // Args[ArgIdx] can be null in malformed code.
5448       if (const Expr *Arg = Args[ArgIdx]) {
5449         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5450           checkVariadicArgument(Arg, CallType);
5451       }
5452     }
5453   }
5454 
5455   if (FDecl || Proto) {
5456     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5457 
5458     // Type safety checking.
5459     if (FDecl) {
5460       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5461         CheckArgumentWithTypeTag(I, Args, Loc);
5462     }
5463   }
5464 
5465   // Check that passed arguments match the alignment of original arguments.
5466   // Try to get the missing prototype from the declaration.
5467   if (!Proto && FDecl) {
5468     const auto *FT = FDecl->getFunctionType();
5469     if (isa_and_nonnull<FunctionProtoType>(FT))
5470       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5471   }
5472   if (Proto) {
5473     // For variadic functions, we may have more args than parameters.
5474     // For some K&R functions, we may have less args than parameters.
5475     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5476     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5477       // Args[ArgIdx] can be null in malformed code.
5478       if (const Expr *Arg = Args[ArgIdx]) {
5479         if (Arg->containsErrors())
5480           continue;
5481 
5482         QualType ParamTy = Proto->getParamType(ArgIdx);
5483         QualType ArgTy = Arg->getType();
5484         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5485                           ArgTy, ParamTy);
5486       }
5487     }
5488   }
5489 
5490   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5491     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5492     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5493     if (!Arg->isValueDependent()) {
5494       Expr::EvalResult Align;
5495       if (Arg->EvaluateAsInt(Align, Context)) {
5496         const llvm::APSInt &I = Align.Val.getInt();
5497         if (!I.isPowerOf2())
5498           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5499               << Arg->getSourceRange();
5500 
5501         if (I > Sema::MaximumAlignment)
5502           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5503               << Arg->getSourceRange() << Sema::MaximumAlignment;
5504       }
5505     }
5506   }
5507 
5508   if (FD)
5509     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5510 }
5511 
5512 /// CheckConstructorCall - Check a constructor call for correctness and safety
5513 /// properties not enforced by the C type system.
5514 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5515                                 ArrayRef<const Expr *> Args,
5516                                 const FunctionProtoType *Proto,
5517                                 SourceLocation Loc) {
5518   VariadicCallType CallType =
5519       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5520 
5521   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5522   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5523                     Context.getPointerType(Ctor->getThisObjectType()));
5524 
5525   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5526             Loc, SourceRange(), CallType);
5527 }
5528 
5529 /// CheckFunctionCall - Check a direct function call for various correctness
5530 /// and safety properties not strictly enforced by the C type system.
5531 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5532                              const FunctionProtoType *Proto) {
5533   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5534                               isa<CXXMethodDecl>(FDecl);
5535   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5536                           IsMemberOperatorCall;
5537   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5538                                                   TheCall->getCallee());
5539   Expr** Args = TheCall->getArgs();
5540   unsigned NumArgs = TheCall->getNumArgs();
5541 
5542   Expr *ImplicitThis = nullptr;
5543   if (IsMemberOperatorCall) {
5544     // If this is a call to a member operator, hide the first argument
5545     // from checkCall.
5546     // FIXME: Our choice of AST representation here is less than ideal.
5547     ImplicitThis = Args[0];
5548     ++Args;
5549     --NumArgs;
5550   } else if (IsMemberFunction)
5551     ImplicitThis =
5552         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5553 
5554   if (ImplicitThis) {
5555     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5556     // used.
5557     QualType ThisType = ImplicitThis->getType();
5558     if (!ThisType->isPointerType()) {
5559       assert(!ThisType->isReferenceType());
5560       ThisType = Context.getPointerType(ThisType);
5561     }
5562 
5563     QualType ThisTypeFromDecl =
5564         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5565 
5566     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5567                       ThisTypeFromDecl);
5568   }
5569 
5570   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5571             IsMemberFunction, TheCall->getRParenLoc(),
5572             TheCall->getCallee()->getSourceRange(), CallType);
5573 
5574   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5575   // None of the checks below are needed for functions that don't have
5576   // simple names (e.g., C++ conversion functions).
5577   if (!FnInfo)
5578     return false;
5579 
5580   // Enforce TCB except for builtin calls, which are always allowed.
5581   if (FDecl->getBuiltinID() == 0)
5582     CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
5583 
5584   CheckAbsoluteValueFunction(TheCall, FDecl);
5585   CheckMaxUnsignedZero(TheCall, FDecl);
5586 
5587   if (getLangOpts().ObjC)
5588     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5589 
5590   unsigned CMId = FDecl->getMemoryFunctionKind();
5591 
5592   // Handle memory setting and copying functions.
5593   switch (CMId) {
5594   case 0:
5595     return false;
5596   case Builtin::BIstrlcpy: // fallthrough
5597   case Builtin::BIstrlcat:
5598     CheckStrlcpycatArguments(TheCall, FnInfo);
5599     break;
5600   case Builtin::BIstrncat:
5601     CheckStrncatArguments(TheCall, FnInfo);
5602     break;
5603   case Builtin::BIfree:
5604     CheckFreeArguments(TheCall);
5605     break;
5606   default:
5607     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5608   }
5609 
5610   return false;
5611 }
5612 
5613 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5614                                ArrayRef<const Expr *> Args) {
5615   VariadicCallType CallType =
5616       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5617 
5618   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5619             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5620             CallType);
5621 
5622   CheckTCBEnforcement(lbrac, Method);
5623 
5624   return false;
5625 }
5626 
5627 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5628                             const FunctionProtoType *Proto) {
5629   QualType Ty;
5630   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5631     Ty = V->getType().getNonReferenceType();
5632   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5633     Ty = F->getType().getNonReferenceType();
5634   else
5635     return false;
5636 
5637   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5638       !Ty->isFunctionProtoType())
5639     return false;
5640 
5641   VariadicCallType CallType;
5642   if (!Proto || !Proto->isVariadic()) {
5643     CallType = VariadicDoesNotApply;
5644   } else if (Ty->isBlockPointerType()) {
5645     CallType = VariadicBlock;
5646   } else { // Ty->isFunctionPointerType()
5647     CallType = VariadicFunction;
5648   }
5649 
5650   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5651             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5652             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5653             TheCall->getCallee()->getSourceRange(), CallType);
5654 
5655   return false;
5656 }
5657 
5658 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5659 /// such as function pointers returned from functions.
5660 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5661   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5662                                                   TheCall->getCallee());
5663   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5664             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5665             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5666             TheCall->getCallee()->getSourceRange(), CallType);
5667 
5668   return false;
5669 }
5670 
5671 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5672   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5673     return false;
5674 
5675   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5676   switch (Op) {
5677   case AtomicExpr::AO__c11_atomic_init:
5678   case AtomicExpr::AO__opencl_atomic_init:
5679     llvm_unreachable("There is no ordering argument for an init");
5680 
5681   case AtomicExpr::AO__c11_atomic_load:
5682   case AtomicExpr::AO__opencl_atomic_load:
5683   case AtomicExpr::AO__hip_atomic_load:
5684   case AtomicExpr::AO__atomic_load_n:
5685   case AtomicExpr::AO__atomic_load:
5686     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5687            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5688 
5689   case AtomicExpr::AO__c11_atomic_store:
5690   case AtomicExpr::AO__opencl_atomic_store:
5691   case AtomicExpr::AO__hip_atomic_store:
5692   case AtomicExpr::AO__atomic_store:
5693   case AtomicExpr::AO__atomic_store_n:
5694     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5695            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5696            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5697 
5698   default:
5699     return true;
5700   }
5701 }
5702 
5703 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5704                                          AtomicExpr::AtomicOp Op) {
5705   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5706   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5707   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5708   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5709                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5710                          Op);
5711 }
5712 
5713 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5714                                  SourceLocation RParenLoc, MultiExprArg Args,
5715                                  AtomicExpr::AtomicOp Op,
5716                                  AtomicArgumentOrder ArgOrder) {
5717   // All the non-OpenCL operations take one of the following forms.
5718   // The OpenCL operations take the __c11 forms with one extra argument for
5719   // synchronization scope.
5720   enum {
5721     // C    __c11_atomic_init(A *, C)
5722     Init,
5723 
5724     // C    __c11_atomic_load(A *, int)
5725     Load,
5726 
5727     // void __atomic_load(A *, CP, int)
5728     LoadCopy,
5729 
5730     // void __atomic_store(A *, CP, int)
5731     Copy,
5732 
5733     // C    __c11_atomic_add(A *, M, int)
5734     Arithmetic,
5735 
5736     // C    __atomic_exchange_n(A *, CP, int)
5737     Xchg,
5738 
5739     // void __atomic_exchange(A *, C *, CP, int)
5740     GNUXchg,
5741 
5742     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5743     C11CmpXchg,
5744 
5745     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5746     GNUCmpXchg
5747   } Form = Init;
5748 
5749   const unsigned NumForm = GNUCmpXchg + 1;
5750   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5751   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5752   // where:
5753   //   C is an appropriate type,
5754   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5755   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5756   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5757   //   the int parameters are for orderings.
5758 
5759   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5760       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5761       "need to update code for modified forms");
5762   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5763                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5764                         AtomicExpr::AO__atomic_load,
5765                 "need to update code for modified C11 atomics");
5766   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5767                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5768   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5769                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5770   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5771                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5772                IsOpenCL;
5773   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5774              Op == AtomicExpr::AO__atomic_store_n ||
5775              Op == AtomicExpr::AO__atomic_exchange_n ||
5776              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5777   bool IsAddSub = false;
5778 
5779   switch (Op) {
5780   case AtomicExpr::AO__c11_atomic_init:
5781   case AtomicExpr::AO__opencl_atomic_init:
5782     Form = Init;
5783     break;
5784 
5785   case AtomicExpr::AO__c11_atomic_load:
5786   case AtomicExpr::AO__opencl_atomic_load:
5787   case AtomicExpr::AO__hip_atomic_load:
5788   case AtomicExpr::AO__atomic_load_n:
5789     Form = Load;
5790     break;
5791 
5792   case AtomicExpr::AO__atomic_load:
5793     Form = LoadCopy;
5794     break;
5795 
5796   case AtomicExpr::AO__c11_atomic_store:
5797   case AtomicExpr::AO__opencl_atomic_store:
5798   case AtomicExpr::AO__hip_atomic_store:
5799   case AtomicExpr::AO__atomic_store:
5800   case AtomicExpr::AO__atomic_store_n:
5801     Form = Copy;
5802     break;
5803   case AtomicExpr::AO__hip_atomic_fetch_add:
5804   case AtomicExpr::AO__hip_atomic_fetch_min:
5805   case AtomicExpr::AO__hip_atomic_fetch_max:
5806   case AtomicExpr::AO__c11_atomic_fetch_add:
5807   case AtomicExpr::AO__c11_atomic_fetch_sub:
5808   case AtomicExpr::AO__opencl_atomic_fetch_add:
5809   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5810   case AtomicExpr::AO__atomic_fetch_add:
5811   case AtomicExpr::AO__atomic_fetch_sub:
5812   case AtomicExpr::AO__atomic_add_fetch:
5813   case AtomicExpr::AO__atomic_sub_fetch:
5814     IsAddSub = true;
5815     Form = Arithmetic;
5816     break;
5817   case AtomicExpr::AO__c11_atomic_fetch_and:
5818   case AtomicExpr::AO__c11_atomic_fetch_or:
5819   case AtomicExpr::AO__c11_atomic_fetch_xor:
5820   case AtomicExpr::AO__hip_atomic_fetch_and:
5821   case AtomicExpr::AO__hip_atomic_fetch_or:
5822   case AtomicExpr::AO__hip_atomic_fetch_xor:
5823   case AtomicExpr::AO__c11_atomic_fetch_nand:
5824   case AtomicExpr::AO__opencl_atomic_fetch_and:
5825   case AtomicExpr::AO__opencl_atomic_fetch_or:
5826   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5827   case AtomicExpr::AO__atomic_fetch_and:
5828   case AtomicExpr::AO__atomic_fetch_or:
5829   case AtomicExpr::AO__atomic_fetch_xor:
5830   case AtomicExpr::AO__atomic_fetch_nand:
5831   case AtomicExpr::AO__atomic_and_fetch:
5832   case AtomicExpr::AO__atomic_or_fetch:
5833   case AtomicExpr::AO__atomic_xor_fetch:
5834   case AtomicExpr::AO__atomic_nand_fetch:
5835     Form = Arithmetic;
5836     break;
5837   case AtomicExpr::AO__c11_atomic_fetch_min:
5838   case AtomicExpr::AO__c11_atomic_fetch_max:
5839   case AtomicExpr::AO__opencl_atomic_fetch_min:
5840   case AtomicExpr::AO__opencl_atomic_fetch_max:
5841   case AtomicExpr::AO__atomic_min_fetch:
5842   case AtomicExpr::AO__atomic_max_fetch:
5843   case AtomicExpr::AO__atomic_fetch_min:
5844   case AtomicExpr::AO__atomic_fetch_max:
5845     Form = Arithmetic;
5846     break;
5847 
5848   case AtomicExpr::AO__c11_atomic_exchange:
5849   case AtomicExpr::AO__hip_atomic_exchange:
5850   case AtomicExpr::AO__opencl_atomic_exchange:
5851   case AtomicExpr::AO__atomic_exchange_n:
5852     Form = Xchg;
5853     break;
5854 
5855   case AtomicExpr::AO__atomic_exchange:
5856     Form = GNUXchg;
5857     break;
5858 
5859   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5860   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5861   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5862   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5863   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5864   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5865     Form = C11CmpXchg;
5866     break;
5867 
5868   case AtomicExpr::AO__atomic_compare_exchange:
5869   case AtomicExpr::AO__atomic_compare_exchange_n:
5870     Form = GNUCmpXchg;
5871     break;
5872   }
5873 
5874   unsigned AdjustedNumArgs = NumArgs[Form];
5875   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5876     ++AdjustedNumArgs;
5877   // Check we have the right number of arguments.
5878   if (Args.size() < AdjustedNumArgs) {
5879     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5880         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5881         << ExprRange;
5882     return ExprError();
5883   } else if (Args.size() > AdjustedNumArgs) {
5884     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5885          diag::err_typecheck_call_too_many_args)
5886         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5887         << ExprRange;
5888     return ExprError();
5889   }
5890 
5891   // Inspect the first argument of the atomic operation.
5892   Expr *Ptr = Args[0];
5893   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5894   if (ConvertedPtr.isInvalid())
5895     return ExprError();
5896 
5897   Ptr = ConvertedPtr.get();
5898   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5899   if (!pointerType) {
5900     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5901         << Ptr->getType() << Ptr->getSourceRange();
5902     return ExprError();
5903   }
5904 
5905   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5906   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5907   QualType ValType = AtomTy; // 'C'
5908   if (IsC11) {
5909     if (!AtomTy->isAtomicType()) {
5910       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5911           << Ptr->getType() << Ptr->getSourceRange();
5912       return ExprError();
5913     }
5914     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5915         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5916       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5917           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5918           << Ptr->getSourceRange();
5919       return ExprError();
5920     }
5921     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5922   } else if (Form != Load && Form != LoadCopy) {
5923     if (ValType.isConstQualified()) {
5924       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5925           << Ptr->getType() << Ptr->getSourceRange();
5926       return ExprError();
5927     }
5928   }
5929 
5930   // For an arithmetic operation, the implied arithmetic must be well-formed.
5931   if (Form == Arithmetic) {
5932     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5933     // trivial type errors.
5934     auto IsAllowedValueType = [&](QualType ValType) {
5935       if (ValType->isIntegerType())
5936         return true;
5937       if (ValType->isPointerType())
5938         return true;
5939       if (!ValType->isFloatingType())
5940         return false;
5941       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5942       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5943           &Context.getTargetInfo().getLongDoubleFormat() ==
5944               &llvm::APFloat::x87DoubleExtended())
5945         return false;
5946       return true;
5947     };
5948     if (IsAddSub && !IsAllowedValueType(ValType)) {
5949       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5950           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5951       return ExprError();
5952     }
5953     if (!IsAddSub && !ValType->isIntegerType()) {
5954       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5955           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5956       return ExprError();
5957     }
5958     if (IsC11 && ValType->isPointerType() &&
5959         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5960                             diag::err_incomplete_type)) {
5961       return ExprError();
5962     }
5963   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5964     // For __atomic_*_n operations, the value type must be a scalar integral or
5965     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5966     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5967         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5968     return ExprError();
5969   }
5970 
5971   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5972       !AtomTy->isScalarType()) {
5973     // For GNU atomics, require a trivially-copyable type. This is not part of
5974     // the GNU atomics specification but we enforce it for consistency with
5975     // other atomics which generally all require a trivially-copyable type. This
5976     // is because atomics just copy bits.
5977     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5978         << Ptr->getType() << Ptr->getSourceRange();
5979     return ExprError();
5980   }
5981 
5982   switch (ValType.getObjCLifetime()) {
5983   case Qualifiers::OCL_None:
5984   case Qualifiers::OCL_ExplicitNone:
5985     // okay
5986     break;
5987 
5988   case Qualifiers::OCL_Weak:
5989   case Qualifiers::OCL_Strong:
5990   case Qualifiers::OCL_Autoreleasing:
5991     // FIXME: Can this happen? By this point, ValType should be known
5992     // to be trivially copyable.
5993     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5994         << ValType << Ptr->getSourceRange();
5995     return ExprError();
5996   }
5997 
5998   // All atomic operations have an overload which takes a pointer to a volatile
5999   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
6000   // into the result or the other operands. Similarly atomic_load takes a
6001   // pointer to a const 'A'.
6002   ValType.removeLocalVolatile();
6003   ValType.removeLocalConst();
6004   QualType ResultType = ValType;
6005   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
6006       Form == Init)
6007     ResultType = Context.VoidTy;
6008   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
6009     ResultType = Context.BoolTy;
6010 
6011   // The type of a parameter passed 'by value'. In the GNU atomics, such
6012   // arguments are actually passed as pointers.
6013   QualType ByValType = ValType; // 'CP'
6014   bool IsPassedByAddress = false;
6015   if (!IsC11 && !IsHIP && !IsN) {
6016     ByValType = Ptr->getType();
6017     IsPassedByAddress = true;
6018   }
6019 
6020   SmallVector<Expr *, 5> APIOrderedArgs;
6021   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
6022     APIOrderedArgs.push_back(Args[0]);
6023     switch (Form) {
6024     case Init:
6025     case Load:
6026       APIOrderedArgs.push_back(Args[1]); // Val1/Order
6027       break;
6028     case LoadCopy:
6029     case Copy:
6030     case Arithmetic:
6031     case Xchg:
6032       APIOrderedArgs.push_back(Args[2]); // Val1
6033       APIOrderedArgs.push_back(Args[1]); // Order
6034       break;
6035     case GNUXchg:
6036       APIOrderedArgs.push_back(Args[2]); // Val1
6037       APIOrderedArgs.push_back(Args[3]); // Val2
6038       APIOrderedArgs.push_back(Args[1]); // Order
6039       break;
6040     case C11CmpXchg:
6041       APIOrderedArgs.push_back(Args[2]); // Val1
6042       APIOrderedArgs.push_back(Args[4]); // Val2
6043       APIOrderedArgs.push_back(Args[1]); // Order
6044       APIOrderedArgs.push_back(Args[3]); // OrderFail
6045       break;
6046     case GNUCmpXchg:
6047       APIOrderedArgs.push_back(Args[2]); // Val1
6048       APIOrderedArgs.push_back(Args[4]); // Val2
6049       APIOrderedArgs.push_back(Args[5]); // Weak
6050       APIOrderedArgs.push_back(Args[1]); // Order
6051       APIOrderedArgs.push_back(Args[3]); // OrderFail
6052       break;
6053     }
6054   } else
6055     APIOrderedArgs.append(Args.begin(), Args.end());
6056 
6057   // The first argument's non-CV pointer type is used to deduce the type of
6058   // subsequent arguments, except for:
6059   //  - weak flag (always converted to bool)
6060   //  - memory order (always converted to int)
6061   //  - scope  (always converted to int)
6062   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
6063     QualType Ty;
6064     if (i < NumVals[Form] + 1) {
6065       switch (i) {
6066       case 0:
6067         // The first argument is always a pointer. It has a fixed type.
6068         // It is always dereferenced, a nullptr is undefined.
6069         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6070         // Nothing else to do: we already know all we want about this pointer.
6071         continue;
6072       case 1:
6073         // The second argument is the non-atomic operand. For arithmetic, this
6074         // is always passed by value, and for a compare_exchange it is always
6075         // passed by address. For the rest, GNU uses by-address and C11 uses
6076         // by-value.
6077         assert(Form != Load);
6078         if (Form == Arithmetic && ValType->isPointerType())
6079           Ty = Context.getPointerDiffType();
6080         else if (Form == Init || Form == Arithmetic)
6081           Ty = ValType;
6082         else if (Form == Copy || Form == Xchg) {
6083           if (IsPassedByAddress) {
6084             // The value pointer is always dereferenced, a nullptr is undefined.
6085             CheckNonNullArgument(*this, APIOrderedArgs[i],
6086                                  ExprRange.getBegin());
6087           }
6088           Ty = ByValType;
6089         } else {
6090           Expr *ValArg = APIOrderedArgs[i];
6091           // The value pointer is always dereferenced, a nullptr is undefined.
6092           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
6093           LangAS AS = LangAS::Default;
6094           // Keep address space of non-atomic pointer type.
6095           if (const PointerType *PtrTy =
6096                   ValArg->getType()->getAs<PointerType>()) {
6097             AS = PtrTy->getPointeeType().getAddressSpace();
6098           }
6099           Ty = Context.getPointerType(
6100               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
6101         }
6102         break;
6103       case 2:
6104         // The third argument to compare_exchange / GNU exchange is the desired
6105         // value, either by-value (for the C11 and *_n variant) or as a pointer.
6106         if (IsPassedByAddress)
6107           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6108         Ty = ByValType;
6109         break;
6110       case 3:
6111         // The fourth argument to GNU compare_exchange is a 'weak' flag.
6112         Ty = Context.BoolTy;
6113         break;
6114       }
6115     } else {
6116       // The order(s) and scope are always converted to int.
6117       Ty = Context.IntTy;
6118     }
6119 
6120     InitializedEntity Entity =
6121         InitializedEntity::InitializeParameter(Context, Ty, false);
6122     ExprResult Arg = APIOrderedArgs[i];
6123     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6124     if (Arg.isInvalid())
6125       return true;
6126     APIOrderedArgs[i] = Arg.get();
6127   }
6128 
6129   // Permute the arguments into a 'consistent' order.
6130   SmallVector<Expr*, 5> SubExprs;
6131   SubExprs.push_back(Ptr);
6132   switch (Form) {
6133   case Init:
6134     // Note, AtomicExpr::getVal1() has a special case for this atomic.
6135     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6136     break;
6137   case Load:
6138     SubExprs.push_back(APIOrderedArgs[1]); // Order
6139     break;
6140   case LoadCopy:
6141   case Copy:
6142   case Arithmetic:
6143   case Xchg:
6144     SubExprs.push_back(APIOrderedArgs[2]); // Order
6145     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6146     break;
6147   case GNUXchg:
6148     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6149     SubExprs.push_back(APIOrderedArgs[3]); // Order
6150     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6151     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6152     break;
6153   case C11CmpXchg:
6154     SubExprs.push_back(APIOrderedArgs[3]); // Order
6155     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6156     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6157     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6158     break;
6159   case GNUCmpXchg:
6160     SubExprs.push_back(APIOrderedArgs[4]); // Order
6161     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6162     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6163     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6164     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6165     break;
6166   }
6167 
6168   if (SubExprs.size() >= 2 && Form != Init) {
6169     if (Optional<llvm::APSInt> Result =
6170             SubExprs[1]->getIntegerConstantExpr(Context))
6171       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6172         Diag(SubExprs[1]->getBeginLoc(),
6173              diag::warn_atomic_op_has_invalid_memory_order)
6174             << SubExprs[1]->getSourceRange();
6175   }
6176 
6177   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6178     auto *Scope = Args[Args.size() - 1];
6179     if (Optional<llvm::APSInt> Result =
6180             Scope->getIntegerConstantExpr(Context)) {
6181       if (!ScopeModel->isValid(Result->getZExtValue()))
6182         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6183             << Scope->getSourceRange();
6184     }
6185     SubExprs.push_back(Scope);
6186   }
6187 
6188   AtomicExpr *AE = new (Context)
6189       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6190 
6191   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6192        Op == AtomicExpr::AO__c11_atomic_store ||
6193        Op == AtomicExpr::AO__opencl_atomic_load ||
6194        Op == AtomicExpr::AO__hip_atomic_load ||
6195        Op == AtomicExpr::AO__opencl_atomic_store ||
6196        Op == AtomicExpr::AO__hip_atomic_store) &&
6197       Context.AtomicUsesUnsupportedLibcall(AE))
6198     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6199         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6200              Op == AtomicExpr::AO__opencl_atomic_load ||
6201              Op == AtomicExpr::AO__hip_atomic_load)
6202                 ? 0
6203                 : 1);
6204 
6205   if (ValType->isBitIntType()) {
6206     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6207     return ExprError();
6208   }
6209 
6210   return AE;
6211 }
6212 
6213 /// checkBuiltinArgument - Given a call to a builtin function, perform
6214 /// normal type-checking on the given argument, updating the call in
6215 /// place.  This is useful when a builtin function requires custom
6216 /// type-checking for some of its arguments but not necessarily all of
6217 /// them.
6218 ///
6219 /// Returns true on error.
6220 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6221   FunctionDecl *Fn = E->getDirectCallee();
6222   assert(Fn && "builtin call without direct callee!");
6223 
6224   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6225   InitializedEntity Entity =
6226     InitializedEntity::InitializeParameter(S.Context, Param);
6227 
6228   ExprResult Arg = E->getArg(ArgIndex);
6229   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6230   if (Arg.isInvalid())
6231     return true;
6232 
6233   E->setArg(ArgIndex, Arg.get());
6234   return false;
6235 }
6236 
6237 /// We have a call to a function like __sync_fetch_and_add, which is an
6238 /// overloaded function based on the pointer type of its first argument.
6239 /// The main BuildCallExpr routines have already promoted the types of
6240 /// arguments because all of these calls are prototyped as void(...).
6241 ///
6242 /// This function goes through and does final semantic checking for these
6243 /// builtins, as well as generating any warnings.
6244 ExprResult
6245 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6246   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6247   Expr *Callee = TheCall->getCallee();
6248   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6249   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6250 
6251   // Ensure that we have at least one argument to do type inference from.
6252   if (TheCall->getNumArgs() < 1) {
6253     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6254         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6255     return ExprError();
6256   }
6257 
6258   // Inspect the first argument of the atomic builtin.  This should always be
6259   // a pointer type, whose element is an integral scalar or pointer type.
6260   // Because it is a pointer type, we don't have to worry about any implicit
6261   // casts here.
6262   // FIXME: We don't allow floating point scalars as input.
6263   Expr *FirstArg = TheCall->getArg(0);
6264   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6265   if (FirstArgResult.isInvalid())
6266     return ExprError();
6267   FirstArg = FirstArgResult.get();
6268   TheCall->setArg(0, FirstArg);
6269 
6270   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6271   if (!pointerType) {
6272     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6273         << FirstArg->getType() << FirstArg->getSourceRange();
6274     return ExprError();
6275   }
6276 
6277   QualType ValType = pointerType->getPointeeType();
6278   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6279       !ValType->isBlockPointerType()) {
6280     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6281         << FirstArg->getType() << FirstArg->getSourceRange();
6282     return ExprError();
6283   }
6284 
6285   if (ValType.isConstQualified()) {
6286     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6287         << FirstArg->getType() << FirstArg->getSourceRange();
6288     return ExprError();
6289   }
6290 
6291   switch (ValType.getObjCLifetime()) {
6292   case Qualifiers::OCL_None:
6293   case Qualifiers::OCL_ExplicitNone:
6294     // okay
6295     break;
6296 
6297   case Qualifiers::OCL_Weak:
6298   case Qualifiers::OCL_Strong:
6299   case Qualifiers::OCL_Autoreleasing:
6300     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6301         << ValType << FirstArg->getSourceRange();
6302     return ExprError();
6303   }
6304 
6305   // Strip any qualifiers off ValType.
6306   ValType = ValType.getUnqualifiedType();
6307 
6308   // The majority of builtins return a value, but a few have special return
6309   // types, so allow them to override appropriately below.
6310   QualType ResultType = ValType;
6311 
6312   // We need to figure out which concrete builtin this maps onto.  For example,
6313   // __sync_fetch_and_add with a 2 byte object turns into
6314   // __sync_fetch_and_add_2.
6315 #define BUILTIN_ROW(x) \
6316   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6317     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6318 
6319   static const unsigned BuiltinIndices[][5] = {
6320     BUILTIN_ROW(__sync_fetch_and_add),
6321     BUILTIN_ROW(__sync_fetch_and_sub),
6322     BUILTIN_ROW(__sync_fetch_and_or),
6323     BUILTIN_ROW(__sync_fetch_and_and),
6324     BUILTIN_ROW(__sync_fetch_and_xor),
6325     BUILTIN_ROW(__sync_fetch_and_nand),
6326 
6327     BUILTIN_ROW(__sync_add_and_fetch),
6328     BUILTIN_ROW(__sync_sub_and_fetch),
6329     BUILTIN_ROW(__sync_and_and_fetch),
6330     BUILTIN_ROW(__sync_or_and_fetch),
6331     BUILTIN_ROW(__sync_xor_and_fetch),
6332     BUILTIN_ROW(__sync_nand_and_fetch),
6333 
6334     BUILTIN_ROW(__sync_val_compare_and_swap),
6335     BUILTIN_ROW(__sync_bool_compare_and_swap),
6336     BUILTIN_ROW(__sync_lock_test_and_set),
6337     BUILTIN_ROW(__sync_lock_release),
6338     BUILTIN_ROW(__sync_swap)
6339   };
6340 #undef BUILTIN_ROW
6341 
6342   // Determine the index of the size.
6343   unsigned SizeIndex;
6344   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6345   case 1: SizeIndex = 0; break;
6346   case 2: SizeIndex = 1; break;
6347   case 4: SizeIndex = 2; break;
6348   case 8: SizeIndex = 3; break;
6349   case 16: SizeIndex = 4; break;
6350   default:
6351     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6352         << FirstArg->getType() << FirstArg->getSourceRange();
6353     return ExprError();
6354   }
6355 
6356   // Each of these builtins has one pointer argument, followed by some number of
6357   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6358   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6359   // as the number of fixed args.
6360   unsigned BuiltinID = FDecl->getBuiltinID();
6361   unsigned BuiltinIndex, NumFixed = 1;
6362   bool WarnAboutSemanticsChange = false;
6363   switch (BuiltinID) {
6364   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6365   case Builtin::BI__sync_fetch_and_add:
6366   case Builtin::BI__sync_fetch_and_add_1:
6367   case Builtin::BI__sync_fetch_and_add_2:
6368   case Builtin::BI__sync_fetch_and_add_4:
6369   case Builtin::BI__sync_fetch_and_add_8:
6370   case Builtin::BI__sync_fetch_and_add_16:
6371     BuiltinIndex = 0;
6372     break;
6373 
6374   case Builtin::BI__sync_fetch_and_sub:
6375   case Builtin::BI__sync_fetch_and_sub_1:
6376   case Builtin::BI__sync_fetch_and_sub_2:
6377   case Builtin::BI__sync_fetch_and_sub_4:
6378   case Builtin::BI__sync_fetch_and_sub_8:
6379   case Builtin::BI__sync_fetch_and_sub_16:
6380     BuiltinIndex = 1;
6381     break;
6382 
6383   case Builtin::BI__sync_fetch_and_or:
6384   case Builtin::BI__sync_fetch_and_or_1:
6385   case Builtin::BI__sync_fetch_and_or_2:
6386   case Builtin::BI__sync_fetch_and_or_4:
6387   case Builtin::BI__sync_fetch_and_or_8:
6388   case Builtin::BI__sync_fetch_and_or_16:
6389     BuiltinIndex = 2;
6390     break;
6391 
6392   case Builtin::BI__sync_fetch_and_and:
6393   case Builtin::BI__sync_fetch_and_and_1:
6394   case Builtin::BI__sync_fetch_and_and_2:
6395   case Builtin::BI__sync_fetch_and_and_4:
6396   case Builtin::BI__sync_fetch_and_and_8:
6397   case Builtin::BI__sync_fetch_and_and_16:
6398     BuiltinIndex = 3;
6399     break;
6400 
6401   case Builtin::BI__sync_fetch_and_xor:
6402   case Builtin::BI__sync_fetch_and_xor_1:
6403   case Builtin::BI__sync_fetch_and_xor_2:
6404   case Builtin::BI__sync_fetch_and_xor_4:
6405   case Builtin::BI__sync_fetch_and_xor_8:
6406   case Builtin::BI__sync_fetch_and_xor_16:
6407     BuiltinIndex = 4;
6408     break;
6409 
6410   case Builtin::BI__sync_fetch_and_nand:
6411   case Builtin::BI__sync_fetch_and_nand_1:
6412   case Builtin::BI__sync_fetch_and_nand_2:
6413   case Builtin::BI__sync_fetch_and_nand_4:
6414   case Builtin::BI__sync_fetch_and_nand_8:
6415   case Builtin::BI__sync_fetch_and_nand_16:
6416     BuiltinIndex = 5;
6417     WarnAboutSemanticsChange = true;
6418     break;
6419 
6420   case Builtin::BI__sync_add_and_fetch:
6421   case Builtin::BI__sync_add_and_fetch_1:
6422   case Builtin::BI__sync_add_and_fetch_2:
6423   case Builtin::BI__sync_add_and_fetch_4:
6424   case Builtin::BI__sync_add_and_fetch_8:
6425   case Builtin::BI__sync_add_and_fetch_16:
6426     BuiltinIndex = 6;
6427     break;
6428 
6429   case Builtin::BI__sync_sub_and_fetch:
6430   case Builtin::BI__sync_sub_and_fetch_1:
6431   case Builtin::BI__sync_sub_and_fetch_2:
6432   case Builtin::BI__sync_sub_and_fetch_4:
6433   case Builtin::BI__sync_sub_and_fetch_8:
6434   case Builtin::BI__sync_sub_and_fetch_16:
6435     BuiltinIndex = 7;
6436     break;
6437 
6438   case Builtin::BI__sync_and_and_fetch:
6439   case Builtin::BI__sync_and_and_fetch_1:
6440   case Builtin::BI__sync_and_and_fetch_2:
6441   case Builtin::BI__sync_and_and_fetch_4:
6442   case Builtin::BI__sync_and_and_fetch_8:
6443   case Builtin::BI__sync_and_and_fetch_16:
6444     BuiltinIndex = 8;
6445     break;
6446 
6447   case Builtin::BI__sync_or_and_fetch:
6448   case Builtin::BI__sync_or_and_fetch_1:
6449   case Builtin::BI__sync_or_and_fetch_2:
6450   case Builtin::BI__sync_or_and_fetch_4:
6451   case Builtin::BI__sync_or_and_fetch_8:
6452   case Builtin::BI__sync_or_and_fetch_16:
6453     BuiltinIndex = 9;
6454     break;
6455 
6456   case Builtin::BI__sync_xor_and_fetch:
6457   case Builtin::BI__sync_xor_and_fetch_1:
6458   case Builtin::BI__sync_xor_and_fetch_2:
6459   case Builtin::BI__sync_xor_and_fetch_4:
6460   case Builtin::BI__sync_xor_and_fetch_8:
6461   case Builtin::BI__sync_xor_and_fetch_16:
6462     BuiltinIndex = 10;
6463     break;
6464 
6465   case Builtin::BI__sync_nand_and_fetch:
6466   case Builtin::BI__sync_nand_and_fetch_1:
6467   case Builtin::BI__sync_nand_and_fetch_2:
6468   case Builtin::BI__sync_nand_and_fetch_4:
6469   case Builtin::BI__sync_nand_and_fetch_8:
6470   case Builtin::BI__sync_nand_and_fetch_16:
6471     BuiltinIndex = 11;
6472     WarnAboutSemanticsChange = true;
6473     break;
6474 
6475   case Builtin::BI__sync_val_compare_and_swap:
6476   case Builtin::BI__sync_val_compare_and_swap_1:
6477   case Builtin::BI__sync_val_compare_and_swap_2:
6478   case Builtin::BI__sync_val_compare_and_swap_4:
6479   case Builtin::BI__sync_val_compare_and_swap_8:
6480   case Builtin::BI__sync_val_compare_and_swap_16:
6481     BuiltinIndex = 12;
6482     NumFixed = 2;
6483     break;
6484 
6485   case Builtin::BI__sync_bool_compare_and_swap:
6486   case Builtin::BI__sync_bool_compare_and_swap_1:
6487   case Builtin::BI__sync_bool_compare_and_swap_2:
6488   case Builtin::BI__sync_bool_compare_and_swap_4:
6489   case Builtin::BI__sync_bool_compare_and_swap_8:
6490   case Builtin::BI__sync_bool_compare_and_swap_16:
6491     BuiltinIndex = 13;
6492     NumFixed = 2;
6493     ResultType = Context.BoolTy;
6494     break;
6495 
6496   case Builtin::BI__sync_lock_test_and_set:
6497   case Builtin::BI__sync_lock_test_and_set_1:
6498   case Builtin::BI__sync_lock_test_and_set_2:
6499   case Builtin::BI__sync_lock_test_and_set_4:
6500   case Builtin::BI__sync_lock_test_and_set_8:
6501   case Builtin::BI__sync_lock_test_and_set_16:
6502     BuiltinIndex = 14;
6503     break;
6504 
6505   case Builtin::BI__sync_lock_release:
6506   case Builtin::BI__sync_lock_release_1:
6507   case Builtin::BI__sync_lock_release_2:
6508   case Builtin::BI__sync_lock_release_4:
6509   case Builtin::BI__sync_lock_release_8:
6510   case Builtin::BI__sync_lock_release_16:
6511     BuiltinIndex = 15;
6512     NumFixed = 0;
6513     ResultType = Context.VoidTy;
6514     break;
6515 
6516   case Builtin::BI__sync_swap:
6517   case Builtin::BI__sync_swap_1:
6518   case Builtin::BI__sync_swap_2:
6519   case Builtin::BI__sync_swap_4:
6520   case Builtin::BI__sync_swap_8:
6521   case Builtin::BI__sync_swap_16:
6522     BuiltinIndex = 16;
6523     break;
6524   }
6525 
6526   // Now that we know how many fixed arguments we expect, first check that we
6527   // have at least that many.
6528   if (TheCall->getNumArgs() < 1+NumFixed) {
6529     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6530         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6531         << Callee->getSourceRange();
6532     return ExprError();
6533   }
6534 
6535   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6536       << Callee->getSourceRange();
6537 
6538   if (WarnAboutSemanticsChange) {
6539     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6540         << Callee->getSourceRange();
6541   }
6542 
6543   // Get the decl for the concrete builtin from this, we can tell what the
6544   // concrete integer type we should convert to is.
6545   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6546   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6547   FunctionDecl *NewBuiltinDecl;
6548   if (NewBuiltinID == BuiltinID)
6549     NewBuiltinDecl = FDecl;
6550   else {
6551     // Perform builtin lookup to avoid redeclaring it.
6552     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6553     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6554     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6555     assert(Res.getFoundDecl());
6556     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6557     if (!NewBuiltinDecl)
6558       return ExprError();
6559   }
6560 
6561   // The first argument --- the pointer --- has a fixed type; we
6562   // deduce the types of the rest of the arguments accordingly.  Walk
6563   // the remaining arguments, converting them to the deduced value type.
6564   for (unsigned i = 0; i != NumFixed; ++i) {
6565     ExprResult Arg = TheCall->getArg(i+1);
6566 
6567     // GCC does an implicit conversion to the pointer or integer ValType.  This
6568     // can fail in some cases (1i -> int**), check for this error case now.
6569     // Initialize the argument.
6570     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6571                                                    ValType, /*consume*/ false);
6572     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6573     if (Arg.isInvalid())
6574       return ExprError();
6575 
6576     // Okay, we have something that *can* be converted to the right type.  Check
6577     // to see if there is a potentially weird extension going on here.  This can
6578     // happen when you do an atomic operation on something like an char* and
6579     // pass in 42.  The 42 gets converted to char.  This is even more strange
6580     // for things like 45.123 -> char, etc.
6581     // FIXME: Do this check.
6582     TheCall->setArg(i+1, Arg.get());
6583   }
6584 
6585   // Create a new DeclRefExpr to refer to the new decl.
6586   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6587       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6588       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6589       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6590 
6591   // Set the callee in the CallExpr.
6592   // FIXME: This loses syntactic information.
6593   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6594   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6595                                               CK_BuiltinFnToFnPtr);
6596   TheCall->setCallee(PromotedCall.get());
6597 
6598   // Change the result type of the call to match the original value type. This
6599   // is arbitrary, but the codegen for these builtins ins design to handle it
6600   // gracefully.
6601   TheCall->setType(ResultType);
6602 
6603   // Prohibit problematic uses of bit-precise integer types with atomic
6604   // builtins. The arguments would have already been converted to the first
6605   // argument's type, so only need to check the first argument.
6606   const auto *BitIntValType = ValType->getAs<BitIntType>();
6607   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6608     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6609     return ExprError();
6610   }
6611 
6612   return TheCallResult;
6613 }
6614 
6615 /// SemaBuiltinNontemporalOverloaded - We have a call to
6616 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6617 /// overloaded function based on the pointer type of its last argument.
6618 ///
6619 /// This function goes through and does final semantic checking for these
6620 /// builtins.
6621 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6622   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6623   DeclRefExpr *DRE =
6624       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6625   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6626   unsigned BuiltinID = FDecl->getBuiltinID();
6627   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6628           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6629          "Unexpected nontemporal load/store builtin!");
6630   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6631   unsigned numArgs = isStore ? 2 : 1;
6632 
6633   // Ensure that we have the proper number of arguments.
6634   if (checkArgCount(*this, TheCall, numArgs))
6635     return ExprError();
6636 
6637   // Inspect the last argument of the nontemporal builtin.  This should always
6638   // be a pointer type, from which we imply the type of the memory access.
6639   // Because it is a pointer type, we don't have to worry about any implicit
6640   // casts here.
6641   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6642   ExprResult PointerArgResult =
6643       DefaultFunctionArrayLvalueConversion(PointerArg);
6644 
6645   if (PointerArgResult.isInvalid())
6646     return ExprError();
6647   PointerArg = PointerArgResult.get();
6648   TheCall->setArg(numArgs - 1, PointerArg);
6649 
6650   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6651   if (!pointerType) {
6652     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6653         << PointerArg->getType() << PointerArg->getSourceRange();
6654     return ExprError();
6655   }
6656 
6657   QualType ValType = pointerType->getPointeeType();
6658 
6659   // Strip any qualifiers off ValType.
6660   ValType = ValType.getUnqualifiedType();
6661   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6662       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6663       !ValType->isVectorType()) {
6664     Diag(DRE->getBeginLoc(),
6665          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6666         << PointerArg->getType() << PointerArg->getSourceRange();
6667     return ExprError();
6668   }
6669 
6670   if (!isStore) {
6671     TheCall->setType(ValType);
6672     return TheCallResult;
6673   }
6674 
6675   ExprResult ValArg = TheCall->getArg(0);
6676   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6677       Context, ValType, /*consume*/ false);
6678   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6679   if (ValArg.isInvalid())
6680     return ExprError();
6681 
6682   TheCall->setArg(0, ValArg.get());
6683   TheCall->setType(Context.VoidTy);
6684   return TheCallResult;
6685 }
6686 
6687 /// CheckObjCString - Checks that the argument to the builtin
6688 /// CFString constructor is correct
6689 /// Note: It might also make sense to do the UTF-16 conversion here (would
6690 /// simplify the backend).
6691 bool Sema::CheckObjCString(Expr *Arg) {
6692   Arg = Arg->IgnoreParenCasts();
6693   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6694 
6695   if (!Literal || !Literal->isAscii()) {
6696     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6697         << Arg->getSourceRange();
6698     return true;
6699   }
6700 
6701   if (Literal->containsNonAsciiOrNull()) {
6702     StringRef String = Literal->getString();
6703     unsigned NumBytes = String.size();
6704     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6705     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6706     llvm::UTF16 *ToPtr = &ToBuf[0];
6707 
6708     llvm::ConversionResult Result =
6709         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6710                                  ToPtr + NumBytes, llvm::strictConversion);
6711     // Check for conversion failure.
6712     if (Result != llvm::conversionOK)
6713       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6714           << Arg->getSourceRange();
6715   }
6716   return false;
6717 }
6718 
6719 /// CheckObjCString - Checks that the format string argument to the os_log()
6720 /// and os_trace() functions is correct, and converts it to const char *.
6721 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6722   Arg = Arg->IgnoreParenCasts();
6723   auto *Literal = dyn_cast<StringLiteral>(Arg);
6724   if (!Literal) {
6725     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6726       Literal = ObjcLiteral->getString();
6727     }
6728   }
6729 
6730   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6731     return ExprError(
6732         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6733         << Arg->getSourceRange());
6734   }
6735 
6736   ExprResult Result(Literal);
6737   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6738   InitializedEntity Entity =
6739       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6740   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6741   return Result;
6742 }
6743 
6744 /// Check that the user is calling the appropriate va_start builtin for the
6745 /// target and calling convention.
6746 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6747   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6748   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6749   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6750                     TT.getArch() == llvm::Triple::aarch64_32);
6751   bool IsWindows = TT.isOSWindows();
6752   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6753   if (IsX64 || IsAArch64) {
6754     CallingConv CC = CC_C;
6755     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6756       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6757     if (IsMSVAStart) {
6758       // Don't allow this in System V ABI functions.
6759       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6760         return S.Diag(Fn->getBeginLoc(),
6761                       diag::err_ms_va_start_used_in_sysv_function);
6762     } else {
6763       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6764       // On x64 Windows, don't allow this in System V ABI functions.
6765       // (Yes, that means there's no corresponding way to support variadic
6766       // System V ABI functions on Windows.)
6767       if ((IsWindows && CC == CC_X86_64SysV) ||
6768           (!IsWindows && CC == CC_Win64))
6769         return S.Diag(Fn->getBeginLoc(),
6770                       diag::err_va_start_used_in_wrong_abi_function)
6771                << !IsWindows;
6772     }
6773     return false;
6774   }
6775 
6776   if (IsMSVAStart)
6777     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6778   return false;
6779 }
6780 
6781 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6782                                              ParmVarDecl **LastParam = nullptr) {
6783   // Determine whether the current function, block, or obj-c method is variadic
6784   // and get its parameter list.
6785   bool IsVariadic = false;
6786   ArrayRef<ParmVarDecl *> Params;
6787   DeclContext *Caller = S.CurContext;
6788   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6789     IsVariadic = Block->isVariadic();
6790     Params = Block->parameters();
6791   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6792     IsVariadic = FD->isVariadic();
6793     Params = FD->parameters();
6794   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6795     IsVariadic = MD->isVariadic();
6796     // FIXME: This isn't correct for methods (results in bogus warning).
6797     Params = MD->parameters();
6798   } else if (isa<CapturedDecl>(Caller)) {
6799     // We don't support va_start in a CapturedDecl.
6800     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6801     return true;
6802   } else {
6803     // This must be some other declcontext that parses exprs.
6804     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6805     return true;
6806   }
6807 
6808   if (!IsVariadic) {
6809     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6810     return true;
6811   }
6812 
6813   if (LastParam)
6814     *LastParam = Params.empty() ? nullptr : Params.back();
6815 
6816   return false;
6817 }
6818 
6819 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6820 /// for validity.  Emit an error and return true on failure; return false
6821 /// on success.
6822 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6823   Expr *Fn = TheCall->getCallee();
6824 
6825   if (checkVAStartABI(*this, BuiltinID, Fn))
6826     return true;
6827 
6828   if (checkArgCount(*this, TheCall, 2))
6829     return true;
6830 
6831   // Type-check the first argument normally.
6832   if (checkBuiltinArgument(*this, TheCall, 0))
6833     return true;
6834 
6835   // Check that the current function is variadic, and get its last parameter.
6836   ParmVarDecl *LastParam;
6837   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6838     return true;
6839 
6840   // Verify that the second argument to the builtin is the last argument of the
6841   // current function or method.
6842   bool SecondArgIsLastNamedArgument = false;
6843   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6844 
6845   // These are valid if SecondArgIsLastNamedArgument is false after the next
6846   // block.
6847   QualType Type;
6848   SourceLocation ParamLoc;
6849   bool IsCRegister = false;
6850 
6851   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6852     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6853       SecondArgIsLastNamedArgument = PV == LastParam;
6854 
6855       Type = PV->getType();
6856       ParamLoc = PV->getLocation();
6857       IsCRegister =
6858           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6859     }
6860   }
6861 
6862   if (!SecondArgIsLastNamedArgument)
6863     Diag(TheCall->getArg(1)->getBeginLoc(),
6864          diag::warn_second_arg_of_va_start_not_last_named_param);
6865   else if (IsCRegister || Type->isReferenceType() ||
6866            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6867              // Promotable integers are UB, but enumerations need a bit of
6868              // extra checking to see what their promotable type actually is.
6869              if (!Type->isPromotableIntegerType())
6870                return false;
6871              if (!Type->isEnumeralType())
6872                return true;
6873              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6874              return !(ED &&
6875                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6876            }()) {
6877     unsigned Reason = 0;
6878     if (Type->isReferenceType())  Reason = 1;
6879     else if (IsCRegister)         Reason = 2;
6880     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6881     Diag(ParamLoc, diag::note_parameter_type) << Type;
6882   }
6883 
6884   TheCall->setType(Context.VoidTy);
6885   return false;
6886 }
6887 
6888 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6889   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6890     const LangOptions &LO = getLangOpts();
6891 
6892     if (LO.CPlusPlus)
6893       return Arg->getType()
6894                  .getCanonicalType()
6895                  .getTypePtr()
6896                  ->getPointeeType()
6897                  .withoutLocalFastQualifiers() == Context.CharTy;
6898 
6899     // In C, allow aliasing through `char *`, this is required for AArch64 at
6900     // least.
6901     return true;
6902   };
6903 
6904   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6905   //                 const char *named_addr);
6906 
6907   Expr *Func = Call->getCallee();
6908 
6909   if (Call->getNumArgs() < 3)
6910     return Diag(Call->getEndLoc(),
6911                 diag::err_typecheck_call_too_few_args_at_least)
6912            << 0 /*function call*/ << 3 << Call->getNumArgs();
6913 
6914   // Type-check the first argument normally.
6915   if (checkBuiltinArgument(*this, Call, 0))
6916     return true;
6917 
6918   // Check that the current function is variadic.
6919   if (checkVAStartIsInVariadicFunction(*this, Func))
6920     return true;
6921 
6922   // __va_start on Windows does not validate the parameter qualifiers
6923 
6924   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6925   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6926 
6927   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6928   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6929 
6930   const QualType &ConstCharPtrTy =
6931       Context.getPointerType(Context.CharTy.withConst());
6932   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6933     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6934         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6935         << 0                                      /* qualifier difference */
6936         << 3                                      /* parameter mismatch */
6937         << 2 << Arg1->getType() << ConstCharPtrTy;
6938 
6939   const QualType SizeTy = Context.getSizeType();
6940   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6941     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6942         << Arg2->getType() << SizeTy << 1 /* different class */
6943         << 0                              /* qualifier difference */
6944         << 3                              /* parameter mismatch */
6945         << 3 << Arg2->getType() << SizeTy;
6946 
6947   return false;
6948 }
6949 
6950 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6951 /// friends.  This is declared to take (...), so we have to check everything.
6952 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6953   if (checkArgCount(*this, TheCall, 2))
6954     return true;
6955 
6956   ExprResult OrigArg0 = TheCall->getArg(0);
6957   ExprResult OrigArg1 = TheCall->getArg(1);
6958 
6959   // Do standard promotions between the two arguments, returning their common
6960   // type.
6961   QualType Res = UsualArithmeticConversions(
6962       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6963   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6964     return true;
6965 
6966   // Make sure any conversions are pushed back into the call; this is
6967   // type safe since unordered compare builtins are declared as "_Bool
6968   // foo(...)".
6969   TheCall->setArg(0, OrigArg0.get());
6970   TheCall->setArg(1, OrigArg1.get());
6971 
6972   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6973     return false;
6974 
6975   // If the common type isn't a real floating type, then the arguments were
6976   // invalid for this operation.
6977   if (Res.isNull() || !Res->isRealFloatingType())
6978     return Diag(OrigArg0.get()->getBeginLoc(),
6979                 diag::err_typecheck_call_invalid_ordered_compare)
6980            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6981            << SourceRange(OrigArg0.get()->getBeginLoc(),
6982                           OrigArg1.get()->getEndLoc());
6983 
6984   return false;
6985 }
6986 
6987 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6988 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6989 /// to check everything. We expect the last argument to be a floating point
6990 /// value.
6991 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6992   if (checkArgCount(*this, TheCall, NumArgs))
6993     return true;
6994 
6995   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6996   // on all preceding parameters just being int.  Try all of those.
6997   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6998     Expr *Arg = TheCall->getArg(i);
6999 
7000     if (Arg->isTypeDependent())
7001       return false;
7002 
7003     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
7004 
7005     if (Res.isInvalid())
7006       return true;
7007     TheCall->setArg(i, Res.get());
7008   }
7009 
7010   Expr *OrigArg = TheCall->getArg(NumArgs-1);
7011 
7012   if (OrigArg->isTypeDependent())
7013     return false;
7014 
7015   // Usual Unary Conversions will convert half to float, which we want for
7016   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
7017   // type how it is, but do normal L->Rvalue conversions.
7018   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
7019     OrigArg = UsualUnaryConversions(OrigArg).get();
7020   else
7021     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
7022   TheCall->setArg(NumArgs - 1, OrigArg);
7023 
7024   // This operation requires a non-_Complex floating-point number.
7025   if (!OrigArg->getType()->isRealFloatingType())
7026     return Diag(OrigArg->getBeginLoc(),
7027                 diag::err_typecheck_call_invalid_unary_fp)
7028            << OrigArg->getType() << OrigArg->getSourceRange();
7029 
7030   return false;
7031 }
7032 
7033 /// Perform semantic analysis for a call to __builtin_complex.
7034 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
7035   if (checkArgCount(*this, TheCall, 2))
7036     return true;
7037 
7038   bool Dependent = false;
7039   for (unsigned I = 0; I != 2; ++I) {
7040     Expr *Arg = TheCall->getArg(I);
7041     QualType T = Arg->getType();
7042     if (T->isDependentType()) {
7043       Dependent = true;
7044       continue;
7045     }
7046 
7047     // Despite supporting _Complex int, GCC requires a real floating point type
7048     // for the operands of __builtin_complex.
7049     if (!T->isRealFloatingType()) {
7050       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
7051              << Arg->getType() << Arg->getSourceRange();
7052     }
7053 
7054     ExprResult Converted = DefaultLvalueConversion(Arg);
7055     if (Converted.isInvalid())
7056       return true;
7057     TheCall->setArg(I, Converted.get());
7058   }
7059 
7060   if (Dependent) {
7061     TheCall->setType(Context.DependentTy);
7062     return false;
7063   }
7064 
7065   Expr *Real = TheCall->getArg(0);
7066   Expr *Imag = TheCall->getArg(1);
7067   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
7068     return Diag(Real->getBeginLoc(),
7069                 diag::err_typecheck_call_different_arg_types)
7070            << Real->getType() << Imag->getType()
7071            << Real->getSourceRange() << Imag->getSourceRange();
7072   }
7073 
7074   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
7075   // don't allow this builtin to form those types either.
7076   // FIXME: Should we allow these types?
7077   if (Real->getType()->isFloat16Type())
7078     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7079            << "_Float16";
7080   if (Real->getType()->isHalfType())
7081     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7082            << "half";
7083 
7084   TheCall->setType(Context.getComplexType(Real->getType()));
7085   return false;
7086 }
7087 
7088 // Customized Sema Checking for VSX builtins that have the following signature:
7089 // vector [...] builtinName(vector [...], vector [...], const int);
7090 // Which takes the same type of vectors (any legal vector type) for the first
7091 // two arguments and takes compile time constant for the third argument.
7092 // Example builtins are :
7093 // vector double vec_xxpermdi(vector double, vector double, int);
7094 // vector short vec_xxsldwi(vector short, vector short, int);
7095 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
7096   unsigned ExpectedNumArgs = 3;
7097   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
7098     return true;
7099 
7100   // Check the third argument is a compile time constant
7101   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
7102     return Diag(TheCall->getBeginLoc(),
7103                 diag::err_vsx_builtin_nonconstant_argument)
7104            << 3 /* argument index */ << TheCall->getDirectCallee()
7105            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
7106                           TheCall->getArg(2)->getEndLoc());
7107 
7108   QualType Arg1Ty = TheCall->getArg(0)->getType();
7109   QualType Arg2Ty = TheCall->getArg(1)->getType();
7110 
7111   // Check the type of argument 1 and argument 2 are vectors.
7112   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
7113   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
7114       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
7115     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
7116            << TheCall->getDirectCallee()
7117            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7118                           TheCall->getArg(1)->getEndLoc());
7119   }
7120 
7121   // Check the first two arguments are the same type.
7122   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
7123     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
7124            << TheCall->getDirectCallee()
7125            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7126                           TheCall->getArg(1)->getEndLoc());
7127   }
7128 
7129   // When default clang type checking is turned off and the customized type
7130   // checking is used, the returning type of the function must be explicitly
7131   // set. Otherwise it is _Bool by default.
7132   TheCall->setType(Arg1Ty);
7133 
7134   return false;
7135 }
7136 
7137 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
7138 // This is declared to take (...), so we have to check everything.
7139 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
7140   if (TheCall->getNumArgs() < 2)
7141     return ExprError(Diag(TheCall->getEndLoc(),
7142                           diag::err_typecheck_call_too_few_args_at_least)
7143                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7144                      << TheCall->getSourceRange());
7145 
7146   // Determine which of the following types of shufflevector we're checking:
7147   // 1) unary, vector mask: (lhs, mask)
7148   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7149   QualType resType = TheCall->getArg(0)->getType();
7150   unsigned numElements = 0;
7151 
7152   if (!TheCall->getArg(0)->isTypeDependent() &&
7153       !TheCall->getArg(1)->isTypeDependent()) {
7154     QualType LHSType = TheCall->getArg(0)->getType();
7155     QualType RHSType = TheCall->getArg(1)->getType();
7156 
7157     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7158       return ExprError(
7159           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7160           << TheCall->getDirectCallee()
7161           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7162                          TheCall->getArg(1)->getEndLoc()));
7163 
7164     numElements = LHSType->castAs<VectorType>()->getNumElements();
7165     unsigned numResElements = TheCall->getNumArgs() - 2;
7166 
7167     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7168     // with mask.  If so, verify that RHS is an integer vector type with the
7169     // same number of elts as lhs.
7170     if (TheCall->getNumArgs() == 2) {
7171       if (!RHSType->hasIntegerRepresentation() ||
7172           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7173         return ExprError(Diag(TheCall->getBeginLoc(),
7174                               diag::err_vec_builtin_incompatible_vector)
7175                          << TheCall->getDirectCallee()
7176                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7177                                         TheCall->getArg(1)->getEndLoc()));
7178     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7179       return ExprError(Diag(TheCall->getBeginLoc(),
7180                             diag::err_vec_builtin_incompatible_vector)
7181                        << TheCall->getDirectCallee()
7182                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7183                                       TheCall->getArg(1)->getEndLoc()));
7184     } else if (numElements != numResElements) {
7185       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7186       resType = Context.getVectorType(eltType, numResElements,
7187                                       VectorType::GenericVector);
7188     }
7189   }
7190 
7191   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7192     if (TheCall->getArg(i)->isTypeDependent() ||
7193         TheCall->getArg(i)->isValueDependent())
7194       continue;
7195 
7196     Optional<llvm::APSInt> Result;
7197     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7198       return ExprError(Diag(TheCall->getBeginLoc(),
7199                             diag::err_shufflevector_nonconstant_argument)
7200                        << TheCall->getArg(i)->getSourceRange());
7201 
7202     // Allow -1 which will be translated to undef in the IR.
7203     if (Result->isSigned() && Result->isAllOnes())
7204       continue;
7205 
7206     if (Result->getActiveBits() > 64 ||
7207         Result->getZExtValue() >= numElements * 2)
7208       return ExprError(Diag(TheCall->getBeginLoc(),
7209                             diag::err_shufflevector_argument_too_large)
7210                        << TheCall->getArg(i)->getSourceRange());
7211   }
7212 
7213   SmallVector<Expr*, 32> exprs;
7214 
7215   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7216     exprs.push_back(TheCall->getArg(i));
7217     TheCall->setArg(i, nullptr);
7218   }
7219 
7220   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7221                                          TheCall->getCallee()->getBeginLoc(),
7222                                          TheCall->getRParenLoc());
7223 }
7224 
7225 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7226 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7227                                        SourceLocation BuiltinLoc,
7228                                        SourceLocation RParenLoc) {
7229   ExprValueKind VK = VK_PRValue;
7230   ExprObjectKind OK = OK_Ordinary;
7231   QualType DstTy = TInfo->getType();
7232   QualType SrcTy = E->getType();
7233 
7234   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7235     return ExprError(Diag(BuiltinLoc,
7236                           diag::err_convertvector_non_vector)
7237                      << E->getSourceRange());
7238   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7239     return ExprError(Diag(BuiltinLoc,
7240                           diag::err_convertvector_non_vector_type));
7241 
7242   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7243     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7244     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7245     if (SrcElts != DstElts)
7246       return ExprError(Diag(BuiltinLoc,
7247                             diag::err_convertvector_incompatible_vector)
7248                        << E->getSourceRange());
7249   }
7250 
7251   return new (Context)
7252       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7253 }
7254 
7255 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7256 // This is declared to take (const void*, ...) and can take two
7257 // optional constant int args.
7258 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7259   unsigned NumArgs = TheCall->getNumArgs();
7260 
7261   if (NumArgs > 3)
7262     return Diag(TheCall->getEndLoc(),
7263                 diag::err_typecheck_call_too_many_args_at_most)
7264            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7265 
7266   // Argument 0 is checked for us and the remaining arguments must be
7267   // constant integers.
7268   for (unsigned i = 1; i != NumArgs; ++i)
7269     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7270       return true;
7271 
7272   return false;
7273 }
7274 
7275 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7276 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7277   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7278     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7279            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7280   if (checkArgCount(*this, TheCall, 1))
7281     return true;
7282   Expr *Arg = TheCall->getArg(0);
7283   if (Arg->isInstantiationDependent())
7284     return false;
7285 
7286   QualType ArgTy = Arg->getType();
7287   if (!ArgTy->hasFloatingRepresentation())
7288     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7289            << ArgTy;
7290   if (Arg->isLValue()) {
7291     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7292     TheCall->setArg(0, FirstArg.get());
7293   }
7294   TheCall->setType(TheCall->getArg(0)->getType());
7295   return false;
7296 }
7297 
7298 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7299 // __assume does not evaluate its arguments, and should warn if its argument
7300 // has side effects.
7301 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7302   Expr *Arg = TheCall->getArg(0);
7303   if (Arg->isInstantiationDependent()) return false;
7304 
7305   if (Arg->HasSideEffects(Context))
7306     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7307         << Arg->getSourceRange()
7308         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7309 
7310   return false;
7311 }
7312 
7313 /// Handle __builtin_alloca_with_align. This is declared
7314 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7315 /// than 8.
7316 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7317   // The alignment must be a constant integer.
7318   Expr *Arg = TheCall->getArg(1);
7319 
7320   // We can't check the value of a dependent argument.
7321   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7322     if (const auto *UE =
7323             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7324       if (UE->getKind() == UETT_AlignOf ||
7325           UE->getKind() == UETT_PreferredAlignOf)
7326         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7327             << Arg->getSourceRange();
7328 
7329     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7330 
7331     if (!Result.isPowerOf2())
7332       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7333              << Arg->getSourceRange();
7334 
7335     if (Result < Context.getCharWidth())
7336       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7337              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7338 
7339     if (Result > std::numeric_limits<int32_t>::max())
7340       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7341              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7342   }
7343 
7344   return false;
7345 }
7346 
7347 /// Handle __builtin_assume_aligned. This is declared
7348 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7349 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7350   unsigned NumArgs = TheCall->getNumArgs();
7351 
7352   if (NumArgs > 3)
7353     return Diag(TheCall->getEndLoc(),
7354                 diag::err_typecheck_call_too_many_args_at_most)
7355            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7356 
7357   // The alignment must be a constant integer.
7358   Expr *Arg = TheCall->getArg(1);
7359 
7360   // We can't check the value of a dependent argument.
7361   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7362     llvm::APSInt Result;
7363     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7364       return true;
7365 
7366     if (!Result.isPowerOf2())
7367       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7368              << Arg->getSourceRange();
7369 
7370     if (Result > Sema::MaximumAlignment)
7371       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7372           << Arg->getSourceRange() << Sema::MaximumAlignment;
7373   }
7374 
7375   if (NumArgs > 2) {
7376     ExprResult Arg(TheCall->getArg(2));
7377     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7378       Context.getSizeType(), false);
7379     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7380     if (Arg.isInvalid()) return true;
7381     TheCall->setArg(2, Arg.get());
7382   }
7383 
7384   return false;
7385 }
7386 
7387 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7388   unsigned BuiltinID =
7389       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7390   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7391 
7392   unsigned NumArgs = TheCall->getNumArgs();
7393   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7394   if (NumArgs < NumRequiredArgs) {
7395     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7396            << 0 /* function call */ << NumRequiredArgs << NumArgs
7397            << TheCall->getSourceRange();
7398   }
7399   if (NumArgs >= NumRequiredArgs + 0x100) {
7400     return Diag(TheCall->getEndLoc(),
7401                 diag::err_typecheck_call_too_many_args_at_most)
7402            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7403            << TheCall->getSourceRange();
7404   }
7405   unsigned i = 0;
7406 
7407   // For formatting call, check buffer arg.
7408   if (!IsSizeCall) {
7409     ExprResult Arg(TheCall->getArg(i));
7410     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7411         Context, Context.VoidPtrTy, false);
7412     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7413     if (Arg.isInvalid())
7414       return true;
7415     TheCall->setArg(i, Arg.get());
7416     i++;
7417   }
7418 
7419   // Check string literal arg.
7420   unsigned FormatIdx = i;
7421   {
7422     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7423     if (Arg.isInvalid())
7424       return true;
7425     TheCall->setArg(i, Arg.get());
7426     i++;
7427   }
7428 
7429   // Make sure variadic args are scalar.
7430   unsigned FirstDataArg = i;
7431   while (i < NumArgs) {
7432     ExprResult Arg = DefaultVariadicArgumentPromotion(
7433         TheCall->getArg(i), VariadicFunction, nullptr);
7434     if (Arg.isInvalid())
7435       return true;
7436     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7437     if (ArgSize.getQuantity() >= 0x100) {
7438       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7439              << i << (int)ArgSize.getQuantity() << 0xff
7440              << TheCall->getSourceRange();
7441     }
7442     TheCall->setArg(i, Arg.get());
7443     i++;
7444   }
7445 
7446   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7447   // call to avoid duplicate diagnostics.
7448   if (!IsSizeCall) {
7449     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7450     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7451     bool Success = CheckFormatArguments(
7452         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7453         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7454         CheckedVarArgs);
7455     if (!Success)
7456       return true;
7457   }
7458 
7459   if (IsSizeCall) {
7460     TheCall->setType(Context.getSizeType());
7461   } else {
7462     TheCall->setType(Context.VoidPtrTy);
7463   }
7464   return false;
7465 }
7466 
7467 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7468 /// TheCall is a constant expression.
7469 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7470                                   llvm::APSInt &Result) {
7471   Expr *Arg = TheCall->getArg(ArgNum);
7472   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7473   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7474 
7475   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7476 
7477   Optional<llvm::APSInt> R;
7478   if (!(R = Arg->getIntegerConstantExpr(Context)))
7479     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7480            << FDecl->getDeclName() << Arg->getSourceRange();
7481   Result = *R;
7482   return false;
7483 }
7484 
7485 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7486 /// TheCall is a constant expression in the range [Low, High].
7487 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7488                                        int Low, int High, bool RangeIsError) {
7489   if (isConstantEvaluated())
7490     return false;
7491   llvm::APSInt Result;
7492 
7493   // We can't check the value of a dependent argument.
7494   Expr *Arg = TheCall->getArg(ArgNum);
7495   if (Arg->isTypeDependent() || Arg->isValueDependent())
7496     return false;
7497 
7498   // Check constant-ness first.
7499   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7500     return true;
7501 
7502   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7503     if (RangeIsError)
7504       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7505              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7506     else
7507       // Defer the warning until we know if the code will be emitted so that
7508       // dead code can ignore this.
7509       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7510                           PDiag(diag::warn_argument_invalid_range)
7511                               << toString(Result, 10) << Low << High
7512                               << Arg->getSourceRange());
7513   }
7514 
7515   return false;
7516 }
7517 
7518 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7519 /// TheCall is a constant expression is a multiple of Num..
7520 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7521                                           unsigned Num) {
7522   llvm::APSInt Result;
7523 
7524   // We can't check the value of a dependent argument.
7525   Expr *Arg = TheCall->getArg(ArgNum);
7526   if (Arg->isTypeDependent() || Arg->isValueDependent())
7527     return false;
7528 
7529   // Check constant-ness first.
7530   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7531     return true;
7532 
7533   if (Result.getSExtValue() % Num != 0)
7534     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7535            << Num << Arg->getSourceRange();
7536 
7537   return false;
7538 }
7539 
7540 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7541 /// constant expression representing a power of 2.
7542 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7543   llvm::APSInt Result;
7544 
7545   // We can't check the value of a dependent argument.
7546   Expr *Arg = TheCall->getArg(ArgNum);
7547   if (Arg->isTypeDependent() || Arg->isValueDependent())
7548     return false;
7549 
7550   // Check constant-ness first.
7551   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7552     return true;
7553 
7554   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7555   // and only if x is a power of 2.
7556   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7557     return false;
7558 
7559   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7560          << Arg->getSourceRange();
7561 }
7562 
7563 static bool IsShiftedByte(llvm::APSInt Value) {
7564   if (Value.isNegative())
7565     return false;
7566 
7567   // Check if it's a shifted byte, by shifting it down
7568   while (true) {
7569     // If the value fits in the bottom byte, the check passes.
7570     if (Value < 0x100)
7571       return true;
7572 
7573     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7574     // fails.
7575     if ((Value & 0xFF) != 0)
7576       return false;
7577 
7578     // If the bottom 8 bits are all 0, but something above that is nonzero,
7579     // then shifting the value right by 8 bits won't affect whether it's a
7580     // shifted byte or not. So do that, and go round again.
7581     Value >>= 8;
7582   }
7583 }
7584 
7585 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7586 /// a constant expression representing an arbitrary byte value shifted left by
7587 /// a multiple of 8 bits.
7588 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7589                                              unsigned ArgBits) {
7590   llvm::APSInt Result;
7591 
7592   // We can't check the value of a dependent argument.
7593   Expr *Arg = TheCall->getArg(ArgNum);
7594   if (Arg->isTypeDependent() || Arg->isValueDependent())
7595     return false;
7596 
7597   // Check constant-ness first.
7598   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7599     return true;
7600 
7601   // Truncate to the given size.
7602   Result = Result.getLoBits(ArgBits);
7603   Result.setIsUnsigned(true);
7604 
7605   if (IsShiftedByte(Result))
7606     return false;
7607 
7608   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7609          << Arg->getSourceRange();
7610 }
7611 
7612 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7613 /// TheCall is a constant expression representing either a shifted byte value,
7614 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7615 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7616 /// Arm MVE intrinsics.
7617 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7618                                                    int ArgNum,
7619                                                    unsigned ArgBits) {
7620   llvm::APSInt Result;
7621 
7622   // We can't check the value of a dependent argument.
7623   Expr *Arg = TheCall->getArg(ArgNum);
7624   if (Arg->isTypeDependent() || Arg->isValueDependent())
7625     return false;
7626 
7627   // Check constant-ness first.
7628   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7629     return true;
7630 
7631   // Truncate to the given size.
7632   Result = Result.getLoBits(ArgBits);
7633   Result.setIsUnsigned(true);
7634 
7635   // Check to see if it's in either of the required forms.
7636   if (IsShiftedByte(Result) ||
7637       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7638     return false;
7639 
7640   return Diag(TheCall->getBeginLoc(),
7641               diag::err_argument_not_shifted_byte_or_xxff)
7642          << Arg->getSourceRange();
7643 }
7644 
7645 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7646 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7647   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7648     if (checkArgCount(*this, TheCall, 2))
7649       return true;
7650     Expr *Arg0 = TheCall->getArg(0);
7651     Expr *Arg1 = TheCall->getArg(1);
7652 
7653     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7654     if (FirstArg.isInvalid())
7655       return true;
7656     QualType FirstArgType = FirstArg.get()->getType();
7657     if (!FirstArgType->isAnyPointerType())
7658       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7659                << "first" << FirstArgType << Arg0->getSourceRange();
7660     TheCall->setArg(0, FirstArg.get());
7661 
7662     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7663     if (SecArg.isInvalid())
7664       return true;
7665     QualType SecArgType = SecArg.get()->getType();
7666     if (!SecArgType->isIntegerType())
7667       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7668                << "second" << SecArgType << Arg1->getSourceRange();
7669 
7670     // Derive the return type from the pointer argument.
7671     TheCall->setType(FirstArgType);
7672     return false;
7673   }
7674 
7675   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7676     if (checkArgCount(*this, TheCall, 2))
7677       return true;
7678 
7679     Expr *Arg0 = TheCall->getArg(0);
7680     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7681     if (FirstArg.isInvalid())
7682       return true;
7683     QualType FirstArgType = FirstArg.get()->getType();
7684     if (!FirstArgType->isAnyPointerType())
7685       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7686                << "first" << FirstArgType << Arg0->getSourceRange();
7687     TheCall->setArg(0, FirstArg.get());
7688 
7689     // Derive the return type from the pointer argument.
7690     TheCall->setType(FirstArgType);
7691 
7692     // Second arg must be an constant in range [0,15]
7693     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7694   }
7695 
7696   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7697     if (checkArgCount(*this, TheCall, 2))
7698       return true;
7699     Expr *Arg0 = TheCall->getArg(0);
7700     Expr *Arg1 = TheCall->getArg(1);
7701 
7702     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7703     if (FirstArg.isInvalid())
7704       return true;
7705     QualType FirstArgType = FirstArg.get()->getType();
7706     if (!FirstArgType->isAnyPointerType())
7707       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7708                << "first" << FirstArgType << Arg0->getSourceRange();
7709 
7710     QualType SecArgType = Arg1->getType();
7711     if (!SecArgType->isIntegerType())
7712       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7713                << "second" << SecArgType << Arg1->getSourceRange();
7714     TheCall->setType(Context.IntTy);
7715     return false;
7716   }
7717 
7718   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7719       BuiltinID == AArch64::BI__builtin_arm_stg) {
7720     if (checkArgCount(*this, TheCall, 1))
7721       return true;
7722     Expr *Arg0 = TheCall->getArg(0);
7723     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7724     if (FirstArg.isInvalid())
7725       return true;
7726 
7727     QualType FirstArgType = FirstArg.get()->getType();
7728     if (!FirstArgType->isAnyPointerType())
7729       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7730                << "first" << FirstArgType << Arg0->getSourceRange();
7731     TheCall->setArg(0, FirstArg.get());
7732 
7733     // Derive the return type from the pointer argument.
7734     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7735       TheCall->setType(FirstArgType);
7736     return false;
7737   }
7738 
7739   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7740     Expr *ArgA = TheCall->getArg(0);
7741     Expr *ArgB = TheCall->getArg(1);
7742 
7743     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7744     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7745 
7746     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7747       return true;
7748 
7749     QualType ArgTypeA = ArgExprA.get()->getType();
7750     QualType ArgTypeB = ArgExprB.get()->getType();
7751 
7752     auto isNull = [&] (Expr *E) -> bool {
7753       return E->isNullPointerConstant(
7754                         Context, Expr::NPC_ValueDependentIsNotNull); };
7755 
7756     // argument should be either a pointer or null
7757     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7758       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7759         << "first" << ArgTypeA << ArgA->getSourceRange();
7760 
7761     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7762       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7763         << "second" << ArgTypeB << ArgB->getSourceRange();
7764 
7765     // Ensure Pointee types are compatible
7766     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7767         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7768       QualType pointeeA = ArgTypeA->getPointeeType();
7769       QualType pointeeB = ArgTypeB->getPointeeType();
7770       if (!Context.typesAreCompatible(
7771              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7772              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7773         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7774           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7775           << ArgB->getSourceRange();
7776       }
7777     }
7778 
7779     // at least one argument should be pointer type
7780     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7781       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7782         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7783 
7784     if (isNull(ArgA)) // adopt type of the other pointer
7785       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7786 
7787     if (isNull(ArgB))
7788       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7789 
7790     TheCall->setArg(0, ArgExprA.get());
7791     TheCall->setArg(1, ArgExprB.get());
7792     TheCall->setType(Context.LongLongTy);
7793     return false;
7794   }
7795   assert(false && "Unhandled ARM MTE intrinsic");
7796   return true;
7797 }
7798 
7799 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7800 /// TheCall is an ARM/AArch64 special register string literal.
7801 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7802                                     int ArgNum, unsigned ExpectedFieldNum,
7803                                     bool AllowName) {
7804   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7805                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7806                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7807                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7808                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7809                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7810   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7811                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7812                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7813                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7814                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7815                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7816   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7817 
7818   // We can't check the value of a dependent argument.
7819   Expr *Arg = TheCall->getArg(ArgNum);
7820   if (Arg->isTypeDependent() || Arg->isValueDependent())
7821     return false;
7822 
7823   // Check if the argument is a string literal.
7824   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7825     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7826            << Arg->getSourceRange();
7827 
7828   // Check the type of special register given.
7829   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7830   SmallVector<StringRef, 6> Fields;
7831   Reg.split(Fields, ":");
7832 
7833   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7834     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7835            << Arg->getSourceRange();
7836 
7837   // If the string is the name of a register then we cannot check that it is
7838   // valid here but if the string is of one the forms described in ACLE then we
7839   // can check that the supplied fields are integers and within the valid
7840   // ranges.
7841   if (Fields.size() > 1) {
7842     bool FiveFields = Fields.size() == 5;
7843 
7844     bool ValidString = true;
7845     if (IsARMBuiltin) {
7846       ValidString &= Fields[0].startswith_insensitive("cp") ||
7847                      Fields[0].startswith_insensitive("p");
7848       if (ValidString)
7849         Fields[0] = Fields[0].drop_front(
7850             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7851 
7852       ValidString &= Fields[2].startswith_insensitive("c");
7853       if (ValidString)
7854         Fields[2] = Fields[2].drop_front(1);
7855 
7856       if (FiveFields) {
7857         ValidString &= Fields[3].startswith_insensitive("c");
7858         if (ValidString)
7859           Fields[3] = Fields[3].drop_front(1);
7860       }
7861     }
7862 
7863     SmallVector<int, 5> Ranges;
7864     if (FiveFields)
7865       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7866     else
7867       Ranges.append({15, 7, 15});
7868 
7869     for (unsigned i=0; i<Fields.size(); ++i) {
7870       int IntField;
7871       ValidString &= !Fields[i].getAsInteger(10, IntField);
7872       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7873     }
7874 
7875     if (!ValidString)
7876       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7877              << Arg->getSourceRange();
7878   } else if (IsAArch64Builtin && Fields.size() == 1) {
7879     // If the register name is one of those that appear in the condition below
7880     // and the special register builtin being used is one of the write builtins,
7881     // then we require that the argument provided for writing to the register
7882     // is an integer constant expression. This is because it will be lowered to
7883     // an MSR (immediate) instruction, so we need to know the immediate at
7884     // compile time.
7885     if (TheCall->getNumArgs() != 2)
7886       return false;
7887 
7888     std::string RegLower = Reg.lower();
7889     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7890         RegLower != "pan" && RegLower != "uao")
7891       return false;
7892 
7893     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7894   }
7895 
7896   return false;
7897 }
7898 
7899 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7900 /// Emit an error and return true on failure; return false on success.
7901 /// TypeStr is a string containing the type descriptor of the value returned by
7902 /// the builtin and the descriptors of the expected type of the arguments.
7903 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7904                                  const char *TypeStr) {
7905 
7906   assert((TypeStr[0] != '\0') &&
7907          "Invalid types in PPC MMA builtin declaration");
7908 
7909   switch (BuiltinID) {
7910   default:
7911     // This function is called in CheckPPCBuiltinFunctionCall where the
7912     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7913     // we are isolating the pair vector memop builtins that can be used with mma
7914     // off so the default case is every builtin that requires mma and paired
7915     // vector memops.
7916     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7917                          diag::err_ppc_builtin_only_on_arch, "10") ||
7918         SemaFeatureCheck(*this, TheCall, "mma",
7919                          diag::err_ppc_builtin_only_on_arch, "10"))
7920       return true;
7921     break;
7922   case PPC::BI__builtin_vsx_lxvp:
7923   case PPC::BI__builtin_vsx_stxvp:
7924   case PPC::BI__builtin_vsx_assemble_pair:
7925   case PPC::BI__builtin_vsx_disassemble_pair:
7926     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7927                          diag::err_ppc_builtin_only_on_arch, "10"))
7928       return true;
7929     break;
7930   }
7931 
7932   unsigned Mask = 0;
7933   unsigned ArgNum = 0;
7934 
7935   // The first type in TypeStr is the type of the value returned by the
7936   // builtin. So we first read that type and change the type of TheCall.
7937   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7938   TheCall->setType(type);
7939 
7940   while (*TypeStr != '\0') {
7941     Mask = 0;
7942     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7943     if (ArgNum >= TheCall->getNumArgs()) {
7944       ArgNum++;
7945       break;
7946     }
7947 
7948     Expr *Arg = TheCall->getArg(ArgNum);
7949     QualType PassedType = Arg->getType();
7950     QualType StrippedRVType = PassedType.getCanonicalType();
7951 
7952     // Strip Restrict/Volatile qualifiers.
7953     if (StrippedRVType.isRestrictQualified() ||
7954         StrippedRVType.isVolatileQualified())
7955       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7956 
7957     // The only case where the argument type and expected type are allowed to
7958     // mismatch is if the argument type is a non-void pointer (or array) and
7959     // expected type is a void pointer.
7960     if (StrippedRVType != ExpectedType)
7961       if (!(ExpectedType->isVoidPointerType() &&
7962             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7963         return Diag(Arg->getBeginLoc(),
7964                     diag::err_typecheck_convert_incompatible)
7965                << PassedType << ExpectedType << 1 << 0 << 0;
7966 
7967     // If the value of the Mask is not 0, we have a constraint in the size of
7968     // the integer argument so here we ensure the argument is a constant that
7969     // is in the valid range.
7970     if (Mask != 0 &&
7971         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7972       return true;
7973 
7974     ArgNum++;
7975   }
7976 
7977   // In case we exited early from the previous loop, there are other types to
7978   // read from TypeStr. So we need to read them all to ensure we have the right
7979   // number of arguments in TheCall and if it is not the case, to display a
7980   // better error message.
7981   while (*TypeStr != '\0') {
7982     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7983     ArgNum++;
7984   }
7985   if (checkArgCount(*this, TheCall, ArgNum))
7986     return true;
7987 
7988   return false;
7989 }
7990 
7991 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7992 /// This checks that the target supports __builtin_longjmp and
7993 /// that val is a constant 1.
7994 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7995   if (!Context.getTargetInfo().hasSjLjLowering())
7996     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7997            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7998 
7999   Expr *Arg = TheCall->getArg(1);
8000   llvm::APSInt Result;
8001 
8002   // TODO: This is less than ideal. Overload this to take a value.
8003   if (SemaBuiltinConstantArg(TheCall, 1, Result))
8004     return true;
8005 
8006   if (Result != 1)
8007     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
8008            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
8009 
8010   return false;
8011 }
8012 
8013 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
8014 /// This checks that the target supports __builtin_setjmp.
8015 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
8016   if (!Context.getTargetInfo().hasSjLjLowering())
8017     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
8018            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
8019   return false;
8020 }
8021 
8022 namespace {
8023 
8024 class UncoveredArgHandler {
8025   enum { Unknown = -1, AllCovered = -2 };
8026 
8027   signed FirstUncoveredArg = Unknown;
8028   SmallVector<const Expr *, 4> DiagnosticExprs;
8029 
8030 public:
8031   UncoveredArgHandler() = default;
8032 
8033   bool hasUncoveredArg() const {
8034     return (FirstUncoveredArg >= 0);
8035   }
8036 
8037   unsigned getUncoveredArg() const {
8038     assert(hasUncoveredArg() && "no uncovered argument");
8039     return FirstUncoveredArg;
8040   }
8041 
8042   void setAllCovered() {
8043     // A string has been found with all arguments covered, so clear out
8044     // the diagnostics.
8045     DiagnosticExprs.clear();
8046     FirstUncoveredArg = AllCovered;
8047   }
8048 
8049   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
8050     assert(NewFirstUncoveredArg >= 0 && "Outside range");
8051 
8052     // Don't update if a previous string covers all arguments.
8053     if (FirstUncoveredArg == AllCovered)
8054       return;
8055 
8056     // UncoveredArgHandler tracks the highest uncovered argument index
8057     // and with it all the strings that match this index.
8058     if (NewFirstUncoveredArg == FirstUncoveredArg)
8059       DiagnosticExprs.push_back(StrExpr);
8060     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
8061       DiagnosticExprs.clear();
8062       DiagnosticExprs.push_back(StrExpr);
8063       FirstUncoveredArg = NewFirstUncoveredArg;
8064     }
8065   }
8066 
8067   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
8068 };
8069 
8070 enum StringLiteralCheckType {
8071   SLCT_NotALiteral,
8072   SLCT_UncheckedLiteral,
8073   SLCT_CheckedLiteral
8074 };
8075 
8076 } // namespace
8077 
8078 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
8079                                      BinaryOperatorKind BinOpKind,
8080                                      bool AddendIsRight) {
8081   unsigned BitWidth = Offset.getBitWidth();
8082   unsigned AddendBitWidth = Addend.getBitWidth();
8083   // There might be negative interim results.
8084   if (Addend.isUnsigned()) {
8085     Addend = Addend.zext(++AddendBitWidth);
8086     Addend.setIsSigned(true);
8087   }
8088   // Adjust the bit width of the APSInts.
8089   if (AddendBitWidth > BitWidth) {
8090     Offset = Offset.sext(AddendBitWidth);
8091     BitWidth = AddendBitWidth;
8092   } else if (BitWidth > AddendBitWidth) {
8093     Addend = Addend.sext(BitWidth);
8094   }
8095 
8096   bool Ov = false;
8097   llvm::APSInt ResOffset = Offset;
8098   if (BinOpKind == BO_Add)
8099     ResOffset = Offset.sadd_ov(Addend, Ov);
8100   else {
8101     assert(AddendIsRight && BinOpKind == BO_Sub &&
8102            "operator must be add or sub with addend on the right");
8103     ResOffset = Offset.ssub_ov(Addend, Ov);
8104   }
8105 
8106   // We add an offset to a pointer here so we should support an offset as big as
8107   // possible.
8108   if (Ov) {
8109     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
8110            "index (intermediate) result too big");
8111     Offset = Offset.sext(2 * BitWidth);
8112     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
8113     return;
8114   }
8115 
8116   Offset = ResOffset;
8117 }
8118 
8119 namespace {
8120 
8121 // This is a wrapper class around StringLiteral to support offsetted string
8122 // literals as format strings. It takes the offset into account when returning
8123 // the string and its length or the source locations to display notes correctly.
8124 class FormatStringLiteral {
8125   const StringLiteral *FExpr;
8126   int64_t Offset;
8127 
8128  public:
8129   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
8130       : FExpr(fexpr), Offset(Offset) {}
8131 
8132   StringRef getString() const {
8133     return FExpr->getString().drop_front(Offset);
8134   }
8135 
8136   unsigned getByteLength() const {
8137     return FExpr->getByteLength() - getCharByteWidth() * Offset;
8138   }
8139 
8140   unsigned getLength() const { return FExpr->getLength() - Offset; }
8141   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
8142 
8143   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8144 
8145   QualType getType() const { return FExpr->getType(); }
8146 
8147   bool isAscii() const { return FExpr->isAscii(); }
8148   bool isWide() const { return FExpr->isWide(); }
8149   bool isUTF8() const { return FExpr->isUTF8(); }
8150   bool isUTF16() const { return FExpr->isUTF16(); }
8151   bool isUTF32() const { return FExpr->isUTF32(); }
8152   bool isPascal() const { return FExpr->isPascal(); }
8153 
8154   SourceLocation getLocationOfByte(
8155       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8156       const TargetInfo &Target, unsigned *StartToken = nullptr,
8157       unsigned *StartTokenByteOffset = nullptr) const {
8158     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8159                                     StartToken, StartTokenByteOffset);
8160   }
8161 
8162   SourceLocation getBeginLoc() const LLVM_READONLY {
8163     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8164   }
8165 
8166   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8167 };
8168 
8169 }  // namespace
8170 
8171 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8172                               const Expr *OrigFormatExpr,
8173                               ArrayRef<const Expr *> Args,
8174                               bool HasVAListArg, unsigned format_idx,
8175                               unsigned firstDataArg,
8176                               Sema::FormatStringType Type,
8177                               bool inFunctionCall,
8178                               Sema::VariadicCallType CallType,
8179                               llvm::SmallBitVector &CheckedVarArgs,
8180                               UncoveredArgHandler &UncoveredArg,
8181                               bool IgnoreStringsWithoutSpecifiers);
8182 
8183 // Determine if an expression is a string literal or constant string.
8184 // If this function returns false on the arguments to a function expecting a
8185 // format string, we will usually need to emit a warning.
8186 // True string literals are then checked by CheckFormatString.
8187 static StringLiteralCheckType
8188 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8189                       bool HasVAListArg, unsigned format_idx,
8190                       unsigned firstDataArg, Sema::FormatStringType Type,
8191                       Sema::VariadicCallType CallType, bool InFunctionCall,
8192                       llvm::SmallBitVector &CheckedVarArgs,
8193                       UncoveredArgHandler &UncoveredArg,
8194                       llvm::APSInt Offset,
8195                       bool IgnoreStringsWithoutSpecifiers = false) {
8196   if (S.isConstantEvaluated())
8197     return SLCT_NotALiteral;
8198  tryAgain:
8199   assert(Offset.isSigned() && "invalid offset");
8200 
8201   if (E->isTypeDependent() || E->isValueDependent())
8202     return SLCT_NotALiteral;
8203 
8204   E = E->IgnoreParenCasts();
8205 
8206   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8207     // Technically -Wformat-nonliteral does not warn about this case.
8208     // The behavior of printf and friends in this case is implementation
8209     // dependent.  Ideally if the format string cannot be null then
8210     // it should have a 'nonnull' attribute in the function prototype.
8211     return SLCT_UncheckedLiteral;
8212 
8213   switch (E->getStmtClass()) {
8214   case Stmt::BinaryConditionalOperatorClass:
8215   case Stmt::ConditionalOperatorClass: {
8216     // The expression is a literal if both sub-expressions were, and it was
8217     // completely checked only if both sub-expressions were checked.
8218     const AbstractConditionalOperator *C =
8219         cast<AbstractConditionalOperator>(E);
8220 
8221     // Determine whether it is necessary to check both sub-expressions, for
8222     // example, because the condition expression is a constant that can be
8223     // evaluated at compile time.
8224     bool CheckLeft = true, CheckRight = true;
8225 
8226     bool Cond;
8227     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8228                                                  S.isConstantEvaluated())) {
8229       if (Cond)
8230         CheckRight = false;
8231       else
8232         CheckLeft = false;
8233     }
8234 
8235     // We need to maintain the offsets for the right and the left hand side
8236     // separately to check if every possible indexed expression is a valid
8237     // string literal. They might have different offsets for different string
8238     // literals in the end.
8239     StringLiteralCheckType Left;
8240     if (!CheckLeft)
8241       Left = SLCT_UncheckedLiteral;
8242     else {
8243       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8244                                    HasVAListArg, format_idx, firstDataArg,
8245                                    Type, CallType, InFunctionCall,
8246                                    CheckedVarArgs, UncoveredArg, Offset,
8247                                    IgnoreStringsWithoutSpecifiers);
8248       if (Left == SLCT_NotALiteral || !CheckRight) {
8249         return Left;
8250       }
8251     }
8252 
8253     StringLiteralCheckType Right = checkFormatStringExpr(
8254         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8255         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8256         IgnoreStringsWithoutSpecifiers);
8257 
8258     return (CheckLeft && Left < Right) ? Left : Right;
8259   }
8260 
8261   case Stmt::ImplicitCastExprClass:
8262     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8263     goto tryAgain;
8264 
8265   case Stmt::OpaqueValueExprClass:
8266     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8267       E = src;
8268       goto tryAgain;
8269     }
8270     return SLCT_NotALiteral;
8271 
8272   case Stmt::PredefinedExprClass:
8273     // While __func__, etc., are technically not string literals, they
8274     // cannot contain format specifiers and thus are not a security
8275     // liability.
8276     return SLCT_UncheckedLiteral;
8277 
8278   case Stmt::DeclRefExprClass: {
8279     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8280 
8281     // As an exception, do not flag errors for variables binding to
8282     // const string literals.
8283     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8284       bool isConstant = false;
8285       QualType T = DR->getType();
8286 
8287       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8288         isConstant = AT->getElementType().isConstant(S.Context);
8289       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8290         isConstant = T.isConstant(S.Context) &&
8291                      PT->getPointeeType().isConstant(S.Context);
8292       } else if (T->isObjCObjectPointerType()) {
8293         // In ObjC, there is usually no "const ObjectPointer" type,
8294         // so don't check if the pointee type is constant.
8295         isConstant = T.isConstant(S.Context);
8296       }
8297 
8298       if (isConstant) {
8299         if (const Expr *Init = VD->getAnyInitializer()) {
8300           // Look through initializers like const char c[] = { "foo" }
8301           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8302             if (InitList->isStringLiteralInit())
8303               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8304           }
8305           return checkFormatStringExpr(S, Init, Args,
8306                                        HasVAListArg, format_idx,
8307                                        firstDataArg, Type, CallType,
8308                                        /*InFunctionCall*/ false, CheckedVarArgs,
8309                                        UncoveredArg, Offset);
8310         }
8311       }
8312 
8313       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8314       // special check to see if the format string is a function parameter
8315       // of the function calling the printf function.  If the function
8316       // has an attribute indicating it is a printf-like function, then we
8317       // should suppress warnings concerning non-literals being used in a call
8318       // to a vprintf function.  For example:
8319       //
8320       // void
8321       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8322       //      va_list ap;
8323       //      va_start(ap, fmt);
8324       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8325       //      ...
8326       // }
8327       if (HasVAListArg) {
8328         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8329           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8330             int PVIndex = PV->getFunctionScopeIndex() + 1;
8331             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8332               // adjust for implicit parameter
8333               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8334                 if (MD->isInstance())
8335                   ++PVIndex;
8336               // We also check if the formats are compatible.
8337               // We can't pass a 'scanf' string to a 'printf' function.
8338               if (PVIndex == PVFormat->getFormatIdx() &&
8339                   Type == S.GetFormatStringType(PVFormat))
8340                 return SLCT_UncheckedLiteral;
8341             }
8342           }
8343         }
8344       }
8345     }
8346 
8347     return SLCT_NotALiteral;
8348   }
8349 
8350   case Stmt::CallExprClass:
8351   case Stmt::CXXMemberCallExprClass: {
8352     const CallExpr *CE = cast<CallExpr>(E);
8353     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8354       bool IsFirst = true;
8355       StringLiteralCheckType CommonResult;
8356       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8357         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8358         StringLiteralCheckType Result = checkFormatStringExpr(
8359             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8360             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8361             IgnoreStringsWithoutSpecifiers);
8362         if (IsFirst) {
8363           CommonResult = Result;
8364           IsFirst = false;
8365         }
8366       }
8367       if (!IsFirst)
8368         return CommonResult;
8369 
8370       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8371         unsigned BuiltinID = FD->getBuiltinID();
8372         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8373             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8374           const Expr *Arg = CE->getArg(0);
8375           return checkFormatStringExpr(S, Arg, Args,
8376                                        HasVAListArg, format_idx,
8377                                        firstDataArg, Type, CallType,
8378                                        InFunctionCall, CheckedVarArgs,
8379                                        UncoveredArg, Offset,
8380                                        IgnoreStringsWithoutSpecifiers);
8381         }
8382       }
8383     }
8384 
8385     return SLCT_NotALiteral;
8386   }
8387   case Stmt::ObjCMessageExprClass: {
8388     const auto *ME = cast<ObjCMessageExpr>(E);
8389     if (const auto *MD = ME->getMethodDecl()) {
8390       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8391         // As a special case heuristic, if we're using the method -[NSBundle
8392         // localizedStringForKey:value:table:], ignore any key strings that lack
8393         // format specifiers. The idea is that if the key doesn't have any
8394         // format specifiers then its probably just a key to map to the
8395         // localized strings. If it does have format specifiers though, then its
8396         // likely that the text of the key is the format string in the
8397         // programmer's language, and should be checked.
8398         const ObjCInterfaceDecl *IFace;
8399         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8400             IFace->getIdentifier()->isStr("NSBundle") &&
8401             MD->getSelector().isKeywordSelector(
8402                 {"localizedStringForKey", "value", "table"})) {
8403           IgnoreStringsWithoutSpecifiers = true;
8404         }
8405 
8406         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8407         return checkFormatStringExpr(
8408             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8409             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8410             IgnoreStringsWithoutSpecifiers);
8411       }
8412     }
8413 
8414     return SLCT_NotALiteral;
8415   }
8416   case Stmt::ObjCStringLiteralClass:
8417   case Stmt::StringLiteralClass: {
8418     const StringLiteral *StrE = nullptr;
8419 
8420     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8421       StrE = ObjCFExpr->getString();
8422     else
8423       StrE = cast<StringLiteral>(E);
8424 
8425     if (StrE) {
8426       if (Offset.isNegative() || Offset > StrE->getLength()) {
8427         // TODO: It would be better to have an explicit warning for out of
8428         // bounds literals.
8429         return SLCT_NotALiteral;
8430       }
8431       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8432       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8433                         firstDataArg, Type, InFunctionCall, CallType,
8434                         CheckedVarArgs, UncoveredArg,
8435                         IgnoreStringsWithoutSpecifiers);
8436       return SLCT_CheckedLiteral;
8437     }
8438 
8439     return SLCT_NotALiteral;
8440   }
8441   case Stmt::BinaryOperatorClass: {
8442     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8443 
8444     // A string literal + an int offset is still a string literal.
8445     if (BinOp->isAdditiveOp()) {
8446       Expr::EvalResult LResult, RResult;
8447 
8448       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8449           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8450       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8451           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8452 
8453       if (LIsInt != RIsInt) {
8454         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8455 
8456         if (LIsInt) {
8457           if (BinOpKind == BO_Add) {
8458             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8459             E = BinOp->getRHS();
8460             goto tryAgain;
8461           }
8462         } else {
8463           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8464           E = BinOp->getLHS();
8465           goto tryAgain;
8466         }
8467       }
8468     }
8469 
8470     return SLCT_NotALiteral;
8471   }
8472   case Stmt::UnaryOperatorClass: {
8473     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8474     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8475     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8476       Expr::EvalResult IndexResult;
8477       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8478                                        Expr::SE_NoSideEffects,
8479                                        S.isConstantEvaluated())) {
8480         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8481                    /*RHS is int*/ true);
8482         E = ASE->getBase();
8483         goto tryAgain;
8484       }
8485     }
8486 
8487     return SLCT_NotALiteral;
8488   }
8489 
8490   default:
8491     return SLCT_NotALiteral;
8492   }
8493 }
8494 
8495 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8496   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8497       .Case("scanf", FST_Scanf)
8498       .Cases("printf", "printf0", FST_Printf)
8499       .Cases("NSString", "CFString", FST_NSString)
8500       .Case("strftime", FST_Strftime)
8501       .Case("strfmon", FST_Strfmon)
8502       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8503       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8504       .Case("os_trace", FST_OSLog)
8505       .Case("os_log", FST_OSLog)
8506       .Default(FST_Unknown);
8507 }
8508 
8509 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8510 /// functions) for correct use of format strings.
8511 /// Returns true if a format string has been fully checked.
8512 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8513                                 ArrayRef<const Expr *> Args,
8514                                 bool IsCXXMember,
8515                                 VariadicCallType CallType,
8516                                 SourceLocation Loc, SourceRange Range,
8517                                 llvm::SmallBitVector &CheckedVarArgs) {
8518   FormatStringInfo FSI;
8519   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8520     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8521                                 FSI.FirstDataArg, GetFormatStringType(Format),
8522                                 CallType, Loc, Range, CheckedVarArgs);
8523   return false;
8524 }
8525 
8526 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8527                                 bool HasVAListArg, unsigned format_idx,
8528                                 unsigned firstDataArg, FormatStringType Type,
8529                                 VariadicCallType CallType,
8530                                 SourceLocation Loc, SourceRange Range,
8531                                 llvm::SmallBitVector &CheckedVarArgs) {
8532   // CHECK: printf/scanf-like function is called with no format string.
8533   if (format_idx >= Args.size()) {
8534     Diag(Loc, diag::warn_missing_format_string) << Range;
8535     return false;
8536   }
8537 
8538   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8539 
8540   // CHECK: format string is not a string literal.
8541   //
8542   // Dynamically generated format strings are difficult to
8543   // automatically vet at compile time.  Requiring that format strings
8544   // are string literals: (1) permits the checking of format strings by
8545   // the compiler and thereby (2) can practically remove the source of
8546   // many format string exploits.
8547 
8548   // Format string can be either ObjC string (e.g. @"%d") or
8549   // C string (e.g. "%d")
8550   // ObjC string uses the same format specifiers as C string, so we can use
8551   // the same format string checking logic for both ObjC and C strings.
8552   UncoveredArgHandler UncoveredArg;
8553   StringLiteralCheckType CT =
8554       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8555                             format_idx, firstDataArg, Type, CallType,
8556                             /*IsFunctionCall*/ true, CheckedVarArgs,
8557                             UncoveredArg,
8558                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8559 
8560   // Generate a diagnostic where an uncovered argument is detected.
8561   if (UncoveredArg.hasUncoveredArg()) {
8562     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8563     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8564     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8565   }
8566 
8567   if (CT != SLCT_NotALiteral)
8568     // Literal format string found, check done!
8569     return CT == SLCT_CheckedLiteral;
8570 
8571   // Strftime is particular as it always uses a single 'time' argument,
8572   // so it is safe to pass a non-literal string.
8573   if (Type == FST_Strftime)
8574     return false;
8575 
8576   // Do not emit diag when the string param is a macro expansion and the
8577   // format is either NSString or CFString. This is a hack to prevent
8578   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8579   // which are usually used in place of NS and CF string literals.
8580   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8581   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8582     return false;
8583 
8584   // If there are no arguments specified, warn with -Wformat-security, otherwise
8585   // warn only with -Wformat-nonliteral.
8586   if (Args.size() == firstDataArg) {
8587     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8588       << OrigFormatExpr->getSourceRange();
8589     switch (Type) {
8590     default:
8591       break;
8592     case FST_Kprintf:
8593     case FST_FreeBSDKPrintf:
8594     case FST_Printf:
8595       Diag(FormatLoc, diag::note_format_security_fixit)
8596         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8597       break;
8598     case FST_NSString:
8599       Diag(FormatLoc, diag::note_format_security_fixit)
8600         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8601       break;
8602     }
8603   } else {
8604     Diag(FormatLoc, diag::warn_format_nonliteral)
8605       << OrigFormatExpr->getSourceRange();
8606   }
8607   return false;
8608 }
8609 
8610 namespace {
8611 
8612 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8613 protected:
8614   Sema &S;
8615   const FormatStringLiteral *FExpr;
8616   const Expr *OrigFormatExpr;
8617   const Sema::FormatStringType FSType;
8618   const unsigned FirstDataArg;
8619   const unsigned NumDataArgs;
8620   const char *Beg; // Start of format string.
8621   const bool HasVAListArg;
8622   ArrayRef<const Expr *> Args;
8623   unsigned FormatIdx;
8624   llvm::SmallBitVector CoveredArgs;
8625   bool usesPositionalArgs = false;
8626   bool atFirstArg = true;
8627   bool inFunctionCall;
8628   Sema::VariadicCallType CallType;
8629   llvm::SmallBitVector &CheckedVarArgs;
8630   UncoveredArgHandler &UncoveredArg;
8631 
8632 public:
8633   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8634                      const Expr *origFormatExpr,
8635                      const Sema::FormatStringType type, unsigned firstDataArg,
8636                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8637                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8638                      bool inFunctionCall, Sema::VariadicCallType callType,
8639                      llvm::SmallBitVector &CheckedVarArgs,
8640                      UncoveredArgHandler &UncoveredArg)
8641       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8642         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8643         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8644         inFunctionCall(inFunctionCall), CallType(callType),
8645         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8646     CoveredArgs.resize(numDataArgs);
8647     CoveredArgs.reset();
8648   }
8649 
8650   void DoneProcessing();
8651 
8652   void HandleIncompleteSpecifier(const char *startSpecifier,
8653                                  unsigned specifierLen) override;
8654 
8655   void HandleInvalidLengthModifier(
8656                            const analyze_format_string::FormatSpecifier &FS,
8657                            const analyze_format_string::ConversionSpecifier &CS,
8658                            const char *startSpecifier, unsigned specifierLen,
8659                            unsigned DiagID);
8660 
8661   void HandleNonStandardLengthModifier(
8662                     const analyze_format_string::FormatSpecifier &FS,
8663                     const char *startSpecifier, unsigned specifierLen);
8664 
8665   void HandleNonStandardConversionSpecifier(
8666                     const analyze_format_string::ConversionSpecifier &CS,
8667                     const char *startSpecifier, unsigned specifierLen);
8668 
8669   void HandlePosition(const char *startPos, unsigned posLen) override;
8670 
8671   void HandleInvalidPosition(const char *startSpecifier,
8672                              unsigned specifierLen,
8673                              analyze_format_string::PositionContext p) override;
8674 
8675   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8676 
8677   void HandleNullChar(const char *nullCharacter) override;
8678 
8679   template <typename Range>
8680   static void
8681   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8682                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8683                        bool IsStringLocation, Range StringRange,
8684                        ArrayRef<FixItHint> Fixit = None);
8685 
8686 protected:
8687   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8688                                         const char *startSpec,
8689                                         unsigned specifierLen,
8690                                         const char *csStart, unsigned csLen);
8691 
8692   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8693                                          const char *startSpec,
8694                                          unsigned specifierLen);
8695 
8696   SourceRange getFormatStringRange();
8697   CharSourceRange getSpecifierRange(const char *startSpecifier,
8698                                     unsigned specifierLen);
8699   SourceLocation getLocationOfByte(const char *x);
8700 
8701   const Expr *getDataArg(unsigned i) const;
8702 
8703   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8704                     const analyze_format_string::ConversionSpecifier &CS,
8705                     const char *startSpecifier, unsigned specifierLen,
8706                     unsigned argIndex);
8707 
8708   template <typename Range>
8709   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8710                             bool IsStringLocation, Range StringRange,
8711                             ArrayRef<FixItHint> Fixit = None);
8712 };
8713 
8714 } // namespace
8715 
8716 SourceRange CheckFormatHandler::getFormatStringRange() {
8717   return OrigFormatExpr->getSourceRange();
8718 }
8719 
8720 CharSourceRange CheckFormatHandler::
8721 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8722   SourceLocation Start = getLocationOfByte(startSpecifier);
8723   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8724 
8725   // Advance the end SourceLocation by one due to half-open ranges.
8726   End = End.getLocWithOffset(1);
8727 
8728   return CharSourceRange::getCharRange(Start, End);
8729 }
8730 
8731 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8732   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8733                                   S.getLangOpts(), S.Context.getTargetInfo());
8734 }
8735 
8736 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8737                                                    unsigned specifierLen){
8738   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8739                        getLocationOfByte(startSpecifier),
8740                        /*IsStringLocation*/true,
8741                        getSpecifierRange(startSpecifier, specifierLen));
8742 }
8743 
8744 void CheckFormatHandler::HandleInvalidLengthModifier(
8745     const analyze_format_string::FormatSpecifier &FS,
8746     const analyze_format_string::ConversionSpecifier &CS,
8747     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8748   using namespace analyze_format_string;
8749 
8750   const LengthModifier &LM = FS.getLengthModifier();
8751   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8752 
8753   // See if we know how to fix this length modifier.
8754   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8755   if (FixedLM) {
8756     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8757                          getLocationOfByte(LM.getStart()),
8758                          /*IsStringLocation*/true,
8759                          getSpecifierRange(startSpecifier, specifierLen));
8760 
8761     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8762       << FixedLM->toString()
8763       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8764 
8765   } else {
8766     FixItHint Hint;
8767     if (DiagID == diag::warn_format_nonsensical_length)
8768       Hint = FixItHint::CreateRemoval(LMRange);
8769 
8770     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8771                          getLocationOfByte(LM.getStart()),
8772                          /*IsStringLocation*/true,
8773                          getSpecifierRange(startSpecifier, specifierLen),
8774                          Hint);
8775   }
8776 }
8777 
8778 void CheckFormatHandler::HandleNonStandardLengthModifier(
8779     const analyze_format_string::FormatSpecifier &FS,
8780     const char *startSpecifier, unsigned specifierLen) {
8781   using namespace analyze_format_string;
8782 
8783   const LengthModifier &LM = FS.getLengthModifier();
8784   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8785 
8786   // See if we know how to fix this length modifier.
8787   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8788   if (FixedLM) {
8789     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8790                            << LM.toString() << 0,
8791                          getLocationOfByte(LM.getStart()),
8792                          /*IsStringLocation*/true,
8793                          getSpecifierRange(startSpecifier, specifierLen));
8794 
8795     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8796       << FixedLM->toString()
8797       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8798 
8799   } else {
8800     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8801                            << LM.toString() << 0,
8802                          getLocationOfByte(LM.getStart()),
8803                          /*IsStringLocation*/true,
8804                          getSpecifierRange(startSpecifier, specifierLen));
8805   }
8806 }
8807 
8808 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8809     const analyze_format_string::ConversionSpecifier &CS,
8810     const char *startSpecifier, unsigned specifierLen) {
8811   using namespace analyze_format_string;
8812 
8813   // See if we know how to fix this conversion specifier.
8814   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8815   if (FixedCS) {
8816     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8817                           << CS.toString() << /*conversion specifier*/1,
8818                          getLocationOfByte(CS.getStart()),
8819                          /*IsStringLocation*/true,
8820                          getSpecifierRange(startSpecifier, specifierLen));
8821 
8822     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8823     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8824       << FixedCS->toString()
8825       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8826   } else {
8827     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8828                           << CS.toString() << /*conversion specifier*/1,
8829                          getLocationOfByte(CS.getStart()),
8830                          /*IsStringLocation*/true,
8831                          getSpecifierRange(startSpecifier, specifierLen));
8832   }
8833 }
8834 
8835 void CheckFormatHandler::HandlePosition(const char *startPos,
8836                                         unsigned posLen) {
8837   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8838                                getLocationOfByte(startPos),
8839                                /*IsStringLocation*/true,
8840                                getSpecifierRange(startPos, posLen));
8841 }
8842 
8843 void
8844 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8845                                      analyze_format_string::PositionContext p) {
8846   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8847                          << (unsigned) p,
8848                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8849                        getSpecifierRange(startPos, posLen));
8850 }
8851 
8852 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8853                                             unsigned posLen) {
8854   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8855                                getLocationOfByte(startPos),
8856                                /*IsStringLocation*/true,
8857                                getSpecifierRange(startPos, posLen));
8858 }
8859 
8860 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8861   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8862     // The presence of a null character is likely an error.
8863     EmitFormatDiagnostic(
8864       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8865       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8866       getFormatStringRange());
8867   }
8868 }
8869 
8870 // Note that this may return NULL if there was an error parsing or building
8871 // one of the argument expressions.
8872 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8873   return Args[FirstDataArg + i];
8874 }
8875 
8876 void CheckFormatHandler::DoneProcessing() {
8877   // Does the number of data arguments exceed the number of
8878   // format conversions in the format string?
8879   if (!HasVAListArg) {
8880       // Find any arguments that weren't covered.
8881     CoveredArgs.flip();
8882     signed notCoveredArg = CoveredArgs.find_first();
8883     if (notCoveredArg >= 0) {
8884       assert((unsigned)notCoveredArg < NumDataArgs);
8885       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8886     } else {
8887       UncoveredArg.setAllCovered();
8888     }
8889   }
8890 }
8891 
8892 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8893                                    const Expr *ArgExpr) {
8894   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8895          "Invalid state");
8896 
8897   if (!ArgExpr)
8898     return;
8899 
8900   SourceLocation Loc = ArgExpr->getBeginLoc();
8901 
8902   if (S.getSourceManager().isInSystemMacro(Loc))
8903     return;
8904 
8905   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8906   for (auto E : DiagnosticExprs)
8907     PDiag << E->getSourceRange();
8908 
8909   CheckFormatHandler::EmitFormatDiagnostic(
8910                                   S, IsFunctionCall, DiagnosticExprs[0],
8911                                   PDiag, Loc, /*IsStringLocation*/false,
8912                                   DiagnosticExprs[0]->getSourceRange());
8913 }
8914 
8915 bool
8916 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8917                                                      SourceLocation Loc,
8918                                                      const char *startSpec,
8919                                                      unsigned specifierLen,
8920                                                      const char *csStart,
8921                                                      unsigned csLen) {
8922   bool keepGoing = true;
8923   if (argIndex < NumDataArgs) {
8924     // Consider the argument coverered, even though the specifier doesn't
8925     // make sense.
8926     CoveredArgs.set(argIndex);
8927   }
8928   else {
8929     // If argIndex exceeds the number of data arguments we
8930     // don't issue a warning because that is just a cascade of warnings (and
8931     // they may have intended '%%' anyway). We don't want to continue processing
8932     // the format string after this point, however, as we will like just get
8933     // gibberish when trying to match arguments.
8934     keepGoing = false;
8935   }
8936 
8937   StringRef Specifier(csStart, csLen);
8938 
8939   // If the specifier in non-printable, it could be the first byte of a UTF-8
8940   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8941   // hex value.
8942   std::string CodePointStr;
8943   if (!llvm::sys::locale::isPrint(*csStart)) {
8944     llvm::UTF32 CodePoint;
8945     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8946     const llvm::UTF8 *E =
8947         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8948     llvm::ConversionResult Result =
8949         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8950 
8951     if (Result != llvm::conversionOK) {
8952       unsigned char FirstChar = *csStart;
8953       CodePoint = (llvm::UTF32)FirstChar;
8954     }
8955 
8956     llvm::raw_string_ostream OS(CodePointStr);
8957     if (CodePoint < 256)
8958       OS << "\\x" << llvm::format("%02x", CodePoint);
8959     else if (CodePoint <= 0xFFFF)
8960       OS << "\\u" << llvm::format("%04x", CodePoint);
8961     else
8962       OS << "\\U" << llvm::format("%08x", CodePoint);
8963     OS.flush();
8964     Specifier = CodePointStr;
8965   }
8966 
8967   EmitFormatDiagnostic(
8968       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8969       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8970 
8971   return keepGoing;
8972 }
8973 
8974 void
8975 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8976                                                       const char *startSpec,
8977                                                       unsigned specifierLen) {
8978   EmitFormatDiagnostic(
8979     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8980     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8981 }
8982 
8983 bool
8984 CheckFormatHandler::CheckNumArgs(
8985   const analyze_format_string::FormatSpecifier &FS,
8986   const analyze_format_string::ConversionSpecifier &CS,
8987   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8988 
8989   if (argIndex >= NumDataArgs) {
8990     PartialDiagnostic PDiag = FS.usesPositionalArg()
8991       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8992            << (argIndex+1) << NumDataArgs)
8993       : S.PDiag(diag::warn_printf_insufficient_data_args);
8994     EmitFormatDiagnostic(
8995       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8996       getSpecifierRange(startSpecifier, specifierLen));
8997 
8998     // Since more arguments than conversion tokens are given, by extension
8999     // all arguments are covered, so mark this as so.
9000     UncoveredArg.setAllCovered();
9001     return false;
9002   }
9003   return true;
9004 }
9005 
9006 template<typename Range>
9007 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
9008                                               SourceLocation Loc,
9009                                               bool IsStringLocation,
9010                                               Range StringRange,
9011                                               ArrayRef<FixItHint> FixIt) {
9012   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
9013                        Loc, IsStringLocation, StringRange, FixIt);
9014 }
9015 
9016 /// If the format string is not within the function call, emit a note
9017 /// so that the function call and string are in diagnostic messages.
9018 ///
9019 /// \param InFunctionCall if true, the format string is within the function
9020 /// call and only one diagnostic message will be produced.  Otherwise, an
9021 /// extra note will be emitted pointing to location of the format string.
9022 ///
9023 /// \param ArgumentExpr the expression that is passed as the format string
9024 /// argument in the function call.  Used for getting locations when two
9025 /// diagnostics are emitted.
9026 ///
9027 /// \param PDiag the callee should already have provided any strings for the
9028 /// diagnostic message.  This function only adds locations and fixits
9029 /// to diagnostics.
9030 ///
9031 /// \param Loc primary location for diagnostic.  If two diagnostics are
9032 /// required, one will be at Loc and a new SourceLocation will be created for
9033 /// the other one.
9034 ///
9035 /// \param IsStringLocation if true, Loc points to the format string should be
9036 /// used for the note.  Otherwise, Loc points to the argument list and will
9037 /// be used with PDiag.
9038 ///
9039 /// \param StringRange some or all of the string to highlight.  This is
9040 /// templated so it can accept either a CharSourceRange or a SourceRange.
9041 ///
9042 /// \param FixIt optional fix it hint for the format string.
9043 template <typename Range>
9044 void CheckFormatHandler::EmitFormatDiagnostic(
9045     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
9046     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
9047     Range StringRange, ArrayRef<FixItHint> FixIt) {
9048   if (InFunctionCall) {
9049     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
9050     D << StringRange;
9051     D << FixIt;
9052   } else {
9053     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
9054       << ArgumentExpr->getSourceRange();
9055 
9056     const Sema::SemaDiagnosticBuilder &Note =
9057       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
9058              diag::note_format_string_defined);
9059 
9060     Note << StringRange;
9061     Note << FixIt;
9062   }
9063 }
9064 
9065 //===--- CHECK: Printf format string checking ------------------------------===//
9066 
9067 namespace {
9068 
9069 class CheckPrintfHandler : public CheckFormatHandler {
9070 public:
9071   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
9072                      const Expr *origFormatExpr,
9073                      const Sema::FormatStringType type, unsigned firstDataArg,
9074                      unsigned numDataArgs, bool isObjC, const char *beg,
9075                      bool hasVAListArg, ArrayRef<const Expr *> Args,
9076                      unsigned formatIdx, bool inFunctionCall,
9077                      Sema::VariadicCallType CallType,
9078                      llvm::SmallBitVector &CheckedVarArgs,
9079                      UncoveredArgHandler &UncoveredArg)
9080       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9081                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9082                            inFunctionCall, CallType, CheckedVarArgs,
9083                            UncoveredArg) {}
9084 
9085   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
9086 
9087   /// Returns true if '%@' specifiers are allowed in the format string.
9088   bool allowsObjCArg() const {
9089     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
9090            FSType == Sema::FST_OSTrace;
9091   }
9092 
9093   bool HandleInvalidPrintfConversionSpecifier(
9094                                       const analyze_printf::PrintfSpecifier &FS,
9095                                       const char *startSpecifier,
9096                                       unsigned specifierLen) override;
9097 
9098   void handleInvalidMaskType(StringRef MaskType) override;
9099 
9100   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
9101                              const char *startSpecifier, unsigned specifierLen,
9102                              const TargetInfo &Target) override;
9103   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9104                        const char *StartSpecifier,
9105                        unsigned SpecifierLen,
9106                        const Expr *E);
9107 
9108   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
9109                     const char *startSpecifier, unsigned specifierLen);
9110   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
9111                            const analyze_printf::OptionalAmount &Amt,
9112                            unsigned type,
9113                            const char *startSpecifier, unsigned specifierLen);
9114   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9115                   const analyze_printf::OptionalFlag &flag,
9116                   const char *startSpecifier, unsigned specifierLen);
9117   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
9118                          const analyze_printf::OptionalFlag &ignoredFlag,
9119                          const analyze_printf::OptionalFlag &flag,
9120                          const char *startSpecifier, unsigned specifierLen);
9121   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
9122                            const Expr *E);
9123 
9124   void HandleEmptyObjCModifierFlag(const char *startFlag,
9125                                    unsigned flagLen) override;
9126 
9127   void HandleInvalidObjCModifierFlag(const char *startFlag,
9128                                             unsigned flagLen) override;
9129 
9130   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
9131                                            const char *flagsEnd,
9132                                            const char *conversionPosition)
9133                                              override;
9134 };
9135 
9136 } // namespace
9137 
9138 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
9139                                       const analyze_printf::PrintfSpecifier &FS,
9140                                       const char *startSpecifier,
9141                                       unsigned specifierLen) {
9142   const analyze_printf::PrintfConversionSpecifier &CS =
9143     FS.getConversionSpecifier();
9144 
9145   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9146                                           getLocationOfByte(CS.getStart()),
9147                                           startSpecifier, specifierLen,
9148                                           CS.getStart(), CS.getLength());
9149 }
9150 
9151 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9152   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9153 }
9154 
9155 bool CheckPrintfHandler::HandleAmount(
9156                                const analyze_format_string::OptionalAmount &Amt,
9157                                unsigned k, const char *startSpecifier,
9158                                unsigned specifierLen) {
9159   if (Amt.hasDataArgument()) {
9160     if (!HasVAListArg) {
9161       unsigned argIndex = Amt.getArgIndex();
9162       if (argIndex >= NumDataArgs) {
9163         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9164                                << k,
9165                              getLocationOfByte(Amt.getStart()),
9166                              /*IsStringLocation*/true,
9167                              getSpecifierRange(startSpecifier, specifierLen));
9168         // Don't do any more checking.  We will just emit
9169         // spurious errors.
9170         return false;
9171       }
9172 
9173       // Type check the data argument.  It should be an 'int'.
9174       // Although not in conformance with C99, we also allow the argument to be
9175       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9176       // doesn't emit a warning for that case.
9177       CoveredArgs.set(argIndex);
9178       const Expr *Arg = getDataArg(argIndex);
9179       if (!Arg)
9180         return false;
9181 
9182       QualType T = Arg->getType();
9183 
9184       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9185       assert(AT.isValid());
9186 
9187       if (!AT.matchesType(S.Context, T)) {
9188         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9189                                << k << AT.getRepresentativeTypeName(S.Context)
9190                                << T << Arg->getSourceRange(),
9191                              getLocationOfByte(Amt.getStart()),
9192                              /*IsStringLocation*/true,
9193                              getSpecifierRange(startSpecifier, specifierLen));
9194         // Don't do any more checking.  We will just emit
9195         // spurious errors.
9196         return false;
9197       }
9198     }
9199   }
9200   return true;
9201 }
9202 
9203 void CheckPrintfHandler::HandleInvalidAmount(
9204                                       const analyze_printf::PrintfSpecifier &FS,
9205                                       const analyze_printf::OptionalAmount &Amt,
9206                                       unsigned type,
9207                                       const char *startSpecifier,
9208                                       unsigned specifierLen) {
9209   const analyze_printf::PrintfConversionSpecifier &CS =
9210     FS.getConversionSpecifier();
9211 
9212   FixItHint fixit =
9213     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9214       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9215                                  Amt.getConstantLength()))
9216       : FixItHint();
9217 
9218   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9219                          << type << CS.toString(),
9220                        getLocationOfByte(Amt.getStart()),
9221                        /*IsStringLocation*/true,
9222                        getSpecifierRange(startSpecifier, specifierLen),
9223                        fixit);
9224 }
9225 
9226 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9227                                     const analyze_printf::OptionalFlag &flag,
9228                                     const char *startSpecifier,
9229                                     unsigned specifierLen) {
9230   // Warn about pointless flag with a fixit removal.
9231   const analyze_printf::PrintfConversionSpecifier &CS =
9232     FS.getConversionSpecifier();
9233   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9234                          << flag.toString() << CS.toString(),
9235                        getLocationOfByte(flag.getPosition()),
9236                        /*IsStringLocation*/true,
9237                        getSpecifierRange(startSpecifier, specifierLen),
9238                        FixItHint::CreateRemoval(
9239                          getSpecifierRange(flag.getPosition(), 1)));
9240 }
9241 
9242 void CheckPrintfHandler::HandleIgnoredFlag(
9243                                 const analyze_printf::PrintfSpecifier &FS,
9244                                 const analyze_printf::OptionalFlag &ignoredFlag,
9245                                 const analyze_printf::OptionalFlag &flag,
9246                                 const char *startSpecifier,
9247                                 unsigned specifierLen) {
9248   // Warn about ignored flag with a fixit removal.
9249   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9250                          << ignoredFlag.toString() << flag.toString(),
9251                        getLocationOfByte(ignoredFlag.getPosition()),
9252                        /*IsStringLocation*/true,
9253                        getSpecifierRange(startSpecifier, specifierLen),
9254                        FixItHint::CreateRemoval(
9255                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9256 }
9257 
9258 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9259                                                      unsigned flagLen) {
9260   // Warn about an empty flag.
9261   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9262                        getLocationOfByte(startFlag),
9263                        /*IsStringLocation*/true,
9264                        getSpecifierRange(startFlag, flagLen));
9265 }
9266 
9267 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9268                                                        unsigned flagLen) {
9269   // Warn about an invalid flag.
9270   auto Range = getSpecifierRange(startFlag, flagLen);
9271   StringRef flag(startFlag, flagLen);
9272   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9273                       getLocationOfByte(startFlag),
9274                       /*IsStringLocation*/true,
9275                       Range, FixItHint::CreateRemoval(Range));
9276 }
9277 
9278 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9279     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9280     // Warn about using '[...]' without a '@' conversion.
9281     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9282     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9283     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9284                          getLocationOfByte(conversionPosition),
9285                          /*IsStringLocation*/true,
9286                          Range, FixItHint::CreateRemoval(Range));
9287 }
9288 
9289 // Determines if the specified is a C++ class or struct containing
9290 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9291 // "c_str()").
9292 template<typename MemberKind>
9293 static llvm::SmallPtrSet<MemberKind*, 1>
9294 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9295   const RecordType *RT = Ty->getAs<RecordType>();
9296   llvm::SmallPtrSet<MemberKind*, 1> Results;
9297 
9298   if (!RT)
9299     return Results;
9300   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9301   if (!RD || !RD->getDefinition())
9302     return Results;
9303 
9304   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9305                  Sema::LookupMemberName);
9306   R.suppressDiagnostics();
9307 
9308   // We just need to include all members of the right kind turned up by the
9309   // filter, at this point.
9310   if (S.LookupQualifiedName(R, RT->getDecl()))
9311     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9312       NamedDecl *decl = (*I)->getUnderlyingDecl();
9313       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9314         Results.insert(FK);
9315     }
9316   return Results;
9317 }
9318 
9319 /// Check if we could call '.c_str()' on an object.
9320 ///
9321 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9322 /// allow the call, or if it would be ambiguous).
9323 bool Sema::hasCStrMethod(const Expr *E) {
9324   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9325 
9326   MethodSet Results =
9327       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9328   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9329        MI != ME; ++MI)
9330     if ((*MI)->getMinRequiredArguments() == 0)
9331       return true;
9332   return false;
9333 }
9334 
9335 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9336 // better diagnostic if so. AT is assumed to be valid.
9337 // Returns true when a c_str() conversion method is found.
9338 bool CheckPrintfHandler::checkForCStrMembers(
9339     const analyze_printf::ArgType &AT, const Expr *E) {
9340   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9341 
9342   MethodSet Results =
9343       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9344 
9345   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9346        MI != ME; ++MI) {
9347     const CXXMethodDecl *Method = *MI;
9348     if (Method->getMinRequiredArguments() == 0 &&
9349         AT.matchesType(S.Context, Method->getReturnType())) {
9350       // FIXME: Suggest parens if the expression needs them.
9351       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9352       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9353           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9354       return true;
9355     }
9356   }
9357 
9358   return false;
9359 }
9360 
9361 bool CheckPrintfHandler::HandlePrintfSpecifier(
9362     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9363     unsigned specifierLen, const TargetInfo &Target) {
9364   using namespace analyze_format_string;
9365   using namespace analyze_printf;
9366 
9367   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9368 
9369   if (FS.consumesDataArgument()) {
9370     if (atFirstArg) {
9371         atFirstArg = false;
9372         usesPositionalArgs = FS.usesPositionalArg();
9373     }
9374     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9375       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9376                                         startSpecifier, specifierLen);
9377       return false;
9378     }
9379   }
9380 
9381   // First check if the field width, precision, and conversion specifier
9382   // have matching data arguments.
9383   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9384                     startSpecifier, specifierLen)) {
9385     return false;
9386   }
9387 
9388   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9389                     startSpecifier, specifierLen)) {
9390     return false;
9391   }
9392 
9393   if (!CS.consumesDataArgument()) {
9394     // FIXME: Technically specifying a precision or field width here
9395     // makes no sense.  Worth issuing a warning at some point.
9396     return true;
9397   }
9398 
9399   // Consume the argument.
9400   unsigned argIndex = FS.getArgIndex();
9401   if (argIndex < NumDataArgs) {
9402     // The check to see if the argIndex is valid will come later.
9403     // We set the bit here because we may exit early from this
9404     // function if we encounter some other error.
9405     CoveredArgs.set(argIndex);
9406   }
9407 
9408   // FreeBSD kernel extensions.
9409   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9410       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9411     // We need at least two arguments.
9412     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9413       return false;
9414 
9415     // Claim the second argument.
9416     CoveredArgs.set(argIndex + 1);
9417 
9418     // Type check the first argument (int for %b, pointer for %D)
9419     const Expr *Ex = getDataArg(argIndex);
9420     const analyze_printf::ArgType &AT =
9421       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9422         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9423     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9424       EmitFormatDiagnostic(
9425           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9426               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9427               << false << Ex->getSourceRange(),
9428           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9429           getSpecifierRange(startSpecifier, specifierLen));
9430 
9431     // Type check the second argument (char * for both %b and %D)
9432     Ex = getDataArg(argIndex + 1);
9433     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9434     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9435       EmitFormatDiagnostic(
9436           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9437               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9438               << false << Ex->getSourceRange(),
9439           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9440           getSpecifierRange(startSpecifier, specifierLen));
9441 
9442      return true;
9443   }
9444 
9445   // Check for using an Objective-C specific conversion specifier
9446   // in a non-ObjC literal.
9447   if (!allowsObjCArg() && CS.isObjCArg()) {
9448     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9449                                                   specifierLen);
9450   }
9451 
9452   // %P can only be used with os_log.
9453   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9454     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9455                                                   specifierLen);
9456   }
9457 
9458   // %n is not allowed with os_log.
9459   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9460     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9461                          getLocationOfByte(CS.getStart()),
9462                          /*IsStringLocation*/ false,
9463                          getSpecifierRange(startSpecifier, specifierLen));
9464 
9465     return true;
9466   }
9467 
9468   // Only scalars are allowed for os_trace.
9469   if (FSType == Sema::FST_OSTrace &&
9470       (CS.getKind() == ConversionSpecifier::PArg ||
9471        CS.getKind() == ConversionSpecifier::sArg ||
9472        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9473     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9474                                                   specifierLen);
9475   }
9476 
9477   // Check for use of public/private annotation outside of os_log().
9478   if (FSType != Sema::FST_OSLog) {
9479     if (FS.isPublic().isSet()) {
9480       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9481                                << "public",
9482                            getLocationOfByte(FS.isPublic().getPosition()),
9483                            /*IsStringLocation*/ false,
9484                            getSpecifierRange(startSpecifier, specifierLen));
9485     }
9486     if (FS.isPrivate().isSet()) {
9487       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9488                                << "private",
9489                            getLocationOfByte(FS.isPrivate().getPosition()),
9490                            /*IsStringLocation*/ false,
9491                            getSpecifierRange(startSpecifier, specifierLen));
9492     }
9493   }
9494 
9495   const llvm::Triple &Triple = Target.getTriple();
9496   if (CS.getKind() == ConversionSpecifier::nArg &&
9497       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9498     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9499                          getLocationOfByte(CS.getStart()),
9500                          /*IsStringLocation*/ false,
9501                          getSpecifierRange(startSpecifier, specifierLen));
9502   }
9503 
9504   // Check for invalid use of field width
9505   if (!FS.hasValidFieldWidth()) {
9506     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9507         startSpecifier, specifierLen);
9508   }
9509 
9510   // Check for invalid use of precision
9511   if (!FS.hasValidPrecision()) {
9512     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9513         startSpecifier, specifierLen);
9514   }
9515 
9516   // Precision is mandatory for %P specifier.
9517   if (CS.getKind() == ConversionSpecifier::PArg &&
9518       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9519     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9520                          getLocationOfByte(startSpecifier),
9521                          /*IsStringLocation*/ false,
9522                          getSpecifierRange(startSpecifier, specifierLen));
9523   }
9524 
9525   // Check each flag does not conflict with any other component.
9526   if (!FS.hasValidThousandsGroupingPrefix())
9527     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9528   if (!FS.hasValidLeadingZeros())
9529     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9530   if (!FS.hasValidPlusPrefix())
9531     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9532   if (!FS.hasValidSpacePrefix())
9533     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9534   if (!FS.hasValidAlternativeForm())
9535     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9536   if (!FS.hasValidLeftJustified())
9537     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9538 
9539   // Check that flags are not ignored by another flag
9540   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9541     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9542         startSpecifier, specifierLen);
9543   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9544     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9545             startSpecifier, specifierLen);
9546 
9547   // Check the length modifier is valid with the given conversion specifier.
9548   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9549                                  S.getLangOpts()))
9550     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9551                                 diag::warn_format_nonsensical_length);
9552   else if (!FS.hasStandardLengthModifier())
9553     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9554   else if (!FS.hasStandardLengthConversionCombination())
9555     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9556                                 diag::warn_format_non_standard_conversion_spec);
9557 
9558   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9559     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9560 
9561   // The remaining checks depend on the data arguments.
9562   if (HasVAListArg)
9563     return true;
9564 
9565   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9566     return false;
9567 
9568   const Expr *Arg = getDataArg(argIndex);
9569   if (!Arg)
9570     return true;
9571 
9572   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9573 }
9574 
9575 static bool requiresParensToAddCast(const Expr *E) {
9576   // FIXME: We should have a general way to reason about operator
9577   // precedence and whether parens are actually needed here.
9578   // Take care of a few common cases where they aren't.
9579   const Expr *Inside = E->IgnoreImpCasts();
9580   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9581     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9582 
9583   switch (Inside->getStmtClass()) {
9584   case Stmt::ArraySubscriptExprClass:
9585   case Stmt::CallExprClass:
9586   case Stmt::CharacterLiteralClass:
9587   case Stmt::CXXBoolLiteralExprClass:
9588   case Stmt::DeclRefExprClass:
9589   case Stmt::FloatingLiteralClass:
9590   case Stmt::IntegerLiteralClass:
9591   case Stmt::MemberExprClass:
9592   case Stmt::ObjCArrayLiteralClass:
9593   case Stmt::ObjCBoolLiteralExprClass:
9594   case Stmt::ObjCBoxedExprClass:
9595   case Stmt::ObjCDictionaryLiteralClass:
9596   case Stmt::ObjCEncodeExprClass:
9597   case Stmt::ObjCIvarRefExprClass:
9598   case Stmt::ObjCMessageExprClass:
9599   case Stmt::ObjCPropertyRefExprClass:
9600   case Stmt::ObjCStringLiteralClass:
9601   case Stmt::ObjCSubscriptRefExprClass:
9602   case Stmt::ParenExprClass:
9603   case Stmt::StringLiteralClass:
9604   case Stmt::UnaryOperatorClass:
9605     return false;
9606   default:
9607     return true;
9608   }
9609 }
9610 
9611 static std::pair<QualType, StringRef>
9612 shouldNotPrintDirectly(const ASTContext &Context,
9613                        QualType IntendedTy,
9614                        const Expr *E) {
9615   // Use a 'while' to peel off layers of typedefs.
9616   QualType TyTy = IntendedTy;
9617   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9618     StringRef Name = UserTy->getDecl()->getName();
9619     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9620       .Case("CFIndex", Context.getNSIntegerType())
9621       .Case("NSInteger", Context.getNSIntegerType())
9622       .Case("NSUInteger", Context.getNSUIntegerType())
9623       .Case("SInt32", Context.IntTy)
9624       .Case("UInt32", Context.UnsignedIntTy)
9625       .Default(QualType());
9626 
9627     if (!CastTy.isNull())
9628       return std::make_pair(CastTy, Name);
9629 
9630     TyTy = UserTy->desugar();
9631   }
9632 
9633   // Strip parens if necessary.
9634   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9635     return shouldNotPrintDirectly(Context,
9636                                   PE->getSubExpr()->getType(),
9637                                   PE->getSubExpr());
9638 
9639   // If this is a conditional expression, then its result type is constructed
9640   // via usual arithmetic conversions and thus there might be no necessary
9641   // typedef sugar there.  Recurse to operands to check for NSInteger &
9642   // Co. usage condition.
9643   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9644     QualType TrueTy, FalseTy;
9645     StringRef TrueName, FalseName;
9646 
9647     std::tie(TrueTy, TrueName) =
9648       shouldNotPrintDirectly(Context,
9649                              CO->getTrueExpr()->getType(),
9650                              CO->getTrueExpr());
9651     std::tie(FalseTy, FalseName) =
9652       shouldNotPrintDirectly(Context,
9653                              CO->getFalseExpr()->getType(),
9654                              CO->getFalseExpr());
9655 
9656     if (TrueTy == FalseTy)
9657       return std::make_pair(TrueTy, TrueName);
9658     else if (TrueTy.isNull())
9659       return std::make_pair(FalseTy, FalseName);
9660     else if (FalseTy.isNull())
9661       return std::make_pair(TrueTy, TrueName);
9662   }
9663 
9664   return std::make_pair(QualType(), StringRef());
9665 }
9666 
9667 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9668 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9669 /// type do not count.
9670 static bool
9671 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9672   QualType From = ICE->getSubExpr()->getType();
9673   QualType To = ICE->getType();
9674   // It's an integer promotion if the destination type is the promoted
9675   // source type.
9676   if (ICE->getCastKind() == CK_IntegralCast &&
9677       From->isPromotableIntegerType() &&
9678       S.Context.getPromotedIntegerType(From) == To)
9679     return true;
9680   // Look through vector types, since we do default argument promotion for
9681   // those in OpenCL.
9682   if (const auto *VecTy = From->getAs<ExtVectorType>())
9683     From = VecTy->getElementType();
9684   if (const auto *VecTy = To->getAs<ExtVectorType>())
9685     To = VecTy->getElementType();
9686   // It's a floating promotion if the source type is a lower rank.
9687   return ICE->getCastKind() == CK_FloatingCast &&
9688          S.Context.getFloatingTypeOrder(From, To) < 0;
9689 }
9690 
9691 bool
9692 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9693                                     const char *StartSpecifier,
9694                                     unsigned SpecifierLen,
9695                                     const Expr *E) {
9696   using namespace analyze_format_string;
9697   using namespace analyze_printf;
9698 
9699   // Now type check the data expression that matches the
9700   // format specifier.
9701   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9702   if (!AT.isValid())
9703     return true;
9704 
9705   QualType ExprTy = E->getType();
9706   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9707     ExprTy = TET->getUnderlyingExpr()->getType();
9708   }
9709 
9710   // Diagnose attempts to print a boolean value as a character. Unlike other
9711   // -Wformat diagnostics, this is fine from a type perspective, but it still
9712   // doesn't make sense.
9713   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9714       E->isKnownToHaveBooleanValue()) {
9715     const CharSourceRange &CSR =
9716         getSpecifierRange(StartSpecifier, SpecifierLen);
9717     SmallString<4> FSString;
9718     llvm::raw_svector_ostream os(FSString);
9719     FS.toString(os);
9720     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9721                              << FSString,
9722                          E->getExprLoc(), false, CSR);
9723     return true;
9724   }
9725 
9726   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9727   if (Match == analyze_printf::ArgType::Match)
9728     return true;
9729 
9730   // Look through argument promotions for our error message's reported type.
9731   // This includes the integral and floating promotions, but excludes array
9732   // and function pointer decay (seeing that an argument intended to be a
9733   // string has type 'char [6]' is probably more confusing than 'char *') and
9734   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9735   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9736     if (isArithmeticArgumentPromotion(S, ICE)) {
9737       E = ICE->getSubExpr();
9738       ExprTy = E->getType();
9739 
9740       // Check if we didn't match because of an implicit cast from a 'char'
9741       // or 'short' to an 'int'.  This is done because printf is a varargs
9742       // function.
9743       if (ICE->getType() == S.Context.IntTy ||
9744           ICE->getType() == S.Context.UnsignedIntTy) {
9745         // All further checking is done on the subexpression
9746         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9747             AT.matchesType(S.Context, ExprTy);
9748         if (ImplicitMatch == analyze_printf::ArgType::Match)
9749           return true;
9750         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9751             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9752           Match = ImplicitMatch;
9753       }
9754     }
9755   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9756     // Special case for 'a', which has type 'int' in C.
9757     // Note, however, that we do /not/ want to treat multibyte constants like
9758     // 'MooV' as characters! This form is deprecated but still exists. In
9759     // addition, don't treat expressions as of type 'char' if one byte length
9760     // modifier is provided.
9761     if (ExprTy == S.Context.IntTy &&
9762         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9763       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9764         ExprTy = S.Context.CharTy;
9765   }
9766 
9767   // Look through enums to their underlying type.
9768   bool IsEnum = false;
9769   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9770     ExprTy = EnumTy->getDecl()->getIntegerType();
9771     IsEnum = true;
9772   }
9773 
9774   // %C in an Objective-C context prints a unichar, not a wchar_t.
9775   // If the argument is an integer of some kind, believe the %C and suggest
9776   // a cast instead of changing the conversion specifier.
9777   QualType IntendedTy = ExprTy;
9778   if (isObjCContext() &&
9779       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9780     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9781         !ExprTy->isCharType()) {
9782       // 'unichar' is defined as a typedef of unsigned short, but we should
9783       // prefer using the typedef if it is visible.
9784       IntendedTy = S.Context.UnsignedShortTy;
9785 
9786       // While we are here, check if the value is an IntegerLiteral that happens
9787       // to be within the valid range.
9788       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9789         const llvm::APInt &V = IL->getValue();
9790         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9791           return true;
9792       }
9793 
9794       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9795                           Sema::LookupOrdinaryName);
9796       if (S.LookupName(Result, S.getCurScope())) {
9797         NamedDecl *ND = Result.getFoundDecl();
9798         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9799           if (TD->getUnderlyingType() == IntendedTy)
9800             IntendedTy = S.Context.getTypedefType(TD);
9801       }
9802     }
9803   }
9804 
9805   // Special-case some of Darwin's platform-independence types by suggesting
9806   // casts to primitive types that are known to be large enough.
9807   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9808   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9809     QualType CastTy;
9810     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9811     if (!CastTy.isNull()) {
9812       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9813       // (long in ASTContext). Only complain to pedants.
9814       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9815           (AT.isSizeT() || AT.isPtrdiffT()) &&
9816           AT.matchesType(S.Context, CastTy))
9817         Match = ArgType::NoMatchPedantic;
9818       IntendedTy = CastTy;
9819       ShouldNotPrintDirectly = true;
9820     }
9821   }
9822 
9823   // We may be able to offer a FixItHint if it is a supported type.
9824   PrintfSpecifier fixedFS = FS;
9825   bool Success =
9826       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9827 
9828   if (Success) {
9829     // Get the fix string from the fixed format specifier
9830     SmallString<16> buf;
9831     llvm::raw_svector_ostream os(buf);
9832     fixedFS.toString(os);
9833 
9834     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9835 
9836     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9837       unsigned Diag;
9838       switch (Match) {
9839       case ArgType::Match: llvm_unreachable("expected non-matching");
9840       case ArgType::NoMatchPedantic:
9841         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9842         break;
9843       case ArgType::NoMatchTypeConfusion:
9844         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9845         break;
9846       case ArgType::NoMatch:
9847         Diag = diag::warn_format_conversion_argument_type_mismatch;
9848         break;
9849       }
9850 
9851       // In this case, the specifier is wrong and should be changed to match
9852       // the argument.
9853       EmitFormatDiagnostic(S.PDiag(Diag)
9854                                << AT.getRepresentativeTypeName(S.Context)
9855                                << IntendedTy << IsEnum << E->getSourceRange(),
9856                            E->getBeginLoc(),
9857                            /*IsStringLocation*/ false, SpecRange,
9858                            FixItHint::CreateReplacement(SpecRange, os.str()));
9859     } else {
9860       // The canonical type for formatting this value is different from the
9861       // actual type of the expression. (This occurs, for example, with Darwin's
9862       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9863       // should be printed as 'long' for 64-bit compatibility.)
9864       // Rather than emitting a normal format/argument mismatch, we want to
9865       // add a cast to the recommended type (and correct the format string
9866       // if necessary).
9867       SmallString<16> CastBuf;
9868       llvm::raw_svector_ostream CastFix(CastBuf);
9869       CastFix << "(";
9870       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9871       CastFix << ")";
9872 
9873       SmallVector<FixItHint,4> Hints;
9874       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9875         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9876 
9877       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9878         // If there's already a cast present, just replace it.
9879         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9880         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9881 
9882       } else if (!requiresParensToAddCast(E)) {
9883         // If the expression has high enough precedence,
9884         // just write the C-style cast.
9885         Hints.push_back(
9886             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9887       } else {
9888         // Otherwise, add parens around the expression as well as the cast.
9889         CastFix << "(";
9890         Hints.push_back(
9891             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9892 
9893         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9894         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9895       }
9896 
9897       if (ShouldNotPrintDirectly) {
9898         // The expression has a type that should not be printed directly.
9899         // We extract the name from the typedef because we don't want to show
9900         // the underlying type in the diagnostic.
9901         StringRef Name;
9902         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9903           Name = TypedefTy->getDecl()->getName();
9904         else
9905           Name = CastTyName;
9906         unsigned Diag = Match == ArgType::NoMatchPedantic
9907                             ? diag::warn_format_argument_needs_cast_pedantic
9908                             : diag::warn_format_argument_needs_cast;
9909         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9910                                            << E->getSourceRange(),
9911                              E->getBeginLoc(), /*IsStringLocation=*/false,
9912                              SpecRange, Hints);
9913       } else {
9914         // In this case, the expression could be printed using a different
9915         // specifier, but we've decided that the specifier is probably correct
9916         // and we should cast instead. Just use the normal warning message.
9917         EmitFormatDiagnostic(
9918             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9919                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9920                 << E->getSourceRange(),
9921             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9922       }
9923     }
9924   } else {
9925     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9926                                                    SpecifierLen);
9927     // Since the warning for passing non-POD types to variadic functions
9928     // was deferred until now, we emit a warning for non-POD
9929     // arguments here.
9930     switch (S.isValidVarArgType(ExprTy)) {
9931     case Sema::VAK_Valid:
9932     case Sema::VAK_ValidInCXX11: {
9933       unsigned Diag;
9934       switch (Match) {
9935       case ArgType::Match: llvm_unreachable("expected non-matching");
9936       case ArgType::NoMatchPedantic:
9937         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9938         break;
9939       case ArgType::NoMatchTypeConfusion:
9940         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9941         break;
9942       case ArgType::NoMatch:
9943         Diag = diag::warn_format_conversion_argument_type_mismatch;
9944         break;
9945       }
9946 
9947       EmitFormatDiagnostic(
9948           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9949                         << IsEnum << CSR << E->getSourceRange(),
9950           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9951       break;
9952     }
9953     case Sema::VAK_Undefined:
9954     case Sema::VAK_MSVCUndefined:
9955       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9956                                << S.getLangOpts().CPlusPlus11 << ExprTy
9957                                << CallType
9958                                << AT.getRepresentativeTypeName(S.Context) << CSR
9959                                << E->getSourceRange(),
9960                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9961       checkForCStrMembers(AT, E);
9962       break;
9963 
9964     case Sema::VAK_Invalid:
9965       if (ExprTy->isObjCObjectType())
9966         EmitFormatDiagnostic(
9967             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9968                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9969                 << AT.getRepresentativeTypeName(S.Context) << CSR
9970                 << E->getSourceRange(),
9971             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9972       else
9973         // FIXME: If this is an initializer list, suggest removing the braces
9974         // or inserting a cast to the target type.
9975         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9976             << isa<InitListExpr>(E) << ExprTy << CallType
9977             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9978       break;
9979     }
9980 
9981     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9982            "format string specifier index out of range");
9983     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9984   }
9985 
9986   return true;
9987 }
9988 
9989 //===--- CHECK: Scanf format string checking ------------------------------===//
9990 
9991 namespace {
9992 
9993 class CheckScanfHandler : public CheckFormatHandler {
9994 public:
9995   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9996                     const Expr *origFormatExpr, Sema::FormatStringType type,
9997                     unsigned firstDataArg, unsigned numDataArgs,
9998                     const char *beg, bool hasVAListArg,
9999                     ArrayRef<const Expr *> Args, unsigned formatIdx,
10000                     bool inFunctionCall, Sema::VariadicCallType CallType,
10001                     llvm::SmallBitVector &CheckedVarArgs,
10002                     UncoveredArgHandler &UncoveredArg)
10003       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10004                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
10005                            inFunctionCall, CallType, CheckedVarArgs,
10006                            UncoveredArg) {}
10007 
10008   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10009                             const char *startSpecifier,
10010                             unsigned specifierLen) override;
10011 
10012   bool HandleInvalidScanfConversionSpecifier(
10013           const analyze_scanf::ScanfSpecifier &FS,
10014           const char *startSpecifier,
10015           unsigned specifierLen) override;
10016 
10017   void HandleIncompleteScanList(const char *start, const char *end) override;
10018 };
10019 
10020 } // namespace
10021 
10022 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10023                                                  const char *end) {
10024   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
10025                        getLocationOfByte(end), /*IsStringLocation*/true,
10026                        getSpecifierRange(start, end - start));
10027 }
10028 
10029 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10030                                         const analyze_scanf::ScanfSpecifier &FS,
10031                                         const char *startSpecifier,
10032                                         unsigned specifierLen) {
10033   const analyze_scanf::ScanfConversionSpecifier &CS =
10034     FS.getConversionSpecifier();
10035 
10036   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
10037                                           getLocationOfByte(CS.getStart()),
10038                                           startSpecifier, specifierLen,
10039                                           CS.getStart(), CS.getLength());
10040 }
10041 
10042 bool CheckScanfHandler::HandleScanfSpecifier(
10043                                        const analyze_scanf::ScanfSpecifier &FS,
10044                                        const char *startSpecifier,
10045                                        unsigned specifierLen) {
10046   using namespace analyze_scanf;
10047   using namespace analyze_format_string;
10048 
10049   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10050 
10051   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
10052   // be used to decide if we are using positional arguments consistently.
10053   if (FS.consumesDataArgument()) {
10054     if (atFirstArg) {
10055       atFirstArg = false;
10056       usesPositionalArgs = FS.usesPositionalArg();
10057     }
10058     else if (usesPositionalArgs != FS.usesPositionalArg()) {
10059       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
10060                                         startSpecifier, specifierLen);
10061       return false;
10062     }
10063   }
10064 
10065   // Check if the field with is non-zero.
10066   const OptionalAmount &Amt = FS.getFieldWidth();
10067   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
10068     if (Amt.getConstantAmount() == 0) {
10069       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
10070                                                    Amt.getConstantLength());
10071       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
10072                            getLocationOfByte(Amt.getStart()),
10073                            /*IsStringLocation*/true, R,
10074                            FixItHint::CreateRemoval(R));
10075     }
10076   }
10077 
10078   if (!FS.consumesDataArgument()) {
10079     // FIXME: Technically specifying a precision or field width here
10080     // makes no sense.  Worth issuing a warning at some point.
10081     return true;
10082   }
10083 
10084   // Consume the argument.
10085   unsigned argIndex = FS.getArgIndex();
10086   if (argIndex < NumDataArgs) {
10087       // The check to see if the argIndex is valid will come later.
10088       // We set the bit here because we may exit early from this
10089       // function if we encounter some other error.
10090     CoveredArgs.set(argIndex);
10091   }
10092 
10093   // Check the length modifier is valid with the given conversion specifier.
10094   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
10095                                  S.getLangOpts()))
10096     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10097                                 diag::warn_format_nonsensical_length);
10098   else if (!FS.hasStandardLengthModifier())
10099     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10100   else if (!FS.hasStandardLengthConversionCombination())
10101     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10102                                 diag::warn_format_non_standard_conversion_spec);
10103 
10104   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
10105     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10106 
10107   // The remaining checks depend on the data arguments.
10108   if (HasVAListArg)
10109     return true;
10110 
10111   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10112     return false;
10113 
10114   // Check that the argument type matches the format specifier.
10115   const Expr *Ex = getDataArg(argIndex);
10116   if (!Ex)
10117     return true;
10118 
10119   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
10120 
10121   if (!AT.isValid()) {
10122     return true;
10123   }
10124 
10125   analyze_format_string::ArgType::MatchKind Match =
10126       AT.matchesType(S.Context, Ex->getType());
10127   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10128   if (Match == analyze_format_string::ArgType::Match)
10129     return true;
10130 
10131   ScanfSpecifier fixedFS = FS;
10132   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10133                                  S.getLangOpts(), S.Context);
10134 
10135   unsigned Diag =
10136       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10137                : diag::warn_format_conversion_argument_type_mismatch;
10138 
10139   if (Success) {
10140     // Get the fix string from the fixed format specifier.
10141     SmallString<128> buf;
10142     llvm::raw_svector_ostream os(buf);
10143     fixedFS.toString(os);
10144 
10145     EmitFormatDiagnostic(
10146         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10147                       << Ex->getType() << false << Ex->getSourceRange(),
10148         Ex->getBeginLoc(),
10149         /*IsStringLocation*/ false,
10150         getSpecifierRange(startSpecifier, specifierLen),
10151         FixItHint::CreateReplacement(
10152             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10153   } else {
10154     EmitFormatDiagnostic(S.PDiag(Diag)
10155                              << AT.getRepresentativeTypeName(S.Context)
10156                              << Ex->getType() << false << Ex->getSourceRange(),
10157                          Ex->getBeginLoc(),
10158                          /*IsStringLocation*/ false,
10159                          getSpecifierRange(startSpecifier, specifierLen));
10160   }
10161 
10162   return true;
10163 }
10164 
10165 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10166                               const Expr *OrigFormatExpr,
10167                               ArrayRef<const Expr *> Args,
10168                               bool HasVAListArg, unsigned format_idx,
10169                               unsigned firstDataArg,
10170                               Sema::FormatStringType Type,
10171                               bool inFunctionCall,
10172                               Sema::VariadicCallType CallType,
10173                               llvm::SmallBitVector &CheckedVarArgs,
10174                               UncoveredArgHandler &UncoveredArg,
10175                               bool IgnoreStringsWithoutSpecifiers) {
10176   // CHECK: is the format string a wide literal?
10177   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10178     CheckFormatHandler::EmitFormatDiagnostic(
10179         S, inFunctionCall, Args[format_idx],
10180         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10181         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10182     return;
10183   }
10184 
10185   // Str - The format string.  NOTE: this is NOT null-terminated!
10186   StringRef StrRef = FExpr->getString();
10187   const char *Str = StrRef.data();
10188   // Account for cases where the string literal is truncated in a declaration.
10189   const ConstantArrayType *T =
10190     S.Context.getAsConstantArrayType(FExpr->getType());
10191   assert(T && "String literal not of constant array type!");
10192   size_t TypeSize = T->getSize().getZExtValue();
10193   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10194   const unsigned numDataArgs = Args.size() - firstDataArg;
10195 
10196   if (IgnoreStringsWithoutSpecifiers &&
10197       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10198           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10199     return;
10200 
10201   // Emit a warning if the string literal is truncated and does not contain an
10202   // embedded null character.
10203   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10204     CheckFormatHandler::EmitFormatDiagnostic(
10205         S, inFunctionCall, Args[format_idx],
10206         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10207         FExpr->getBeginLoc(),
10208         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10209     return;
10210   }
10211 
10212   // CHECK: empty format string?
10213   if (StrLen == 0 && numDataArgs > 0) {
10214     CheckFormatHandler::EmitFormatDiagnostic(
10215         S, inFunctionCall, Args[format_idx],
10216         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10217         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10218     return;
10219   }
10220 
10221   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10222       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10223       Type == Sema::FST_OSTrace) {
10224     CheckPrintfHandler H(
10225         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10226         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10227         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10228         CheckedVarArgs, UncoveredArg);
10229 
10230     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10231                                                   S.getLangOpts(),
10232                                                   S.Context.getTargetInfo(),
10233                                             Type == Sema::FST_FreeBSDKPrintf))
10234       H.DoneProcessing();
10235   } else if (Type == Sema::FST_Scanf) {
10236     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10237                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10238                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10239 
10240     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10241                                                  S.getLangOpts(),
10242                                                  S.Context.getTargetInfo()))
10243       H.DoneProcessing();
10244   } // TODO: handle other formats
10245 }
10246 
10247 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10248   // Str - The format string.  NOTE: this is NOT null-terminated!
10249   StringRef StrRef = FExpr->getString();
10250   const char *Str = StrRef.data();
10251   // Account for cases where the string literal is truncated in a declaration.
10252   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10253   assert(T && "String literal not of constant array type!");
10254   size_t TypeSize = T->getSize().getZExtValue();
10255   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10256   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10257                                                          getLangOpts(),
10258                                                          Context.getTargetInfo());
10259 }
10260 
10261 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10262 
10263 // Returns the related absolute value function that is larger, of 0 if one
10264 // does not exist.
10265 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10266   switch (AbsFunction) {
10267   default:
10268     return 0;
10269 
10270   case Builtin::BI__builtin_abs:
10271     return Builtin::BI__builtin_labs;
10272   case Builtin::BI__builtin_labs:
10273     return Builtin::BI__builtin_llabs;
10274   case Builtin::BI__builtin_llabs:
10275     return 0;
10276 
10277   case Builtin::BI__builtin_fabsf:
10278     return Builtin::BI__builtin_fabs;
10279   case Builtin::BI__builtin_fabs:
10280     return Builtin::BI__builtin_fabsl;
10281   case Builtin::BI__builtin_fabsl:
10282     return 0;
10283 
10284   case Builtin::BI__builtin_cabsf:
10285     return Builtin::BI__builtin_cabs;
10286   case Builtin::BI__builtin_cabs:
10287     return Builtin::BI__builtin_cabsl;
10288   case Builtin::BI__builtin_cabsl:
10289     return 0;
10290 
10291   case Builtin::BIabs:
10292     return Builtin::BIlabs;
10293   case Builtin::BIlabs:
10294     return Builtin::BIllabs;
10295   case Builtin::BIllabs:
10296     return 0;
10297 
10298   case Builtin::BIfabsf:
10299     return Builtin::BIfabs;
10300   case Builtin::BIfabs:
10301     return Builtin::BIfabsl;
10302   case Builtin::BIfabsl:
10303     return 0;
10304 
10305   case Builtin::BIcabsf:
10306    return Builtin::BIcabs;
10307   case Builtin::BIcabs:
10308     return Builtin::BIcabsl;
10309   case Builtin::BIcabsl:
10310     return 0;
10311   }
10312 }
10313 
10314 // Returns the argument type of the absolute value function.
10315 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10316                                              unsigned AbsType) {
10317   if (AbsType == 0)
10318     return QualType();
10319 
10320   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10321   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10322   if (Error != ASTContext::GE_None)
10323     return QualType();
10324 
10325   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10326   if (!FT)
10327     return QualType();
10328 
10329   if (FT->getNumParams() != 1)
10330     return QualType();
10331 
10332   return FT->getParamType(0);
10333 }
10334 
10335 // Returns the best absolute value function, or zero, based on type and
10336 // current absolute value function.
10337 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10338                                    unsigned AbsFunctionKind) {
10339   unsigned BestKind = 0;
10340   uint64_t ArgSize = Context.getTypeSize(ArgType);
10341   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10342        Kind = getLargerAbsoluteValueFunction(Kind)) {
10343     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10344     if (Context.getTypeSize(ParamType) >= ArgSize) {
10345       if (BestKind == 0)
10346         BestKind = Kind;
10347       else if (Context.hasSameType(ParamType, ArgType)) {
10348         BestKind = Kind;
10349         break;
10350       }
10351     }
10352   }
10353   return BestKind;
10354 }
10355 
10356 enum AbsoluteValueKind {
10357   AVK_Integer,
10358   AVK_Floating,
10359   AVK_Complex
10360 };
10361 
10362 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10363   if (T->isIntegralOrEnumerationType())
10364     return AVK_Integer;
10365   if (T->isRealFloatingType())
10366     return AVK_Floating;
10367   if (T->isAnyComplexType())
10368     return AVK_Complex;
10369 
10370   llvm_unreachable("Type not integer, floating, or complex");
10371 }
10372 
10373 // Changes the absolute value function to a different type.  Preserves whether
10374 // the function is a builtin.
10375 static unsigned changeAbsFunction(unsigned AbsKind,
10376                                   AbsoluteValueKind ValueKind) {
10377   switch (ValueKind) {
10378   case AVK_Integer:
10379     switch (AbsKind) {
10380     default:
10381       return 0;
10382     case Builtin::BI__builtin_fabsf:
10383     case Builtin::BI__builtin_fabs:
10384     case Builtin::BI__builtin_fabsl:
10385     case Builtin::BI__builtin_cabsf:
10386     case Builtin::BI__builtin_cabs:
10387     case Builtin::BI__builtin_cabsl:
10388       return Builtin::BI__builtin_abs;
10389     case Builtin::BIfabsf:
10390     case Builtin::BIfabs:
10391     case Builtin::BIfabsl:
10392     case Builtin::BIcabsf:
10393     case Builtin::BIcabs:
10394     case Builtin::BIcabsl:
10395       return Builtin::BIabs;
10396     }
10397   case AVK_Floating:
10398     switch (AbsKind) {
10399     default:
10400       return 0;
10401     case Builtin::BI__builtin_abs:
10402     case Builtin::BI__builtin_labs:
10403     case Builtin::BI__builtin_llabs:
10404     case Builtin::BI__builtin_cabsf:
10405     case Builtin::BI__builtin_cabs:
10406     case Builtin::BI__builtin_cabsl:
10407       return Builtin::BI__builtin_fabsf;
10408     case Builtin::BIabs:
10409     case Builtin::BIlabs:
10410     case Builtin::BIllabs:
10411     case Builtin::BIcabsf:
10412     case Builtin::BIcabs:
10413     case Builtin::BIcabsl:
10414       return Builtin::BIfabsf;
10415     }
10416   case AVK_Complex:
10417     switch (AbsKind) {
10418     default:
10419       return 0;
10420     case Builtin::BI__builtin_abs:
10421     case Builtin::BI__builtin_labs:
10422     case Builtin::BI__builtin_llabs:
10423     case Builtin::BI__builtin_fabsf:
10424     case Builtin::BI__builtin_fabs:
10425     case Builtin::BI__builtin_fabsl:
10426       return Builtin::BI__builtin_cabsf;
10427     case Builtin::BIabs:
10428     case Builtin::BIlabs:
10429     case Builtin::BIllabs:
10430     case Builtin::BIfabsf:
10431     case Builtin::BIfabs:
10432     case Builtin::BIfabsl:
10433       return Builtin::BIcabsf;
10434     }
10435   }
10436   llvm_unreachable("Unable to convert function");
10437 }
10438 
10439 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10440   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10441   if (!FnInfo)
10442     return 0;
10443 
10444   switch (FDecl->getBuiltinID()) {
10445   default:
10446     return 0;
10447   case Builtin::BI__builtin_abs:
10448   case Builtin::BI__builtin_fabs:
10449   case Builtin::BI__builtin_fabsf:
10450   case Builtin::BI__builtin_fabsl:
10451   case Builtin::BI__builtin_labs:
10452   case Builtin::BI__builtin_llabs:
10453   case Builtin::BI__builtin_cabs:
10454   case Builtin::BI__builtin_cabsf:
10455   case Builtin::BI__builtin_cabsl:
10456   case Builtin::BIabs:
10457   case Builtin::BIlabs:
10458   case Builtin::BIllabs:
10459   case Builtin::BIfabs:
10460   case Builtin::BIfabsf:
10461   case Builtin::BIfabsl:
10462   case Builtin::BIcabs:
10463   case Builtin::BIcabsf:
10464   case Builtin::BIcabsl:
10465     return FDecl->getBuiltinID();
10466   }
10467   llvm_unreachable("Unknown Builtin type");
10468 }
10469 
10470 // If the replacement is valid, emit a note with replacement function.
10471 // Additionally, suggest including the proper header if not already included.
10472 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10473                             unsigned AbsKind, QualType ArgType) {
10474   bool EmitHeaderHint = true;
10475   const char *HeaderName = nullptr;
10476   const char *FunctionName = nullptr;
10477   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10478     FunctionName = "std::abs";
10479     if (ArgType->isIntegralOrEnumerationType()) {
10480       HeaderName = "cstdlib";
10481     } else if (ArgType->isRealFloatingType()) {
10482       HeaderName = "cmath";
10483     } else {
10484       llvm_unreachable("Invalid Type");
10485     }
10486 
10487     // Lookup all std::abs
10488     if (NamespaceDecl *Std = S.getStdNamespace()) {
10489       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10490       R.suppressDiagnostics();
10491       S.LookupQualifiedName(R, Std);
10492 
10493       for (const auto *I : R) {
10494         const FunctionDecl *FDecl = nullptr;
10495         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10496           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10497         } else {
10498           FDecl = dyn_cast<FunctionDecl>(I);
10499         }
10500         if (!FDecl)
10501           continue;
10502 
10503         // Found std::abs(), check that they are the right ones.
10504         if (FDecl->getNumParams() != 1)
10505           continue;
10506 
10507         // Check that the parameter type can handle the argument.
10508         QualType ParamType = FDecl->getParamDecl(0)->getType();
10509         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10510             S.Context.getTypeSize(ArgType) <=
10511                 S.Context.getTypeSize(ParamType)) {
10512           // Found a function, don't need the header hint.
10513           EmitHeaderHint = false;
10514           break;
10515         }
10516       }
10517     }
10518   } else {
10519     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10520     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10521 
10522     if (HeaderName) {
10523       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10524       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10525       R.suppressDiagnostics();
10526       S.LookupName(R, S.getCurScope());
10527 
10528       if (R.isSingleResult()) {
10529         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10530         if (FD && FD->getBuiltinID() == AbsKind) {
10531           EmitHeaderHint = false;
10532         } else {
10533           return;
10534         }
10535       } else if (!R.empty()) {
10536         return;
10537       }
10538     }
10539   }
10540 
10541   S.Diag(Loc, diag::note_replace_abs_function)
10542       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10543 
10544   if (!HeaderName)
10545     return;
10546 
10547   if (!EmitHeaderHint)
10548     return;
10549 
10550   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10551                                                     << FunctionName;
10552 }
10553 
10554 template <std::size_t StrLen>
10555 static bool IsStdFunction(const FunctionDecl *FDecl,
10556                           const char (&Str)[StrLen]) {
10557   if (!FDecl)
10558     return false;
10559   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10560     return false;
10561   if (!FDecl->isInStdNamespace())
10562     return false;
10563 
10564   return true;
10565 }
10566 
10567 // Warn when using the wrong abs() function.
10568 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10569                                       const FunctionDecl *FDecl) {
10570   if (Call->getNumArgs() != 1)
10571     return;
10572 
10573   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10574   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10575   if (AbsKind == 0 && !IsStdAbs)
10576     return;
10577 
10578   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10579   QualType ParamType = Call->getArg(0)->getType();
10580 
10581   // Unsigned types cannot be negative.  Suggest removing the absolute value
10582   // function call.
10583   if (ArgType->isUnsignedIntegerType()) {
10584     const char *FunctionName =
10585         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10586     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10587     Diag(Call->getExprLoc(), diag::note_remove_abs)
10588         << FunctionName
10589         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10590     return;
10591   }
10592 
10593   // Taking the absolute value of a pointer is very suspicious, they probably
10594   // wanted to index into an array, dereference a pointer, call a function, etc.
10595   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10596     unsigned DiagType = 0;
10597     if (ArgType->isFunctionType())
10598       DiagType = 1;
10599     else if (ArgType->isArrayType())
10600       DiagType = 2;
10601 
10602     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10603     return;
10604   }
10605 
10606   // std::abs has overloads which prevent most of the absolute value problems
10607   // from occurring.
10608   if (IsStdAbs)
10609     return;
10610 
10611   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10612   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10613 
10614   // The argument and parameter are the same kind.  Check if they are the right
10615   // size.
10616   if (ArgValueKind == ParamValueKind) {
10617     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10618       return;
10619 
10620     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10621     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10622         << FDecl << ArgType << ParamType;
10623 
10624     if (NewAbsKind == 0)
10625       return;
10626 
10627     emitReplacement(*this, Call->getExprLoc(),
10628                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10629     return;
10630   }
10631 
10632   // ArgValueKind != ParamValueKind
10633   // The wrong type of absolute value function was used.  Attempt to find the
10634   // proper one.
10635   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10636   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10637   if (NewAbsKind == 0)
10638     return;
10639 
10640   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10641       << FDecl << ParamValueKind << ArgValueKind;
10642 
10643   emitReplacement(*this, Call->getExprLoc(),
10644                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10645 }
10646 
10647 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10648 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10649                                 const FunctionDecl *FDecl) {
10650   if (!Call || !FDecl) return;
10651 
10652   // Ignore template specializations and macros.
10653   if (inTemplateInstantiation()) return;
10654   if (Call->getExprLoc().isMacroID()) return;
10655 
10656   // Only care about the one template argument, two function parameter std::max
10657   if (Call->getNumArgs() != 2) return;
10658   if (!IsStdFunction(FDecl, "max")) return;
10659   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10660   if (!ArgList) return;
10661   if (ArgList->size() != 1) return;
10662 
10663   // Check that template type argument is unsigned integer.
10664   const auto& TA = ArgList->get(0);
10665   if (TA.getKind() != TemplateArgument::Type) return;
10666   QualType ArgType = TA.getAsType();
10667   if (!ArgType->isUnsignedIntegerType()) return;
10668 
10669   // See if either argument is a literal zero.
10670   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10671     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10672     if (!MTE) return false;
10673     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10674     if (!Num) return false;
10675     if (Num->getValue() != 0) return false;
10676     return true;
10677   };
10678 
10679   const Expr *FirstArg = Call->getArg(0);
10680   const Expr *SecondArg = Call->getArg(1);
10681   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10682   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10683 
10684   // Only warn when exactly one argument is zero.
10685   if (IsFirstArgZero == IsSecondArgZero) return;
10686 
10687   SourceRange FirstRange = FirstArg->getSourceRange();
10688   SourceRange SecondRange = SecondArg->getSourceRange();
10689 
10690   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10691 
10692   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10693       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10694 
10695   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10696   SourceRange RemovalRange;
10697   if (IsFirstArgZero) {
10698     RemovalRange = SourceRange(FirstRange.getBegin(),
10699                                SecondRange.getBegin().getLocWithOffset(-1));
10700   } else {
10701     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10702                                SecondRange.getEnd());
10703   }
10704 
10705   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10706         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10707         << FixItHint::CreateRemoval(RemovalRange);
10708 }
10709 
10710 //===--- CHECK: Standard memory functions ---------------------------------===//
10711 
10712 /// Takes the expression passed to the size_t parameter of functions
10713 /// such as memcmp, strncat, etc and warns if it's a comparison.
10714 ///
10715 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10716 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10717                                            IdentifierInfo *FnName,
10718                                            SourceLocation FnLoc,
10719                                            SourceLocation RParenLoc) {
10720   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10721   if (!Size)
10722     return false;
10723 
10724   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10725   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10726     return false;
10727 
10728   SourceRange SizeRange = Size->getSourceRange();
10729   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10730       << SizeRange << FnName;
10731   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10732       << FnName
10733       << FixItHint::CreateInsertion(
10734              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10735       << FixItHint::CreateRemoval(RParenLoc);
10736   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10737       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10738       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10739                                     ")");
10740 
10741   return true;
10742 }
10743 
10744 /// Determine whether the given type is or contains a dynamic class type
10745 /// (e.g., whether it has a vtable).
10746 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10747                                                      bool &IsContained) {
10748   // Look through array types while ignoring qualifiers.
10749   const Type *Ty = T->getBaseElementTypeUnsafe();
10750   IsContained = false;
10751 
10752   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10753   RD = RD ? RD->getDefinition() : nullptr;
10754   if (!RD || RD->isInvalidDecl())
10755     return nullptr;
10756 
10757   if (RD->isDynamicClass())
10758     return RD;
10759 
10760   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10761   // It's impossible for a class to transitively contain itself by value, so
10762   // infinite recursion is impossible.
10763   for (auto *FD : RD->fields()) {
10764     bool SubContained;
10765     if (const CXXRecordDecl *ContainedRD =
10766             getContainedDynamicClass(FD->getType(), SubContained)) {
10767       IsContained = true;
10768       return ContainedRD;
10769     }
10770   }
10771 
10772   return nullptr;
10773 }
10774 
10775 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10776   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10777     if (Unary->getKind() == UETT_SizeOf)
10778       return Unary;
10779   return nullptr;
10780 }
10781 
10782 /// If E is a sizeof expression, returns its argument expression,
10783 /// otherwise returns NULL.
10784 static const Expr *getSizeOfExprArg(const Expr *E) {
10785   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10786     if (!SizeOf->isArgumentType())
10787       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10788   return nullptr;
10789 }
10790 
10791 /// If E is a sizeof expression, returns its argument type.
10792 static QualType getSizeOfArgType(const Expr *E) {
10793   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10794     return SizeOf->getTypeOfArgument();
10795   return QualType();
10796 }
10797 
10798 namespace {
10799 
10800 struct SearchNonTrivialToInitializeField
10801     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10802   using Super =
10803       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10804 
10805   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10806 
10807   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10808                      SourceLocation SL) {
10809     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10810       asDerived().visitArray(PDIK, AT, SL);
10811       return;
10812     }
10813 
10814     Super::visitWithKind(PDIK, FT, SL);
10815   }
10816 
10817   void visitARCStrong(QualType FT, SourceLocation SL) {
10818     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10819   }
10820   void visitARCWeak(QualType FT, SourceLocation SL) {
10821     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10822   }
10823   void visitStruct(QualType FT, SourceLocation SL) {
10824     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10825       visit(FD->getType(), FD->getLocation());
10826   }
10827   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10828                   const ArrayType *AT, SourceLocation SL) {
10829     visit(getContext().getBaseElementType(AT), SL);
10830   }
10831   void visitTrivial(QualType FT, SourceLocation SL) {}
10832 
10833   static void diag(QualType RT, const Expr *E, Sema &S) {
10834     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10835   }
10836 
10837   ASTContext &getContext() { return S.getASTContext(); }
10838 
10839   const Expr *E;
10840   Sema &S;
10841 };
10842 
10843 struct SearchNonTrivialToCopyField
10844     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10845   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10846 
10847   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10848 
10849   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10850                      SourceLocation SL) {
10851     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10852       asDerived().visitArray(PCK, AT, SL);
10853       return;
10854     }
10855 
10856     Super::visitWithKind(PCK, FT, SL);
10857   }
10858 
10859   void visitARCStrong(QualType FT, SourceLocation SL) {
10860     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10861   }
10862   void visitARCWeak(QualType FT, SourceLocation SL) {
10863     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10864   }
10865   void visitStruct(QualType FT, SourceLocation SL) {
10866     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10867       visit(FD->getType(), FD->getLocation());
10868   }
10869   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10870                   SourceLocation SL) {
10871     visit(getContext().getBaseElementType(AT), SL);
10872   }
10873   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10874                 SourceLocation SL) {}
10875   void visitTrivial(QualType FT, SourceLocation SL) {}
10876   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10877 
10878   static void diag(QualType RT, const Expr *E, Sema &S) {
10879     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10880   }
10881 
10882   ASTContext &getContext() { return S.getASTContext(); }
10883 
10884   const Expr *E;
10885   Sema &S;
10886 };
10887 
10888 }
10889 
10890 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10891 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10892   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10893 
10894   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10895     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10896       return false;
10897 
10898     return doesExprLikelyComputeSize(BO->getLHS()) ||
10899            doesExprLikelyComputeSize(BO->getRHS());
10900   }
10901 
10902   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10903 }
10904 
10905 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10906 ///
10907 /// \code
10908 ///   #define MACRO 0
10909 ///   foo(MACRO);
10910 ///   foo(0);
10911 /// \endcode
10912 ///
10913 /// This should return true for the first call to foo, but not for the second
10914 /// (regardless of whether foo is a macro or function).
10915 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10916                                         SourceLocation CallLoc,
10917                                         SourceLocation ArgLoc) {
10918   if (!CallLoc.isMacroID())
10919     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10920 
10921   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10922          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10923 }
10924 
10925 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10926 /// last two arguments transposed.
10927 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10928   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10929     return;
10930 
10931   const Expr *SizeArg =
10932     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10933 
10934   auto isLiteralZero = [](const Expr *E) {
10935     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10936   };
10937 
10938   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10939   SourceLocation CallLoc = Call->getRParenLoc();
10940   SourceManager &SM = S.getSourceManager();
10941   if (isLiteralZero(SizeArg) &&
10942       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10943 
10944     SourceLocation DiagLoc = SizeArg->getExprLoc();
10945 
10946     // Some platforms #define bzero to __builtin_memset. See if this is the
10947     // case, and if so, emit a better diagnostic.
10948     if (BId == Builtin::BIbzero ||
10949         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10950                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10951       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10952       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10953     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10954       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10955       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10956     }
10957     return;
10958   }
10959 
10960   // If the second argument to a memset is a sizeof expression and the third
10961   // isn't, this is also likely an error. This should catch
10962   // 'memset(buf, sizeof(buf), 0xff)'.
10963   if (BId == Builtin::BImemset &&
10964       doesExprLikelyComputeSize(Call->getArg(1)) &&
10965       !doesExprLikelyComputeSize(Call->getArg(2))) {
10966     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10967     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10968     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10969     return;
10970   }
10971 }
10972 
10973 /// Check for dangerous or invalid arguments to memset().
10974 ///
10975 /// This issues warnings on known problematic, dangerous or unspecified
10976 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10977 /// function calls.
10978 ///
10979 /// \param Call The call expression to diagnose.
10980 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10981                                    unsigned BId,
10982                                    IdentifierInfo *FnName) {
10983   assert(BId != 0);
10984 
10985   // It is possible to have a non-standard definition of memset.  Validate
10986   // we have enough arguments, and if not, abort further checking.
10987   unsigned ExpectedNumArgs =
10988       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10989   if (Call->getNumArgs() < ExpectedNumArgs)
10990     return;
10991 
10992   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10993                       BId == Builtin::BIstrndup ? 1 : 2);
10994   unsigned LenArg =
10995       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10996   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10997 
10998   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10999                                      Call->getBeginLoc(), Call->getRParenLoc()))
11000     return;
11001 
11002   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11003   CheckMemaccessSize(*this, BId, Call);
11004 
11005   // We have special checking when the length is a sizeof expression.
11006   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11007   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11008   llvm::FoldingSetNodeID SizeOfArgID;
11009 
11010   // Although widely used, 'bzero' is not a standard function. Be more strict
11011   // with the argument types before allowing diagnostics and only allow the
11012   // form bzero(ptr, sizeof(...)).
11013   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11014   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11015     return;
11016 
11017   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11018     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11019     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11020 
11021     QualType DestTy = Dest->getType();
11022     QualType PointeeTy;
11023     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11024       PointeeTy = DestPtrTy->getPointeeType();
11025 
11026       // Never warn about void type pointers. This can be used to suppress
11027       // false positives.
11028       if (PointeeTy->isVoidType())
11029         continue;
11030 
11031       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11032       // actually comparing the expressions for equality. Because computing the
11033       // expression IDs can be expensive, we only do this if the diagnostic is
11034       // enabled.
11035       if (SizeOfArg &&
11036           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11037                            SizeOfArg->getExprLoc())) {
11038         // We only compute IDs for expressions if the warning is enabled, and
11039         // cache the sizeof arg's ID.
11040         if (SizeOfArgID == llvm::FoldingSetNodeID())
11041           SizeOfArg->Profile(SizeOfArgID, Context, true);
11042         llvm::FoldingSetNodeID DestID;
11043         Dest->Profile(DestID, Context, true);
11044         if (DestID == SizeOfArgID) {
11045           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11046           //       over sizeof(src) as well.
11047           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11048           StringRef ReadableName = FnName->getName();
11049 
11050           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
11051             if (UnaryOp->getOpcode() == UO_AddrOf)
11052               ActionIdx = 1; // If its an address-of operator, just remove it.
11053           if (!PointeeTy->isIncompleteType() &&
11054               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11055             ActionIdx = 2; // If the pointee's size is sizeof(char),
11056                            // suggest an explicit length.
11057 
11058           // If the function is defined as a builtin macro, do not show macro
11059           // expansion.
11060           SourceLocation SL = SizeOfArg->getExprLoc();
11061           SourceRange DSR = Dest->getSourceRange();
11062           SourceRange SSR = SizeOfArg->getSourceRange();
11063           SourceManager &SM = getSourceManager();
11064 
11065           if (SM.isMacroArgExpansion(SL)) {
11066             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11067             SL = SM.getSpellingLoc(SL);
11068             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11069                              SM.getSpellingLoc(DSR.getEnd()));
11070             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11071                              SM.getSpellingLoc(SSR.getEnd()));
11072           }
11073 
11074           DiagRuntimeBehavior(SL, SizeOfArg,
11075                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11076                                 << ReadableName
11077                                 << PointeeTy
11078                                 << DestTy
11079                                 << DSR
11080                                 << SSR);
11081           DiagRuntimeBehavior(SL, SizeOfArg,
11082                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11083                                 << ActionIdx
11084                                 << SSR);
11085 
11086           break;
11087         }
11088       }
11089 
11090       // Also check for cases where the sizeof argument is the exact same
11091       // type as the memory argument, and where it points to a user-defined
11092       // record type.
11093       if (SizeOfArgTy != QualType()) {
11094         if (PointeeTy->isRecordType() &&
11095             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11096           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11097                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
11098                                 << FnName << SizeOfArgTy << ArgIdx
11099                                 << PointeeTy << Dest->getSourceRange()
11100                                 << LenExpr->getSourceRange());
11101           break;
11102         }
11103       }
11104     } else if (DestTy->isArrayType()) {
11105       PointeeTy = DestTy;
11106     }
11107 
11108     if (PointeeTy == QualType())
11109       continue;
11110 
11111     // Always complain about dynamic classes.
11112     bool IsContained;
11113     if (const CXXRecordDecl *ContainedRD =
11114             getContainedDynamicClass(PointeeTy, IsContained)) {
11115 
11116       unsigned OperationType = 0;
11117       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11118       // "overwritten" if we're warning about the destination for any call
11119       // but memcmp; otherwise a verb appropriate to the call.
11120       if (ArgIdx != 0 || IsCmp) {
11121         if (BId == Builtin::BImemcpy)
11122           OperationType = 1;
11123         else if(BId == Builtin::BImemmove)
11124           OperationType = 2;
11125         else if (IsCmp)
11126           OperationType = 3;
11127       }
11128 
11129       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11130                           PDiag(diag::warn_dyn_class_memaccess)
11131                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11132                               << IsContained << ContainedRD << OperationType
11133                               << Call->getCallee()->getSourceRange());
11134     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11135              BId != Builtin::BImemset)
11136       DiagRuntimeBehavior(
11137         Dest->getExprLoc(), Dest,
11138         PDiag(diag::warn_arc_object_memaccess)
11139           << ArgIdx << FnName << PointeeTy
11140           << Call->getCallee()->getSourceRange());
11141     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
11142       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11143           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11144         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11145                             PDiag(diag::warn_cstruct_memaccess)
11146                                 << ArgIdx << FnName << PointeeTy << 0);
11147         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11148       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11149                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11150         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11151                             PDiag(diag::warn_cstruct_memaccess)
11152                                 << ArgIdx << FnName << PointeeTy << 1);
11153         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11154       } else {
11155         continue;
11156       }
11157     } else
11158       continue;
11159 
11160     DiagRuntimeBehavior(
11161       Dest->getExprLoc(), Dest,
11162       PDiag(diag::note_bad_memaccess_silence)
11163         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11164     break;
11165   }
11166 }
11167 
11168 // A little helper routine: ignore addition and subtraction of integer literals.
11169 // This intentionally does not ignore all integer constant expressions because
11170 // we don't want to remove sizeof().
11171 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11172   Ex = Ex->IgnoreParenCasts();
11173 
11174   while (true) {
11175     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11176     if (!BO || !BO->isAdditiveOp())
11177       break;
11178 
11179     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11180     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11181 
11182     if (isa<IntegerLiteral>(RHS))
11183       Ex = LHS;
11184     else if (isa<IntegerLiteral>(LHS))
11185       Ex = RHS;
11186     else
11187       break;
11188   }
11189 
11190   return Ex;
11191 }
11192 
11193 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11194                                                       ASTContext &Context) {
11195   // Only handle constant-sized or VLAs, but not flexible members.
11196   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11197     // Only issue the FIXIT for arrays of size > 1.
11198     if (CAT->getSize().getSExtValue() <= 1)
11199       return false;
11200   } else if (!Ty->isVariableArrayType()) {
11201     return false;
11202   }
11203   return true;
11204 }
11205 
11206 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11207 // be the size of the source, instead of the destination.
11208 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11209                                     IdentifierInfo *FnName) {
11210 
11211   // Don't crash if the user has the wrong number of arguments
11212   unsigned NumArgs = Call->getNumArgs();
11213   if ((NumArgs != 3) && (NumArgs != 4))
11214     return;
11215 
11216   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11217   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11218   const Expr *CompareWithSrc = nullptr;
11219 
11220   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11221                                      Call->getBeginLoc(), Call->getRParenLoc()))
11222     return;
11223 
11224   // Look for 'strlcpy(dst, x, sizeof(x))'
11225   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11226     CompareWithSrc = Ex;
11227   else {
11228     // Look for 'strlcpy(dst, x, strlen(x))'
11229     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11230       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11231           SizeCall->getNumArgs() == 1)
11232         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11233     }
11234   }
11235 
11236   if (!CompareWithSrc)
11237     return;
11238 
11239   // Determine if the argument to sizeof/strlen is equal to the source
11240   // argument.  In principle there's all kinds of things you could do
11241   // here, for instance creating an == expression and evaluating it with
11242   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11243   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11244   if (!SrcArgDRE)
11245     return;
11246 
11247   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11248   if (!CompareWithSrcDRE ||
11249       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11250     return;
11251 
11252   const Expr *OriginalSizeArg = Call->getArg(2);
11253   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11254       << OriginalSizeArg->getSourceRange() << FnName;
11255 
11256   // Output a FIXIT hint if the destination is an array (rather than a
11257   // pointer to an array).  This could be enhanced to handle some
11258   // pointers if we know the actual size, like if DstArg is 'array+2'
11259   // we could say 'sizeof(array)-2'.
11260   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11261   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11262     return;
11263 
11264   SmallString<128> sizeString;
11265   llvm::raw_svector_ostream OS(sizeString);
11266   OS << "sizeof(";
11267   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11268   OS << ")";
11269 
11270   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11271       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11272                                       OS.str());
11273 }
11274 
11275 /// Check if two expressions refer to the same declaration.
11276 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11277   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11278     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11279       return D1->getDecl() == D2->getDecl();
11280   return false;
11281 }
11282 
11283 static const Expr *getStrlenExprArg(const Expr *E) {
11284   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11285     const FunctionDecl *FD = CE->getDirectCallee();
11286     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11287       return nullptr;
11288     return CE->getArg(0)->IgnoreParenCasts();
11289   }
11290   return nullptr;
11291 }
11292 
11293 // Warn on anti-patterns as the 'size' argument to strncat.
11294 // The correct size argument should look like following:
11295 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11296 void Sema::CheckStrncatArguments(const CallExpr *CE,
11297                                  IdentifierInfo *FnName) {
11298   // Don't crash if the user has the wrong number of arguments.
11299   if (CE->getNumArgs() < 3)
11300     return;
11301   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11302   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11303   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11304 
11305   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11306                                      CE->getRParenLoc()))
11307     return;
11308 
11309   // Identify common expressions, which are wrongly used as the size argument
11310   // to strncat and may lead to buffer overflows.
11311   unsigned PatternType = 0;
11312   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11313     // - sizeof(dst)
11314     if (referToTheSameDecl(SizeOfArg, DstArg))
11315       PatternType = 1;
11316     // - sizeof(src)
11317     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11318       PatternType = 2;
11319   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11320     if (BE->getOpcode() == BO_Sub) {
11321       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11322       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11323       // - sizeof(dst) - strlen(dst)
11324       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11325           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11326         PatternType = 1;
11327       // - sizeof(src) - (anything)
11328       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11329         PatternType = 2;
11330     }
11331   }
11332 
11333   if (PatternType == 0)
11334     return;
11335 
11336   // Generate the diagnostic.
11337   SourceLocation SL = LenArg->getBeginLoc();
11338   SourceRange SR = LenArg->getSourceRange();
11339   SourceManager &SM = getSourceManager();
11340 
11341   // If the function is defined as a builtin macro, do not show macro expansion.
11342   if (SM.isMacroArgExpansion(SL)) {
11343     SL = SM.getSpellingLoc(SL);
11344     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11345                      SM.getSpellingLoc(SR.getEnd()));
11346   }
11347 
11348   // Check if the destination is an array (rather than a pointer to an array).
11349   QualType DstTy = DstArg->getType();
11350   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11351                                                                     Context);
11352   if (!isKnownSizeArray) {
11353     if (PatternType == 1)
11354       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11355     else
11356       Diag(SL, diag::warn_strncat_src_size) << SR;
11357     return;
11358   }
11359 
11360   if (PatternType == 1)
11361     Diag(SL, diag::warn_strncat_large_size) << SR;
11362   else
11363     Diag(SL, diag::warn_strncat_src_size) << SR;
11364 
11365   SmallString<128> sizeString;
11366   llvm::raw_svector_ostream OS(sizeString);
11367   OS << "sizeof(";
11368   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11369   OS << ") - ";
11370   OS << "strlen(";
11371   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11372   OS << ") - 1";
11373 
11374   Diag(SL, diag::note_strncat_wrong_size)
11375     << FixItHint::CreateReplacement(SR, OS.str());
11376 }
11377 
11378 namespace {
11379 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11380                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11381   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11382     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11383         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11384     return;
11385   }
11386 }
11387 
11388 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11389                                  const UnaryOperator *UnaryExpr) {
11390   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11391     const Decl *D = Lvalue->getDecl();
11392     if (isa<DeclaratorDecl>(D))
11393       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11394         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11395   }
11396 
11397   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11398     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11399                                       Lvalue->getMemberDecl());
11400 }
11401 
11402 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11403                             const UnaryOperator *UnaryExpr) {
11404   const auto *Lambda = dyn_cast<LambdaExpr>(
11405       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11406   if (!Lambda)
11407     return;
11408 
11409   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11410       << CalleeName << 2 /*object: lambda expression*/;
11411 }
11412 
11413 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11414                                   const DeclRefExpr *Lvalue) {
11415   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11416   if (Var == nullptr)
11417     return;
11418 
11419   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11420       << CalleeName << 0 /*object: */ << Var;
11421 }
11422 
11423 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11424                             const CastExpr *Cast) {
11425   SmallString<128> SizeString;
11426   llvm::raw_svector_ostream OS(SizeString);
11427 
11428   clang::CastKind Kind = Cast->getCastKind();
11429   if (Kind == clang::CK_BitCast &&
11430       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11431     return;
11432   if (Kind == clang::CK_IntegralToPointer &&
11433       !isa<IntegerLiteral>(
11434           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11435     return;
11436 
11437   switch (Cast->getCastKind()) {
11438   case clang::CK_BitCast:
11439   case clang::CK_IntegralToPointer:
11440   case clang::CK_FunctionToPointerDecay:
11441     OS << '\'';
11442     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11443     OS << '\'';
11444     break;
11445   default:
11446     return;
11447   }
11448 
11449   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11450       << CalleeName << 0 /*object: */ << OS.str();
11451 }
11452 } // namespace
11453 
11454 /// Alerts the user that they are attempting to free a non-malloc'd object.
11455 void Sema::CheckFreeArguments(const CallExpr *E) {
11456   const std::string CalleeName =
11457       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11458 
11459   { // Prefer something that doesn't involve a cast to make things simpler.
11460     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11461     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11462       switch (UnaryExpr->getOpcode()) {
11463       case UnaryOperator::Opcode::UO_AddrOf:
11464         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11465       case UnaryOperator::Opcode::UO_Plus:
11466         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11467       default:
11468         break;
11469       }
11470 
11471     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11472       if (Lvalue->getType()->isArrayType())
11473         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11474 
11475     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11476       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11477           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11478       return;
11479     }
11480 
11481     if (isa<BlockExpr>(Arg)) {
11482       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11483           << CalleeName << 1 /*object: block*/;
11484       return;
11485     }
11486   }
11487   // Maybe the cast was important, check after the other cases.
11488   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11489     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11490 }
11491 
11492 void
11493 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11494                          SourceLocation ReturnLoc,
11495                          bool isObjCMethod,
11496                          const AttrVec *Attrs,
11497                          const FunctionDecl *FD) {
11498   // Check if the return value is null but should not be.
11499   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11500        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11501       CheckNonNullExpr(*this, RetValExp))
11502     Diag(ReturnLoc, diag::warn_null_ret)
11503       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11504 
11505   // C++11 [basic.stc.dynamic.allocation]p4:
11506   //   If an allocation function declared with a non-throwing
11507   //   exception-specification fails to allocate storage, it shall return
11508   //   a null pointer. Any other allocation function that fails to allocate
11509   //   storage shall indicate failure only by throwing an exception [...]
11510   if (FD) {
11511     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11512     if (Op == OO_New || Op == OO_Array_New) {
11513       const FunctionProtoType *Proto
11514         = FD->getType()->castAs<FunctionProtoType>();
11515       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11516           CheckNonNullExpr(*this, RetValExp))
11517         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11518           << FD << getLangOpts().CPlusPlus11;
11519     }
11520   }
11521 
11522   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11523   // here prevent the user from using a PPC MMA type as trailing return type.
11524   if (Context.getTargetInfo().getTriple().isPPC64())
11525     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11526 }
11527 
11528 /// Check for comparisons of floating-point values using == and !=. Issue a
11529 /// warning if the comparison is not likely to do what the programmer intended.
11530 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
11531                                 BinaryOperatorKind Opcode) {
11532   // Match and capture subexpressions such as "(float) X == 0.1".
11533   FloatingLiteral *FPLiteral;
11534   CastExpr *FPCast;
11535   auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
11536     FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11537     FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11538     return FPLiteral && FPCast;
11539   };
11540 
11541   if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11542     auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11543     auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11544     if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11545         TargetTy->isFloatingPoint()) {
11546       bool Lossy;
11547       llvm::APFloat TargetC = FPLiteral->getValue();
11548       TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11549                       llvm::APFloat::rmNearestTiesToEven, &Lossy);
11550       if (Lossy) {
11551         // If the literal cannot be represented in the source type, then a
11552         // check for == is always false and check for != is always true.
11553         Diag(Loc, diag::warn_float_compare_literal)
11554             << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11555             << LHS->getSourceRange() << RHS->getSourceRange();
11556         return;
11557       }
11558     }
11559   }
11560 
11561   // Match a more general floating-point equality comparison (-Wfloat-equal).
11562   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11563   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11564 
11565   // Special case: check for x == x (which is OK).
11566   // Do not emit warnings for such cases.
11567   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11568     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11569       if (DRL->getDecl() == DRR->getDecl())
11570         return;
11571 
11572   // Special case: check for comparisons against literals that can be exactly
11573   //  represented by APFloat.  In such cases, do not emit a warning.  This
11574   //  is a heuristic: often comparison against such literals are used to
11575   //  detect if a value in a variable has not changed.  This clearly can
11576   //  lead to false negatives.
11577   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11578     if (FLL->isExact())
11579       return;
11580   } else
11581     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11582       if (FLR->isExact())
11583         return;
11584 
11585   // Check for comparisons with builtin types.
11586   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11587     if (CL->getBuiltinCallee())
11588       return;
11589 
11590   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11591     if (CR->getBuiltinCallee())
11592       return;
11593 
11594   // Emit the diagnostic.
11595   Diag(Loc, diag::warn_floatingpoint_eq)
11596     << LHS->getSourceRange() << RHS->getSourceRange();
11597 }
11598 
11599 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11600 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11601 
11602 namespace {
11603 
11604 /// Structure recording the 'active' range of an integer-valued
11605 /// expression.
11606 struct IntRange {
11607   /// The number of bits active in the int. Note that this includes exactly one
11608   /// sign bit if !NonNegative.
11609   unsigned Width;
11610 
11611   /// True if the int is known not to have negative values. If so, all leading
11612   /// bits before Width are known zero, otherwise they are known to be the
11613   /// same as the MSB within Width.
11614   bool NonNegative;
11615 
11616   IntRange(unsigned Width, bool NonNegative)
11617       : Width(Width), NonNegative(NonNegative) {}
11618 
11619   /// Number of bits excluding the sign bit.
11620   unsigned valueBits() const {
11621     return NonNegative ? Width : Width - 1;
11622   }
11623 
11624   /// Returns the range of the bool type.
11625   static IntRange forBoolType() {
11626     return IntRange(1, true);
11627   }
11628 
11629   /// Returns the range of an opaque value of the given integral type.
11630   static IntRange forValueOfType(ASTContext &C, QualType T) {
11631     return forValueOfCanonicalType(C,
11632                           T->getCanonicalTypeInternal().getTypePtr());
11633   }
11634 
11635   /// Returns the range of an opaque value of a canonical integral type.
11636   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11637     assert(T->isCanonicalUnqualified());
11638 
11639     if (const VectorType *VT = dyn_cast<VectorType>(T))
11640       T = VT->getElementType().getTypePtr();
11641     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11642       T = CT->getElementType().getTypePtr();
11643     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11644       T = AT->getValueType().getTypePtr();
11645 
11646     if (!C.getLangOpts().CPlusPlus) {
11647       // For enum types in C code, use the underlying datatype.
11648       if (const EnumType *ET = dyn_cast<EnumType>(T))
11649         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11650     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11651       // For enum types in C++, use the known bit width of the enumerators.
11652       EnumDecl *Enum = ET->getDecl();
11653       // In C++11, enums can have a fixed underlying type. Use this type to
11654       // compute the range.
11655       if (Enum->isFixed()) {
11656         return IntRange(C.getIntWidth(QualType(T, 0)),
11657                         !ET->isSignedIntegerOrEnumerationType());
11658       }
11659 
11660       unsigned NumPositive = Enum->getNumPositiveBits();
11661       unsigned NumNegative = Enum->getNumNegativeBits();
11662 
11663       if (NumNegative == 0)
11664         return IntRange(NumPositive, true/*NonNegative*/);
11665       else
11666         return IntRange(std::max(NumPositive + 1, NumNegative),
11667                         false/*NonNegative*/);
11668     }
11669 
11670     if (const auto *EIT = dyn_cast<BitIntType>(T))
11671       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11672 
11673     const BuiltinType *BT = cast<BuiltinType>(T);
11674     assert(BT->isInteger());
11675 
11676     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11677   }
11678 
11679   /// Returns the "target" range of a canonical integral type, i.e.
11680   /// the range of values expressible in the type.
11681   ///
11682   /// This matches forValueOfCanonicalType except that enums have the
11683   /// full range of their type, not the range of their enumerators.
11684   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11685     assert(T->isCanonicalUnqualified());
11686 
11687     if (const VectorType *VT = dyn_cast<VectorType>(T))
11688       T = VT->getElementType().getTypePtr();
11689     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11690       T = CT->getElementType().getTypePtr();
11691     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11692       T = AT->getValueType().getTypePtr();
11693     if (const EnumType *ET = dyn_cast<EnumType>(T))
11694       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11695 
11696     if (const auto *EIT = dyn_cast<BitIntType>(T))
11697       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11698 
11699     const BuiltinType *BT = cast<BuiltinType>(T);
11700     assert(BT->isInteger());
11701 
11702     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11703   }
11704 
11705   /// Returns the supremum of two ranges: i.e. their conservative merge.
11706   static IntRange join(IntRange L, IntRange R) {
11707     bool Unsigned = L.NonNegative && R.NonNegative;
11708     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11709                     L.NonNegative && R.NonNegative);
11710   }
11711 
11712   /// Return the range of a bitwise-AND of the two ranges.
11713   static IntRange bit_and(IntRange L, IntRange R) {
11714     unsigned Bits = std::max(L.Width, R.Width);
11715     bool NonNegative = false;
11716     if (L.NonNegative) {
11717       Bits = std::min(Bits, L.Width);
11718       NonNegative = true;
11719     }
11720     if (R.NonNegative) {
11721       Bits = std::min(Bits, R.Width);
11722       NonNegative = true;
11723     }
11724     return IntRange(Bits, NonNegative);
11725   }
11726 
11727   /// Return the range of a sum of the two ranges.
11728   static IntRange sum(IntRange L, IntRange R) {
11729     bool Unsigned = L.NonNegative && R.NonNegative;
11730     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11731                     Unsigned);
11732   }
11733 
11734   /// Return the range of a difference of the two ranges.
11735   static IntRange difference(IntRange L, IntRange R) {
11736     // We need a 1-bit-wider range if:
11737     //   1) LHS can be negative: least value can be reduced.
11738     //   2) RHS can be negative: greatest value can be increased.
11739     bool CanWiden = !L.NonNegative || !R.NonNegative;
11740     bool Unsigned = L.NonNegative && R.Width == 0;
11741     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11742                         !Unsigned,
11743                     Unsigned);
11744   }
11745 
11746   /// Return the range of a product of the two ranges.
11747   static IntRange product(IntRange L, IntRange R) {
11748     // If both LHS and RHS can be negative, we can form
11749     //   -2^L * -2^R = 2^(L + R)
11750     // which requires L + R + 1 value bits to represent.
11751     bool CanWiden = !L.NonNegative && !R.NonNegative;
11752     bool Unsigned = L.NonNegative && R.NonNegative;
11753     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11754                     Unsigned);
11755   }
11756 
11757   /// Return the range of a remainder operation between the two ranges.
11758   static IntRange rem(IntRange L, IntRange R) {
11759     // The result of a remainder can't be larger than the result of
11760     // either side. The sign of the result is the sign of the LHS.
11761     bool Unsigned = L.NonNegative;
11762     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11763                     Unsigned);
11764   }
11765 };
11766 
11767 } // namespace
11768 
11769 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11770                               unsigned MaxWidth) {
11771   if (value.isSigned() && value.isNegative())
11772     return IntRange(value.getMinSignedBits(), false);
11773 
11774   if (value.getBitWidth() > MaxWidth)
11775     value = value.trunc(MaxWidth);
11776 
11777   // isNonNegative() just checks the sign bit without considering
11778   // signedness.
11779   return IntRange(value.getActiveBits(), true);
11780 }
11781 
11782 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11783                               unsigned MaxWidth) {
11784   if (result.isInt())
11785     return GetValueRange(C, result.getInt(), MaxWidth);
11786 
11787   if (result.isVector()) {
11788     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11789     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11790       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11791       R = IntRange::join(R, El);
11792     }
11793     return R;
11794   }
11795 
11796   if (result.isComplexInt()) {
11797     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11798     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11799     return IntRange::join(R, I);
11800   }
11801 
11802   // This can happen with lossless casts to intptr_t of "based" lvalues.
11803   // Assume it might use arbitrary bits.
11804   // FIXME: The only reason we need to pass the type in here is to get
11805   // the sign right on this one case.  It would be nice if APValue
11806   // preserved this.
11807   assert(result.isLValue() || result.isAddrLabelDiff());
11808   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11809 }
11810 
11811 static QualType GetExprType(const Expr *E) {
11812   QualType Ty = E->getType();
11813   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11814     Ty = AtomicRHS->getValueType();
11815   return Ty;
11816 }
11817 
11818 /// Pseudo-evaluate the given integer expression, estimating the
11819 /// range of values it might take.
11820 ///
11821 /// \param MaxWidth The width to which the value will be truncated.
11822 /// \param Approximate If \c true, return a likely range for the result: in
11823 ///        particular, assume that arithmetic on narrower types doesn't leave
11824 ///        those types. If \c false, return a range including all possible
11825 ///        result values.
11826 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11827                              bool InConstantContext, bool Approximate) {
11828   E = E->IgnoreParens();
11829 
11830   // Try a full evaluation first.
11831   Expr::EvalResult result;
11832   if (E->EvaluateAsRValue(result, C, InConstantContext))
11833     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11834 
11835   // I think we only want to look through implicit casts here; if the
11836   // user has an explicit widening cast, we should treat the value as
11837   // being of the new, wider type.
11838   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11839     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11840       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11841                           Approximate);
11842 
11843     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11844 
11845     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11846                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11847 
11848     // Assume that non-integer casts can span the full range of the type.
11849     if (!isIntegerCast)
11850       return OutputTypeRange;
11851 
11852     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11853                                      std::min(MaxWidth, OutputTypeRange.Width),
11854                                      InConstantContext, Approximate);
11855 
11856     // Bail out if the subexpr's range is as wide as the cast type.
11857     if (SubRange.Width >= OutputTypeRange.Width)
11858       return OutputTypeRange;
11859 
11860     // Otherwise, we take the smaller width, and we're non-negative if
11861     // either the output type or the subexpr is.
11862     return IntRange(SubRange.Width,
11863                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11864   }
11865 
11866   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11867     // If we can fold the condition, just take that operand.
11868     bool CondResult;
11869     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11870       return GetExprRange(C,
11871                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11872                           MaxWidth, InConstantContext, Approximate);
11873 
11874     // Otherwise, conservatively merge.
11875     // GetExprRange requires an integer expression, but a throw expression
11876     // results in a void type.
11877     Expr *E = CO->getTrueExpr();
11878     IntRange L = E->getType()->isVoidType()
11879                      ? IntRange{0, true}
11880                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11881     E = CO->getFalseExpr();
11882     IntRange R = E->getType()->isVoidType()
11883                      ? IntRange{0, true}
11884                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11885     return IntRange::join(L, R);
11886   }
11887 
11888   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11889     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11890 
11891     switch (BO->getOpcode()) {
11892     case BO_Cmp:
11893       llvm_unreachable("builtin <=> should have class type");
11894 
11895     // Boolean-valued operations are single-bit and positive.
11896     case BO_LAnd:
11897     case BO_LOr:
11898     case BO_LT:
11899     case BO_GT:
11900     case BO_LE:
11901     case BO_GE:
11902     case BO_EQ:
11903     case BO_NE:
11904       return IntRange::forBoolType();
11905 
11906     // The type of the assignments is the type of the LHS, so the RHS
11907     // is not necessarily the same type.
11908     case BO_MulAssign:
11909     case BO_DivAssign:
11910     case BO_RemAssign:
11911     case BO_AddAssign:
11912     case BO_SubAssign:
11913     case BO_XorAssign:
11914     case BO_OrAssign:
11915       // TODO: bitfields?
11916       return IntRange::forValueOfType(C, GetExprType(E));
11917 
11918     // Simple assignments just pass through the RHS, which will have
11919     // been coerced to the LHS type.
11920     case BO_Assign:
11921       // TODO: bitfields?
11922       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11923                           Approximate);
11924 
11925     // Operations with opaque sources are black-listed.
11926     case BO_PtrMemD:
11927     case BO_PtrMemI:
11928       return IntRange::forValueOfType(C, GetExprType(E));
11929 
11930     // Bitwise-and uses the *infinum* of the two source ranges.
11931     case BO_And:
11932     case BO_AndAssign:
11933       Combine = IntRange::bit_and;
11934       break;
11935 
11936     // Left shift gets black-listed based on a judgement call.
11937     case BO_Shl:
11938       // ...except that we want to treat '1 << (blah)' as logically
11939       // positive.  It's an important idiom.
11940       if (IntegerLiteral *I
11941             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11942         if (I->getValue() == 1) {
11943           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11944           return IntRange(R.Width, /*NonNegative*/ true);
11945         }
11946       }
11947       LLVM_FALLTHROUGH;
11948 
11949     case BO_ShlAssign:
11950       return IntRange::forValueOfType(C, GetExprType(E));
11951 
11952     // Right shift by a constant can narrow its left argument.
11953     case BO_Shr:
11954     case BO_ShrAssign: {
11955       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11956                                 Approximate);
11957 
11958       // If the shift amount is a positive constant, drop the width by
11959       // that much.
11960       if (Optional<llvm::APSInt> shift =
11961               BO->getRHS()->getIntegerConstantExpr(C)) {
11962         if (shift->isNonNegative()) {
11963           unsigned zext = shift->getZExtValue();
11964           if (zext >= L.Width)
11965             L.Width = (L.NonNegative ? 0 : 1);
11966           else
11967             L.Width -= zext;
11968         }
11969       }
11970 
11971       return L;
11972     }
11973 
11974     // Comma acts as its right operand.
11975     case BO_Comma:
11976       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11977                           Approximate);
11978 
11979     case BO_Add:
11980       if (!Approximate)
11981         Combine = IntRange::sum;
11982       break;
11983 
11984     case BO_Sub:
11985       if (BO->getLHS()->getType()->isPointerType())
11986         return IntRange::forValueOfType(C, GetExprType(E));
11987       if (!Approximate)
11988         Combine = IntRange::difference;
11989       break;
11990 
11991     case BO_Mul:
11992       if (!Approximate)
11993         Combine = IntRange::product;
11994       break;
11995 
11996     // The width of a division result is mostly determined by the size
11997     // of the LHS.
11998     case BO_Div: {
11999       // Don't 'pre-truncate' the operands.
12000       unsigned opWidth = C.getIntWidth(GetExprType(E));
12001       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
12002                                 Approximate);
12003 
12004       // If the divisor is constant, use that.
12005       if (Optional<llvm::APSInt> divisor =
12006               BO->getRHS()->getIntegerConstantExpr(C)) {
12007         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12008         if (log2 >= L.Width)
12009           L.Width = (L.NonNegative ? 0 : 1);
12010         else
12011           L.Width = std::min(L.Width - log2, MaxWidth);
12012         return L;
12013       }
12014 
12015       // Otherwise, just use the LHS's width.
12016       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12017       // could be -1.
12018       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
12019                                 Approximate);
12020       return IntRange(L.Width, L.NonNegative && R.NonNegative);
12021     }
12022 
12023     case BO_Rem:
12024       Combine = IntRange::rem;
12025       break;
12026 
12027     // The default behavior is okay for these.
12028     case BO_Xor:
12029     case BO_Or:
12030       break;
12031     }
12032 
12033     // Combine the two ranges, but limit the result to the type in which we
12034     // performed the computation.
12035     QualType T = GetExprType(E);
12036     unsigned opWidth = C.getIntWidth(T);
12037     IntRange L =
12038         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12039     IntRange R =
12040         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12041     IntRange C = Combine(L, R);
12042     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12043     C.Width = std::min(C.Width, MaxWidth);
12044     return C;
12045   }
12046 
12047   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12048     switch (UO->getOpcode()) {
12049     // Boolean-valued operations are white-listed.
12050     case UO_LNot:
12051       return IntRange::forBoolType();
12052 
12053     // Operations with opaque sources are black-listed.
12054     case UO_Deref:
12055     case UO_AddrOf: // should be impossible
12056       return IntRange::forValueOfType(C, GetExprType(E));
12057 
12058     default:
12059       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12060                           Approximate);
12061     }
12062   }
12063 
12064   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12065     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
12066                         Approximate);
12067 
12068   if (const auto *BitField = E->getSourceBitField())
12069     return IntRange(BitField->getBitWidthValue(C),
12070                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
12071 
12072   return IntRange::forValueOfType(C, GetExprType(E));
12073 }
12074 
12075 static IntRange GetExprRange(ASTContext &C, const Expr *E,
12076                              bool InConstantContext, bool Approximate) {
12077   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12078                       Approximate);
12079 }
12080 
12081 /// Checks whether the given value, which currently has the given
12082 /// source semantics, has the same value when coerced through the
12083 /// target semantics.
12084 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12085                                  const llvm::fltSemantics &Src,
12086                                  const llvm::fltSemantics &Tgt) {
12087   llvm::APFloat truncated = value;
12088 
12089   bool ignored;
12090   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12091   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12092 
12093   return truncated.bitwiseIsEqual(value);
12094 }
12095 
12096 /// Checks whether the given value, which currently has the given
12097 /// source semantics, has the same value when coerced through the
12098 /// target semantics.
12099 ///
12100 /// The value might be a vector of floats (or a complex number).
12101 static bool IsSameFloatAfterCast(const APValue &value,
12102                                  const llvm::fltSemantics &Src,
12103                                  const llvm::fltSemantics &Tgt) {
12104   if (value.isFloat())
12105     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12106 
12107   if (value.isVector()) {
12108     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12109       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12110         return false;
12111     return true;
12112   }
12113 
12114   assert(value.isComplexFloat());
12115   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12116           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12117 }
12118 
12119 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12120                                        bool IsListInit = false);
12121 
12122 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
12123   // Suppress cases where we are comparing against an enum constant.
12124   if (const DeclRefExpr *DR =
12125       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12126     if (isa<EnumConstantDecl>(DR->getDecl()))
12127       return true;
12128 
12129   // Suppress cases where the value is expanded from a macro, unless that macro
12130   // is how a language represents a boolean literal. This is the case in both C
12131   // and Objective-C.
12132   SourceLocation BeginLoc = E->getBeginLoc();
12133   if (BeginLoc.isMacroID()) {
12134     StringRef MacroName = Lexer::getImmediateMacroName(
12135         BeginLoc, S.getSourceManager(), S.getLangOpts());
12136     return MacroName != "YES" && MacroName != "NO" &&
12137            MacroName != "true" && MacroName != "false";
12138   }
12139 
12140   return false;
12141 }
12142 
12143 static bool isKnownToHaveUnsignedValue(Expr *E) {
12144   return E->getType()->isIntegerType() &&
12145          (!E->getType()->isSignedIntegerType() ||
12146           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12147 }
12148 
12149 namespace {
12150 /// The promoted range of values of a type. In general this has the
12151 /// following structure:
12152 ///
12153 ///     |-----------| . . . |-----------|
12154 ///     ^           ^       ^           ^
12155 ///    Min       HoleMin  HoleMax      Max
12156 ///
12157 /// ... where there is only a hole if a signed type is promoted to unsigned
12158 /// (in which case Min and Max are the smallest and largest representable
12159 /// values).
12160 struct PromotedRange {
12161   // Min, or HoleMax if there is a hole.
12162   llvm::APSInt PromotedMin;
12163   // Max, or HoleMin if there is a hole.
12164   llvm::APSInt PromotedMax;
12165 
12166   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12167     if (R.Width == 0)
12168       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12169     else if (R.Width >= BitWidth && !Unsigned) {
12170       // Promotion made the type *narrower*. This happens when promoting
12171       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12172       // Treat all values of 'signed int' as being in range for now.
12173       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12174       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12175     } else {
12176       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12177                         .extOrTrunc(BitWidth);
12178       PromotedMin.setIsUnsigned(Unsigned);
12179 
12180       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12181                         .extOrTrunc(BitWidth);
12182       PromotedMax.setIsUnsigned(Unsigned);
12183     }
12184   }
12185 
12186   // Determine whether this range is contiguous (has no hole).
12187   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12188 
12189   // Where a constant value is within the range.
12190   enum ComparisonResult {
12191     LT = 0x1,
12192     LE = 0x2,
12193     GT = 0x4,
12194     GE = 0x8,
12195     EQ = 0x10,
12196     NE = 0x20,
12197     InRangeFlag = 0x40,
12198 
12199     Less = LE | LT | NE,
12200     Min = LE | InRangeFlag,
12201     InRange = InRangeFlag,
12202     Max = GE | InRangeFlag,
12203     Greater = GE | GT | NE,
12204 
12205     OnlyValue = LE | GE | EQ | InRangeFlag,
12206     InHole = NE
12207   };
12208 
12209   ComparisonResult compare(const llvm::APSInt &Value) const {
12210     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12211            Value.isUnsigned() == PromotedMin.isUnsigned());
12212     if (!isContiguous()) {
12213       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12214       if (Value.isMinValue()) return Min;
12215       if (Value.isMaxValue()) return Max;
12216       if (Value >= PromotedMin) return InRange;
12217       if (Value <= PromotedMax) return InRange;
12218       return InHole;
12219     }
12220 
12221     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12222     case -1: return Less;
12223     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12224     case 1:
12225       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12226       case -1: return InRange;
12227       case 0: return Max;
12228       case 1: return Greater;
12229       }
12230     }
12231 
12232     llvm_unreachable("impossible compare result");
12233   }
12234 
12235   static llvm::Optional<StringRef>
12236   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12237     if (Op == BO_Cmp) {
12238       ComparisonResult LTFlag = LT, GTFlag = GT;
12239       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12240 
12241       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12242       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12243       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12244       return llvm::None;
12245     }
12246 
12247     ComparisonResult TrueFlag, FalseFlag;
12248     if (Op == BO_EQ) {
12249       TrueFlag = EQ;
12250       FalseFlag = NE;
12251     } else if (Op == BO_NE) {
12252       TrueFlag = NE;
12253       FalseFlag = EQ;
12254     } else {
12255       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12256         TrueFlag = LT;
12257         FalseFlag = GE;
12258       } else {
12259         TrueFlag = GT;
12260         FalseFlag = LE;
12261       }
12262       if (Op == BO_GE || Op == BO_LE)
12263         std::swap(TrueFlag, FalseFlag);
12264     }
12265     if (R & TrueFlag)
12266       return StringRef("true");
12267     if (R & FalseFlag)
12268       return StringRef("false");
12269     return llvm::None;
12270   }
12271 };
12272 }
12273 
12274 static bool HasEnumType(Expr *E) {
12275   // Strip off implicit integral promotions.
12276   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12277     if (ICE->getCastKind() != CK_IntegralCast &&
12278         ICE->getCastKind() != CK_NoOp)
12279       break;
12280     E = ICE->getSubExpr();
12281   }
12282 
12283   return E->getType()->isEnumeralType();
12284 }
12285 
12286 static int classifyConstantValue(Expr *Constant) {
12287   // The values of this enumeration are used in the diagnostics
12288   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12289   enum ConstantValueKind {
12290     Miscellaneous = 0,
12291     LiteralTrue,
12292     LiteralFalse
12293   };
12294   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12295     return BL->getValue() ? ConstantValueKind::LiteralTrue
12296                           : ConstantValueKind::LiteralFalse;
12297   return ConstantValueKind::Miscellaneous;
12298 }
12299 
12300 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12301                                         Expr *Constant, Expr *Other,
12302                                         const llvm::APSInt &Value,
12303                                         bool RhsConstant) {
12304   if (S.inTemplateInstantiation())
12305     return false;
12306 
12307   Expr *OriginalOther = Other;
12308 
12309   Constant = Constant->IgnoreParenImpCasts();
12310   Other = Other->IgnoreParenImpCasts();
12311 
12312   // Suppress warnings on tautological comparisons between values of the same
12313   // enumeration type. There are only two ways we could warn on this:
12314   //  - If the constant is outside the range of representable values of
12315   //    the enumeration. In such a case, we should warn about the cast
12316   //    to enumeration type, not about the comparison.
12317   //  - If the constant is the maximum / minimum in-range value. For an
12318   //    enumeratin type, such comparisons can be meaningful and useful.
12319   if (Constant->getType()->isEnumeralType() &&
12320       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12321     return false;
12322 
12323   IntRange OtherValueRange = GetExprRange(
12324       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12325 
12326   QualType OtherT = Other->getType();
12327   if (const auto *AT = OtherT->getAs<AtomicType>())
12328     OtherT = AT->getValueType();
12329   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12330 
12331   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12332   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12333   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12334                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12335                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12336 
12337   // Whether we're treating Other as being a bool because of the form of
12338   // expression despite it having another type (typically 'int' in C).
12339   bool OtherIsBooleanDespiteType =
12340       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12341   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12342     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12343 
12344   // Check if all values in the range of possible values of this expression
12345   // lead to the same comparison outcome.
12346   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12347                                         Value.isUnsigned());
12348   auto Cmp = OtherPromotedValueRange.compare(Value);
12349   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12350   if (!Result)
12351     return false;
12352 
12353   // Also consider the range determined by the type alone. This allows us to
12354   // classify the warning under the proper diagnostic group.
12355   bool TautologicalTypeCompare = false;
12356   {
12357     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12358                                          Value.isUnsigned());
12359     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12360     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12361                                                        RhsConstant)) {
12362       TautologicalTypeCompare = true;
12363       Cmp = TypeCmp;
12364       Result = TypeResult;
12365     }
12366   }
12367 
12368   // Don't warn if the non-constant operand actually always evaluates to the
12369   // same value.
12370   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12371     return false;
12372 
12373   // Suppress the diagnostic for an in-range comparison if the constant comes
12374   // from a macro or enumerator. We don't want to diagnose
12375   //
12376   //   some_long_value <= INT_MAX
12377   //
12378   // when sizeof(int) == sizeof(long).
12379   bool InRange = Cmp & PromotedRange::InRangeFlag;
12380   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12381     return false;
12382 
12383   // A comparison of an unsigned bit-field against 0 is really a type problem,
12384   // even though at the type level the bit-field might promote to 'signed int'.
12385   if (Other->refersToBitField() && InRange && Value == 0 &&
12386       Other->getType()->isUnsignedIntegerOrEnumerationType())
12387     TautologicalTypeCompare = true;
12388 
12389   // If this is a comparison to an enum constant, include that
12390   // constant in the diagnostic.
12391   const EnumConstantDecl *ED = nullptr;
12392   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12393     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12394 
12395   // Should be enough for uint128 (39 decimal digits)
12396   SmallString<64> PrettySourceValue;
12397   llvm::raw_svector_ostream OS(PrettySourceValue);
12398   if (ED) {
12399     OS << '\'' << *ED << "' (" << Value << ")";
12400   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12401                Constant->IgnoreParenImpCasts())) {
12402     OS << (BL->getValue() ? "YES" : "NO");
12403   } else {
12404     OS << Value;
12405   }
12406 
12407   if (!TautologicalTypeCompare) {
12408     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12409         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12410         << E->getOpcodeStr() << OS.str() << *Result
12411         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12412     return true;
12413   }
12414 
12415   if (IsObjCSignedCharBool) {
12416     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12417                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12418                               << OS.str() << *Result);
12419     return true;
12420   }
12421 
12422   // FIXME: We use a somewhat different formatting for the in-range cases and
12423   // cases involving boolean values for historical reasons. We should pick a
12424   // consistent way of presenting these diagnostics.
12425   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12426 
12427     S.DiagRuntimeBehavior(
12428         E->getOperatorLoc(), E,
12429         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12430                          : diag::warn_tautological_bool_compare)
12431             << OS.str() << classifyConstantValue(Constant) << OtherT
12432             << OtherIsBooleanDespiteType << *Result
12433             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12434   } else {
12435     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12436     unsigned Diag =
12437         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12438             ? (HasEnumType(OriginalOther)
12439                    ? diag::warn_unsigned_enum_always_true_comparison
12440                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12441                               : diag::warn_unsigned_always_true_comparison)
12442             : diag::warn_tautological_constant_compare;
12443 
12444     S.Diag(E->getOperatorLoc(), Diag)
12445         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12446         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12447   }
12448 
12449   return true;
12450 }
12451 
12452 /// Analyze the operands of the given comparison.  Implements the
12453 /// fallback case from AnalyzeComparison.
12454 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12455   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12456   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12457 }
12458 
12459 /// Implements -Wsign-compare.
12460 ///
12461 /// \param E the binary operator to check for warnings
12462 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12463   // The type the comparison is being performed in.
12464   QualType T = E->getLHS()->getType();
12465 
12466   // Only analyze comparison operators where both sides have been converted to
12467   // the same type.
12468   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12469     return AnalyzeImpConvsInComparison(S, E);
12470 
12471   // Don't analyze value-dependent comparisons directly.
12472   if (E->isValueDependent())
12473     return AnalyzeImpConvsInComparison(S, E);
12474 
12475   Expr *LHS = E->getLHS();
12476   Expr *RHS = E->getRHS();
12477 
12478   if (T->isIntegralType(S.Context)) {
12479     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12480     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12481 
12482     // We don't care about expressions whose result is a constant.
12483     if (RHSValue && LHSValue)
12484       return AnalyzeImpConvsInComparison(S, E);
12485 
12486     // We only care about expressions where just one side is literal
12487     if ((bool)RHSValue ^ (bool)LHSValue) {
12488       // Is the constant on the RHS or LHS?
12489       const bool RhsConstant = (bool)RHSValue;
12490       Expr *Const = RhsConstant ? RHS : LHS;
12491       Expr *Other = RhsConstant ? LHS : RHS;
12492       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12493 
12494       // Check whether an integer constant comparison results in a value
12495       // of 'true' or 'false'.
12496       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12497         return AnalyzeImpConvsInComparison(S, E);
12498     }
12499   }
12500 
12501   if (!T->hasUnsignedIntegerRepresentation()) {
12502     // We don't do anything special if this isn't an unsigned integral
12503     // comparison:  we're only interested in integral comparisons, and
12504     // signed comparisons only happen in cases we don't care to warn about.
12505     return AnalyzeImpConvsInComparison(S, E);
12506   }
12507 
12508   LHS = LHS->IgnoreParenImpCasts();
12509   RHS = RHS->IgnoreParenImpCasts();
12510 
12511   if (!S.getLangOpts().CPlusPlus) {
12512     // Avoid warning about comparison of integers with different signs when
12513     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12514     // the type of `E`.
12515     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12516       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12517     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12518       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12519   }
12520 
12521   // Check to see if one of the (unmodified) operands is of different
12522   // signedness.
12523   Expr *signedOperand, *unsignedOperand;
12524   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12525     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12526            "unsigned comparison between two signed integer expressions?");
12527     signedOperand = LHS;
12528     unsignedOperand = RHS;
12529   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12530     signedOperand = RHS;
12531     unsignedOperand = LHS;
12532   } else {
12533     return AnalyzeImpConvsInComparison(S, E);
12534   }
12535 
12536   // Otherwise, calculate the effective range of the signed operand.
12537   IntRange signedRange = GetExprRange(
12538       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12539 
12540   // Go ahead and analyze implicit conversions in the operands.  Note
12541   // that we skip the implicit conversions on both sides.
12542   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12543   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12544 
12545   // If the signed range is non-negative, -Wsign-compare won't fire.
12546   if (signedRange.NonNegative)
12547     return;
12548 
12549   // For (in)equality comparisons, if the unsigned operand is a
12550   // constant which cannot collide with a overflowed signed operand,
12551   // then reinterpreting the signed operand as unsigned will not
12552   // change the result of the comparison.
12553   if (E->isEqualityOp()) {
12554     unsigned comparisonWidth = S.Context.getIntWidth(T);
12555     IntRange unsignedRange =
12556         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12557                      /*Approximate*/ true);
12558 
12559     // We should never be unable to prove that the unsigned operand is
12560     // non-negative.
12561     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12562 
12563     if (unsignedRange.Width < comparisonWidth)
12564       return;
12565   }
12566 
12567   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12568                         S.PDiag(diag::warn_mixed_sign_comparison)
12569                             << LHS->getType() << RHS->getType()
12570                             << LHS->getSourceRange() << RHS->getSourceRange());
12571 }
12572 
12573 /// Analyzes an attempt to assign the given value to a bitfield.
12574 ///
12575 /// Returns true if there was something fishy about the attempt.
12576 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12577                                       SourceLocation InitLoc) {
12578   assert(Bitfield->isBitField());
12579   if (Bitfield->isInvalidDecl())
12580     return false;
12581 
12582   // White-list bool bitfields.
12583   QualType BitfieldType = Bitfield->getType();
12584   if (BitfieldType->isBooleanType())
12585      return false;
12586 
12587   if (BitfieldType->isEnumeralType()) {
12588     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12589     // If the underlying enum type was not explicitly specified as an unsigned
12590     // type and the enum contain only positive values, MSVC++ will cause an
12591     // inconsistency by storing this as a signed type.
12592     if (S.getLangOpts().CPlusPlus11 &&
12593         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12594         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12595         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12596       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12597           << BitfieldEnumDecl;
12598     }
12599   }
12600 
12601   if (Bitfield->getType()->isBooleanType())
12602     return false;
12603 
12604   // Ignore value- or type-dependent expressions.
12605   if (Bitfield->getBitWidth()->isValueDependent() ||
12606       Bitfield->getBitWidth()->isTypeDependent() ||
12607       Init->isValueDependent() ||
12608       Init->isTypeDependent())
12609     return false;
12610 
12611   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12612   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12613 
12614   Expr::EvalResult Result;
12615   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12616                                    Expr::SE_AllowSideEffects)) {
12617     // The RHS is not constant.  If the RHS has an enum type, make sure the
12618     // bitfield is wide enough to hold all the values of the enum without
12619     // truncation.
12620     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12621       EnumDecl *ED = EnumTy->getDecl();
12622       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12623 
12624       // Enum types are implicitly signed on Windows, so check if there are any
12625       // negative enumerators to see if the enum was intended to be signed or
12626       // not.
12627       bool SignedEnum = ED->getNumNegativeBits() > 0;
12628 
12629       // Check for surprising sign changes when assigning enum values to a
12630       // bitfield of different signedness.  If the bitfield is signed and we
12631       // have exactly the right number of bits to store this unsigned enum,
12632       // suggest changing the enum to an unsigned type. This typically happens
12633       // on Windows where unfixed enums always use an underlying type of 'int'.
12634       unsigned DiagID = 0;
12635       if (SignedEnum && !SignedBitfield) {
12636         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12637       } else if (SignedBitfield && !SignedEnum &&
12638                  ED->getNumPositiveBits() == FieldWidth) {
12639         DiagID = diag::warn_signed_bitfield_enum_conversion;
12640       }
12641 
12642       if (DiagID) {
12643         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12644         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12645         SourceRange TypeRange =
12646             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12647         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12648             << SignedEnum << TypeRange;
12649       }
12650 
12651       // Compute the required bitwidth. If the enum has negative values, we need
12652       // one more bit than the normal number of positive bits to represent the
12653       // sign bit.
12654       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12655                                                   ED->getNumNegativeBits())
12656                                        : ED->getNumPositiveBits();
12657 
12658       // Check the bitwidth.
12659       if (BitsNeeded > FieldWidth) {
12660         Expr *WidthExpr = Bitfield->getBitWidth();
12661         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12662             << Bitfield << ED;
12663         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12664             << BitsNeeded << ED << WidthExpr->getSourceRange();
12665       }
12666     }
12667 
12668     return false;
12669   }
12670 
12671   llvm::APSInt Value = Result.Val.getInt();
12672 
12673   unsigned OriginalWidth = Value.getBitWidth();
12674 
12675   if (!Value.isSigned() || Value.isNegative())
12676     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12677       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12678         OriginalWidth = Value.getMinSignedBits();
12679 
12680   if (OriginalWidth <= FieldWidth)
12681     return false;
12682 
12683   // Compute the value which the bitfield will contain.
12684   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12685   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12686 
12687   // Check whether the stored value is equal to the original value.
12688   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12689   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12690     return false;
12691 
12692   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12693   // therefore don't strictly fit into a signed bitfield of width 1.
12694   if (FieldWidth == 1 && Value == 1)
12695     return false;
12696 
12697   std::string PrettyValue = toString(Value, 10);
12698   std::string PrettyTrunc = toString(TruncatedValue, 10);
12699 
12700   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12701     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12702     << Init->getSourceRange();
12703 
12704   return true;
12705 }
12706 
12707 /// Analyze the given simple or compound assignment for warning-worthy
12708 /// operations.
12709 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12710   // Just recurse on the LHS.
12711   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12712 
12713   // We want to recurse on the RHS as normal unless we're assigning to
12714   // a bitfield.
12715   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12716     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12717                                   E->getOperatorLoc())) {
12718       // Recurse, ignoring any implicit conversions on the RHS.
12719       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12720                                         E->getOperatorLoc());
12721     }
12722   }
12723 
12724   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12725 
12726   // Diagnose implicitly sequentially-consistent atomic assignment.
12727   if (E->getLHS()->getType()->isAtomicType())
12728     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12729 }
12730 
12731 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12732 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12733                             SourceLocation CContext, unsigned diag,
12734                             bool pruneControlFlow = false) {
12735   if (pruneControlFlow) {
12736     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12737                           S.PDiag(diag)
12738                               << SourceType << T << E->getSourceRange()
12739                               << SourceRange(CContext));
12740     return;
12741   }
12742   S.Diag(E->getExprLoc(), diag)
12743     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12744 }
12745 
12746 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12747 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12748                             SourceLocation CContext,
12749                             unsigned diag, bool pruneControlFlow = false) {
12750   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12751 }
12752 
12753 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12754   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12755       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12756 }
12757 
12758 static void adornObjCBoolConversionDiagWithTernaryFixit(
12759     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12760   Expr *Ignored = SourceExpr->IgnoreImplicit();
12761   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12762     Ignored = OVE->getSourceExpr();
12763   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12764                      isa<BinaryOperator>(Ignored) ||
12765                      isa<CXXOperatorCallExpr>(Ignored);
12766   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12767   if (NeedsParens)
12768     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12769             << FixItHint::CreateInsertion(EndLoc, ")");
12770   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12771 }
12772 
12773 /// Diagnose an implicit cast from a floating point value to an integer value.
12774 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12775                                     SourceLocation CContext) {
12776   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12777   const bool PruneWarnings = S.inTemplateInstantiation();
12778 
12779   Expr *InnerE = E->IgnoreParenImpCasts();
12780   // We also want to warn on, e.g., "int i = -1.234"
12781   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12782     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12783       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12784 
12785   const bool IsLiteral =
12786       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12787 
12788   llvm::APFloat Value(0.0);
12789   bool IsConstant =
12790     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12791   if (!IsConstant) {
12792     if (isObjCSignedCharBool(S, T)) {
12793       return adornObjCBoolConversionDiagWithTernaryFixit(
12794           S, E,
12795           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12796               << E->getType());
12797     }
12798 
12799     return DiagnoseImpCast(S, E, T, CContext,
12800                            diag::warn_impcast_float_integer, PruneWarnings);
12801   }
12802 
12803   bool isExact = false;
12804 
12805   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12806                             T->hasUnsignedIntegerRepresentation());
12807   llvm::APFloat::opStatus Result = Value.convertToInteger(
12808       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12809 
12810   // FIXME: Force the precision of the source value down so we don't print
12811   // digits which are usually useless (we don't really care here if we
12812   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12813   // would automatically print the shortest representation, but it's a bit
12814   // tricky to implement.
12815   SmallString<16> PrettySourceValue;
12816   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12817   precision = (precision * 59 + 195) / 196;
12818   Value.toString(PrettySourceValue, precision);
12819 
12820   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12821     return adornObjCBoolConversionDiagWithTernaryFixit(
12822         S, E,
12823         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12824             << PrettySourceValue);
12825   }
12826 
12827   if (Result == llvm::APFloat::opOK && isExact) {
12828     if (IsLiteral) return;
12829     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12830                            PruneWarnings);
12831   }
12832 
12833   // Conversion of a floating-point value to a non-bool integer where the
12834   // integral part cannot be represented by the integer type is undefined.
12835   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12836     return DiagnoseImpCast(
12837         S, E, T, CContext,
12838         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12839                   : diag::warn_impcast_float_to_integer_out_of_range,
12840         PruneWarnings);
12841 
12842   unsigned DiagID = 0;
12843   if (IsLiteral) {
12844     // Warn on floating point literal to integer.
12845     DiagID = diag::warn_impcast_literal_float_to_integer;
12846   } else if (IntegerValue == 0) {
12847     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12848       return DiagnoseImpCast(S, E, T, CContext,
12849                              diag::warn_impcast_float_integer, PruneWarnings);
12850     }
12851     // Warn on non-zero to zero conversion.
12852     DiagID = diag::warn_impcast_float_to_integer_zero;
12853   } else {
12854     if (IntegerValue.isUnsigned()) {
12855       if (!IntegerValue.isMaxValue()) {
12856         return DiagnoseImpCast(S, E, T, CContext,
12857                                diag::warn_impcast_float_integer, PruneWarnings);
12858       }
12859     } else {  // IntegerValue.isSigned()
12860       if (!IntegerValue.isMaxSignedValue() &&
12861           !IntegerValue.isMinSignedValue()) {
12862         return DiagnoseImpCast(S, E, T, CContext,
12863                                diag::warn_impcast_float_integer, PruneWarnings);
12864       }
12865     }
12866     // Warn on evaluatable floating point expression to integer conversion.
12867     DiagID = diag::warn_impcast_float_to_integer;
12868   }
12869 
12870   SmallString<16> PrettyTargetValue;
12871   if (IsBool)
12872     PrettyTargetValue = Value.isZero() ? "false" : "true";
12873   else
12874     IntegerValue.toString(PrettyTargetValue);
12875 
12876   if (PruneWarnings) {
12877     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12878                           S.PDiag(DiagID)
12879                               << E->getType() << T.getUnqualifiedType()
12880                               << PrettySourceValue << PrettyTargetValue
12881                               << E->getSourceRange() << SourceRange(CContext));
12882   } else {
12883     S.Diag(E->getExprLoc(), DiagID)
12884         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12885         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12886   }
12887 }
12888 
12889 /// Analyze the given compound assignment for the possible losing of
12890 /// floating-point precision.
12891 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12892   assert(isa<CompoundAssignOperator>(E) &&
12893          "Must be compound assignment operation");
12894   // Recurse on the LHS and RHS in here
12895   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12896   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12897 
12898   if (E->getLHS()->getType()->isAtomicType())
12899     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12900 
12901   // Now check the outermost expression
12902   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12903   const auto *RBT = cast<CompoundAssignOperator>(E)
12904                         ->getComputationResultType()
12905                         ->getAs<BuiltinType>();
12906 
12907   // The below checks assume source is floating point.
12908   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12909 
12910   // If source is floating point but target is an integer.
12911   if (ResultBT->isInteger())
12912     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12913                            E->getExprLoc(), diag::warn_impcast_float_integer);
12914 
12915   if (!ResultBT->isFloatingPoint())
12916     return;
12917 
12918   // If both source and target are floating points, warn about losing precision.
12919   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12920       QualType(ResultBT, 0), QualType(RBT, 0));
12921   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12922     // warn about dropping FP rank.
12923     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12924                     diag::warn_impcast_float_result_precision);
12925 }
12926 
12927 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12928                                       IntRange Range) {
12929   if (!Range.Width) return "0";
12930 
12931   llvm::APSInt ValueInRange = Value;
12932   ValueInRange.setIsSigned(!Range.NonNegative);
12933   ValueInRange = ValueInRange.trunc(Range.Width);
12934   return toString(ValueInRange, 10);
12935 }
12936 
12937 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12938   if (!isa<ImplicitCastExpr>(Ex))
12939     return false;
12940 
12941   Expr *InnerE = Ex->IgnoreParenImpCasts();
12942   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12943   const Type *Source =
12944     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12945   if (Target->isDependentType())
12946     return false;
12947 
12948   const BuiltinType *FloatCandidateBT =
12949     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12950   const Type *BoolCandidateType = ToBool ? Target : Source;
12951 
12952   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12953           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12954 }
12955 
12956 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12957                                              SourceLocation CC) {
12958   unsigned NumArgs = TheCall->getNumArgs();
12959   for (unsigned i = 0; i < NumArgs; ++i) {
12960     Expr *CurrA = TheCall->getArg(i);
12961     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12962       continue;
12963 
12964     bool IsSwapped = ((i > 0) &&
12965         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12966     IsSwapped |= ((i < (NumArgs - 1)) &&
12967         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12968     if (IsSwapped) {
12969       // Warn on this floating-point to bool conversion.
12970       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12971                       CurrA->getType(), CC,
12972                       diag::warn_impcast_floating_point_to_bool);
12973     }
12974   }
12975 }
12976 
12977 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12978                                    SourceLocation CC) {
12979   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12980                         E->getExprLoc()))
12981     return;
12982 
12983   // Don't warn on functions which have return type nullptr_t.
12984   if (isa<CallExpr>(E))
12985     return;
12986 
12987   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12988   const Expr::NullPointerConstantKind NullKind =
12989       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12990   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12991     return;
12992 
12993   // Return if target type is a safe conversion.
12994   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12995       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12996     return;
12997 
12998   SourceLocation Loc = E->getSourceRange().getBegin();
12999 
13000   // Venture through the macro stacks to get to the source of macro arguments.
13001   // The new location is a better location than the complete location that was
13002   // passed in.
13003   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13004   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
13005 
13006   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
13007   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
13008     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13009         Loc, S.SourceMgr, S.getLangOpts());
13010     if (MacroName == "NULL")
13011       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13012   }
13013 
13014   // Only warn if the null and context location are in the same macro expansion.
13015   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13016     return;
13017 
13018   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13019       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
13020       << FixItHint::CreateReplacement(Loc,
13021                                       S.getFixItZeroLiteralForType(T, Loc));
13022 }
13023 
13024 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
13025                                   ObjCArrayLiteral *ArrayLiteral);
13026 
13027 static void
13028 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13029                            ObjCDictionaryLiteral *DictionaryLiteral);
13030 
13031 /// Check a single element within a collection literal against the
13032 /// target element type.
13033 static void checkObjCCollectionLiteralElement(Sema &S,
13034                                               QualType TargetElementType,
13035                                               Expr *Element,
13036                                               unsigned ElementKind) {
13037   // Skip a bitcast to 'id' or qualified 'id'.
13038   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
13039     if (ICE->getCastKind() == CK_BitCast &&
13040         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
13041       Element = ICE->getSubExpr();
13042   }
13043 
13044   QualType ElementType = Element->getType();
13045   ExprResult ElementResult(Element);
13046   if (ElementType->getAs<ObjCObjectPointerType>() &&
13047       S.CheckSingleAssignmentConstraints(TargetElementType,
13048                                          ElementResult,
13049                                          false, false)
13050         != Sema::Compatible) {
13051     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
13052         << ElementType << ElementKind << TargetElementType
13053         << Element->getSourceRange();
13054   }
13055 
13056   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
13057     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
13058   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
13059     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
13060 }
13061 
13062 /// Check an Objective-C array literal being converted to the given
13063 /// target type.
13064 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
13065                                   ObjCArrayLiteral *ArrayLiteral) {
13066   if (!S.NSArrayDecl)
13067     return;
13068 
13069   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13070   if (!TargetObjCPtr)
13071     return;
13072 
13073   if (TargetObjCPtr->isUnspecialized() ||
13074       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13075         != S.NSArrayDecl->getCanonicalDecl())
13076     return;
13077 
13078   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13079   if (TypeArgs.size() != 1)
13080     return;
13081 
13082   QualType TargetElementType = TypeArgs[0];
13083   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
13084     checkObjCCollectionLiteralElement(S, TargetElementType,
13085                                       ArrayLiteral->getElement(I),
13086                                       0);
13087   }
13088 }
13089 
13090 /// Check an Objective-C dictionary literal being converted to the given
13091 /// target type.
13092 static void
13093 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13094                            ObjCDictionaryLiteral *DictionaryLiteral) {
13095   if (!S.NSDictionaryDecl)
13096     return;
13097 
13098   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13099   if (!TargetObjCPtr)
13100     return;
13101 
13102   if (TargetObjCPtr->isUnspecialized() ||
13103       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13104         != S.NSDictionaryDecl->getCanonicalDecl())
13105     return;
13106 
13107   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13108   if (TypeArgs.size() != 2)
13109     return;
13110 
13111   QualType TargetKeyType = TypeArgs[0];
13112   QualType TargetObjectType = TypeArgs[1];
13113   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
13114     auto Element = DictionaryLiteral->getKeyValueElement(I);
13115     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
13116     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
13117   }
13118 }
13119 
13120 // Helper function to filter out cases for constant width constant conversion.
13121 // Don't warn on char array initialization or for non-decimal values.
13122 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13123                                           SourceLocation CC) {
13124   // If initializing from a constant, and the constant starts with '0',
13125   // then it is a binary, octal, or hexadecimal.  Allow these constants
13126   // to fill all the bits, even if there is a sign change.
13127   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13128     const char FirstLiteralCharacter =
13129         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13130     if (FirstLiteralCharacter == '0')
13131       return false;
13132   }
13133 
13134   // If the CC location points to a '{', and the type is char, then assume
13135   // assume it is an array initialization.
13136   if (CC.isValid() && T->isCharType()) {
13137     const char FirstContextCharacter =
13138         S.getSourceManager().getCharacterData(CC)[0];
13139     if (FirstContextCharacter == '{')
13140       return false;
13141   }
13142 
13143   return true;
13144 }
13145 
13146 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13147   const auto *IL = dyn_cast<IntegerLiteral>(E);
13148   if (!IL) {
13149     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13150       if (UO->getOpcode() == UO_Minus)
13151         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13152     }
13153   }
13154 
13155   return IL;
13156 }
13157 
13158 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13159   E = E->IgnoreParenImpCasts();
13160   SourceLocation ExprLoc = E->getExprLoc();
13161 
13162   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13163     BinaryOperator::Opcode Opc = BO->getOpcode();
13164     Expr::EvalResult Result;
13165     // Do not diagnose unsigned shifts.
13166     if (Opc == BO_Shl) {
13167       const auto *LHS = getIntegerLiteral(BO->getLHS());
13168       const auto *RHS = getIntegerLiteral(BO->getRHS());
13169       if (LHS && LHS->getValue() == 0)
13170         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13171       else if (!E->isValueDependent() && LHS && RHS &&
13172                RHS->getValue().isNonNegative() &&
13173                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13174         S.Diag(ExprLoc, diag::warn_left_shift_always)
13175             << (Result.Val.getInt() != 0);
13176       else if (E->getType()->isSignedIntegerType())
13177         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13178     }
13179   }
13180 
13181   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13182     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13183     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13184     if (!LHS || !RHS)
13185       return;
13186     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13187         (RHS->getValue() == 0 || RHS->getValue() == 1))
13188       // Do not diagnose common idioms.
13189       return;
13190     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13191       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13192   }
13193 }
13194 
13195 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13196                                     SourceLocation CC,
13197                                     bool *ICContext = nullptr,
13198                                     bool IsListInit = false) {
13199   if (E->isTypeDependent() || E->isValueDependent()) return;
13200 
13201   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13202   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13203   if (Source == Target) return;
13204   if (Target->isDependentType()) return;
13205 
13206   // If the conversion context location is invalid don't complain. We also
13207   // don't want to emit a warning if the issue occurs from the expansion of
13208   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13209   // delay this check as long as possible. Once we detect we are in that
13210   // scenario, we just return.
13211   if (CC.isInvalid())
13212     return;
13213 
13214   if (Source->isAtomicType())
13215     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13216 
13217   // Diagnose implicit casts to bool.
13218   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13219     if (isa<StringLiteral>(E))
13220       // Warn on string literal to bool.  Checks for string literals in logical
13221       // and expressions, for instance, assert(0 && "error here"), are
13222       // prevented by a check in AnalyzeImplicitConversions().
13223       return DiagnoseImpCast(S, E, T, CC,
13224                              diag::warn_impcast_string_literal_to_bool);
13225     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13226         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13227       // This covers the literal expressions that evaluate to Objective-C
13228       // objects.
13229       return DiagnoseImpCast(S, E, T, CC,
13230                              diag::warn_impcast_objective_c_literal_to_bool);
13231     }
13232     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13233       // Warn on pointer to bool conversion that is always true.
13234       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13235                                      SourceRange(CC));
13236     }
13237   }
13238 
13239   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13240   // is a typedef for signed char (macOS), then that constant value has to be 1
13241   // or 0.
13242   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13243     Expr::EvalResult Result;
13244     if (E->EvaluateAsInt(Result, S.getASTContext(),
13245                          Expr::SE_AllowSideEffects)) {
13246       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13247         adornObjCBoolConversionDiagWithTernaryFixit(
13248             S, E,
13249             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13250                 << toString(Result.Val.getInt(), 10));
13251       }
13252       return;
13253     }
13254   }
13255 
13256   // Check implicit casts from Objective-C collection literals to specialized
13257   // collection types, e.g., NSArray<NSString *> *.
13258   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13259     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13260   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13261     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13262 
13263   // Strip vector types.
13264   if (isa<VectorType>(Source)) {
13265     if (Target->isVLSTBuiltinType() &&
13266         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13267                                          QualType(Source, 0)) ||
13268          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13269                                             QualType(Source, 0))))
13270       return;
13271 
13272     if (!isa<VectorType>(Target)) {
13273       if (S.SourceMgr.isInSystemMacro(CC))
13274         return;
13275       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13276     }
13277 
13278     // If the vector cast is cast between two vectors of the same size, it is
13279     // a bitcast, not a conversion.
13280     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13281       return;
13282 
13283     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13284     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13285   }
13286   if (auto VecTy = dyn_cast<VectorType>(Target))
13287     Target = VecTy->getElementType().getTypePtr();
13288 
13289   // Strip complex types.
13290   if (isa<ComplexType>(Source)) {
13291     if (!isa<ComplexType>(Target)) {
13292       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13293         return;
13294 
13295       return DiagnoseImpCast(S, E, T, CC,
13296                              S.getLangOpts().CPlusPlus
13297                                  ? diag::err_impcast_complex_scalar
13298                                  : diag::warn_impcast_complex_scalar);
13299     }
13300 
13301     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13302     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13303   }
13304 
13305   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13306   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13307 
13308   // If the source is floating point...
13309   if (SourceBT && SourceBT->isFloatingPoint()) {
13310     // ...and the target is floating point...
13311     if (TargetBT && TargetBT->isFloatingPoint()) {
13312       // ...then warn if we're dropping FP rank.
13313 
13314       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13315           QualType(SourceBT, 0), QualType(TargetBT, 0));
13316       if (Order > 0) {
13317         // Don't warn about float constants that are precisely
13318         // representable in the target type.
13319         Expr::EvalResult result;
13320         if (E->EvaluateAsRValue(result, S.Context)) {
13321           // Value might be a float, a float vector, or a float complex.
13322           if (IsSameFloatAfterCast(result.Val,
13323                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13324                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13325             return;
13326         }
13327 
13328         if (S.SourceMgr.isInSystemMacro(CC))
13329           return;
13330 
13331         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13332       }
13333       // ... or possibly if we're increasing rank, too
13334       else if (Order < 0) {
13335         if (S.SourceMgr.isInSystemMacro(CC))
13336           return;
13337 
13338         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13339       }
13340       return;
13341     }
13342 
13343     // If the target is integral, always warn.
13344     if (TargetBT && TargetBT->isInteger()) {
13345       if (S.SourceMgr.isInSystemMacro(CC))
13346         return;
13347 
13348       DiagnoseFloatingImpCast(S, E, T, CC);
13349     }
13350 
13351     // Detect the case where a call result is converted from floating-point to
13352     // to bool, and the final argument to the call is converted from bool, to
13353     // discover this typo:
13354     //
13355     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13356     //
13357     // FIXME: This is an incredibly special case; is there some more general
13358     // way to detect this class of misplaced-parentheses bug?
13359     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13360       // Check last argument of function call to see if it is an
13361       // implicit cast from a type matching the type the result
13362       // is being cast to.
13363       CallExpr *CEx = cast<CallExpr>(E);
13364       if (unsigned NumArgs = CEx->getNumArgs()) {
13365         Expr *LastA = CEx->getArg(NumArgs - 1);
13366         Expr *InnerE = LastA->IgnoreParenImpCasts();
13367         if (isa<ImplicitCastExpr>(LastA) &&
13368             InnerE->getType()->isBooleanType()) {
13369           // Warn on this floating-point to bool conversion
13370           DiagnoseImpCast(S, E, T, CC,
13371                           diag::warn_impcast_floating_point_to_bool);
13372         }
13373       }
13374     }
13375     return;
13376   }
13377 
13378   // Valid casts involving fixed point types should be accounted for here.
13379   if (Source->isFixedPointType()) {
13380     if (Target->isUnsaturatedFixedPointType()) {
13381       Expr::EvalResult Result;
13382       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13383                                   S.isConstantEvaluated())) {
13384         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13385         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13386         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13387         if (Value > MaxVal || Value < MinVal) {
13388           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13389                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13390                                     << Value.toString() << T
13391                                     << E->getSourceRange()
13392                                     << clang::SourceRange(CC));
13393           return;
13394         }
13395       }
13396     } else if (Target->isIntegerType()) {
13397       Expr::EvalResult Result;
13398       if (!S.isConstantEvaluated() &&
13399           E->EvaluateAsFixedPoint(Result, S.Context,
13400                                   Expr::SE_AllowSideEffects)) {
13401         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13402 
13403         bool Overflowed;
13404         llvm::APSInt IntResult = FXResult.convertToInt(
13405             S.Context.getIntWidth(T),
13406             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13407 
13408         if (Overflowed) {
13409           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13410                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13411                                     << FXResult.toString() << T
13412                                     << E->getSourceRange()
13413                                     << clang::SourceRange(CC));
13414           return;
13415         }
13416       }
13417     }
13418   } else if (Target->isUnsaturatedFixedPointType()) {
13419     if (Source->isIntegerType()) {
13420       Expr::EvalResult Result;
13421       if (!S.isConstantEvaluated() &&
13422           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13423         llvm::APSInt Value = Result.Val.getInt();
13424 
13425         bool Overflowed;
13426         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13427             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13428 
13429         if (Overflowed) {
13430           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13431                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13432                                     << toString(Value, /*Radix=*/10) << T
13433                                     << E->getSourceRange()
13434                                     << clang::SourceRange(CC));
13435           return;
13436         }
13437       }
13438     }
13439   }
13440 
13441   // If we are casting an integer type to a floating point type without
13442   // initialization-list syntax, we might lose accuracy if the floating
13443   // point type has a narrower significand than the integer type.
13444   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13445       TargetBT->isFloatingType() && !IsListInit) {
13446     // Determine the number of precision bits in the source integer type.
13447     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13448                                         /*Approximate*/ true);
13449     unsigned int SourcePrecision = SourceRange.Width;
13450 
13451     // Determine the number of precision bits in the
13452     // target floating point type.
13453     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13454         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13455 
13456     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13457         SourcePrecision > TargetPrecision) {
13458 
13459       if (Optional<llvm::APSInt> SourceInt =
13460               E->getIntegerConstantExpr(S.Context)) {
13461         // If the source integer is a constant, convert it to the target
13462         // floating point type. Issue a warning if the value changes
13463         // during the whole conversion.
13464         llvm::APFloat TargetFloatValue(
13465             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13466         llvm::APFloat::opStatus ConversionStatus =
13467             TargetFloatValue.convertFromAPInt(
13468                 *SourceInt, SourceBT->isSignedInteger(),
13469                 llvm::APFloat::rmNearestTiesToEven);
13470 
13471         if (ConversionStatus != llvm::APFloat::opOK) {
13472           SmallString<32> PrettySourceValue;
13473           SourceInt->toString(PrettySourceValue, 10);
13474           SmallString<32> PrettyTargetValue;
13475           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13476 
13477           S.DiagRuntimeBehavior(
13478               E->getExprLoc(), E,
13479               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13480                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13481                   << E->getSourceRange() << clang::SourceRange(CC));
13482         }
13483       } else {
13484         // Otherwise, the implicit conversion may lose precision.
13485         DiagnoseImpCast(S, E, T, CC,
13486                         diag::warn_impcast_integer_float_precision);
13487       }
13488     }
13489   }
13490 
13491   DiagnoseNullConversion(S, E, T, CC);
13492 
13493   S.DiscardMisalignedMemberAddress(Target, E);
13494 
13495   if (Target->isBooleanType())
13496     DiagnoseIntInBoolContext(S, E);
13497 
13498   if (!Source->isIntegerType() || !Target->isIntegerType())
13499     return;
13500 
13501   // TODO: remove this early return once the false positives for constant->bool
13502   // in templates, macros, etc, are reduced or removed.
13503   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13504     return;
13505 
13506   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13507       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13508     return adornObjCBoolConversionDiagWithTernaryFixit(
13509         S, E,
13510         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13511             << E->getType());
13512   }
13513 
13514   IntRange SourceTypeRange =
13515       IntRange::forTargetOfCanonicalType(S.Context, Source);
13516   IntRange LikelySourceRange =
13517       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13518   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13519 
13520   if (LikelySourceRange.Width > TargetRange.Width) {
13521     // If the source is a constant, use a default-on diagnostic.
13522     // TODO: this should happen for bitfield stores, too.
13523     Expr::EvalResult Result;
13524     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13525                          S.isConstantEvaluated())) {
13526       llvm::APSInt Value(32);
13527       Value = Result.Val.getInt();
13528 
13529       if (S.SourceMgr.isInSystemMacro(CC))
13530         return;
13531 
13532       std::string PrettySourceValue = toString(Value, 10);
13533       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13534 
13535       S.DiagRuntimeBehavior(
13536           E->getExprLoc(), E,
13537           S.PDiag(diag::warn_impcast_integer_precision_constant)
13538               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13539               << E->getSourceRange() << SourceRange(CC));
13540       return;
13541     }
13542 
13543     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13544     if (S.SourceMgr.isInSystemMacro(CC))
13545       return;
13546 
13547     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13548       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13549                              /* pruneControlFlow */ true);
13550     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13551   }
13552 
13553   if (TargetRange.Width > SourceTypeRange.Width) {
13554     if (auto *UO = dyn_cast<UnaryOperator>(E))
13555       if (UO->getOpcode() == UO_Minus)
13556         if (Source->isUnsignedIntegerType()) {
13557           if (Target->isUnsignedIntegerType())
13558             return DiagnoseImpCast(S, E, T, CC,
13559                                    diag::warn_impcast_high_order_zero_bits);
13560           if (Target->isSignedIntegerType())
13561             return DiagnoseImpCast(S, E, T, CC,
13562                                    diag::warn_impcast_nonnegative_result);
13563         }
13564   }
13565 
13566   if (TargetRange.Width == LikelySourceRange.Width &&
13567       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13568       Source->isSignedIntegerType()) {
13569     // Warn when doing a signed to signed conversion, warn if the positive
13570     // source value is exactly the width of the target type, which will
13571     // cause a negative value to be stored.
13572 
13573     Expr::EvalResult Result;
13574     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13575         !S.SourceMgr.isInSystemMacro(CC)) {
13576       llvm::APSInt Value = Result.Val.getInt();
13577       if (isSameWidthConstantConversion(S, E, T, CC)) {
13578         std::string PrettySourceValue = toString(Value, 10);
13579         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13580 
13581         S.DiagRuntimeBehavior(
13582             E->getExprLoc(), E,
13583             S.PDiag(diag::warn_impcast_integer_precision_constant)
13584                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13585                 << E->getSourceRange() << SourceRange(CC));
13586         return;
13587       }
13588     }
13589 
13590     // Fall through for non-constants to give a sign conversion warning.
13591   }
13592 
13593   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13594       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13595        LikelySourceRange.Width == TargetRange.Width)) {
13596     if (S.SourceMgr.isInSystemMacro(CC))
13597       return;
13598 
13599     unsigned DiagID = diag::warn_impcast_integer_sign;
13600 
13601     // Traditionally, gcc has warned about this under -Wsign-compare.
13602     // We also want to warn about it in -Wconversion.
13603     // So if -Wconversion is off, use a completely identical diagnostic
13604     // in the sign-compare group.
13605     // The conditional-checking code will
13606     if (ICContext) {
13607       DiagID = diag::warn_impcast_integer_sign_conditional;
13608       *ICContext = true;
13609     }
13610 
13611     return DiagnoseImpCast(S, E, T, CC, DiagID);
13612   }
13613 
13614   // Diagnose conversions between different enumeration types.
13615   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13616   // type, to give us better diagnostics.
13617   QualType SourceType = E->getType();
13618   if (!S.getLangOpts().CPlusPlus) {
13619     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13620       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13621         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13622         SourceType = S.Context.getTypeDeclType(Enum);
13623         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13624       }
13625   }
13626 
13627   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13628     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13629       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13630           TargetEnum->getDecl()->hasNameForLinkage() &&
13631           SourceEnum != TargetEnum) {
13632         if (S.SourceMgr.isInSystemMacro(CC))
13633           return;
13634 
13635         return DiagnoseImpCast(S, E, SourceType, T, CC,
13636                                diag::warn_impcast_different_enum_types);
13637       }
13638 }
13639 
13640 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13641                                      SourceLocation CC, QualType T);
13642 
13643 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13644                                     SourceLocation CC, bool &ICContext) {
13645   E = E->IgnoreParenImpCasts();
13646 
13647   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13648     return CheckConditionalOperator(S, CO, CC, T);
13649 
13650   AnalyzeImplicitConversions(S, E, CC);
13651   if (E->getType() != T)
13652     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13653 }
13654 
13655 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13656                                      SourceLocation CC, QualType T) {
13657   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13658 
13659   Expr *TrueExpr = E->getTrueExpr();
13660   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13661     TrueExpr = BCO->getCommon();
13662 
13663   bool Suspicious = false;
13664   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13665   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13666 
13667   if (T->isBooleanType())
13668     DiagnoseIntInBoolContext(S, E);
13669 
13670   // If -Wconversion would have warned about either of the candidates
13671   // for a signedness conversion to the context type...
13672   if (!Suspicious) return;
13673 
13674   // ...but it's currently ignored...
13675   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13676     return;
13677 
13678   // ...then check whether it would have warned about either of the
13679   // candidates for a signedness conversion to the condition type.
13680   if (E->getType() == T) return;
13681 
13682   Suspicious = false;
13683   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13684                           E->getType(), CC, &Suspicious);
13685   if (!Suspicious)
13686     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13687                             E->getType(), CC, &Suspicious);
13688 }
13689 
13690 /// Check conversion of given expression to boolean.
13691 /// Input argument E is a logical expression.
13692 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13693   if (S.getLangOpts().Bool)
13694     return;
13695   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13696     return;
13697   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13698 }
13699 
13700 namespace {
13701 struct AnalyzeImplicitConversionsWorkItem {
13702   Expr *E;
13703   SourceLocation CC;
13704   bool IsListInit;
13705 };
13706 }
13707 
13708 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13709 /// that should be visited are added to WorkList.
13710 static void AnalyzeImplicitConversions(
13711     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13712     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13713   Expr *OrigE = Item.E;
13714   SourceLocation CC = Item.CC;
13715 
13716   QualType T = OrigE->getType();
13717   Expr *E = OrigE->IgnoreParenImpCasts();
13718 
13719   // Propagate whether we are in a C++ list initialization expression.
13720   // If so, we do not issue warnings for implicit int-float conversion
13721   // precision loss, because C++11 narrowing already handles it.
13722   bool IsListInit = Item.IsListInit ||
13723                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13724 
13725   if (E->isTypeDependent() || E->isValueDependent())
13726     return;
13727 
13728   Expr *SourceExpr = E;
13729   // Examine, but don't traverse into the source expression of an
13730   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13731   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13732   // evaluate it in the context of checking the specific conversion to T though.
13733   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13734     if (auto *Src = OVE->getSourceExpr())
13735       SourceExpr = Src;
13736 
13737   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13738     if (UO->getOpcode() == UO_Not &&
13739         UO->getSubExpr()->isKnownToHaveBooleanValue())
13740       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13741           << OrigE->getSourceRange() << T->isBooleanType()
13742           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13743 
13744   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13745     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13746         BO->getLHS()->isKnownToHaveBooleanValue() &&
13747         BO->getRHS()->isKnownToHaveBooleanValue() &&
13748         BO->getLHS()->HasSideEffects(S.Context) &&
13749         BO->getRHS()->HasSideEffects(S.Context)) {
13750       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13751           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13752           << FixItHint::CreateReplacement(
13753                  BO->getOperatorLoc(),
13754                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13755       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13756     }
13757 
13758   // For conditional operators, we analyze the arguments as if they
13759   // were being fed directly into the output.
13760   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13761     CheckConditionalOperator(S, CO, CC, T);
13762     return;
13763   }
13764 
13765   // Check implicit argument conversions for function calls.
13766   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13767     CheckImplicitArgumentConversions(S, Call, CC);
13768 
13769   // Go ahead and check any implicit conversions we might have skipped.
13770   // The non-canonical typecheck is just an optimization;
13771   // CheckImplicitConversion will filter out dead implicit conversions.
13772   if (SourceExpr->getType() != T)
13773     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13774 
13775   // Now continue drilling into this expression.
13776 
13777   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13778     // The bound subexpressions in a PseudoObjectExpr are not reachable
13779     // as transitive children.
13780     // FIXME: Use a more uniform representation for this.
13781     for (auto *SE : POE->semantics())
13782       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13783         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13784   }
13785 
13786   // Skip past explicit casts.
13787   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13788     E = CE->getSubExpr()->IgnoreParenImpCasts();
13789     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13790       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13791     WorkList.push_back({E, CC, IsListInit});
13792     return;
13793   }
13794 
13795   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13796     // Do a somewhat different check with comparison operators.
13797     if (BO->isComparisonOp())
13798       return AnalyzeComparison(S, BO);
13799 
13800     // And with simple assignments.
13801     if (BO->getOpcode() == BO_Assign)
13802       return AnalyzeAssignment(S, BO);
13803     // And with compound assignments.
13804     if (BO->isAssignmentOp())
13805       return AnalyzeCompoundAssignment(S, BO);
13806   }
13807 
13808   // These break the otherwise-useful invariant below.  Fortunately,
13809   // we don't really need to recurse into them, because any internal
13810   // expressions should have been analyzed already when they were
13811   // built into statements.
13812   if (isa<StmtExpr>(E)) return;
13813 
13814   // Don't descend into unevaluated contexts.
13815   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13816 
13817   // Now just recurse over the expression's children.
13818   CC = E->getExprLoc();
13819   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13820   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13821   for (Stmt *SubStmt : E->children()) {
13822     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13823     if (!ChildExpr)
13824       continue;
13825 
13826     if (IsLogicalAndOperator &&
13827         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13828       // Ignore checking string literals that are in logical and operators.
13829       // This is a common pattern for asserts.
13830       continue;
13831     WorkList.push_back({ChildExpr, CC, IsListInit});
13832   }
13833 
13834   if (BO && BO->isLogicalOp()) {
13835     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13836     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13837       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13838 
13839     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13840     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13841       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13842   }
13843 
13844   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13845     if (U->getOpcode() == UO_LNot) {
13846       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13847     } else if (U->getOpcode() != UO_AddrOf) {
13848       if (U->getSubExpr()->getType()->isAtomicType())
13849         S.Diag(U->getSubExpr()->getBeginLoc(),
13850                diag::warn_atomic_implicit_seq_cst);
13851     }
13852   }
13853 }
13854 
13855 /// AnalyzeImplicitConversions - Find and report any interesting
13856 /// implicit conversions in the given expression.  There are a couple
13857 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13858 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13859                                        bool IsListInit/*= false*/) {
13860   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13861   WorkList.push_back({OrigE, CC, IsListInit});
13862   while (!WorkList.empty())
13863     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13864 }
13865 
13866 /// Diagnose integer type and any valid implicit conversion to it.
13867 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13868   // Taking into account implicit conversions,
13869   // allow any integer.
13870   if (!E->getType()->isIntegerType()) {
13871     S.Diag(E->getBeginLoc(),
13872            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13873     return true;
13874   }
13875   // Potentially emit standard warnings for implicit conversions if enabled
13876   // using -Wconversion.
13877   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13878   return false;
13879 }
13880 
13881 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13882 // Returns true when emitting a warning about taking the address of a reference.
13883 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13884                               const PartialDiagnostic &PD) {
13885   E = E->IgnoreParenImpCasts();
13886 
13887   const FunctionDecl *FD = nullptr;
13888 
13889   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13890     if (!DRE->getDecl()->getType()->isReferenceType())
13891       return false;
13892   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13893     if (!M->getMemberDecl()->getType()->isReferenceType())
13894       return false;
13895   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13896     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13897       return false;
13898     FD = Call->getDirectCallee();
13899   } else {
13900     return false;
13901   }
13902 
13903   SemaRef.Diag(E->getExprLoc(), PD);
13904 
13905   // If possible, point to location of function.
13906   if (FD) {
13907     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13908   }
13909 
13910   return true;
13911 }
13912 
13913 // Returns true if the SourceLocation is expanded from any macro body.
13914 // Returns false if the SourceLocation is invalid, is from not in a macro
13915 // expansion, or is from expanded from a top-level macro argument.
13916 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13917   if (Loc.isInvalid())
13918     return false;
13919 
13920   while (Loc.isMacroID()) {
13921     if (SM.isMacroBodyExpansion(Loc))
13922       return true;
13923     Loc = SM.getImmediateMacroCallerLoc(Loc);
13924   }
13925 
13926   return false;
13927 }
13928 
13929 /// Diagnose pointers that are always non-null.
13930 /// \param E the expression containing the pointer
13931 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13932 /// compared to a null pointer
13933 /// \param IsEqual True when the comparison is equal to a null pointer
13934 /// \param Range Extra SourceRange to highlight in the diagnostic
13935 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13936                                         Expr::NullPointerConstantKind NullKind,
13937                                         bool IsEqual, SourceRange Range) {
13938   if (!E)
13939     return;
13940 
13941   // Don't warn inside macros.
13942   if (E->getExprLoc().isMacroID()) {
13943     const SourceManager &SM = getSourceManager();
13944     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13945         IsInAnyMacroBody(SM, Range.getBegin()))
13946       return;
13947   }
13948   E = E->IgnoreImpCasts();
13949 
13950   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13951 
13952   if (isa<CXXThisExpr>(E)) {
13953     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13954                                 : diag::warn_this_bool_conversion;
13955     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13956     return;
13957   }
13958 
13959   bool IsAddressOf = false;
13960 
13961   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13962     if (UO->getOpcode() != UO_AddrOf)
13963       return;
13964     IsAddressOf = true;
13965     E = UO->getSubExpr();
13966   }
13967 
13968   if (IsAddressOf) {
13969     unsigned DiagID = IsCompare
13970                           ? diag::warn_address_of_reference_null_compare
13971                           : diag::warn_address_of_reference_bool_conversion;
13972     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13973                                          << IsEqual;
13974     if (CheckForReference(*this, E, PD)) {
13975       return;
13976     }
13977   }
13978 
13979   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13980     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13981     std::string Str;
13982     llvm::raw_string_ostream S(Str);
13983     E->printPretty(S, nullptr, getPrintingPolicy());
13984     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13985                                 : diag::warn_cast_nonnull_to_bool;
13986     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13987       << E->getSourceRange() << Range << IsEqual;
13988     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13989   };
13990 
13991   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13992   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13993     if (auto *Callee = Call->getDirectCallee()) {
13994       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13995         ComplainAboutNonnullParamOrCall(A);
13996         return;
13997       }
13998     }
13999   }
14000 
14001   // Expect to find a single Decl.  Skip anything more complicated.
14002   ValueDecl *D = nullptr;
14003   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14004     D = R->getDecl();
14005   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14006     D = M->getMemberDecl();
14007   }
14008 
14009   // Weak Decls can be null.
14010   if (!D || D->isWeak())
14011     return;
14012 
14013   // Check for parameter decl with nonnull attribute
14014   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14015     if (getCurFunction() &&
14016         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14017       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14018         ComplainAboutNonnullParamOrCall(A);
14019         return;
14020       }
14021 
14022       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14023         // Skip function template not specialized yet.
14024         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14025           return;
14026         auto ParamIter = llvm::find(FD->parameters(), PV);
14027         assert(ParamIter != FD->param_end());
14028         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14029 
14030         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14031           if (!NonNull->args_size()) {
14032               ComplainAboutNonnullParamOrCall(NonNull);
14033               return;
14034           }
14035 
14036           for (const ParamIdx &ArgNo : NonNull->args()) {
14037             if (ArgNo.getASTIndex() == ParamNo) {
14038               ComplainAboutNonnullParamOrCall(NonNull);
14039               return;
14040             }
14041           }
14042         }
14043       }
14044     }
14045   }
14046 
14047   QualType T = D->getType();
14048   const bool IsArray = T->isArrayType();
14049   const bool IsFunction = T->isFunctionType();
14050 
14051   // Address of function is used to silence the function warning.
14052   if (IsAddressOf && IsFunction) {
14053     return;
14054   }
14055 
14056   // Found nothing.
14057   if (!IsAddressOf && !IsFunction && !IsArray)
14058     return;
14059 
14060   // Pretty print the expression for the diagnostic.
14061   std::string Str;
14062   llvm::raw_string_ostream S(Str);
14063   E->printPretty(S, nullptr, getPrintingPolicy());
14064 
14065   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14066                               : diag::warn_impcast_pointer_to_bool;
14067   enum {
14068     AddressOf,
14069     FunctionPointer,
14070     ArrayPointer
14071   } DiagType;
14072   if (IsAddressOf)
14073     DiagType = AddressOf;
14074   else if (IsFunction)
14075     DiagType = FunctionPointer;
14076   else if (IsArray)
14077     DiagType = ArrayPointer;
14078   else
14079     llvm_unreachable("Could not determine diagnostic.");
14080   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14081                                 << Range << IsEqual;
14082 
14083   if (!IsFunction)
14084     return;
14085 
14086   // Suggest '&' to silence the function warning.
14087   Diag(E->getExprLoc(), diag::note_function_warning_silence)
14088       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
14089 
14090   // Check to see if '()' fixit should be emitted.
14091   QualType ReturnType;
14092   UnresolvedSet<4> NonTemplateOverloads;
14093   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14094   if (ReturnType.isNull())
14095     return;
14096 
14097   if (IsCompare) {
14098     // There are two cases here.  If there is null constant, the only suggest
14099     // for a pointer return type.  If the null is 0, then suggest if the return
14100     // type is a pointer or an integer type.
14101     if (!ReturnType->isPointerType()) {
14102       if (NullKind == Expr::NPCK_ZeroExpression ||
14103           NullKind == Expr::NPCK_ZeroLiteral) {
14104         if (!ReturnType->isIntegerType())
14105           return;
14106       } else {
14107         return;
14108       }
14109     }
14110   } else { // !IsCompare
14111     // For function to bool, only suggest if the function pointer has bool
14112     // return type.
14113     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14114       return;
14115   }
14116   Diag(E->getExprLoc(), diag::note_function_to_function_call)
14117       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
14118 }
14119 
14120 /// Diagnoses "dangerous" implicit conversions within the given
14121 /// expression (which is a full expression).  Implements -Wconversion
14122 /// and -Wsign-compare.
14123 ///
14124 /// \param CC the "context" location of the implicit conversion, i.e.
14125 ///   the most location of the syntactic entity requiring the implicit
14126 ///   conversion
14127 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14128   // Don't diagnose in unevaluated contexts.
14129   if (isUnevaluatedContext())
14130     return;
14131 
14132   // Don't diagnose for value- or type-dependent expressions.
14133   if (E->isTypeDependent() || E->isValueDependent())
14134     return;
14135 
14136   // Check for array bounds violations in cases where the check isn't triggered
14137   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14138   // ArraySubscriptExpr is on the RHS of a variable initialization.
14139   CheckArrayAccess(E);
14140 
14141   // This is not the right CC for (e.g.) a variable initialization.
14142   AnalyzeImplicitConversions(*this, E, CC);
14143 }
14144 
14145 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
14146 /// Input argument E is a logical expression.
14147 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14148   ::CheckBoolLikeConversion(*this, E, CC);
14149 }
14150 
14151 /// Diagnose when expression is an integer constant expression and its evaluation
14152 /// results in integer overflow
14153 void Sema::CheckForIntOverflow (Expr *E) {
14154   // Use a work list to deal with nested struct initializers.
14155   SmallVector<Expr *, 2> Exprs(1, E);
14156 
14157   do {
14158     Expr *OriginalE = Exprs.pop_back_val();
14159     Expr *E = OriginalE->IgnoreParenCasts();
14160 
14161     if (isa<BinaryOperator>(E)) {
14162       E->EvaluateForOverflow(Context);
14163       continue;
14164     }
14165 
14166     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14167       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14168     else if (isa<ObjCBoxedExpr>(OriginalE))
14169       E->EvaluateForOverflow(Context);
14170     else if (auto Call = dyn_cast<CallExpr>(E))
14171       Exprs.append(Call->arg_begin(), Call->arg_end());
14172     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14173       Exprs.append(Message->arg_begin(), Message->arg_end());
14174   } while (!Exprs.empty());
14175 }
14176 
14177 namespace {
14178 
14179 /// Visitor for expressions which looks for unsequenced operations on the
14180 /// same object.
14181 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14182   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14183 
14184   /// A tree of sequenced regions within an expression. Two regions are
14185   /// unsequenced if one is an ancestor or a descendent of the other. When we
14186   /// finish processing an expression with sequencing, such as a comma
14187   /// expression, we fold its tree nodes into its parent, since they are
14188   /// unsequenced with respect to nodes we will visit later.
14189   class SequenceTree {
14190     struct Value {
14191       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14192       unsigned Parent : 31;
14193       unsigned Merged : 1;
14194     };
14195     SmallVector<Value, 8> Values;
14196 
14197   public:
14198     /// A region within an expression which may be sequenced with respect
14199     /// to some other region.
14200     class Seq {
14201       friend class SequenceTree;
14202 
14203       unsigned Index;
14204 
14205       explicit Seq(unsigned N) : Index(N) {}
14206 
14207     public:
14208       Seq() : Index(0) {}
14209     };
14210 
14211     SequenceTree() { Values.push_back(Value(0)); }
14212     Seq root() const { return Seq(0); }
14213 
14214     /// Create a new sequence of operations, which is an unsequenced
14215     /// subset of \p Parent. This sequence of operations is sequenced with
14216     /// respect to other children of \p Parent.
14217     Seq allocate(Seq Parent) {
14218       Values.push_back(Value(Parent.Index));
14219       return Seq(Values.size() - 1);
14220     }
14221 
14222     /// Merge a sequence of operations into its parent.
14223     void merge(Seq S) {
14224       Values[S.Index].Merged = true;
14225     }
14226 
14227     /// Determine whether two operations are unsequenced. This operation
14228     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14229     /// should have been merged into its parent as appropriate.
14230     bool isUnsequenced(Seq Cur, Seq Old) {
14231       unsigned C = representative(Cur.Index);
14232       unsigned Target = representative(Old.Index);
14233       while (C >= Target) {
14234         if (C == Target)
14235           return true;
14236         C = Values[C].Parent;
14237       }
14238       return false;
14239     }
14240 
14241   private:
14242     /// Pick a representative for a sequence.
14243     unsigned representative(unsigned K) {
14244       if (Values[K].Merged)
14245         // Perform path compression as we go.
14246         return Values[K].Parent = representative(Values[K].Parent);
14247       return K;
14248     }
14249   };
14250 
14251   /// An object for which we can track unsequenced uses.
14252   using Object = const NamedDecl *;
14253 
14254   /// Different flavors of object usage which we track. We only track the
14255   /// least-sequenced usage of each kind.
14256   enum UsageKind {
14257     /// A read of an object. Multiple unsequenced reads are OK.
14258     UK_Use,
14259 
14260     /// A modification of an object which is sequenced before the value
14261     /// computation of the expression, such as ++n in C++.
14262     UK_ModAsValue,
14263 
14264     /// A modification of an object which is not sequenced before the value
14265     /// computation of the expression, such as n++.
14266     UK_ModAsSideEffect,
14267 
14268     UK_Count = UK_ModAsSideEffect + 1
14269   };
14270 
14271   /// Bundle together a sequencing region and the expression corresponding
14272   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14273   struct Usage {
14274     const Expr *UsageExpr;
14275     SequenceTree::Seq Seq;
14276 
14277     Usage() : UsageExpr(nullptr) {}
14278   };
14279 
14280   struct UsageInfo {
14281     Usage Uses[UK_Count];
14282 
14283     /// Have we issued a diagnostic for this object already?
14284     bool Diagnosed;
14285 
14286     UsageInfo() : Diagnosed(false) {}
14287   };
14288   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14289 
14290   Sema &SemaRef;
14291 
14292   /// Sequenced regions within the expression.
14293   SequenceTree Tree;
14294 
14295   /// Declaration modifications and references which we have seen.
14296   UsageInfoMap UsageMap;
14297 
14298   /// The region we are currently within.
14299   SequenceTree::Seq Region;
14300 
14301   /// Filled in with declarations which were modified as a side-effect
14302   /// (that is, post-increment operations).
14303   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14304 
14305   /// Expressions to check later. We defer checking these to reduce
14306   /// stack usage.
14307   SmallVectorImpl<const Expr *> &WorkList;
14308 
14309   /// RAII object wrapping the visitation of a sequenced subexpression of an
14310   /// expression. At the end of this process, the side-effects of the evaluation
14311   /// become sequenced with respect to the value computation of the result, so
14312   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14313   /// UK_ModAsValue.
14314   struct SequencedSubexpression {
14315     SequencedSubexpression(SequenceChecker &Self)
14316       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14317       Self.ModAsSideEffect = &ModAsSideEffect;
14318     }
14319 
14320     ~SequencedSubexpression() {
14321       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14322         // Add a new usage with usage kind UK_ModAsValue, and then restore
14323         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14324         // the previous one was empty).
14325         UsageInfo &UI = Self.UsageMap[M.first];
14326         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14327         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14328         SideEffectUsage = M.second;
14329       }
14330       Self.ModAsSideEffect = OldModAsSideEffect;
14331     }
14332 
14333     SequenceChecker &Self;
14334     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14335     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14336   };
14337 
14338   /// RAII object wrapping the visitation of a subexpression which we might
14339   /// choose to evaluate as a constant. If any subexpression is evaluated and
14340   /// found to be non-constant, this allows us to suppress the evaluation of
14341   /// the outer expression.
14342   class EvaluationTracker {
14343   public:
14344     EvaluationTracker(SequenceChecker &Self)
14345         : Self(Self), Prev(Self.EvalTracker) {
14346       Self.EvalTracker = this;
14347     }
14348 
14349     ~EvaluationTracker() {
14350       Self.EvalTracker = Prev;
14351       if (Prev)
14352         Prev->EvalOK &= EvalOK;
14353     }
14354 
14355     bool evaluate(const Expr *E, bool &Result) {
14356       if (!EvalOK || E->isValueDependent())
14357         return false;
14358       EvalOK = E->EvaluateAsBooleanCondition(
14359           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14360       return EvalOK;
14361     }
14362 
14363   private:
14364     SequenceChecker &Self;
14365     EvaluationTracker *Prev;
14366     bool EvalOK = true;
14367   } *EvalTracker = nullptr;
14368 
14369   /// Find the object which is produced by the specified expression,
14370   /// if any.
14371   Object getObject(const Expr *E, bool Mod) const {
14372     E = E->IgnoreParenCasts();
14373     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14374       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14375         return getObject(UO->getSubExpr(), Mod);
14376     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14377       if (BO->getOpcode() == BO_Comma)
14378         return getObject(BO->getRHS(), Mod);
14379       if (Mod && BO->isAssignmentOp())
14380         return getObject(BO->getLHS(), Mod);
14381     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14382       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14383       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14384         return ME->getMemberDecl();
14385     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14386       // FIXME: If this is a reference, map through to its value.
14387       return DRE->getDecl();
14388     return nullptr;
14389   }
14390 
14391   /// Note that an object \p O was modified or used by an expression
14392   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14393   /// the object \p O as obtained via the \p UsageMap.
14394   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14395     // Get the old usage for the given object and usage kind.
14396     Usage &U = UI.Uses[UK];
14397     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14398       // If we have a modification as side effect and are in a sequenced
14399       // subexpression, save the old Usage so that we can restore it later
14400       // in SequencedSubexpression::~SequencedSubexpression.
14401       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14402         ModAsSideEffect->push_back(std::make_pair(O, U));
14403       // Then record the new usage with the current sequencing region.
14404       U.UsageExpr = UsageExpr;
14405       U.Seq = Region;
14406     }
14407   }
14408 
14409   /// Check whether a modification or use of an object \p O in an expression
14410   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14411   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14412   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14413   /// usage and false we are checking for a mod-use unsequenced usage.
14414   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14415                   UsageKind OtherKind, bool IsModMod) {
14416     if (UI.Diagnosed)
14417       return;
14418 
14419     const Usage &U = UI.Uses[OtherKind];
14420     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14421       return;
14422 
14423     const Expr *Mod = U.UsageExpr;
14424     const Expr *ModOrUse = UsageExpr;
14425     if (OtherKind == UK_Use)
14426       std::swap(Mod, ModOrUse);
14427 
14428     SemaRef.DiagRuntimeBehavior(
14429         Mod->getExprLoc(), {Mod, ModOrUse},
14430         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14431                                : diag::warn_unsequenced_mod_use)
14432             << O << SourceRange(ModOrUse->getExprLoc()));
14433     UI.Diagnosed = true;
14434   }
14435 
14436   // A note on note{Pre, Post}{Use, Mod}:
14437   //
14438   // (It helps to follow the algorithm with an expression such as
14439   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14440   //  operations before C++17 and both are well-defined in C++17).
14441   //
14442   // When visiting a node which uses/modify an object we first call notePreUse
14443   // or notePreMod before visiting its sub-expression(s). At this point the
14444   // children of the current node have not yet been visited and so the eventual
14445   // uses/modifications resulting from the children of the current node have not
14446   // been recorded yet.
14447   //
14448   // We then visit the children of the current node. After that notePostUse or
14449   // notePostMod is called. These will 1) detect an unsequenced modification
14450   // as side effect (as in "k++ + k") and 2) add a new usage with the
14451   // appropriate usage kind.
14452   //
14453   // We also have to be careful that some operation sequences modification as
14454   // side effect as well (for example: || or ,). To account for this we wrap
14455   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14456   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14457   // which record usages which are modifications as side effect, and then
14458   // downgrade them (or more accurately restore the previous usage which was a
14459   // modification as side effect) when exiting the scope of the sequenced
14460   // subexpression.
14461 
14462   void notePreUse(Object O, const Expr *UseExpr) {
14463     UsageInfo &UI = UsageMap[O];
14464     // Uses conflict with other modifications.
14465     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14466   }
14467 
14468   void notePostUse(Object O, const Expr *UseExpr) {
14469     UsageInfo &UI = UsageMap[O];
14470     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14471                /*IsModMod=*/false);
14472     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14473   }
14474 
14475   void notePreMod(Object O, const Expr *ModExpr) {
14476     UsageInfo &UI = UsageMap[O];
14477     // Modifications conflict with other modifications and with uses.
14478     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14479     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14480   }
14481 
14482   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14483     UsageInfo &UI = UsageMap[O];
14484     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14485                /*IsModMod=*/true);
14486     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14487   }
14488 
14489 public:
14490   SequenceChecker(Sema &S, const Expr *E,
14491                   SmallVectorImpl<const Expr *> &WorkList)
14492       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14493     Visit(E);
14494     // Silence a -Wunused-private-field since WorkList is now unused.
14495     // TODO: Evaluate if it can be used, and if not remove it.
14496     (void)this->WorkList;
14497   }
14498 
14499   void VisitStmt(const Stmt *S) {
14500     // Skip all statements which aren't expressions for now.
14501   }
14502 
14503   void VisitExpr(const Expr *E) {
14504     // By default, just recurse to evaluated subexpressions.
14505     Base::VisitStmt(E);
14506   }
14507 
14508   void VisitCastExpr(const CastExpr *E) {
14509     Object O = Object();
14510     if (E->getCastKind() == CK_LValueToRValue)
14511       O = getObject(E->getSubExpr(), false);
14512 
14513     if (O)
14514       notePreUse(O, E);
14515     VisitExpr(E);
14516     if (O)
14517       notePostUse(O, E);
14518   }
14519 
14520   void VisitSequencedExpressions(const Expr *SequencedBefore,
14521                                  const Expr *SequencedAfter) {
14522     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14523     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14524     SequenceTree::Seq OldRegion = Region;
14525 
14526     {
14527       SequencedSubexpression SeqBefore(*this);
14528       Region = BeforeRegion;
14529       Visit(SequencedBefore);
14530     }
14531 
14532     Region = AfterRegion;
14533     Visit(SequencedAfter);
14534 
14535     Region = OldRegion;
14536 
14537     Tree.merge(BeforeRegion);
14538     Tree.merge(AfterRegion);
14539   }
14540 
14541   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14542     // C++17 [expr.sub]p1:
14543     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14544     //   expression E1 is sequenced before the expression E2.
14545     if (SemaRef.getLangOpts().CPlusPlus17)
14546       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14547     else {
14548       Visit(ASE->getLHS());
14549       Visit(ASE->getRHS());
14550     }
14551   }
14552 
14553   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14554   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14555   void VisitBinPtrMem(const BinaryOperator *BO) {
14556     // C++17 [expr.mptr.oper]p4:
14557     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14558     //  the expression E1 is sequenced before the expression E2.
14559     if (SemaRef.getLangOpts().CPlusPlus17)
14560       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14561     else {
14562       Visit(BO->getLHS());
14563       Visit(BO->getRHS());
14564     }
14565   }
14566 
14567   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14568   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14569   void VisitBinShlShr(const BinaryOperator *BO) {
14570     // C++17 [expr.shift]p4:
14571     //  The expression E1 is sequenced before the expression E2.
14572     if (SemaRef.getLangOpts().CPlusPlus17)
14573       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14574     else {
14575       Visit(BO->getLHS());
14576       Visit(BO->getRHS());
14577     }
14578   }
14579 
14580   void VisitBinComma(const BinaryOperator *BO) {
14581     // C++11 [expr.comma]p1:
14582     //   Every value computation and side effect associated with the left
14583     //   expression is sequenced before every value computation and side
14584     //   effect associated with the right expression.
14585     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14586   }
14587 
14588   void VisitBinAssign(const BinaryOperator *BO) {
14589     SequenceTree::Seq RHSRegion;
14590     SequenceTree::Seq LHSRegion;
14591     if (SemaRef.getLangOpts().CPlusPlus17) {
14592       RHSRegion = Tree.allocate(Region);
14593       LHSRegion = Tree.allocate(Region);
14594     } else {
14595       RHSRegion = Region;
14596       LHSRegion = Region;
14597     }
14598     SequenceTree::Seq OldRegion = Region;
14599 
14600     // C++11 [expr.ass]p1:
14601     //  [...] the assignment is sequenced after the value computation
14602     //  of the right and left operands, [...]
14603     //
14604     // so check it before inspecting the operands and update the
14605     // map afterwards.
14606     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14607     if (O)
14608       notePreMod(O, BO);
14609 
14610     if (SemaRef.getLangOpts().CPlusPlus17) {
14611       // C++17 [expr.ass]p1:
14612       //  [...] The right operand is sequenced before the left operand. [...]
14613       {
14614         SequencedSubexpression SeqBefore(*this);
14615         Region = RHSRegion;
14616         Visit(BO->getRHS());
14617       }
14618 
14619       Region = LHSRegion;
14620       Visit(BO->getLHS());
14621 
14622       if (O && isa<CompoundAssignOperator>(BO))
14623         notePostUse(O, BO);
14624 
14625     } else {
14626       // C++11 does not specify any sequencing between the LHS and RHS.
14627       Region = LHSRegion;
14628       Visit(BO->getLHS());
14629 
14630       if (O && isa<CompoundAssignOperator>(BO))
14631         notePostUse(O, BO);
14632 
14633       Region = RHSRegion;
14634       Visit(BO->getRHS());
14635     }
14636 
14637     // C++11 [expr.ass]p1:
14638     //  the assignment is sequenced [...] before the value computation of the
14639     //  assignment expression.
14640     // C11 6.5.16/3 has no such rule.
14641     Region = OldRegion;
14642     if (O)
14643       notePostMod(O, BO,
14644                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14645                                                   : UK_ModAsSideEffect);
14646     if (SemaRef.getLangOpts().CPlusPlus17) {
14647       Tree.merge(RHSRegion);
14648       Tree.merge(LHSRegion);
14649     }
14650   }
14651 
14652   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14653     VisitBinAssign(CAO);
14654   }
14655 
14656   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14657   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14658   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14659     Object O = getObject(UO->getSubExpr(), true);
14660     if (!O)
14661       return VisitExpr(UO);
14662 
14663     notePreMod(O, UO);
14664     Visit(UO->getSubExpr());
14665     // C++11 [expr.pre.incr]p1:
14666     //   the expression ++x is equivalent to x+=1
14667     notePostMod(O, UO,
14668                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14669                                                 : UK_ModAsSideEffect);
14670   }
14671 
14672   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14673   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14674   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14675     Object O = getObject(UO->getSubExpr(), true);
14676     if (!O)
14677       return VisitExpr(UO);
14678 
14679     notePreMod(O, UO);
14680     Visit(UO->getSubExpr());
14681     notePostMod(O, UO, UK_ModAsSideEffect);
14682   }
14683 
14684   void VisitBinLOr(const BinaryOperator *BO) {
14685     // C++11 [expr.log.or]p2:
14686     //  If the second expression is evaluated, every value computation and
14687     //  side effect associated with the first expression is sequenced before
14688     //  every value computation and side effect associated with the
14689     //  second expression.
14690     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14691     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14692     SequenceTree::Seq OldRegion = Region;
14693 
14694     EvaluationTracker Eval(*this);
14695     {
14696       SequencedSubexpression Sequenced(*this);
14697       Region = LHSRegion;
14698       Visit(BO->getLHS());
14699     }
14700 
14701     // C++11 [expr.log.or]p1:
14702     //  [...] the second operand is not evaluated if the first operand
14703     //  evaluates to true.
14704     bool EvalResult = false;
14705     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14706     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14707     if (ShouldVisitRHS) {
14708       Region = RHSRegion;
14709       Visit(BO->getRHS());
14710     }
14711 
14712     Region = OldRegion;
14713     Tree.merge(LHSRegion);
14714     Tree.merge(RHSRegion);
14715   }
14716 
14717   void VisitBinLAnd(const BinaryOperator *BO) {
14718     // C++11 [expr.log.and]p2:
14719     //  If the second expression is evaluated, every value computation and
14720     //  side effect associated with the first expression is sequenced before
14721     //  every value computation and side effect associated with the
14722     //  second expression.
14723     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14724     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14725     SequenceTree::Seq OldRegion = Region;
14726 
14727     EvaluationTracker Eval(*this);
14728     {
14729       SequencedSubexpression Sequenced(*this);
14730       Region = LHSRegion;
14731       Visit(BO->getLHS());
14732     }
14733 
14734     // C++11 [expr.log.and]p1:
14735     //  [...] the second operand is not evaluated if the first operand is false.
14736     bool EvalResult = false;
14737     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14738     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14739     if (ShouldVisitRHS) {
14740       Region = RHSRegion;
14741       Visit(BO->getRHS());
14742     }
14743 
14744     Region = OldRegion;
14745     Tree.merge(LHSRegion);
14746     Tree.merge(RHSRegion);
14747   }
14748 
14749   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14750     // C++11 [expr.cond]p1:
14751     //  [...] Every value computation and side effect associated with the first
14752     //  expression is sequenced before every value computation and side effect
14753     //  associated with the second or third expression.
14754     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14755 
14756     // No sequencing is specified between the true and false expression.
14757     // However since exactly one of both is going to be evaluated we can
14758     // consider them to be sequenced. This is needed to avoid warning on
14759     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14760     // both the true and false expressions because we can't evaluate x.
14761     // This will still allow us to detect an expression like (pre C++17)
14762     // "(x ? y += 1 : y += 2) = y".
14763     //
14764     // We don't wrap the visitation of the true and false expression with
14765     // SequencedSubexpression because we don't want to downgrade modifications
14766     // as side effect in the true and false expressions after the visition
14767     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14768     // not warn between the two "y++", but we should warn between the "y++"
14769     // and the "y".
14770     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14771     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14772     SequenceTree::Seq OldRegion = Region;
14773 
14774     EvaluationTracker Eval(*this);
14775     {
14776       SequencedSubexpression Sequenced(*this);
14777       Region = ConditionRegion;
14778       Visit(CO->getCond());
14779     }
14780 
14781     // C++11 [expr.cond]p1:
14782     // [...] The first expression is contextually converted to bool (Clause 4).
14783     // It is evaluated and if it is true, the result of the conditional
14784     // expression is the value of the second expression, otherwise that of the
14785     // third expression. Only one of the second and third expressions is
14786     // evaluated. [...]
14787     bool EvalResult = false;
14788     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14789     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14790     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14791     if (ShouldVisitTrueExpr) {
14792       Region = TrueRegion;
14793       Visit(CO->getTrueExpr());
14794     }
14795     if (ShouldVisitFalseExpr) {
14796       Region = FalseRegion;
14797       Visit(CO->getFalseExpr());
14798     }
14799 
14800     Region = OldRegion;
14801     Tree.merge(ConditionRegion);
14802     Tree.merge(TrueRegion);
14803     Tree.merge(FalseRegion);
14804   }
14805 
14806   void VisitCallExpr(const CallExpr *CE) {
14807     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14808 
14809     if (CE->isUnevaluatedBuiltinCall(Context))
14810       return;
14811 
14812     // C++11 [intro.execution]p15:
14813     //   When calling a function [...], every value computation and side effect
14814     //   associated with any argument expression, or with the postfix expression
14815     //   designating the called function, is sequenced before execution of every
14816     //   expression or statement in the body of the function [and thus before
14817     //   the value computation of its result].
14818     SequencedSubexpression Sequenced(*this);
14819     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14820       // C++17 [expr.call]p5
14821       //   The postfix-expression is sequenced before each expression in the
14822       //   expression-list and any default argument. [...]
14823       SequenceTree::Seq CalleeRegion;
14824       SequenceTree::Seq OtherRegion;
14825       if (SemaRef.getLangOpts().CPlusPlus17) {
14826         CalleeRegion = Tree.allocate(Region);
14827         OtherRegion = Tree.allocate(Region);
14828       } else {
14829         CalleeRegion = Region;
14830         OtherRegion = Region;
14831       }
14832       SequenceTree::Seq OldRegion = Region;
14833 
14834       // Visit the callee expression first.
14835       Region = CalleeRegion;
14836       if (SemaRef.getLangOpts().CPlusPlus17) {
14837         SequencedSubexpression Sequenced(*this);
14838         Visit(CE->getCallee());
14839       } else {
14840         Visit(CE->getCallee());
14841       }
14842 
14843       // Then visit the argument expressions.
14844       Region = OtherRegion;
14845       for (const Expr *Argument : CE->arguments())
14846         Visit(Argument);
14847 
14848       Region = OldRegion;
14849       if (SemaRef.getLangOpts().CPlusPlus17) {
14850         Tree.merge(CalleeRegion);
14851         Tree.merge(OtherRegion);
14852       }
14853     });
14854   }
14855 
14856   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14857     // C++17 [over.match.oper]p2:
14858     //   [...] the operator notation is first transformed to the equivalent
14859     //   function-call notation as summarized in Table 12 (where @ denotes one
14860     //   of the operators covered in the specified subclause). However, the
14861     //   operands are sequenced in the order prescribed for the built-in
14862     //   operator (Clause 8).
14863     //
14864     // From the above only overloaded binary operators and overloaded call
14865     // operators have sequencing rules in C++17 that we need to handle
14866     // separately.
14867     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14868         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14869       return VisitCallExpr(CXXOCE);
14870 
14871     enum {
14872       NoSequencing,
14873       LHSBeforeRHS,
14874       RHSBeforeLHS,
14875       LHSBeforeRest
14876     } SequencingKind;
14877     switch (CXXOCE->getOperator()) {
14878     case OO_Equal:
14879     case OO_PlusEqual:
14880     case OO_MinusEqual:
14881     case OO_StarEqual:
14882     case OO_SlashEqual:
14883     case OO_PercentEqual:
14884     case OO_CaretEqual:
14885     case OO_AmpEqual:
14886     case OO_PipeEqual:
14887     case OO_LessLessEqual:
14888     case OO_GreaterGreaterEqual:
14889       SequencingKind = RHSBeforeLHS;
14890       break;
14891 
14892     case OO_LessLess:
14893     case OO_GreaterGreater:
14894     case OO_AmpAmp:
14895     case OO_PipePipe:
14896     case OO_Comma:
14897     case OO_ArrowStar:
14898     case OO_Subscript:
14899       SequencingKind = LHSBeforeRHS;
14900       break;
14901 
14902     case OO_Call:
14903       SequencingKind = LHSBeforeRest;
14904       break;
14905 
14906     default:
14907       SequencingKind = NoSequencing;
14908       break;
14909     }
14910 
14911     if (SequencingKind == NoSequencing)
14912       return VisitCallExpr(CXXOCE);
14913 
14914     // This is a call, so all subexpressions are sequenced before the result.
14915     SequencedSubexpression Sequenced(*this);
14916 
14917     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14918       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14919              "Should only get there with C++17 and above!");
14920       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14921              "Should only get there with an overloaded binary operator"
14922              " or an overloaded call operator!");
14923 
14924       if (SequencingKind == LHSBeforeRest) {
14925         assert(CXXOCE->getOperator() == OO_Call &&
14926                "We should only have an overloaded call operator here!");
14927 
14928         // This is very similar to VisitCallExpr, except that we only have the
14929         // C++17 case. The postfix-expression is the first argument of the
14930         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14931         // are in the following arguments.
14932         //
14933         // Note that we intentionally do not visit the callee expression since
14934         // it is just a decayed reference to a function.
14935         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14936         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14937         SequenceTree::Seq OldRegion = Region;
14938 
14939         assert(CXXOCE->getNumArgs() >= 1 &&
14940                "An overloaded call operator must have at least one argument"
14941                " for the postfix-expression!");
14942         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14943         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14944                                           CXXOCE->getNumArgs() - 1);
14945 
14946         // Visit the postfix-expression first.
14947         {
14948           Region = PostfixExprRegion;
14949           SequencedSubexpression Sequenced(*this);
14950           Visit(PostfixExpr);
14951         }
14952 
14953         // Then visit the argument expressions.
14954         Region = ArgsRegion;
14955         for (const Expr *Arg : Args)
14956           Visit(Arg);
14957 
14958         Region = OldRegion;
14959         Tree.merge(PostfixExprRegion);
14960         Tree.merge(ArgsRegion);
14961       } else {
14962         assert(CXXOCE->getNumArgs() == 2 &&
14963                "Should only have two arguments here!");
14964         assert((SequencingKind == LHSBeforeRHS ||
14965                 SequencingKind == RHSBeforeLHS) &&
14966                "Unexpected sequencing kind!");
14967 
14968         // We do not visit the callee expression since it is just a decayed
14969         // reference to a function.
14970         const Expr *E1 = CXXOCE->getArg(0);
14971         const Expr *E2 = CXXOCE->getArg(1);
14972         if (SequencingKind == RHSBeforeLHS)
14973           std::swap(E1, E2);
14974 
14975         return VisitSequencedExpressions(E1, E2);
14976       }
14977     });
14978   }
14979 
14980   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14981     // This is a call, so all subexpressions are sequenced before the result.
14982     SequencedSubexpression Sequenced(*this);
14983 
14984     if (!CCE->isListInitialization())
14985       return VisitExpr(CCE);
14986 
14987     // In C++11, list initializations are sequenced.
14988     SmallVector<SequenceTree::Seq, 32> Elts;
14989     SequenceTree::Seq Parent = Region;
14990     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14991                                               E = CCE->arg_end();
14992          I != E; ++I) {
14993       Region = Tree.allocate(Parent);
14994       Elts.push_back(Region);
14995       Visit(*I);
14996     }
14997 
14998     // Forget that the initializers are sequenced.
14999     Region = Parent;
15000     for (unsigned I = 0; I < Elts.size(); ++I)
15001       Tree.merge(Elts[I]);
15002   }
15003 
15004   void VisitInitListExpr(const InitListExpr *ILE) {
15005     if (!SemaRef.getLangOpts().CPlusPlus11)
15006       return VisitExpr(ILE);
15007 
15008     // In C++11, list initializations are sequenced.
15009     SmallVector<SequenceTree::Seq, 32> Elts;
15010     SequenceTree::Seq Parent = Region;
15011     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
15012       const Expr *E = ILE->getInit(I);
15013       if (!E)
15014         continue;
15015       Region = Tree.allocate(Parent);
15016       Elts.push_back(Region);
15017       Visit(E);
15018     }
15019 
15020     // Forget that the initializers are sequenced.
15021     Region = Parent;
15022     for (unsigned I = 0; I < Elts.size(); ++I)
15023       Tree.merge(Elts[I]);
15024   }
15025 };
15026 
15027 } // namespace
15028 
15029 void Sema::CheckUnsequencedOperations(const Expr *E) {
15030   SmallVector<const Expr *, 8> WorkList;
15031   WorkList.push_back(E);
15032   while (!WorkList.empty()) {
15033     const Expr *Item = WorkList.pop_back_val();
15034     SequenceChecker(*this, Item, WorkList);
15035   }
15036 }
15037 
15038 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15039                               bool IsConstexpr) {
15040   llvm::SaveAndRestore<bool> ConstantContext(
15041       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
15042   CheckImplicitConversions(E, CheckLoc);
15043   if (!E->isInstantiationDependent())
15044     CheckUnsequencedOperations(E);
15045   if (!IsConstexpr && !E->isValueDependent())
15046     CheckForIntOverflow(E);
15047   DiagnoseMisalignedMembers();
15048 }
15049 
15050 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15051                                        FieldDecl *BitField,
15052                                        Expr *Init) {
15053   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15054 }
15055 
15056 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15057                                          SourceLocation Loc) {
15058   if (!PType->isVariablyModifiedType())
15059     return;
15060   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15061     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15062     return;
15063   }
15064   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15065     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15066     return;
15067   }
15068   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15069     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15070     return;
15071   }
15072 
15073   const ArrayType *AT = S.Context.getAsArrayType(PType);
15074   if (!AT)
15075     return;
15076 
15077   if (AT->getSizeModifier() != ArrayType::Star) {
15078     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
15079     return;
15080   }
15081 
15082   S.Diag(Loc, diag::err_array_star_in_function_definition);
15083 }
15084 
15085 /// CheckParmsForFunctionDef - Check that the parameters of the given
15086 /// function are appropriate for the definition of a function. This
15087 /// takes care of any checks that cannot be performed on the
15088 /// declaration itself, e.g., that the types of each of the function
15089 /// parameters are complete.
15090 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15091                                     bool CheckParameterNames) {
15092   bool HasInvalidParm = false;
15093   for (ParmVarDecl *Param : Parameters) {
15094     // C99 6.7.5.3p4: the parameters in a parameter type list in a
15095     // function declarator that is part of a function definition of
15096     // that function shall not have incomplete type.
15097     //
15098     // This is also C++ [dcl.fct]p6.
15099     if (!Param->isInvalidDecl() &&
15100         RequireCompleteType(Param->getLocation(), Param->getType(),
15101                             diag::err_typecheck_decl_incomplete_type)) {
15102       Param->setInvalidDecl();
15103       HasInvalidParm = true;
15104     }
15105 
15106     // C99 6.9.1p5: If the declarator includes a parameter type list, the
15107     // declaration of each parameter shall include an identifier.
15108     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15109         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15110       // Diagnose this as an extension in C17 and earlier.
15111       if (!getLangOpts().C2x)
15112         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15113     }
15114 
15115     // C99 6.7.5.3p12:
15116     //   If the function declarator is not part of a definition of that
15117     //   function, parameters may have incomplete type and may use the [*]
15118     //   notation in their sequences of declarator specifiers to specify
15119     //   variable length array types.
15120     QualType PType = Param->getOriginalType();
15121     // FIXME: This diagnostic should point the '[*]' if source-location
15122     // information is added for it.
15123     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15124 
15125     // If the parameter is a c++ class type and it has to be destructed in the
15126     // callee function, declare the destructor so that it can be called by the
15127     // callee function. Do not perform any direct access check on the dtor here.
15128     if (!Param->isInvalidDecl()) {
15129       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15130         if (!ClassDecl->isInvalidDecl() &&
15131             !ClassDecl->hasIrrelevantDestructor() &&
15132             !ClassDecl->isDependentContext() &&
15133             ClassDecl->isParamDestroyedInCallee()) {
15134           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15135           MarkFunctionReferenced(Param->getLocation(), Destructor);
15136           DiagnoseUseOfDecl(Destructor, Param->getLocation());
15137         }
15138       }
15139     }
15140 
15141     // Parameters with the pass_object_size attribute only need to be marked
15142     // constant at function definitions. Because we lack information about
15143     // whether we're on a declaration or definition when we're instantiating the
15144     // attribute, we need to check for constness here.
15145     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15146       if (!Param->getType().isConstQualified())
15147         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15148             << Attr->getSpelling() << 1;
15149 
15150     // Check for parameter names shadowing fields from the class.
15151     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15152       // The owning context for the parameter should be the function, but we
15153       // want to see if this function's declaration context is a record.
15154       DeclContext *DC = Param->getDeclContext();
15155       if (DC && DC->isFunctionOrMethod()) {
15156         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15157           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15158                                      RD, /*DeclIsField*/ false);
15159       }
15160     }
15161   }
15162 
15163   return HasInvalidParm;
15164 }
15165 
15166 Optional<std::pair<CharUnits, CharUnits>>
15167 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15168 
15169 /// Compute the alignment and offset of the base class object given the
15170 /// derived-to-base cast expression and the alignment and offset of the derived
15171 /// class object.
15172 static std::pair<CharUnits, CharUnits>
15173 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15174                                    CharUnits BaseAlignment, CharUnits Offset,
15175                                    ASTContext &Ctx) {
15176   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15177        ++PathI) {
15178     const CXXBaseSpecifier *Base = *PathI;
15179     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15180     if (Base->isVirtual()) {
15181       // The complete object may have a lower alignment than the non-virtual
15182       // alignment of the base, in which case the base may be misaligned. Choose
15183       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15184       // conservative lower bound of the complete object alignment.
15185       CharUnits NonVirtualAlignment =
15186           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15187       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15188       Offset = CharUnits::Zero();
15189     } else {
15190       const ASTRecordLayout &RL =
15191           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15192       Offset += RL.getBaseClassOffset(BaseDecl);
15193     }
15194     DerivedType = Base->getType();
15195   }
15196 
15197   return std::make_pair(BaseAlignment, Offset);
15198 }
15199 
15200 /// Compute the alignment and offset of a binary additive operator.
15201 static Optional<std::pair<CharUnits, CharUnits>>
15202 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15203                                      bool IsSub, ASTContext &Ctx) {
15204   QualType PointeeType = PtrE->getType()->getPointeeType();
15205 
15206   if (!PointeeType->isConstantSizeType())
15207     return llvm::None;
15208 
15209   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15210 
15211   if (!P)
15212     return llvm::None;
15213 
15214   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15215   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15216     CharUnits Offset = EltSize * IdxRes->getExtValue();
15217     if (IsSub)
15218       Offset = -Offset;
15219     return std::make_pair(P->first, P->second + Offset);
15220   }
15221 
15222   // If the integer expression isn't a constant expression, compute the lower
15223   // bound of the alignment using the alignment and offset of the pointer
15224   // expression and the element size.
15225   return std::make_pair(
15226       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15227       CharUnits::Zero());
15228 }
15229 
15230 /// This helper function takes an lvalue expression and returns the alignment of
15231 /// a VarDecl and a constant offset from the VarDecl.
15232 Optional<std::pair<CharUnits, CharUnits>>
15233 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15234   E = E->IgnoreParens();
15235   switch (E->getStmtClass()) {
15236   default:
15237     break;
15238   case Stmt::CStyleCastExprClass:
15239   case Stmt::CXXStaticCastExprClass:
15240   case Stmt::ImplicitCastExprClass: {
15241     auto *CE = cast<CastExpr>(E);
15242     const Expr *From = CE->getSubExpr();
15243     switch (CE->getCastKind()) {
15244     default:
15245       break;
15246     case CK_NoOp:
15247       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15248     case CK_UncheckedDerivedToBase:
15249     case CK_DerivedToBase: {
15250       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15251       if (!P)
15252         break;
15253       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15254                                                 P->second, Ctx);
15255     }
15256     }
15257     break;
15258   }
15259   case Stmt::ArraySubscriptExprClass: {
15260     auto *ASE = cast<ArraySubscriptExpr>(E);
15261     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15262                                                 false, Ctx);
15263   }
15264   case Stmt::DeclRefExprClass: {
15265     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15266       // FIXME: If VD is captured by copy or is an escaping __block variable,
15267       // use the alignment of VD's type.
15268       if (!VD->getType()->isReferenceType())
15269         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15270       if (VD->hasInit())
15271         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15272     }
15273     break;
15274   }
15275   case Stmt::MemberExprClass: {
15276     auto *ME = cast<MemberExpr>(E);
15277     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15278     if (!FD || FD->getType()->isReferenceType() ||
15279         FD->getParent()->isInvalidDecl())
15280       break;
15281     Optional<std::pair<CharUnits, CharUnits>> P;
15282     if (ME->isArrow())
15283       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15284     else
15285       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15286     if (!P)
15287       break;
15288     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15289     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15290     return std::make_pair(P->first,
15291                           P->second + CharUnits::fromQuantity(Offset));
15292   }
15293   case Stmt::UnaryOperatorClass: {
15294     auto *UO = cast<UnaryOperator>(E);
15295     switch (UO->getOpcode()) {
15296     default:
15297       break;
15298     case UO_Deref:
15299       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15300     }
15301     break;
15302   }
15303   case Stmt::BinaryOperatorClass: {
15304     auto *BO = cast<BinaryOperator>(E);
15305     auto Opcode = BO->getOpcode();
15306     switch (Opcode) {
15307     default:
15308       break;
15309     case BO_Comma:
15310       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15311     }
15312     break;
15313   }
15314   }
15315   return llvm::None;
15316 }
15317 
15318 /// This helper function takes a pointer expression and returns the alignment of
15319 /// a VarDecl and a constant offset from the VarDecl.
15320 Optional<std::pair<CharUnits, CharUnits>>
15321 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15322   E = E->IgnoreParens();
15323   switch (E->getStmtClass()) {
15324   default:
15325     break;
15326   case Stmt::CStyleCastExprClass:
15327   case Stmt::CXXStaticCastExprClass:
15328   case Stmt::ImplicitCastExprClass: {
15329     auto *CE = cast<CastExpr>(E);
15330     const Expr *From = CE->getSubExpr();
15331     switch (CE->getCastKind()) {
15332     default:
15333       break;
15334     case CK_NoOp:
15335       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15336     case CK_ArrayToPointerDecay:
15337       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15338     case CK_UncheckedDerivedToBase:
15339     case CK_DerivedToBase: {
15340       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15341       if (!P)
15342         break;
15343       return getDerivedToBaseAlignmentAndOffset(
15344           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15345     }
15346     }
15347     break;
15348   }
15349   case Stmt::CXXThisExprClass: {
15350     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15351     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15352     return std::make_pair(Alignment, CharUnits::Zero());
15353   }
15354   case Stmt::UnaryOperatorClass: {
15355     auto *UO = cast<UnaryOperator>(E);
15356     if (UO->getOpcode() == UO_AddrOf)
15357       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15358     break;
15359   }
15360   case Stmt::BinaryOperatorClass: {
15361     auto *BO = cast<BinaryOperator>(E);
15362     auto Opcode = BO->getOpcode();
15363     switch (Opcode) {
15364     default:
15365       break;
15366     case BO_Add:
15367     case BO_Sub: {
15368       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15369       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15370         std::swap(LHS, RHS);
15371       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15372                                                   Ctx);
15373     }
15374     case BO_Comma:
15375       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15376     }
15377     break;
15378   }
15379   }
15380   return llvm::None;
15381 }
15382 
15383 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15384   // See if we can compute the alignment of a VarDecl and an offset from it.
15385   Optional<std::pair<CharUnits, CharUnits>> P =
15386       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15387 
15388   if (P)
15389     return P->first.alignmentAtOffset(P->second);
15390 
15391   // If that failed, return the type's alignment.
15392   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15393 }
15394 
15395 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15396 /// pointer cast increases the alignment requirements.
15397 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15398   // This is actually a lot of work to potentially be doing on every
15399   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15400   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15401     return;
15402 
15403   // Ignore dependent types.
15404   if (T->isDependentType() || Op->getType()->isDependentType())
15405     return;
15406 
15407   // Require that the destination be a pointer type.
15408   const PointerType *DestPtr = T->getAs<PointerType>();
15409   if (!DestPtr) return;
15410 
15411   // If the destination has alignment 1, we're done.
15412   QualType DestPointee = DestPtr->getPointeeType();
15413   if (DestPointee->isIncompleteType()) return;
15414   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15415   if (DestAlign.isOne()) return;
15416 
15417   // Require that the source be a pointer type.
15418   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15419   if (!SrcPtr) return;
15420   QualType SrcPointee = SrcPtr->getPointeeType();
15421 
15422   // Explicitly allow casts from cv void*.  We already implicitly
15423   // allowed casts to cv void*, since they have alignment 1.
15424   // Also allow casts involving incomplete types, which implicitly
15425   // includes 'void'.
15426   if (SrcPointee->isIncompleteType()) return;
15427 
15428   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15429 
15430   if (SrcAlign >= DestAlign) return;
15431 
15432   Diag(TRange.getBegin(), diag::warn_cast_align)
15433     << Op->getType() << T
15434     << static_cast<unsigned>(SrcAlign.getQuantity())
15435     << static_cast<unsigned>(DestAlign.getQuantity())
15436     << TRange << Op->getSourceRange();
15437 }
15438 
15439 /// Check whether this array fits the idiom of a size-one tail padded
15440 /// array member of a struct.
15441 ///
15442 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15443 /// commonly used to emulate flexible arrays in C89 code.
15444 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15445                                     const NamedDecl *ND) {
15446   if (Size != 1 || !ND) return false;
15447 
15448   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15449   if (!FD) return false;
15450 
15451   // Don't consider sizes resulting from macro expansions or template argument
15452   // substitution to form C89 tail-padded arrays.
15453 
15454   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15455   while (TInfo) {
15456     TypeLoc TL = TInfo->getTypeLoc();
15457     // Look through typedefs.
15458     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15459       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15460       TInfo = TDL->getTypeSourceInfo();
15461       continue;
15462     }
15463     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15464       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15465       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15466         return false;
15467     }
15468     break;
15469   }
15470 
15471   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15472   if (!RD) return false;
15473   if (RD->isUnion()) return false;
15474   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15475     if (!CRD->isStandardLayout()) return false;
15476   }
15477 
15478   // See if this is the last field decl in the record.
15479   const Decl *D = FD;
15480   while ((D = D->getNextDeclInContext()))
15481     if (isa<FieldDecl>(D))
15482       return false;
15483   return true;
15484 }
15485 
15486 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15487                             const ArraySubscriptExpr *ASE,
15488                             bool AllowOnePastEnd, bool IndexNegated) {
15489   // Already diagnosed by the constant evaluator.
15490   if (isConstantEvaluated())
15491     return;
15492 
15493   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15494   if (IndexExpr->isValueDependent())
15495     return;
15496 
15497   const Type *EffectiveType =
15498       BaseExpr->getType()->getPointeeOrArrayElementType();
15499   BaseExpr = BaseExpr->IgnoreParenCasts();
15500   const ConstantArrayType *ArrayTy =
15501       Context.getAsConstantArrayType(BaseExpr->getType());
15502 
15503   const Type *BaseType =
15504       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15505   bool IsUnboundedArray = (BaseType == nullptr);
15506   if (EffectiveType->isDependentType() ||
15507       (!IsUnboundedArray && BaseType->isDependentType()))
15508     return;
15509 
15510   Expr::EvalResult Result;
15511   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15512     return;
15513 
15514   llvm::APSInt index = Result.Val.getInt();
15515   if (IndexNegated) {
15516     index.setIsUnsigned(false);
15517     index = -index;
15518   }
15519 
15520   const NamedDecl *ND = nullptr;
15521   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15522     ND = DRE->getDecl();
15523   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15524     ND = ME->getMemberDecl();
15525 
15526   if (IsUnboundedArray) {
15527     if (EffectiveType->isFunctionType())
15528       return;
15529     if (index.isUnsigned() || !index.isNegative()) {
15530       const auto &ASTC = getASTContext();
15531       unsigned AddrBits =
15532           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15533               EffectiveType->getCanonicalTypeInternal()));
15534       if (index.getBitWidth() < AddrBits)
15535         index = index.zext(AddrBits);
15536       Optional<CharUnits> ElemCharUnits =
15537           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15538       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15539       // pointer) bounds-checking isn't meaningful.
15540       if (!ElemCharUnits)
15541         return;
15542       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15543       // If index has more active bits than address space, we already know
15544       // we have a bounds violation to warn about.  Otherwise, compute
15545       // address of (index + 1)th element, and warn about bounds violation
15546       // only if that address exceeds address space.
15547       if (index.getActiveBits() <= AddrBits) {
15548         bool Overflow;
15549         llvm::APInt Product(index);
15550         Product += 1;
15551         Product = Product.umul_ov(ElemBytes, Overflow);
15552         if (!Overflow && Product.getActiveBits() <= AddrBits)
15553           return;
15554       }
15555 
15556       // Need to compute max possible elements in address space, since that
15557       // is included in diag message.
15558       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15559       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15560       MaxElems += 1;
15561       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15562       MaxElems = MaxElems.udiv(ElemBytes);
15563 
15564       unsigned DiagID =
15565           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15566               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15567 
15568       // Diag message shows element size in bits and in "bytes" (platform-
15569       // dependent CharUnits)
15570       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15571                           PDiag(DiagID)
15572                               << toString(index, 10, true) << AddrBits
15573                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15574                               << toString(ElemBytes, 10, false)
15575                               << toString(MaxElems, 10, false)
15576                               << (unsigned)MaxElems.getLimitedValue(~0U)
15577                               << IndexExpr->getSourceRange());
15578 
15579       if (!ND) {
15580         // Try harder to find a NamedDecl to point at in the note.
15581         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15582           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15583         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15584           ND = DRE->getDecl();
15585         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15586           ND = ME->getMemberDecl();
15587       }
15588 
15589       if (ND)
15590         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15591                             PDiag(diag::note_array_declared_here) << ND);
15592     }
15593     return;
15594   }
15595 
15596   if (index.isUnsigned() || !index.isNegative()) {
15597     // It is possible that the type of the base expression after
15598     // IgnoreParenCasts is incomplete, even though the type of the base
15599     // expression before IgnoreParenCasts is complete (see PR39746 for an
15600     // example). In this case we have no information about whether the array
15601     // access exceeds the array bounds. However we can still diagnose an array
15602     // access which precedes the array bounds.
15603     if (BaseType->isIncompleteType())
15604       return;
15605 
15606     llvm::APInt size = ArrayTy->getSize();
15607     if (!size.isStrictlyPositive())
15608       return;
15609 
15610     if (BaseType != EffectiveType) {
15611       // Make sure we're comparing apples to apples when comparing index to size
15612       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15613       uint64_t array_typesize = Context.getTypeSize(BaseType);
15614       // Handle ptrarith_typesize being zero, such as when casting to void*
15615       if (!ptrarith_typesize) ptrarith_typesize = 1;
15616       if (ptrarith_typesize != array_typesize) {
15617         // There's a cast to a different size type involved
15618         uint64_t ratio = array_typesize / ptrarith_typesize;
15619         // TODO: Be smarter about handling cases where array_typesize is not a
15620         // multiple of ptrarith_typesize
15621         if (ptrarith_typesize * ratio == array_typesize)
15622           size *= llvm::APInt(size.getBitWidth(), ratio);
15623       }
15624     }
15625 
15626     if (size.getBitWidth() > index.getBitWidth())
15627       index = index.zext(size.getBitWidth());
15628     else if (size.getBitWidth() < index.getBitWidth())
15629       size = size.zext(index.getBitWidth());
15630 
15631     // For array subscripting the index must be less than size, but for pointer
15632     // arithmetic also allow the index (offset) to be equal to size since
15633     // computing the next address after the end of the array is legal and
15634     // commonly done e.g. in C++ iterators and range-based for loops.
15635     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15636       return;
15637 
15638     // Also don't warn for arrays of size 1 which are members of some
15639     // structure. These are often used to approximate flexible arrays in C89
15640     // code.
15641     if (IsTailPaddedMemberArray(*this, size, ND))
15642       return;
15643 
15644     // Suppress the warning if the subscript expression (as identified by the
15645     // ']' location) and the index expression are both from macro expansions
15646     // within a system header.
15647     if (ASE) {
15648       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15649           ASE->getRBracketLoc());
15650       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15651         SourceLocation IndexLoc =
15652             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15653         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15654           return;
15655       }
15656     }
15657 
15658     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15659                           : diag::warn_ptr_arith_exceeds_bounds;
15660 
15661     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15662                         PDiag(DiagID) << toString(index, 10, true)
15663                                       << toString(size, 10, true)
15664                                       << (unsigned)size.getLimitedValue(~0U)
15665                                       << IndexExpr->getSourceRange());
15666   } else {
15667     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15668     if (!ASE) {
15669       DiagID = diag::warn_ptr_arith_precedes_bounds;
15670       if (index.isNegative()) index = -index;
15671     }
15672 
15673     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15674                         PDiag(DiagID) << toString(index, 10, true)
15675                                       << IndexExpr->getSourceRange());
15676   }
15677 
15678   if (!ND) {
15679     // Try harder to find a NamedDecl to point at in the note.
15680     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15681       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15682     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15683       ND = DRE->getDecl();
15684     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15685       ND = ME->getMemberDecl();
15686   }
15687 
15688   if (ND)
15689     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15690                         PDiag(diag::note_array_declared_here) << ND);
15691 }
15692 
15693 void Sema::CheckArrayAccess(const Expr *expr) {
15694   int AllowOnePastEnd = 0;
15695   while (expr) {
15696     expr = expr->IgnoreParenImpCasts();
15697     switch (expr->getStmtClass()) {
15698       case Stmt::ArraySubscriptExprClass: {
15699         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15700         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15701                          AllowOnePastEnd > 0);
15702         expr = ASE->getBase();
15703         break;
15704       }
15705       case Stmt::MemberExprClass: {
15706         expr = cast<MemberExpr>(expr)->getBase();
15707         break;
15708       }
15709       case Stmt::OMPArraySectionExprClass: {
15710         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15711         if (ASE->getLowerBound())
15712           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15713                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15714         return;
15715       }
15716       case Stmt::UnaryOperatorClass: {
15717         // Only unwrap the * and & unary operators
15718         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15719         expr = UO->getSubExpr();
15720         switch (UO->getOpcode()) {
15721           case UO_AddrOf:
15722             AllowOnePastEnd++;
15723             break;
15724           case UO_Deref:
15725             AllowOnePastEnd--;
15726             break;
15727           default:
15728             return;
15729         }
15730         break;
15731       }
15732       case Stmt::ConditionalOperatorClass: {
15733         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15734         if (const Expr *lhs = cond->getLHS())
15735           CheckArrayAccess(lhs);
15736         if (const Expr *rhs = cond->getRHS())
15737           CheckArrayAccess(rhs);
15738         return;
15739       }
15740       case Stmt::CXXOperatorCallExprClass: {
15741         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15742         for (const auto *Arg : OCE->arguments())
15743           CheckArrayAccess(Arg);
15744         return;
15745       }
15746       default:
15747         return;
15748     }
15749   }
15750 }
15751 
15752 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15753 
15754 namespace {
15755 
15756 struct RetainCycleOwner {
15757   VarDecl *Variable = nullptr;
15758   SourceRange Range;
15759   SourceLocation Loc;
15760   bool Indirect = false;
15761 
15762   RetainCycleOwner() = default;
15763 
15764   void setLocsFrom(Expr *e) {
15765     Loc = e->getExprLoc();
15766     Range = e->getSourceRange();
15767   }
15768 };
15769 
15770 } // namespace
15771 
15772 /// Consider whether capturing the given variable can possibly lead to
15773 /// a retain cycle.
15774 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15775   // In ARC, it's captured strongly iff the variable has __strong
15776   // lifetime.  In MRR, it's captured strongly if the variable is
15777   // __block and has an appropriate type.
15778   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15779     return false;
15780 
15781   owner.Variable = var;
15782   if (ref)
15783     owner.setLocsFrom(ref);
15784   return true;
15785 }
15786 
15787 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15788   while (true) {
15789     e = e->IgnoreParens();
15790     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15791       switch (cast->getCastKind()) {
15792       case CK_BitCast:
15793       case CK_LValueBitCast:
15794       case CK_LValueToRValue:
15795       case CK_ARCReclaimReturnedObject:
15796         e = cast->getSubExpr();
15797         continue;
15798 
15799       default:
15800         return false;
15801       }
15802     }
15803 
15804     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15805       ObjCIvarDecl *ivar = ref->getDecl();
15806       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15807         return false;
15808 
15809       // Try to find a retain cycle in the base.
15810       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15811         return false;
15812 
15813       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15814       owner.Indirect = true;
15815       return true;
15816     }
15817 
15818     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15819       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15820       if (!var) return false;
15821       return considerVariable(var, ref, owner);
15822     }
15823 
15824     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15825       if (member->isArrow()) return false;
15826 
15827       // Don't count this as an indirect ownership.
15828       e = member->getBase();
15829       continue;
15830     }
15831 
15832     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15833       // Only pay attention to pseudo-objects on property references.
15834       ObjCPropertyRefExpr *pre
15835         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15836                                               ->IgnoreParens());
15837       if (!pre) return false;
15838       if (pre->isImplicitProperty()) return false;
15839       ObjCPropertyDecl *property = pre->getExplicitProperty();
15840       if (!property->isRetaining() &&
15841           !(property->getPropertyIvarDecl() &&
15842             property->getPropertyIvarDecl()->getType()
15843               .getObjCLifetime() == Qualifiers::OCL_Strong))
15844           return false;
15845 
15846       owner.Indirect = true;
15847       if (pre->isSuperReceiver()) {
15848         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15849         if (!owner.Variable)
15850           return false;
15851         owner.Loc = pre->getLocation();
15852         owner.Range = pre->getSourceRange();
15853         return true;
15854       }
15855       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15856                               ->getSourceExpr());
15857       continue;
15858     }
15859 
15860     // Array ivars?
15861 
15862     return false;
15863   }
15864 }
15865 
15866 namespace {
15867 
15868   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15869     ASTContext &Context;
15870     VarDecl *Variable;
15871     Expr *Capturer = nullptr;
15872     bool VarWillBeReased = false;
15873 
15874     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15875         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15876           Context(Context), Variable(variable) {}
15877 
15878     void VisitDeclRefExpr(DeclRefExpr *ref) {
15879       if (ref->getDecl() == Variable && !Capturer)
15880         Capturer = ref;
15881     }
15882 
15883     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15884       if (Capturer) return;
15885       Visit(ref->getBase());
15886       if (Capturer && ref->isFreeIvar())
15887         Capturer = ref;
15888     }
15889 
15890     void VisitBlockExpr(BlockExpr *block) {
15891       // Look inside nested blocks
15892       if (block->getBlockDecl()->capturesVariable(Variable))
15893         Visit(block->getBlockDecl()->getBody());
15894     }
15895 
15896     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15897       if (Capturer) return;
15898       if (OVE->getSourceExpr())
15899         Visit(OVE->getSourceExpr());
15900     }
15901 
15902     void VisitBinaryOperator(BinaryOperator *BinOp) {
15903       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15904         return;
15905       Expr *LHS = BinOp->getLHS();
15906       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15907         if (DRE->getDecl() != Variable)
15908           return;
15909         if (Expr *RHS = BinOp->getRHS()) {
15910           RHS = RHS->IgnoreParenCasts();
15911           Optional<llvm::APSInt> Value;
15912           VarWillBeReased =
15913               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15914                *Value == 0);
15915         }
15916       }
15917     }
15918   };
15919 
15920 } // namespace
15921 
15922 /// Check whether the given argument is a block which captures a
15923 /// variable.
15924 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15925   assert(owner.Variable && owner.Loc.isValid());
15926 
15927   e = e->IgnoreParenCasts();
15928 
15929   // Look through [^{...} copy] and Block_copy(^{...}).
15930   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15931     Selector Cmd = ME->getSelector();
15932     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15933       e = ME->getInstanceReceiver();
15934       if (!e)
15935         return nullptr;
15936       e = e->IgnoreParenCasts();
15937     }
15938   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15939     if (CE->getNumArgs() == 1) {
15940       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15941       if (Fn) {
15942         const IdentifierInfo *FnI = Fn->getIdentifier();
15943         if (FnI && FnI->isStr("_Block_copy")) {
15944           e = CE->getArg(0)->IgnoreParenCasts();
15945         }
15946       }
15947     }
15948   }
15949 
15950   BlockExpr *block = dyn_cast<BlockExpr>(e);
15951   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15952     return nullptr;
15953 
15954   FindCaptureVisitor visitor(S.Context, owner.Variable);
15955   visitor.Visit(block->getBlockDecl()->getBody());
15956   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15957 }
15958 
15959 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15960                                 RetainCycleOwner &owner) {
15961   assert(capturer);
15962   assert(owner.Variable && owner.Loc.isValid());
15963 
15964   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15965     << owner.Variable << capturer->getSourceRange();
15966   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15967     << owner.Indirect << owner.Range;
15968 }
15969 
15970 /// Check for a keyword selector that starts with the word 'add' or
15971 /// 'set'.
15972 static bool isSetterLikeSelector(Selector sel) {
15973   if (sel.isUnarySelector()) return false;
15974 
15975   StringRef str = sel.getNameForSlot(0);
15976   while (!str.empty() && str.front() == '_') str = str.substr(1);
15977   if (str.startswith("set"))
15978     str = str.substr(3);
15979   else if (str.startswith("add")) {
15980     // Specially allow 'addOperationWithBlock:'.
15981     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15982       return false;
15983     str = str.substr(3);
15984   }
15985   else
15986     return false;
15987 
15988   if (str.empty()) return true;
15989   return !isLowercase(str.front());
15990 }
15991 
15992 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15993                                                     ObjCMessageExpr *Message) {
15994   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15995                                                 Message->getReceiverInterface(),
15996                                                 NSAPI::ClassId_NSMutableArray);
15997   if (!IsMutableArray) {
15998     return None;
15999   }
16000 
16001   Selector Sel = Message->getSelector();
16002 
16003   Optional<NSAPI::NSArrayMethodKind> MKOpt =
16004     S.NSAPIObj->getNSArrayMethodKind(Sel);
16005   if (!MKOpt) {
16006     return None;
16007   }
16008 
16009   NSAPI::NSArrayMethodKind MK = *MKOpt;
16010 
16011   switch (MK) {
16012     case NSAPI::NSMutableArr_addObject:
16013     case NSAPI::NSMutableArr_insertObjectAtIndex:
16014     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
16015       return 0;
16016     case NSAPI::NSMutableArr_replaceObjectAtIndex:
16017       return 1;
16018 
16019     default:
16020       return None;
16021   }
16022 
16023   return None;
16024 }
16025 
16026 static
16027 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
16028                                                   ObjCMessageExpr *Message) {
16029   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
16030                                             Message->getReceiverInterface(),
16031                                             NSAPI::ClassId_NSMutableDictionary);
16032   if (!IsMutableDictionary) {
16033     return None;
16034   }
16035 
16036   Selector Sel = Message->getSelector();
16037 
16038   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
16039     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
16040   if (!MKOpt) {
16041     return None;
16042   }
16043 
16044   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
16045 
16046   switch (MK) {
16047     case NSAPI::NSMutableDict_setObjectForKey:
16048     case NSAPI::NSMutableDict_setValueForKey:
16049     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
16050       return 0;
16051 
16052     default:
16053       return None;
16054   }
16055 
16056   return None;
16057 }
16058 
16059 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
16060   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
16061                                                 Message->getReceiverInterface(),
16062                                                 NSAPI::ClassId_NSMutableSet);
16063 
16064   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
16065                                             Message->getReceiverInterface(),
16066                                             NSAPI::ClassId_NSMutableOrderedSet);
16067   if (!IsMutableSet && !IsMutableOrderedSet) {
16068     return None;
16069   }
16070 
16071   Selector Sel = Message->getSelector();
16072 
16073   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
16074   if (!MKOpt) {
16075     return None;
16076   }
16077 
16078   NSAPI::NSSetMethodKind MK = *MKOpt;
16079 
16080   switch (MK) {
16081     case NSAPI::NSMutableSet_addObject:
16082     case NSAPI::NSOrderedSet_setObjectAtIndex:
16083     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
16084     case NSAPI::NSOrderedSet_insertObjectAtIndex:
16085       return 0;
16086     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
16087       return 1;
16088   }
16089 
16090   return None;
16091 }
16092 
16093 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
16094   if (!Message->isInstanceMessage()) {
16095     return;
16096   }
16097 
16098   Optional<int> ArgOpt;
16099 
16100   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
16101       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
16102       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
16103     return;
16104   }
16105 
16106   int ArgIndex = *ArgOpt;
16107 
16108   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
16109   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
16110     Arg = OE->getSourceExpr()->IgnoreImpCasts();
16111   }
16112 
16113   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
16114     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16115       if (ArgRE->isObjCSelfExpr()) {
16116         Diag(Message->getSourceRange().getBegin(),
16117              diag::warn_objc_circular_container)
16118           << ArgRE->getDecl() << StringRef("'super'");
16119       }
16120     }
16121   } else {
16122     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
16123 
16124     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
16125       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
16126     }
16127 
16128     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
16129       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16130         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
16131           ValueDecl *Decl = ReceiverRE->getDecl();
16132           Diag(Message->getSourceRange().getBegin(),
16133                diag::warn_objc_circular_container)
16134             << Decl << Decl;
16135           if (!ArgRE->isObjCSelfExpr()) {
16136             Diag(Decl->getLocation(),
16137                  diag::note_objc_circular_container_declared_here)
16138               << Decl;
16139           }
16140         }
16141       }
16142     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
16143       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
16144         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
16145           ObjCIvarDecl *Decl = IvarRE->getDecl();
16146           Diag(Message->getSourceRange().getBegin(),
16147                diag::warn_objc_circular_container)
16148             << Decl << Decl;
16149           Diag(Decl->getLocation(),
16150                diag::note_objc_circular_container_declared_here)
16151             << Decl;
16152         }
16153       }
16154     }
16155   }
16156 }
16157 
16158 /// Check a message send to see if it's likely to cause a retain cycle.
16159 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
16160   // Only check instance methods whose selector looks like a setter.
16161   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
16162     return;
16163 
16164   // Try to find a variable that the receiver is strongly owned by.
16165   RetainCycleOwner owner;
16166   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
16167     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16168       return;
16169   } else {
16170     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16171     owner.Variable = getCurMethodDecl()->getSelfDecl();
16172     owner.Loc = msg->getSuperLoc();
16173     owner.Range = msg->getSuperLoc();
16174   }
16175 
16176   // Check whether the receiver is captured by any of the arguments.
16177   const ObjCMethodDecl *MD = msg->getMethodDecl();
16178   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16179     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16180       // noescape blocks should not be retained by the method.
16181       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16182         continue;
16183       return diagnoseRetainCycle(*this, capturer, owner);
16184     }
16185   }
16186 }
16187 
16188 /// Check a property assign to see if it's likely to cause a retain cycle.
16189 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16190   RetainCycleOwner owner;
16191   if (!findRetainCycleOwner(*this, receiver, owner))
16192     return;
16193 
16194   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16195     diagnoseRetainCycle(*this, capturer, owner);
16196 }
16197 
16198 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16199   RetainCycleOwner Owner;
16200   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16201     return;
16202 
16203   // Because we don't have an expression for the variable, we have to set the
16204   // location explicitly here.
16205   Owner.Loc = Var->getLocation();
16206   Owner.Range = Var->getSourceRange();
16207 
16208   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16209     diagnoseRetainCycle(*this, Capturer, Owner);
16210 }
16211 
16212 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16213                                      Expr *RHS, bool isProperty) {
16214   // Check if RHS is an Objective-C object literal, which also can get
16215   // immediately zapped in a weak reference.  Note that we explicitly
16216   // allow ObjCStringLiterals, since those are designed to never really die.
16217   RHS = RHS->IgnoreParenImpCasts();
16218 
16219   // This enum needs to match with the 'select' in
16220   // warn_objc_arc_literal_assign (off-by-1).
16221   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16222   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16223     return false;
16224 
16225   S.Diag(Loc, diag::warn_arc_literal_assign)
16226     << (unsigned) Kind
16227     << (isProperty ? 0 : 1)
16228     << RHS->getSourceRange();
16229 
16230   return true;
16231 }
16232 
16233 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16234                                     Qualifiers::ObjCLifetime LT,
16235                                     Expr *RHS, bool isProperty) {
16236   // Strip off any implicit cast added to get to the one ARC-specific.
16237   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16238     if (cast->getCastKind() == CK_ARCConsumeObject) {
16239       S.Diag(Loc, diag::warn_arc_retained_assign)
16240         << (LT == Qualifiers::OCL_ExplicitNone)
16241         << (isProperty ? 0 : 1)
16242         << RHS->getSourceRange();
16243       return true;
16244     }
16245     RHS = cast->getSubExpr();
16246   }
16247 
16248   if (LT == Qualifiers::OCL_Weak &&
16249       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16250     return true;
16251 
16252   return false;
16253 }
16254 
16255 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16256                               QualType LHS, Expr *RHS) {
16257   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16258 
16259   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16260     return false;
16261 
16262   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16263     return true;
16264 
16265   return false;
16266 }
16267 
16268 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16269                               Expr *LHS, Expr *RHS) {
16270   QualType LHSType;
16271   // PropertyRef on LHS type need be directly obtained from
16272   // its declaration as it has a PseudoType.
16273   ObjCPropertyRefExpr *PRE
16274     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16275   if (PRE && !PRE->isImplicitProperty()) {
16276     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16277     if (PD)
16278       LHSType = PD->getType();
16279   }
16280 
16281   if (LHSType.isNull())
16282     LHSType = LHS->getType();
16283 
16284   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16285 
16286   if (LT == Qualifiers::OCL_Weak) {
16287     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16288       getCurFunction()->markSafeWeakUse(LHS);
16289   }
16290 
16291   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16292     return;
16293 
16294   // FIXME. Check for other life times.
16295   if (LT != Qualifiers::OCL_None)
16296     return;
16297 
16298   if (PRE) {
16299     if (PRE->isImplicitProperty())
16300       return;
16301     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16302     if (!PD)
16303       return;
16304 
16305     unsigned Attributes = PD->getPropertyAttributes();
16306     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16307       // when 'assign' attribute was not explicitly specified
16308       // by user, ignore it and rely on property type itself
16309       // for lifetime info.
16310       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16311       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16312           LHSType->isObjCRetainableType())
16313         return;
16314 
16315       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16316         if (cast->getCastKind() == CK_ARCConsumeObject) {
16317           Diag(Loc, diag::warn_arc_retained_property_assign)
16318           << RHS->getSourceRange();
16319           return;
16320         }
16321         RHS = cast->getSubExpr();
16322       }
16323     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16324       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16325         return;
16326     }
16327   }
16328 }
16329 
16330 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16331 
16332 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16333                                         SourceLocation StmtLoc,
16334                                         const NullStmt *Body) {
16335   // Do not warn if the body is a macro that expands to nothing, e.g:
16336   //
16337   // #define CALL(x)
16338   // if (condition)
16339   //   CALL(0);
16340   if (Body->hasLeadingEmptyMacro())
16341     return false;
16342 
16343   // Get line numbers of statement and body.
16344   bool StmtLineInvalid;
16345   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16346                                                       &StmtLineInvalid);
16347   if (StmtLineInvalid)
16348     return false;
16349 
16350   bool BodyLineInvalid;
16351   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16352                                                       &BodyLineInvalid);
16353   if (BodyLineInvalid)
16354     return false;
16355 
16356   // Warn if null statement and body are on the same line.
16357   if (StmtLine != BodyLine)
16358     return false;
16359 
16360   return true;
16361 }
16362 
16363 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16364                                  const Stmt *Body,
16365                                  unsigned DiagID) {
16366   // Since this is a syntactic check, don't emit diagnostic for template
16367   // instantiations, this just adds noise.
16368   if (CurrentInstantiationScope)
16369     return;
16370 
16371   // The body should be a null statement.
16372   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16373   if (!NBody)
16374     return;
16375 
16376   // Do the usual checks.
16377   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16378     return;
16379 
16380   Diag(NBody->getSemiLoc(), DiagID);
16381   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16382 }
16383 
16384 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16385                                  const Stmt *PossibleBody) {
16386   assert(!CurrentInstantiationScope); // Ensured by caller
16387 
16388   SourceLocation StmtLoc;
16389   const Stmt *Body;
16390   unsigned DiagID;
16391   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16392     StmtLoc = FS->getRParenLoc();
16393     Body = FS->getBody();
16394     DiagID = diag::warn_empty_for_body;
16395   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16396     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16397     Body = WS->getBody();
16398     DiagID = diag::warn_empty_while_body;
16399   } else
16400     return; // Neither `for' nor `while'.
16401 
16402   // The body should be a null statement.
16403   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16404   if (!NBody)
16405     return;
16406 
16407   // Skip expensive checks if diagnostic is disabled.
16408   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16409     return;
16410 
16411   // Do the usual checks.
16412   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16413     return;
16414 
16415   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16416   // noise level low, emit diagnostics only if for/while is followed by a
16417   // CompoundStmt, e.g.:
16418   //    for (int i = 0; i < n; i++);
16419   //    {
16420   //      a(i);
16421   //    }
16422   // or if for/while is followed by a statement with more indentation
16423   // than for/while itself:
16424   //    for (int i = 0; i < n; i++);
16425   //      a(i);
16426   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16427   if (!ProbableTypo) {
16428     bool BodyColInvalid;
16429     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16430         PossibleBody->getBeginLoc(), &BodyColInvalid);
16431     if (BodyColInvalid)
16432       return;
16433 
16434     bool StmtColInvalid;
16435     unsigned StmtCol =
16436         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16437     if (StmtColInvalid)
16438       return;
16439 
16440     if (BodyCol > StmtCol)
16441       ProbableTypo = true;
16442   }
16443 
16444   if (ProbableTypo) {
16445     Diag(NBody->getSemiLoc(), DiagID);
16446     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16447   }
16448 }
16449 
16450 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16451 
16452 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16453 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16454                              SourceLocation OpLoc) {
16455   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16456     return;
16457 
16458   if (inTemplateInstantiation())
16459     return;
16460 
16461   // Strip parens and casts away.
16462   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16463   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16464 
16465   // Check for a call expression
16466   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16467   if (!CE || CE->getNumArgs() != 1)
16468     return;
16469 
16470   // Check for a call to std::move
16471   if (!CE->isCallToStdMove())
16472     return;
16473 
16474   // Get argument from std::move
16475   RHSExpr = CE->getArg(0);
16476 
16477   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16478   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16479 
16480   // Two DeclRefExpr's, check that the decls are the same.
16481   if (LHSDeclRef && RHSDeclRef) {
16482     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16483       return;
16484     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16485         RHSDeclRef->getDecl()->getCanonicalDecl())
16486       return;
16487 
16488     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16489                                         << LHSExpr->getSourceRange()
16490                                         << RHSExpr->getSourceRange();
16491     return;
16492   }
16493 
16494   // Member variables require a different approach to check for self moves.
16495   // MemberExpr's are the same if every nested MemberExpr refers to the same
16496   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16497   // the base Expr's are CXXThisExpr's.
16498   const Expr *LHSBase = LHSExpr;
16499   const Expr *RHSBase = RHSExpr;
16500   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16501   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16502   if (!LHSME || !RHSME)
16503     return;
16504 
16505   while (LHSME && RHSME) {
16506     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16507         RHSME->getMemberDecl()->getCanonicalDecl())
16508       return;
16509 
16510     LHSBase = LHSME->getBase();
16511     RHSBase = RHSME->getBase();
16512     LHSME = dyn_cast<MemberExpr>(LHSBase);
16513     RHSME = dyn_cast<MemberExpr>(RHSBase);
16514   }
16515 
16516   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16517   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16518   if (LHSDeclRef && RHSDeclRef) {
16519     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16520       return;
16521     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16522         RHSDeclRef->getDecl()->getCanonicalDecl())
16523       return;
16524 
16525     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16526                                         << LHSExpr->getSourceRange()
16527                                         << RHSExpr->getSourceRange();
16528     return;
16529   }
16530 
16531   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16532     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16533                                         << LHSExpr->getSourceRange()
16534                                         << RHSExpr->getSourceRange();
16535 }
16536 
16537 //===--- Layout compatibility ----------------------------------------------//
16538 
16539 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16540 
16541 /// Check if two enumeration types are layout-compatible.
16542 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16543   // C++11 [dcl.enum] p8:
16544   // Two enumeration types are layout-compatible if they have the same
16545   // underlying type.
16546   return ED1->isComplete() && ED2->isComplete() &&
16547          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16548 }
16549 
16550 /// Check if two fields are layout-compatible.
16551 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16552                                FieldDecl *Field2) {
16553   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16554     return false;
16555 
16556   if (Field1->isBitField() != Field2->isBitField())
16557     return false;
16558 
16559   if (Field1->isBitField()) {
16560     // Make sure that the bit-fields are the same length.
16561     unsigned Bits1 = Field1->getBitWidthValue(C);
16562     unsigned Bits2 = Field2->getBitWidthValue(C);
16563 
16564     if (Bits1 != Bits2)
16565       return false;
16566   }
16567 
16568   return true;
16569 }
16570 
16571 /// Check if two standard-layout structs are layout-compatible.
16572 /// (C++11 [class.mem] p17)
16573 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16574                                      RecordDecl *RD2) {
16575   // If both records are C++ classes, check that base classes match.
16576   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16577     // If one of records is a CXXRecordDecl we are in C++ mode,
16578     // thus the other one is a CXXRecordDecl, too.
16579     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16580     // Check number of base classes.
16581     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16582       return false;
16583 
16584     // Check the base classes.
16585     for (CXXRecordDecl::base_class_const_iterator
16586                Base1 = D1CXX->bases_begin(),
16587            BaseEnd1 = D1CXX->bases_end(),
16588               Base2 = D2CXX->bases_begin();
16589          Base1 != BaseEnd1;
16590          ++Base1, ++Base2) {
16591       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16592         return false;
16593     }
16594   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16595     // If only RD2 is a C++ class, it should have zero base classes.
16596     if (D2CXX->getNumBases() > 0)
16597       return false;
16598   }
16599 
16600   // Check the fields.
16601   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16602                              Field2End = RD2->field_end(),
16603                              Field1 = RD1->field_begin(),
16604                              Field1End = RD1->field_end();
16605   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16606     if (!isLayoutCompatible(C, *Field1, *Field2))
16607       return false;
16608   }
16609   if (Field1 != Field1End || Field2 != Field2End)
16610     return false;
16611 
16612   return true;
16613 }
16614 
16615 /// Check if two standard-layout unions are layout-compatible.
16616 /// (C++11 [class.mem] p18)
16617 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16618                                     RecordDecl *RD2) {
16619   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16620   for (auto *Field2 : RD2->fields())
16621     UnmatchedFields.insert(Field2);
16622 
16623   for (auto *Field1 : RD1->fields()) {
16624     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16625         I = UnmatchedFields.begin(),
16626         E = UnmatchedFields.end();
16627 
16628     for ( ; I != E; ++I) {
16629       if (isLayoutCompatible(C, Field1, *I)) {
16630         bool Result = UnmatchedFields.erase(*I);
16631         (void) Result;
16632         assert(Result);
16633         break;
16634       }
16635     }
16636     if (I == E)
16637       return false;
16638   }
16639 
16640   return UnmatchedFields.empty();
16641 }
16642 
16643 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16644                                RecordDecl *RD2) {
16645   if (RD1->isUnion() != RD2->isUnion())
16646     return false;
16647 
16648   if (RD1->isUnion())
16649     return isLayoutCompatibleUnion(C, RD1, RD2);
16650   else
16651     return isLayoutCompatibleStruct(C, RD1, RD2);
16652 }
16653 
16654 /// Check if two types are layout-compatible in C++11 sense.
16655 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16656   if (T1.isNull() || T2.isNull())
16657     return false;
16658 
16659   // C++11 [basic.types] p11:
16660   // If two types T1 and T2 are the same type, then T1 and T2 are
16661   // layout-compatible types.
16662   if (C.hasSameType(T1, T2))
16663     return true;
16664 
16665   T1 = T1.getCanonicalType().getUnqualifiedType();
16666   T2 = T2.getCanonicalType().getUnqualifiedType();
16667 
16668   const Type::TypeClass TC1 = T1->getTypeClass();
16669   const Type::TypeClass TC2 = T2->getTypeClass();
16670 
16671   if (TC1 != TC2)
16672     return false;
16673 
16674   if (TC1 == Type::Enum) {
16675     return isLayoutCompatible(C,
16676                               cast<EnumType>(T1)->getDecl(),
16677                               cast<EnumType>(T2)->getDecl());
16678   } else if (TC1 == Type::Record) {
16679     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16680       return false;
16681 
16682     return isLayoutCompatible(C,
16683                               cast<RecordType>(T1)->getDecl(),
16684                               cast<RecordType>(T2)->getDecl());
16685   }
16686 
16687   return false;
16688 }
16689 
16690 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16691 
16692 /// Given a type tag expression find the type tag itself.
16693 ///
16694 /// \param TypeExpr Type tag expression, as it appears in user's code.
16695 ///
16696 /// \param VD Declaration of an identifier that appears in a type tag.
16697 ///
16698 /// \param MagicValue Type tag magic value.
16699 ///
16700 /// \param isConstantEvaluated whether the evalaution should be performed in
16701 
16702 /// constant context.
16703 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16704                             const ValueDecl **VD, uint64_t *MagicValue,
16705                             bool isConstantEvaluated) {
16706   while(true) {
16707     if (!TypeExpr)
16708       return false;
16709 
16710     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16711 
16712     switch (TypeExpr->getStmtClass()) {
16713     case Stmt::UnaryOperatorClass: {
16714       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16715       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16716         TypeExpr = UO->getSubExpr();
16717         continue;
16718       }
16719       return false;
16720     }
16721 
16722     case Stmt::DeclRefExprClass: {
16723       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16724       *VD = DRE->getDecl();
16725       return true;
16726     }
16727 
16728     case Stmt::IntegerLiteralClass: {
16729       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16730       llvm::APInt MagicValueAPInt = IL->getValue();
16731       if (MagicValueAPInt.getActiveBits() <= 64) {
16732         *MagicValue = MagicValueAPInt.getZExtValue();
16733         return true;
16734       } else
16735         return false;
16736     }
16737 
16738     case Stmt::BinaryConditionalOperatorClass:
16739     case Stmt::ConditionalOperatorClass: {
16740       const AbstractConditionalOperator *ACO =
16741           cast<AbstractConditionalOperator>(TypeExpr);
16742       bool Result;
16743       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16744                                                      isConstantEvaluated)) {
16745         if (Result)
16746           TypeExpr = ACO->getTrueExpr();
16747         else
16748           TypeExpr = ACO->getFalseExpr();
16749         continue;
16750       }
16751       return false;
16752     }
16753 
16754     case Stmt::BinaryOperatorClass: {
16755       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16756       if (BO->getOpcode() == BO_Comma) {
16757         TypeExpr = BO->getRHS();
16758         continue;
16759       }
16760       return false;
16761     }
16762 
16763     default:
16764       return false;
16765     }
16766   }
16767 }
16768 
16769 /// Retrieve the C type corresponding to type tag TypeExpr.
16770 ///
16771 /// \param TypeExpr Expression that specifies a type tag.
16772 ///
16773 /// \param MagicValues Registered magic values.
16774 ///
16775 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16776 ///        kind.
16777 ///
16778 /// \param TypeInfo Information about the corresponding C type.
16779 ///
16780 /// \param isConstantEvaluated whether the evalaution should be performed in
16781 /// constant context.
16782 ///
16783 /// \returns true if the corresponding C type was found.
16784 static bool GetMatchingCType(
16785     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16786     const ASTContext &Ctx,
16787     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16788         *MagicValues,
16789     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16790     bool isConstantEvaluated) {
16791   FoundWrongKind = false;
16792 
16793   // Variable declaration that has type_tag_for_datatype attribute.
16794   const ValueDecl *VD = nullptr;
16795 
16796   uint64_t MagicValue;
16797 
16798   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16799     return false;
16800 
16801   if (VD) {
16802     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16803       if (I->getArgumentKind() != ArgumentKind) {
16804         FoundWrongKind = true;
16805         return false;
16806       }
16807       TypeInfo.Type = I->getMatchingCType();
16808       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16809       TypeInfo.MustBeNull = I->getMustBeNull();
16810       return true;
16811     }
16812     return false;
16813   }
16814 
16815   if (!MagicValues)
16816     return false;
16817 
16818   llvm::DenseMap<Sema::TypeTagMagicValue,
16819                  Sema::TypeTagData>::const_iterator I =
16820       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16821   if (I == MagicValues->end())
16822     return false;
16823 
16824   TypeInfo = I->second;
16825   return true;
16826 }
16827 
16828 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16829                                       uint64_t MagicValue, QualType Type,
16830                                       bool LayoutCompatible,
16831                                       bool MustBeNull) {
16832   if (!TypeTagForDatatypeMagicValues)
16833     TypeTagForDatatypeMagicValues.reset(
16834         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16835 
16836   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16837   (*TypeTagForDatatypeMagicValues)[Magic] =
16838       TypeTagData(Type, LayoutCompatible, MustBeNull);
16839 }
16840 
16841 static bool IsSameCharType(QualType T1, QualType T2) {
16842   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16843   if (!BT1)
16844     return false;
16845 
16846   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16847   if (!BT2)
16848     return false;
16849 
16850   BuiltinType::Kind T1Kind = BT1->getKind();
16851   BuiltinType::Kind T2Kind = BT2->getKind();
16852 
16853   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16854          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16855          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16856          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16857 }
16858 
16859 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16860                                     const ArrayRef<const Expr *> ExprArgs,
16861                                     SourceLocation CallSiteLoc) {
16862   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16863   bool IsPointerAttr = Attr->getIsPointer();
16864 
16865   // Retrieve the argument representing the 'type_tag'.
16866   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16867   if (TypeTagIdxAST >= ExprArgs.size()) {
16868     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16869         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16870     return;
16871   }
16872   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16873   bool FoundWrongKind;
16874   TypeTagData TypeInfo;
16875   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16876                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16877                         TypeInfo, isConstantEvaluated())) {
16878     if (FoundWrongKind)
16879       Diag(TypeTagExpr->getExprLoc(),
16880            diag::warn_type_tag_for_datatype_wrong_kind)
16881         << TypeTagExpr->getSourceRange();
16882     return;
16883   }
16884 
16885   // Retrieve the argument representing the 'arg_idx'.
16886   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16887   if (ArgumentIdxAST >= ExprArgs.size()) {
16888     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16889         << 1 << Attr->getArgumentIdx().getSourceIndex();
16890     return;
16891   }
16892   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16893   if (IsPointerAttr) {
16894     // Skip implicit cast of pointer to `void *' (as a function argument).
16895     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16896       if (ICE->getType()->isVoidPointerType() &&
16897           ICE->getCastKind() == CK_BitCast)
16898         ArgumentExpr = ICE->getSubExpr();
16899   }
16900   QualType ArgumentType = ArgumentExpr->getType();
16901 
16902   // Passing a `void*' pointer shouldn't trigger a warning.
16903   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16904     return;
16905 
16906   if (TypeInfo.MustBeNull) {
16907     // Type tag with matching void type requires a null pointer.
16908     if (!ArgumentExpr->isNullPointerConstant(Context,
16909                                              Expr::NPC_ValueDependentIsNotNull)) {
16910       Diag(ArgumentExpr->getExprLoc(),
16911            diag::warn_type_safety_null_pointer_required)
16912           << ArgumentKind->getName()
16913           << ArgumentExpr->getSourceRange()
16914           << TypeTagExpr->getSourceRange();
16915     }
16916     return;
16917   }
16918 
16919   QualType RequiredType = TypeInfo.Type;
16920   if (IsPointerAttr)
16921     RequiredType = Context.getPointerType(RequiredType);
16922 
16923   bool mismatch = false;
16924   if (!TypeInfo.LayoutCompatible) {
16925     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16926 
16927     // C++11 [basic.fundamental] p1:
16928     // Plain char, signed char, and unsigned char are three distinct types.
16929     //
16930     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16931     // char' depending on the current char signedness mode.
16932     if (mismatch)
16933       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16934                                            RequiredType->getPointeeType())) ||
16935           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16936         mismatch = false;
16937   } else
16938     if (IsPointerAttr)
16939       mismatch = !isLayoutCompatible(Context,
16940                                      ArgumentType->getPointeeType(),
16941                                      RequiredType->getPointeeType());
16942     else
16943       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16944 
16945   if (mismatch)
16946     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16947         << ArgumentType << ArgumentKind
16948         << TypeInfo.LayoutCompatible << RequiredType
16949         << ArgumentExpr->getSourceRange()
16950         << TypeTagExpr->getSourceRange();
16951 }
16952 
16953 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16954                                          CharUnits Alignment) {
16955   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16956 }
16957 
16958 void Sema::DiagnoseMisalignedMembers() {
16959   for (MisalignedMember &m : MisalignedMembers) {
16960     const NamedDecl *ND = m.RD;
16961     if (ND->getName().empty()) {
16962       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16963         ND = TD;
16964     }
16965     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16966         << m.MD << ND << m.E->getSourceRange();
16967   }
16968   MisalignedMembers.clear();
16969 }
16970 
16971 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16972   E = E->IgnoreParens();
16973   if (!T->isPointerType() && !T->isIntegerType())
16974     return;
16975   if (isa<UnaryOperator>(E) &&
16976       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16977     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16978     if (isa<MemberExpr>(Op)) {
16979       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16980       if (MA != MisalignedMembers.end() &&
16981           (T->isIntegerType() ||
16982            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16983                                    Context.getTypeAlignInChars(
16984                                        T->getPointeeType()) <= MA->Alignment))))
16985         MisalignedMembers.erase(MA);
16986     }
16987   }
16988 }
16989 
16990 void Sema::RefersToMemberWithReducedAlignment(
16991     Expr *E,
16992     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16993         Action) {
16994   const auto *ME = dyn_cast<MemberExpr>(E);
16995   if (!ME)
16996     return;
16997 
16998   // No need to check expressions with an __unaligned-qualified type.
16999   if (E->getType().getQualifiers().hasUnaligned())
17000     return;
17001 
17002   // For a chain of MemberExpr like "a.b.c.d" this list
17003   // will keep FieldDecl's like [d, c, b].
17004   SmallVector<FieldDecl *, 4> ReverseMemberChain;
17005   const MemberExpr *TopME = nullptr;
17006   bool AnyIsPacked = false;
17007   do {
17008     QualType BaseType = ME->getBase()->getType();
17009     if (BaseType->isDependentType())
17010       return;
17011     if (ME->isArrow())
17012       BaseType = BaseType->getPointeeType();
17013     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
17014     if (RD->isInvalidDecl())
17015       return;
17016 
17017     ValueDecl *MD = ME->getMemberDecl();
17018     auto *FD = dyn_cast<FieldDecl>(MD);
17019     // We do not care about non-data members.
17020     if (!FD || FD->isInvalidDecl())
17021       return;
17022 
17023     AnyIsPacked =
17024         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17025     ReverseMemberChain.push_back(FD);
17026 
17027     TopME = ME;
17028     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17029   } while (ME);
17030   assert(TopME && "We did not compute a topmost MemberExpr!");
17031 
17032   // Not the scope of this diagnostic.
17033   if (!AnyIsPacked)
17034     return;
17035 
17036   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17037   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17038   // TODO: The innermost base of the member expression may be too complicated.
17039   // For now, just disregard these cases. This is left for future
17040   // improvement.
17041   if (!DRE && !isa<CXXThisExpr>(TopBase))
17042       return;
17043 
17044   // Alignment expected by the whole expression.
17045   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17046 
17047   // No need to do anything else with this case.
17048   if (ExpectedAlignment.isOne())
17049     return;
17050 
17051   // Synthesize offset of the whole access.
17052   CharUnits Offset;
17053   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17054     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17055 
17056   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17057   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17058       ReverseMemberChain.back()->getParent()->getTypeForDecl());
17059 
17060   // The base expression of the innermost MemberExpr may give
17061   // stronger guarantees than the class containing the member.
17062   if (DRE && !TopME->isArrow()) {
17063     const ValueDecl *VD = DRE->getDecl();
17064     if (!VD->getType()->isReferenceType())
17065       CompleteObjectAlignment =
17066           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17067   }
17068 
17069   // Check if the synthesized offset fulfills the alignment.
17070   if (Offset % ExpectedAlignment != 0 ||
17071       // It may fulfill the offset it but the effective alignment may still be
17072       // lower than the expected expression alignment.
17073       CompleteObjectAlignment < ExpectedAlignment) {
17074     // If this happens, we want to determine a sensible culprit of this.
17075     // Intuitively, watching the chain of member expressions from right to
17076     // left, we start with the required alignment (as required by the field
17077     // type) but some packed attribute in that chain has reduced the alignment.
17078     // It may happen that another packed structure increases it again. But if
17079     // we are here such increase has not been enough. So pointing the first
17080     // FieldDecl that either is packed or else its RecordDecl is,
17081     // seems reasonable.
17082     FieldDecl *FD = nullptr;
17083     CharUnits Alignment;
17084     for (FieldDecl *FDI : ReverseMemberChain) {
17085       if (FDI->hasAttr<PackedAttr>() ||
17086           FDI->getParent()->hasAttr<PackedAttr>()) {
17087         FD = FDI;
17088         Alignment = std::min(
17089             Context.getTypeAlignInChars(FD->getType()),
17090             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
17091         break;
17092       }
17093     }
17094     assert(FD && "We did not find a packed FieldDecl!");
17095     Action(E, FD->getParent(), FD, Alignment);
17096   }
17097 }
17098 
17099 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17100   using namespace std::placeholders;
17101 
17102   RefersToMemberWithReducedAlignment(
17103       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17104                      _2, _3, _4));
17105 }
17106 
17107 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
17108 // not a valid type, emit an error message and return true. Otherwise return
17109 // false.
17110 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
17111                                         QualType Ty) {
17112   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
17113     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
17114         << 1 << /* vector, integer or float ty*/ 0 << Ty;
17115     return true;
17116   }
17117   return false;
17118 }
17119 
17120 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
17121   if (checkArgCount(*this, TheCall, 1))
17122     return true;
17123 
17124   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17125   if (A.isInvalid())
17126     return true;
17127 
17128   TheCall->setArg(0, A.get());
17129   QualType TyA = A.get()->getType();
17130 
17131   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17132     return true;
17133 
17134   TheCall->setType(TyA);
17135   return false;
17136 }
17137 
17138 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
17139   if (checkArgCount(*this, TheCall, 2))
17140     return true;
17141 
17142   ExprResult A = TheCall->getArg(0);
17143   ExprResult B = TheCall->getArg(1);
17144   // Do standard promotions between the two arguments, returning their common
17145   // type.
17146   QualType Res =
17147       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
17148   if (A.isInvalid() || B.isInvalid())
17149     return true;
17150 
17151   QualType TyA = A.get()->getType();
17152   QualType TyB = B.get()->getType();
17153 
17154   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
17155     return Diag(A.get()->getBeginLoc(),
17156                 diag::err_typecheck_call_different_arg_types)
17157            << TyA << TyB;
17158 
17159   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17160     return true;
17161 
17162   TheCall->setArg(0, A.get());
17163   TheCall->setArg(1, B.get());
17164   TheCall->setType(Res);
17165   return false;
17166 }
17167 
17168 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17169   if (checkArgCount(*this, TheCall, 1))
17170     return true;
17171 
17172   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17173   if (A.isInvalid())
17174     return true;
17175 
17176   TheCall->setArg(0, A.get());
17177   return false;
17178 }
17179 
17180 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17181                                             ExprResult CallResult) {
17182   if (checkArgCount(*this, TheCall, 1))
17183     return ExprError();
17184 
17185   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17186   if (MatrixArg.isInvalid())
17187     return MatrixArg;
17188   Expr *Matrix = MatrixArg.get();
17189 
17190   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17191   if (!MType) {
17192     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17193         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17194     return ExprError();
17195   }
17196 
17197   // Create returned matrix type by swapping rows and columns of the argument
17198   // matrix type.
17199   QualType ResultType = Context.getConstantMatrixType(
17200       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17201 
17202   // Change the return type to the type of the returned matrix.
17203   TheCall->setType(ResultType);
17204 
17205   // Update call argument to use the possibly converted matrix argument.
17206   TheCall->setArg(0, Matrix);
17207   return CallResult;
17208 }
17209 
17210 // Get and verify the matrix dimensions.
17211 static llvm::Optional<unsigned>
17212 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17213   SourceLocation ErrorPos;
17214   Optional<llvm::APSInt> Value =
17215       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17216   if (!Value) {
17217     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17218         << Name;
17219     return {};
17220   }
17221   uint64_t Dim = Value->getZExtValue();
17222   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17223     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17224         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17225     return {};
17226   }
17227   return Dim;
17228 }
17229 
17230 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17231                                                   ExprResult CallResult) {
17232   if (!getLangOpts().MatrixTypes) {
17233     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17234     return ExprError();
17235   }
17236 
17237   if (checkArgCount(*this, TheCall, 4))
17238     return ExprError();
17239 
17240   unsigned PtrArgIdx = 0;
17241   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17242   Expr *RowsExpr = TheCall->getArg(1);
17243   Expr *ColumnsExpr = TheCall->getArg(2);
17244   Expr *StrideExpr = TheCall->getArg(3);
17245 
17246   bool ArgError = false;
17247 
17248   // Check pointer argument.
17249   {
17250     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17251     if (PtrConv.isInvalid())
17252       return PtrConv;
17253     PtrExpr = PtrConv.get();
17254     TheCall->setArg(0, PtrExpr);
17255     if (PtrExpr->isTypeDependent()) {
17256       TheCall->setType(Context.DependentTy);
17257       return TheCall;
17258     }
17259   }
17260 
17261   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17262   QualType ElementTy;
17263   if (!PtrTy) {
17264     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17265         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17266     ArgError = true;
17267   } else {
17268     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17269 
17270     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17271       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17272           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17273           << PtrExpr->getType();
17274       ArgError = true;
17275     }
17276   }
17277 
17278   // Apply default Lvalue conversions and convert the expression to size_t.
17279   auto ApplyArgumentConversions = [this](Expr *E) {
17280     ExprResult Conv = DefaultLvalueConversion(E);
17281     if (Conv.isInvalid())
17282       return Conv;
17283 
17284     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17285   };
17286 
17287   // Apply conversion to row and column expressions.
17288   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17289   if (!RowsConv.isInvalid()) {
17290     RowsExpr = RowsConv.get();
17291     TheCall->setArg(1, RowsExpr);
17292   } else
17293     RowsExpr = nullptr;
17294 
17295   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17296   if (!ColumnsConv.isInvalid()) {
17297     ColumnsExpr = ColumnsConv.get();
17298     TheCall->setArg(2, ColumnsExpr);
17299   } else
17300     ColumnsExpr = nullptr;
17301 
17302   // If any any part of the result matrix type is still pending, just use
17303   // Context.DependentTy, until all parts are resolved.
17304   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17305       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17306     TheCall->setType(Context.DependentTy);
17307     return CallResult;
17308   }
17309 
17310   // Check row and column dimensions.
17311   llvm::Optional<unsigned> MaybeRows;
17312   if (RowsExpr)
17313     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17314 
17315   llvm::Optional<unsigned> MaybeColumns;
17316   if (ColumnsExpr)
17317     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17318 
17319   // Check stride argument.
17320   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17321   if (StrideConv.isInvalid())
17322     return ExprError();
17323   StrideExpr = StrideConv.get();
17324   TheCall->setArg(3, StrideExpr);
17325 
17326   if (MaybeRows) {
17327     if (Optional<llvm::APSInt> Value =
17328             StrideExpr->getIntegerConstantExpr(Context)) {
17329       uint64_t Stride = Value->getZExtValue();
17330       if (Stride < *MaybeRows) {
17331         Diag(StrideExpr->getBeginLoc(),
17332              diag::err_builtin_matrix_stride_too_small);
17333         ArgError = true;
17334       }
17335     }
17336   }
17337 
17338   if (ArgError || !MaybeRows || !MaybeColumns)
17339     return ExprError();
17340 
17341   TheCall->setType(
17342       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17343   return CallResult;
17344 }
17345 
17346 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17347                                                    ExprResult CallResult) {
17348   if (checkArgCount(*this, TheCall, 3))
17349     return ExprError();
17350 
17351   unsigned PtrArgIdx = 1;
17352   Expr *MatrixExpr = TheCall->getArg(0);
17353   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17354   Expr *StrideExpr = TheCall->getArg(2);
17355 
17356   bool ArgError = false;
17357 
17358   {
17359     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17360     if (MatrixConv.isInvalid())
17361       return MatrixConv;
17362     MatrixExpr = MatrixConv.get();
17363     TheCall->setArg(0, MatrixExpr);
17364   }
17365   if (MatrixExpr->isTypeDependent()) {
17366     TheCall->setType(Context.DependentTy);
17367     return TheCall;
17368   }
17369 
17370   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17371   if (!MatrixTy) {
17372     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17373         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17374     ArgError = true;
17375   }
17376 
17377   {
17378     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17379     if (PtrConv.isInvalid())
17380       return PtrConv;
17381     PtrExpr = PtrConv.get();
17382     TheCall->setArg(1, PtrExpr);
17383     if (PtrExpr->isTypeDependent()) {
17384       TheCall->setType(Context.DependentTy);
17385       return TheCall;
17386     }
17387   }
17388 
17389   // Check pointer argument.
17390   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17391   if (!PtrTy) {
17392     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17393         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17394     ArgError = true;
17395   } else {
17396     QualType ElementTy = PtrTy->getPointeeType();
17397     if (ElementTy.isConstQualified()) {
17398       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17399       ArgError = true;
17400     }
17401     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17402     if (MatrixTy &&
17403         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17404       Diag(PtrExpr->getBeginLoc(),
17405            diag::err_builtin_matrix_pointer_arg_mismatch)
17406           << ElementTy << MatrixTy->getElementType();
17407       ArgError = true;
17408     }
17409   }
17410 
17411   // Apply default Lvalue conversions and convert the stride expression to
17412   // size_t.
17413   {
17414     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17415     if (StrideConv.isInvalid())
17416       return StrideConv;
17417 
17418     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17419     if (StrideConv.isInvalid())
17420       return StrideConv;
17421     StrideExpr = StrideConv.get();
17422     TheCall->setArg(2, StrideExpr);
17423   }
17424 
17425   // Check stride argument.
17426   if (MatrixTy) {
17427     if (Optional<llvm::APSInt> Value =
17428             StrideExpr->getIntegerConstantExpr(Context)) {
17429       uint64_t Stride = Value->getZExtValue();
17430       if (Stride < MatrixTy->getNumRows()) {
17431         Diag(StrideExpr->getBeginLoc(),
17432              diag::err_builtin_matrix_stride_too_small);
17433         ArgError = true;
17434       }
17435     }
17436   }
17437 
17438   if (ArgError)
17439     return ExprError();
17440 
17441   return CallResult;
17442 }
17443 
17444 /// \brief Enforce the bounds of a TCB
17445 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17446 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17447 /// and enforce_tcb_leaf attributes.
17448 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17449                                const NamedDecl *Callee) {
17450   const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17451 
17452   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17453     return;
17454 
17455   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17456   // all TCBs the callee is a part of.
17457   llvm::StringSet<> CalleeTCBs;
17458   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17459            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17460   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17461            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17462 
17463   // Go through the TCBs the caller is a part of and emit warnings if Caller
17464   // is in a TCB that the Callee is not.
17465   for_each(
17466       Caller->specific_attrs<EnforceTCBAttr>(),
17467       [&](const auto *A) {
17468         StringRef CallerTCB = A->getTCBName();
17469         if (CalleeTCBs.count(CallerTCB) == 0) {
17470           this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17471               << Callee << CallerTCB;
17472         }
17473       });
17474 }
17475