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 (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2952     return true;
2953 
2954   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2955     return true;
2956 
2957   // For intrinsics which take an immediate value as part of the instruction,
2958   // range check them here.
2959   unsigned i = 0, l = 0, u = 0;
2960   switch (BuiltinID) {
2961   default: return false;
2962   case AArch64::BI__builtin_arm_dmb:
2963   case AArch64::BI__builtin_arm_dsb:
2964   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2965   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2966   }
2967 
2968   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2969 }
2970 
2971 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2972   if (Arg->getType()->getAsPlaceholderType())
2973     return false;
2974 
2975   // The first argument needs to be a record field access.
2976   // If it is an array element access, we delay decision
2977   // to BPF backend to check whether the access is a
2978   // field access or not.
2979   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2980           isa<MemberExpr>(Arg->IgnoreParens()) ||
2981           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2982 }
2983 
2984 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2985                             QualType VectorTy, QualType EltTy) {
2986   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2987   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2988     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2989         << Call->getSourceRange() << VectorEltTy << EltTy;
2990     return false;
2991   }
2992   return true;
2993 }
2994 
2995 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2996   QualType ArgType = Arg->getType();
2997   if (ArgType->getAsPlaceholderType())
2998     return false;
2999 
3000   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
3001   // format:
3002   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
3003   //   2. <type> var;
3004   //      __builtin_preserve_type_info(var, flag);
3005   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
3006       !isa<UnaryOperator>(Arg->IgnoreParens()))
3007     return false;
3008 
3009   // Typedef type.
3010   if (ArgType->getAs<TypedefType>())
3011     return true;
3012 
3013   // Record type or Enum type.
3014   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3015   if (const auto *RT = Ty->getAs<RecordType>()) {
3016     if (!RT->getDecl()->getDeclName().isEmpty())
3017       return true;
3018   } else if (const auto *ET = Ty->getAs<EnumType>()) {
3019     if (!ET->getDecl()->getDeclName().isEmpty())
3020       return true;
3021   }
3022 
3023   return false;
3024 }
3025 
3026 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
3027   QualType ArgType = Arg->getType();
3028   if (ArgType->getAsPlaceholderType())
3029     return false;
3030 
3031   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
3032   // format:
3033   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
3034   //                                 flag);
3035   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
3036   if (!UO)
3037     return false;
3038 
3039   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
3040   if (!CE)
3041     return false;
3042   if (CE->getCastKind() != CK_IntegralToPointer &&
3043       CE->getCastKind() != CK_NullToPointer)
3044     return false;
3045 
3046   // The integer must be from an EnumConstantDecl.
3047   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3048   if (!DR)
3049     return false;
3050 
3051   const EnumConstantDecl *Enumerator =
3052       dyn_cast<EnumConstantDecl>(DR->getDecl());
3053   if (!Enumerator)
3054     return false;
3055 
3056   // The type must be EnumType.
3057   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3058   const auto *ET = Ty->getAs<EnumType>();
3059   if (!ET)
3060     return false;
3061 
3062   // The enum value must be supported.
3063   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3064 }
3065 
3066 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3067                                        CallExpr *TheCall) {
3068   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3069           BuiltinID == BPF::BI__builtin_btf_type_id ||
3070           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3071           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3072          "unexpected BPF builtin");
3073 
3074   if (checkArgCount(*this, TheCall, 2))
3075     return true;
3076 
3077   // The second argument needs to be a constant int
3078   Expr *Arg = TheCall->getArg(1);
3079   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3080   diag::kind kind;
3081   if (!Value) {
3082     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3083       kind = diag::err_preserve_field_info_not_const;
3084     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3085       kind = diag::err_btf_type_id_not_const;
3086     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3087       kind = diag::err_preserve_type_info_not_const;
3088     else
3089       kind = diag::err_preserve_enum_value_not_const;
3090     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3091     return true;
3092   }
3093 
3094   // The first argument
3095   Arg = TheCall->getArg(0);
3096   bool InvalidArg = false;
3097   bool ReturnUnsignedInt = true;
3098   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3099     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3100       InvalidArg = true;
3101       kind = diag::err_preserve_field_info_not_field;
3102     }
3103   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3104     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3105       InvalidArg = true;
3106       kind = diag::err_preserve_type_info_invalid;
3107     }
3108   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3109     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3110       InvalidArg = true;
3111       kind = diag::err_preserve_enum_value_invalid;
3112     }
3113     ReturnUnsignedInt = false;
3114   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3115     ReturnUnsignedInt = false;
3116   }
3117 
3118   if (InvalidArg) {
3119     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3120     return true;
3121   }
3122 
3123   if (ReturnUnsignedInt)
3124     TheCall->setType(Context.UnsignedIntTy);
3125   else
3126     TheCall->setType(Context.UnsignedLongTy);
3127   return false;
3128 }
3129 
3130 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3131   struct ArgInfo {
3132     uint8_t OpNum;
3133     bool IsSigned;
3134     uint8_t BitWidth;
3135     uint8_t Align;
3136   };
3137   struct BuiltinInfo {
3138     unsigned BuiltinID;
3139     ArgInfo Infos[2];
3140   };
3141 
3142   static BuiltinInfo Infos[] = {
3143     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3144     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3145     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3146     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3147     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3148     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3149     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3150     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3151     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3152     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3153     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3154 
3155     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3158     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3159     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3160     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3161     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3163     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3164     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3165     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3166 
3167     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3170     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3171     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3177     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3179     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3185     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3186     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3188     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3190     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3192     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3194     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3196     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3197     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3198     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3201     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3209     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3210     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3212     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3213     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3215     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3216     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3218     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3219                                                       {{ 1, false, 6,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3221     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3222     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3224     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3225     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3226     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3227                                                       {{ 1, false, 5,  0 }} },
3228     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3229     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3230     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3231     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3232     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3233     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3234                                                        { 2, false, 5,  0 }} },
3235     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3236                                                        { 2, false, 6,  0 }} },
3237     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3238                                                        { 3, false, 5,  0 }} },
3239     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3240                                                        { 3, false, 6,  0 }} },
3241     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3242     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3243     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3244     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3245     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3246     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3247     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3248     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3249     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3250     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3251     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3252     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3253     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3254     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3255     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3256     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3257                                                       {{ 2, false, 4,  0 },
3258                                                        { 3, false, 5,  0 }} },
3259     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3260                                                       {{ 2, false, 4,  0 },
3261                                                        { 3, false, 5,  0 }} },
3262     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3263                                                       {{ 2, false, 4,  0 },
3264                                                        { 3, false, 5,  0 }} },
3265     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3266                                                       {{ 2, false, 4,  0 },
3267                                                        { 3, false, 5,  0 }} },
3268     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3269     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3270     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3271     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3272     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3273     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3274     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3275     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3276     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3277     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3278     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3279                                                        { 2, false, 5,  0 }} },
3280     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3281                                                        { 2, false, 6,  0 }} },
3282     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3283     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3284     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3285     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3286     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3287     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3288     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3289     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3290     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3291                                                       {{ 1, false, 4,  0 }} },
3292     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3293     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3294                                                       {{ 1, false, 4,  0 }} },
3295     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3296     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3297     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3298     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3299     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3300     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3301     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3302     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3303     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3304     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3305     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3306     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3307     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3308     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3309     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3310     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3311     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3312     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3313     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3314     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3315                                                       {{ 3, false, 1,  0 }} },
3316     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3317     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3318     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3319     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3320                                                       {{ 3, false, 1,  0 }} },
3321     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3322     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3323     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3324     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3325                                                       {{ 3, false, 1,  0 }} },
3326   };
3327 
3328   // Use a dynamically initialized static to sort the table exactly once on
3329   // first run.
3330   static const bool SortOnce =
3331       (llvm::sort(Infos,
3332                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3333                    return LHS.BuiltinID < RHS.BuiltinID;
3334                  }),
3335        true);
3336   (void)SortOnce;
3337 
3338   const BuiltinInfo *F = llvm::partition_point(
3339       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3340   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3341     return false;
3342 
3343   bool Error = false;
3344 
3345   for (const ArgInfo &A : F->Infos) {
3346     // Ignore empty ArgInfo elements.
3347     if (A.BitWidth == 0)
3348       continue;
3349 
3350     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3351     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3352     if (!A.Align) {
3353       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3354     } else {
3355       unsigned M = 1 << A.Align;
3356       Min *= M;
3357       Max *= M;
3358       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3359       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3360     }
3361   }
3362   return Error;
3363 }
3364 
3365 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3366                                            CallExpr *TheCall) {
3367   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3368 }
3369 
3370 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3371                                         unsigned BuiltinID, CallExpr *TheCall) {
3372   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3373          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3374 }
3375 
3376 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3377                                CallExpr *TheCall) {
3378 
3379   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3380       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3381     if (!TI.hasFeature("dsp"))
3382       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3383   }
3384 
3385   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3386       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3387     if (!TI.hasFeature("dspr2"))
3388       return Diag(TheCall->getBeginLoc(),
3389                   diag::err_mips_builtin_requires_dspr2);
3390   }
3391 
3392   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3393       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3394     if (!TI.hasFeature("msa"))
3395       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3396   }
3397 
3398   return false;
3399 }
3400 
3401 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3402 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3403 // ordering for DSP is unspecified. MSA is ordered by the data format used
3404 // by the underlying instruction i.e., df/m, df/n and then by size.
3405 //
3406 // FIXME: The size tests here should instead be tablegen'd along with the
3407 //        definitions from include/clang/Basic/BuiltinsMips.def.
3408 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3409 //        be too.
3410 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3411   unsigned i = 0, l = 0, u = 0, m = 0;
3412   switch (BuiltinID) {
3413   default: return false;
3414   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3415   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3416   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3417   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3418   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3419   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3420   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3421   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3422   // df/m field.
3423   // These intrinsics take an unsigned 3 bit immediate.
3424   case Mips::BI__builtin_msa_bclri_b:
3425   case Mips::BI__builtin_msa_bnegi_b:
3426   case Mips::BI__builtin_msa_bseti_b:
3427   case Mips::BI__builtin_msa_sat_s_b:
3428   case Mips::BI__builtin_msa_sat_u_b:
3429   case Mips::BI__builtin_msa_slli_b:
3430   case Mips::BI__builtin_msa_srai_b:
3431   case Mips::BI__builtin_msa_srari_b:
3432   case Mips::BI__builtin_msa_srli_b:
3433   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3434   case Mips::BI__builtin_msa_binsli_b:
3435   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3436   // These intrinsics take an unsigned 4 bit immediate.
3437   case Mips::BI__builtin_msa_bclri_h:
3438   case Mips::BI__builtin_msa_bnegi_h:
3439   case Mips::BI__builtin_msa_bseti_h:
3440   case Mips::BI__builtin_msa_sat_s_h:
3441   case Mips::BI__builtin_msa_sat_u_h:
3442   case Mips::BI__builtin_msa_slli_h:
3443   case Mips::BI__builtin_msa_srai_h:
3444   case Mips::BI__builtin_msa_srari_h:
3445   case Mips::BI__builtin_msa_srli_h:
3446   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3447   case Mips::BI__builtin_msa_binsli_h:
3448   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3449   // These intrinsics take an unsigned 5 bit immediate.
3450   // The first block of intrinsics actually have an unsigned 5 bit field,
3451   // not a df/n field.
3452   case Mips::BI__builtin_msa_cfcmsa:
3453   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3454   case Mips::BI__builtin_msa_clei_u_b:
3455   case Mips::BI__builtin_msa_clei_u_h:
3456   case Mips::BI__builtin_msa_clei_u_w:
3457   case Mips::BI__builtin_msa_clei_u_d:
3458   case Mips::BI__builtin_msa_clti_u_b:
3459   case Mips::BI__builtin_msa_clti_u_h:
3460   case Mips::BI__builtin_msa_clti_u_w:
3461   case Mips::BI__builtin_msa_clti_u_d:
3462   case Mips::BI__builtin_msa_maxi_u_b:
3463   case Mips::BI__builtin_msa_maxi_u_h:
3464   case Mips::BI__builtin_msa_maxi_u_w:
3465   case Mips::BI__builtin_msa_maxi_u_d:
3466   case Mips::BI__builtin_msa_mini_u_b:
3467   case Mips::BI__builtin_msa_mini_u_h:
3468   case Mips::BI__builtin_msa_mini_u_w:
3469   case Mips::BI__builtin_msa_mini_u_d:
3470   case Mips::BI__builtin_msa_addvi_b:
3471   case Mips::BI__builtin_msa_addvi_h:
3472   case Mips::BI__builtin_msa_addvi_w:
3473   case Mips::BI__builtin_msa_addvi_d:
3474   case Mips::BI__builtin_msa_bclri_w:
3475   case Mips::BI__builtin_msa_bnegi_w:
3476   case Mips::BI__builtin_msa_bseti_w:
3477   case Mips::BI__builtin_msa_sat_s_w:
3478   case Mips::BI__builtin_msa_sat_u_w:
3479   case Mips::BI__builtin_msa_slli_w:
3480   case Mips::BI__builtin_msa_srai_w:
3481   case Mips::BI__builtin_msa_srari_w:
3482   case Mips::BI__builtin_msa_srli_w:
3483   case Mips::BI__builtin_msa_srlri_w:
3484   case Mips::BI__builtin_msa_subvi_b:
3485   case Mips::BI__builtin_msa_subvi_h:
3486   case Mips::BI__builtin_msa_subvi_w:
3487   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3488   case Mips::BI__builtin_msa_binsli_w:
3489   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3490   // These intrinsics take an unsigned 6 bit immediate.
3491   case Mips::BI__builtin_msa_bclri_d:
3492   case Mips::BI__builtin_msa_bnegi_d:
3493   case Mips::BI__builtin_msa_bseti_d:
3494   case Mips::BI__builtin_msa_sat_s_d:
3495   case Mips::BI__builtin_msa_sat_u_d:
3496   case Mips::BI__builtin_msa_slli_d:
3497   case Mips::BI__builtin_msa_srai_d:
3498   case Mips::BI__builtin_msa_srari_d:
3499   case Mips::BI__builtin_msa_srli_d:
3500   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3501   case Mips::BI__builtin_msa_binsli_d:
3502   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3503   // These intrinsics take a signed 5 bit immediate.
3504   case Mips::BI__builtin_msa_ceqi_b:
3505   case Mips::BI__builtin_msa_ceqi_h:
3506   case Mips::BI__builtin_msa_ceqi_w:
3507   case Mips::BI__builtin_msa_ceqi_d:
3508   case Mips::BI__builtin_msa_clti_s_b:
3509   case Mips::BI__builtin_msa_clti_s_h:
3510   case Mips::BI__builtin_msa_clti_s_w:
3511   case Mips::BI__builtin_msa_clti_s_d:
3512   case Mips::BI__builtin_msa_clei_s_b:
3513   case Mips::BI__builtin_msa_clei_s_h:
3514   case Mips::BI__builtin_msa_clei_s_w:
3515   case Mips::BI__builtin_msa_clei_s_d:
3516   case Mips::BI__builtin_msa_maxi_s_b:
3517   case Mips::BI__builtin_msa_maxi_s_h:
3518   case Mips::BI__builtin_msa_maxi_s_w:
3519   case Mips::BI__builtin_msa_maxi_s_d:
3520   case Mips::BI__builtin_msa_mini_s_b:
3521   case Mips::BI__builtin_msa_mini_s_h:
3522   case Mips::BI__builtin_msa_mini_s_w:
3523   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3524   // These intrinsics take an unsigned 8 bit immediate.
3525   case Mips::BI__builtin_msa_andi_b:
3526   case Mips::BI__builtin_msa_nori_b:
3527   case Mips::BI__builtin_msa_ori_b:
3528   case Mips::BI__builtin_msa_shf_b:
3529   case Mips::BI__builtin_msa_shf_h:
3530   case Mips::BI__builtin_msa_shf_w:
3531   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3532   case Mips::BI__builtin_msa_bseli_b:
3533   case Mips::BI__builtin_msa_bmnzi_b:
3534   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3535   // df/n format
3536   // These intrinsics take an unsigned 4 bit immediate.
3537   case Mips::BI__builtin_msa_copy_s_b:
3538   case Mips::BI__builtin_msa_copy_u_b:
3539   case Mips::BI__builtin_msa_insve_b:
3540   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3541   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3542   // These intrinsics take an unsigned 3 bit immediate.
3543   case Mips::BI__builtin_msa_copy_s_h:
3544   case Mips::BI__builtin_msa_copy_u_h:
3545   case Mips::BI__builtin_msa_insve_h:
3546   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3547   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3548   // These intrinsics take an unsigned 2 bit immediate.
3549   case Mips::BI__builtin_msa_copy_s_w:
3550   case Mips::BI__builtin_msa_copy_u_w:
3551   case Mips::BI__builtin_msa_insve_w:
3552   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3553   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3554   // These intrinsics take an unsigned 1 bit immediate.
3555   case Mips::BI__builtin_msa_copy_s_d:
3556   case Mips::BI__builtin_msa_copy_u_d:
3557   case Mips::BI__builtin_msa_insve_d:
3558   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3559   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3560   // Memory offsets and immediate loads.
3561   // These intrinsics take a signed 10 bit immediate.
3562   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3563   case Mips::BI__builtin_msa_ldi_h:
3564   case Mips::BI__builtin_msa_ldi_w:
3565   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3566   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3567   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3568   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3569   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3570   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3571   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3572   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3573   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3574   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3575   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3576   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3577   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3578   }
3579 
3580   if (!m)
3581     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3582 
3583   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3584          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3585 }
3586 
3587 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3588 /// advancing the pointer over the consumed characters. The decoded type is
3589 /// returned. If the decoded type represents a constant integer with a
3590 /// constraint on its value then Mask is set to that value. The type descriptors
3591 /// used in Str are specific to PPC MMA builtins and are documented in the file
3592 /// defining the PPC builtins.
3593 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3594                                         unsigned &Mask) {
3595   bool RequireICE = false;
3596   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3597   switch (*Str++) {
3598   case 'V':
3599     return Context.getVectorType(Context.UnsignedCharTy, 16,
3600                                  VectorType::VectorKind::AltiVecVector);
3601   case 'i': {
3602     char *End;
3603     unsigned size = strtoul(Str, &End, 10);
3604     assert(End != Str && "Missing constant parameter constraint");
3605     Str = End;
3606     Mask = size;
3607     return Context.IntTy;
3608   }
3609   case 'W': {
3610     char *End;
3611     unsigned size = strtoul(Str, &End, 10);
3612     assert(End != Str && "Missing PowerPC MMA type size");
3613     Str = End;
3614     QualType Type;
3615     switch (size) {
3616   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3617     case size: Type = Context.Id##Ty; break;
3618   #include "clang/Basic/PPCTypes.def"
3619     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3620     }
3621     bool CheckVectorArgs = false;
3622     while (!CheckVectorArgs) {
3623       switch (*Str++) {
3624       case '*':
3625         Type = Context.getPointerType(Type);
3626         break;
3627       case 'C':
3628         Type = Type.withConst();
3629         break;
3630       default:
3631         CheckVectorArgs = true;
3632         --Str;
3633         break;
3634       }
3635     }
3636     return Type;
3637   }
3638   default:
3639     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3640   }
3641 }
3642 
3643 static bool isPPC_64Builtin(unsigned BuiltinID) {
3644   // These builtins only work on PPC 64bit targets.
3645   switch (BuiltinID) {
3646   case PPC::BI__builtin_divde:
3647   case PPC::BI__builtin_divdeu:
3648   case PPC::BI__builtin_bpermd:
3649   case PPC::BI__builtin_pdepd:
3650   case PPC::BI__builtin_pextd:
3651   case PPC::BI__builtin_ppc_ldarx:
3652   case PPC::BI__builtin_ppc_stdcx:
3653   case PPC::BI__builtin_ppc_tdw:
3654   case PPC::BI__builtin_ppc_trapd:
3655   case PPC::BI__builtin_ppc_cmpeqb:
3656   case PPC::BI__builtin_ppc_setb:
3657   case PPC::BI__builtin_ppc_mulhd:
3658   case PPC::BI__builtin_ppc_mulhdu:
3659   case PPC::BI__builtin_ppc_maddhd:
3660   case PPC::BI__builtin_ppc_maddhdu:
3661   case PPC::BI__builtin_ppc_maddld:
3662   case PPC::BI__builtin_ppc_load8r:
3663   case PPC::BI__builtin_ppc_store8r:
3664   case PPC::BI__builtin_ppc_insert_exp:
3665   case PPC::BI__builtin_ppc_extract_sig:
3666   case PPC::BI__builtin_ppc_addex:
3667   case PPC::BI__builtin_darn:
3668   case PPC::BI__builtin_darn_raw:
3669   case PPC::BI__builtin_ppc_compare_and_swaplp:
3670   case PPC::BI__builtin_ppc_fetch_and_addlp:
3671   case PPC::BI__builtin_ppc_fetch_and_andlp:
3672   case PPC::BI__builtin_ppc_fetch_and_orlp:
3673   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3674     return true;
3675   }
3676   return false;
3677 }
3678 
3679 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3680                              StringRef FeatureToCheck, unsigned DiagID,
3681                              StringRef DiagArg = "") {
3682   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3683     return false;
3684 
3685   if (DiagArg.empty())
3686     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3687   else
3688     S.Diag(TheCall->getBeginLoc(), DiagID)
3689         << DiagArg << TheCall->getSourceRange();
3690 
3691   return true;
3692 }
3693 
3694 /// Returns true if the argument consists of one contiguous run of 1s with any
3695 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3696 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3697 /// since all 1s are not contiguous.
3698 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3699   llvm::APSInt Result;
3700   // We can't check the value of a dependent argument.
3701   Expr *Arg = TheCall->getArg(ArgNum);
3702   if (Arg->isTypeDependent() || Arg->isValueDependent())
3703     return false;
3704 
3705   // Check constant-ness first.
3706   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3707     return true;
3708 
3709   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3710   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3711     return false;
3712 
3713   return Diag(TheCall->getBeginLoc(),
3714               diag::err_argument_not_contiguous_bit_field)
3715          << ArgNum << Arg->getSourceRange();
3716 }
3717 
3718 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3719                                        CallExpr *TheCall) {
3720   unsigned i = 0, l = 0, u = 0;
3721   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3722   llvm::APSInt Result;
3723 
3724   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3725     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3726            << TheCall->getSourceRange();
3727 
3728   switch (BuiltinID) {
3729   default: return false;
3730   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3731   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3732     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3733            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3734   case PPC::BI__builtin_altivec_dss:
3735     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3736   case PPC::BI__builtin_tbegin:
3737   case PPC::BI__builtin_tend:
3738     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3739            SemaFeatureCheck(*this, TheCall, "htm",
3740                             diag::err_ppc_builtin_requires_htm);
3741   case PPC::BI__builtin_tsr:
3742     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3743            SemaFeatureCheck(*this, TheCall, "htm",
3744                             diag::err_ppc_builtin_requires_htm);
3745   case PPC::BI__builtin_tabortwc:
3746   case PPC::BI__builtin_tabortdc:
3747     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3748            SemaFeatureCheck(*this, TheCall, "htm",
3749                             diag::err_ppc_builtin_requires_htm);
3750   case PPC::BI__builtin_tabortwci:
3751   case PPC::BI__builtin_tabortdci:
3752     return SemaFeatureCheck(*this, TheCall, "htm",
3753                             diag::err_ppc_builtin_requires_htm) ||
3754            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3755             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3756   case PPC::BI__builtin_tabort:
3757   case PPC::BI__builtin_tcheck:
3758   case PPC::BI__builtin_treclaim:
3759   case PPC::BI__builtin_trechkpt:
3760   case PPC::BI__builtin_tendall:
3761   case PPC::BI__builtin_tresume:
3762   case PPC::BI__builtin_tsuspend:
3763   case PPC::BI__builtin_get_texasr:
3764   case PPC::BI__builtin_get_texasru:
3765   case PPC::BI__builtin_get_tfhar:
3766   case PPC::BI__builtin_get_tfiar:
3767   case PPC::BI__builtin_set_texasr:
3768   case PPC::BI__builtin_set_texasru:
3769   case PPC::BI__builtin_set_tfhar:
3770   case PPC::BI__builtin_set_tfiar:
3771   case PPC::BI__builtin_ttest:
3772     return SemaFeatureCheck(*this, TheCall, "htm",
3773                             diag::err_ppc_builtin_requires_htm);
3774   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3775   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3776   // extended double representation.
3777   case PPC::BI__builtin_unpack_longdouble:
3778     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3779       return true;
3780     LLVM_FALLTHROUGH;
3781   case PPC::BI__builtin_pack_longdouble:
3782     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3783       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3784              << "ibmlongdouble";
3785     return false;
3786   case PPC::BI__builtin_altivec_dst:
3787   case PPC::BI__builtin_altivec_dstt:
3788   case PPC::BI__builtin_altivec_dstst:
3789   case PPC::BI__builtin_altivec_dststt:
3790     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3791   case PPC::BI__builtin_vsx_xxpermdi:
3792   case PPC::BI__builtin_vsx_xxsldwi:
3793     return SemaBuiltinVSX(TheCall);
3794   case PPC::BI__builtin_divwe:
3795   case PPC::BI__builtin_divweu:
3796   case PPC::BI__builtin_divde:
3797   case PPC::BI__builtin_divdeu:
3798     return SemaFeatureCheck(*this, TheCall, "extdiv",
3799                             diag::err_ppc_builtin_only_on_arch, "7");
3800   case PPC::BI__builtin_bpermd:
3801     return SemaFeatureCheck(*this, TheCall, "bpermd",
3802                             diag::err_ppc_builtin_only_on_arch, "7");
3803   case PPC::BI__builtin_unpack_vector_int128:
3804     return SemaFeatureCheck(*this, TheCall, "vsx",
3805                             diag::err_ppc_builtin_only_on_arch, "7") ||
3806            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3807   case PPC::BI__builtin_pack_vector_int128:
3808     return SemaFeatureCheck(*this, TheCall, "vsx",
3809                             diag::err_ppc_builtin_only_on_arch, "7");
3810   case PPC::BI__builtin_pdepd:
3811   case PPC::BI__builtin_pextd:
3812     return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
3813                             diag::err_ppc_builtin_only_on_arch, "10");
3814   case PPC::BI__builtin_altivec_vgnb:
3815      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3816   case PPC::BI__builtin_altivec_vec_replace_elt:
3817   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3818     QualType VecTy = TheCall->getArg(0)->getType();
3819     QualType EltTy = TheCall->getArg(1)->getType();
3820     unsigned Width = Context.getIntWidth(EltTy);
3821     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3822            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3823   }
3824   case PPC::BI__builtin_vsx_xxeval:
3825      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3826   case PPC::BI__builtin_altivec_vsldbi:
3827      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3828   case PPC::BI__builtin_altivec_vsrdbi:
3829      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3830   case PPC::BI__builtin_vsx_xxpermx:
3831      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3832   case PPC::BI__builtin_ppc_tw:
3833   case PPC::BI__builtin_ppc_tdw:
3834     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3835   case PPC::BI__builtin_ppc_cmpeqb:
3836   case PPC::BI__builtin_ppc_setb:
3837   case PPC::BI__builtin_ppc_maddhd:
3838   case PPC::BI__builtin_ppc_maddhdu:
3839   case PPC::BI__builtin_ppc_maddld:
3840     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3841                             diag::err_ppc_builtin_only_on_arch, "9");
3842   case PPC::BI__builtin_ppc_cmprb:
3843     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3844                             diag::err_ppc_builtin_only_on_arch, "9") ||
3845            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3846   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3847   // be a constant that represents a contiguous bit field.
3848   case PPC::BI__builtin_ppc_rlwnm:
3849     return SemaValueIsRunOfOnes(TheCall, 2);
3850   case PPC::BI__builtin_ppc_rlwimi:
3851   case PPC::BI__builtin_ppc_rldimi:
3852     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3853            SemaValueIsRunOfOnes(TheCall, 3);
3854   case PPC::BI__builtin_ppc_extract_exp:
3855   case PPC::BI__builtin_ppc_extract_sig:
3856   case PPC::BI__builtin_ppc_insert_exp:
3857     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3858                             diag::err_ppc_builtin_only_on_arch, "9");
3859   case PPC::BI__builtin_ppc_addex: {
3860     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3861                          diag::err_ppc_builtin_only_on_arch, "9") ||
3862         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3863       return true;
3864     // Output warning for reserved values 1 to 3.
3865     int ArgValue =
3866         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3867     if (ArgValue != 0)
3868       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3869           << ArgValue;
3870     return false;
3871   }
3872   case PPC::BI__builtin_ppc_mtfsb0:
3873   case PPC::BI__builtin_ppc_mtfsb1:
3874     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3875   case PPC::BI__builtin_ppc_mtfsf:
3876     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3877   case PPC::BI__builtin_ppc_mtfsfi:
3878     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3879            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3880   case PPC::BI__builtin_ppc_alignx:
3881     return SemaBuiltinConstantArgPower2(TheCall, 0);
3882   case PPC::BI__builtin_ppc_rdlam:
3883     return SemaValueIsRunOfOnes(TheCall, 2);
3884   case PPC::BI__builtin_ppc_icbt:
3885   case PPC::BI__builtin_ppc_sthcx:
3886   case PPC::BI__builtin_ppc_stbcx:
3887   case PPC::BI__builtin_ppc_lharx:
3888   case PPC::BI__builtin_ppc_lbarx:
3889     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3890                             diag::err_ppc_builtin_only_on_arch, "8");
3891   case PPC::BI__builtin_vsx_ldrmb:
3892   case PPC::BI__builtin_vsx_strmb:
3893     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3894                             diag::err_ppc_builtin_only_on_arch, "8") ||
3895            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3896   case PPC::BI__builtin_altivec_vcntmbb:
3897   case PPC::BI__builtin_altivec_vcntmbh:
3898   case PPC::BI__builtin_altivec_vcntmbw:
3899   case PPC::BI__builtin_altivec_vcntmbd:
3900     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3901   case PPC::BI__builtin_darn:
3902   case PPC::BI__builtin_darn_raw:
3903   case PPC::BI__builtin_darn_32:
3904     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3905                             diag::err_ppc_builtin_only_on_arch, "9");
3906   case PPC::BI__builtin_vsx_xxgenpcvbm:
3907   case PPC::BI__builtin_vsx_xxgenpcvhm:
3908   case PPC::BI__builtin_vsx_xxgenpcvwm:
3909   case PPC::BI__builtin_vsx_xxgenpcvdm:
3910     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3911   case PPC::BI__builtin_ppc_compare_exp_uo:
3912   case PPC::BI__builtin_ppc_compare_exp_lt:
3913   case PPC::BI__builtin_ppc_compare_exp_gt:
3914   case PPC::BI__builtin_ppc_compare_exp_eq:
3915     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3916                             diag::err_ppc_builtin_only_on_arch, "9") ||
3917            SemaFeatureCheck(*this, TheCall, "vsx",
3918                             diag::err_ppc_builtin_requires_vsx);
3919   case PPC::BI__builtin_ppc_test_data_class: {
3920     // Check if the first argument of the __builtin_ppc_test_data_class call is
3921     // valid. The argument must be either a 'float' or a 'double'.
3922     QualType ArgType = TheCall->getArg(0)->getType();
3923     if (ArgType != QualType(Context.FloatTy) &&
3924         ArgType != QualType(Context.DoubleTy))
3925       return Diag(TheCall->getBeginLoc(),
3926                   diag::err_ppc_invalid_test_data_class_type);
3927     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3928                             diag::err_ppc_builtin_only_on_arch, "9") ||
3929            SemaFeatureCheck(*this, TheCall, "vsx",
3930                             diag::err_ppc_builtin_requires_vsx) ||
3931            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3932   }
3933   case PPC::BI__builtin_ppc_maxfe:
3934   case PPC::BI__builtin_ppc_minfe:
3935   case PPC::BI__builtin_ppc_maxfl:
3936   case PPC::BI__builtin_ppc_minfl:
3937   case PPC::BI__builtin_ppc_maxfs:
3938   case PPC::BI__builtin_ppc_minfs: {
3939     if (Context.getTargetInfo().getTriple().isOSAIX() &&
3940         (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
3941          BuiltinID == PPC::BI__builtin_ppc_minfe))
3942       return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
3943              << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
3944              << false << Context.getTargetInfo().getTriple().str();
3945     // Argument type should be exact.
3946     QualType ArgType = QualType(Context.LongDoubleTy);
3947     if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
3948         BuiltinID == PPC::BI__builtin_ppc_minfl)
3949       ArgType = QualType(Context.DoubleTy);
3950     else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
3951              BuiltinID == PPC::BI__builtin_ppc_minfs)
3952       ArgType = QualType(Context.FloatTy);
3953     for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
3954       if (TheCall->getArg(I)->getType() != ArgType)
3955         return Diag(TheCall->getBeginLoc(),
3956                     diag::err_typecheck_convert_incompatible)
3957                << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
3958     return false;
3959   }
3960   case PPC::BI__builtin_ppc_load8r:
3961   case PPC::BI__builtin_ppc_store8r:
3962     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3963                             diag::err_ppc_builtin_only_on_arch, "7");
3964 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3965   case PPC::BI__builtin_##Name:                                                \
3966     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3967 #include "clang/Basic/BuiltinsPPC.def"
3968   }
3969   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3970 }
3971 
3972 // Check if the given type is a non-pointer PPC MMA type. This function is used
3973 // in Sema to prevent invalid uses of restricted PPC MMA types.
3974 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3975   if (Type->isPointerType() || Type->isArrayType())
3976     return false;
3977 
3978   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3979 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3980   if (false
3981 #include "clang/Basic/PPCTypes.def"
3982      ) {
3983     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3984     return true;
3985   }
3986   return false;
3987 }
3988 
3989 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3990                                           CallExpr *TheCall) {
3991   // position of memory order and scope arguments in the builtin
3992   unsigned OrderIndex, ScopeIndex;
3993   switch (BuiltinID) {
3994   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3995   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3996   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3997   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3998     OrderIndex = 2;
3999     ScopeIndex = 3;
4000     break;
4001   case AMDGPU::BI__builtin_amdgcn_fence:
4002     OrderIndex = 0;
4003     ScopeIndex = 1;
4004     break;
4005   default:
4006     return false;
4007   }
4008 
4009   ExprResult Arg = TheCall->getArg(OrderIndex);
4010   auto ArgExpr = Arg.get();
4011   Expr::EvalResult ArgResult;
4012 
4013   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
4014     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
4015            << ArgExpr->getType();
4016   auto Ord = ArgResult.Val.getInt().getZExtValue();
4017 
4018   // Check validity of memory ordering as per C11 / C++11's memody model.
4019   // Only fence needs check. Atomic dec/inc allow all memory orders.
4020   if (!llvm::isValidAtomicOrderingCABI(Ord))
4021     return Diag(ArgExpr->getBeginLoc(),
4022                 diag::warn_atomic_op_has_invalid_memory_order)
4023            << ArgExpr->getSourceRange();
4024   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
4025   case llvm::AtomicOrderingCABI::relaxed:
4026   case llvm::AtomicOrderingCABI::consume:
4027     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
4028       return Diag(ArgExpr->getBeginLoc(),
4029                   diag::warn_atomic_op_has_invalid_memory_order)
4030              << ArgExpr->getSourceRange();
4031     break;
4032   case llvm::AtomicOrderingCABI::acquire:
4033   case llvm::AtomicOrderingCABI::release:
4034   case llvm::AtomicOrderingCABI::acq_rel:
4035   case llvm::AtomicOrderingCABI::seq_cst:
4036     break;
4037   }
4038 
4039   Arg = TheCall->getArg(ScopeIndex);
4040   ArgExpr = Arg.get();
4041   Expr::EvalResult ArgResult1;
4042   // Check that sync scope is a constant literal
4043   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
4044     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
4045            << ArgExpr->getType();
4046 
4047   return false;
4048 }
4049 
4050 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
4051   llvm::APSInt Result;
4052 
4053   // We can't check the value of a dependent argument.
4054   Expr *Arg = TheCall->getArg(ArgNum);
4055   if (Arg->isTypeDependent() || Arg->isValueDependent())
4056     return false;
4057 
4058   // Check constant-ness first.
4059   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4060     return true;
4061 
4062   int64_t Val = Result.getSExtValue();
4063   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
4064     return false;
4065 
4066   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
4067          << Arg->getSourceRange();
4068 }
4069 
4070 static bool isRISCV32Builtin(unsigned BuiltinID) {
4071   // These builtins only work on riscv32 targets.
4072   switch (BuiltinID) {
4073   case RISCV::BI__builtin_riscv_zip_32:
4074   case RISCV::BI__builtin_riscv_unzip_32:
4075   case RISCV::BI__builtin_riscv_aes32dsi_32:
4076   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4077   case RISCV::BI__builtin_riscv_aes32esi_32:
4078   case RISCV::BI__builtin_riscv_aes32esmi_32:
4079   case RISCV::BI__builtin_riscv_sha512sig0h_32:
4080   case RISCV::BI__builtin_riscv_sha512sig0l_32:
4081   case RISCV::BI__builtin_riscv_sha512sig1h_32:
4082   case RISCV::BI__builtin_riscv_sha512sig1l_32:
4083   case RISCV::BI__builtin_riscv_sha512sum0r_32:
4084   case RISCV::BI__builtin_riscv_sha512sum1r_32:
4085     return true;
4086   }
4087 
4088   return false;
4089 }
4090 
4091 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
4092                                          unsigned BuiltinID,
4093                                          CallExpr *TheCall) {
4094   // CodeGenFunction can also detect this, but this gives a better error
4095   // message.
4096   bool FeatureMissing = false;
4097   SmallVector<StringRef> ReqFeatures;
4098   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4099   Features.split(ReqFeatures, ',');
4100 
4101   // Check for 32-bit only builtins on a 64-bit target.
4102   const llvm::Triple &TT = TI.getTriple();
4103   if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID))
4104     return Diag(TheCall->getCallee()->getBeginLoc(),
4105                 diag::err_32_bit_builtin_64_bit_tgt);
4106 
4107   // Check if each required feature is included
4108   for (StringRef F : ReqFeatures) {
4109     SmallVector<StringRef> ReqOpFeatures;
4110     F.split(ReqOpFeatures, '|');
4111     bool HasFeature = false;
4112     for (StringRef OF : ReqOpFeatures) {
4113       if (TI.hasFeature(OF)) {
4114         HasFeature = true;
4115         continue;
4116       }
4117     }
4118 
4119     if (!HasFeature) {
4120       std::string FeatureStrs;
4121       for (StringRef OF : ReqOpFeatures) {
4122         // If the feature is 64bit, alter the string so it will print better in
4123         // the diagnostic.
4124         if (OF == "64bit")
4125           OF = "RV64";
4126 
4127         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4128         OF.consume_front("experimental-");
4129         std::string FeatureStr = OF.str();
4130         FeatureStr[0] = std::toupper(FeatureStr[0]);
4131         // Combine strings.
4132         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4133         FeatureStrs += "'";
4134         FeatureStrs += FeatureStr;
4135         FeatureStrs += "'";
4136       }
4137       // Error message
4138       FeatureMissing = true;
4139       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4140           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4141     }
4142   }
4143 
4144   if (FeatureMissing)
4145     return true;
4146 
4147   switch (BuiltinID) {
4148   case RISCVVector::BI__builtin_rvv_vsetvli:
4149     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4150            CheckRISCVLMUL(TheCall, 2);
4151   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4152     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4153            CheckRISCVLMUL(TheCall, 1);
4154   case RISCVVector::BI__builtin_rvv_vget_v: {
4155     ASTContext::BuiltinVectorTypeInfo ResVecInfo =
4156         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4157             TheCall->getType().getCanonicalType().getTypePtr()));
4158     ASTContext::BuiltinVectorTypeInfo VecInfo =
4159         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4160             TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
4161     unsigned MaxIndex =
4162         (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
4163         (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
4164     return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
4165   }
4166   case RISCVVector::BI__builtin_rvv_vset_v: {
4167     ASTContext::BuiltinVectorTypeInfo ResVecInfo =
4168         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4169             TheCall->getType().getCanonicalType().getTypePtr()));
4170     ASTContext::BuiltinVectorTypeInfo VecInfo =
4171         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4172             TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
4173     unsigned MaxIndex =
4174         (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
4175         (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
4176     return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
4177   }
4178   // Check if byteselect is in [0, 3]
4179   case RISCV::BI__builtin_riscv_aes32dsi_32:
4180   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4181   case RISCV::BI__builtin_riscv_aes32esi_32:
4182   case RISCV::BI__builtin_riscv_aes32esmi_32:
4183   case RISCV::BI__builtin_riscv_sm4ks:
4184   case RISCV::BI__builtin_riscv_sm4ed:
4185     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4186   // Check if rnum is in [0, 10]
4187   case RISCV::BI__builtin_riscv_aes64ks1i_64:
4188     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10);
4189   }
4190 
4191   return false;
4192 }
4193 
4194 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4195                                            CallExpr *TheCall) {
4196   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4197     Expr *Arg = TheCall->getArg(0);
4198     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4199       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4200         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4201                << Arg->getSourceRange();
4202   }
4203 
4204   // For intrinsics which take an immediate value as part of the instruction,
4205   // range check them here.
4206   unsigned i = 0, l = 0, u = 0;
4207   switch (BuiltinID) {
4208   default: return false;
4209   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4210   case SystemZ::BI__builtin_s390_verimb:
4211   case SystemZ::BI__builtin_s390_verimh:
4212   case SystemZ::BI__builtin_s390_verimf:
4213   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4214   case SystemZ::BI__builtin_s390_vfaeb:
4215   case SystemZ::BI__builtin_s390_vfaeh:
4216   case SystemZ::BI__builtin_s390_vfaef:
4217   case SystemZ::BI__builtin_s390_vfaebs:
4218   case SystemZ::BI__builtin_s390_vfaehs:
4219   case SystemZ::BI__builtin_s390_vfaefs:
4220   case SystemZ::BI__builtin_s390_vfaezb:
4221   case SystemZ::BI__builtin_s390_vfaezh:
4222   case SystemZ::BI__builtin_s390_vfaezf:
4223   case SystemZ::BI__builtin_s390_vfaezbs:
4224   case SystemZ::BI__builtin_s390_vfaezhs:
4225   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4226   case SystemZ::BI__builtin_s390_vfisb:
4227   case SystemZ::BI__builtin_s390_vfidb:
4228     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4229            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4230   case SystemZ::BI__builtin_s390_vftcisb:
4231   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4232   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4233   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4234   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4235   case SystemZ::BI__builtin_s390_vstrcb:
4236   case SystemZ::BI__builtin_s390_vstrch:
4237   case SystemZ::BI__builtin_s390_vstrcf:
4238   case SystemZ::BI__builtin_s390_vstrczb:
4239   case SystemZ::BI__builtin_s390_vstrczh:
4240   case SystemZ::BI__builtin_s390_vstrczf:
4241   case SystemZ::BI__builtin_s390_vstrcbs:
4242   case SystemZ::BI__builtin_s390_vstrchs:
4243   case SystemZ::BI__builtin_s390_vstrcfs:
4244   case SystemZ::BI__builtin_s390_vstrczbs:
4245   case SystemZ::BI__builtin_s390_vstrczhs:
4246   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4247   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4248   case SystemZ::BI__builtin_s390_vfminsb:
4249   case SystemZ::BI__builtin_s390_vfmaxsb:
4250   case SystemZ::BI__builtin_s390_vfmindb:
4251   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4252   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4253   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4254   case SystemZ::BI__builtin_s390_vclfnhs:
4255   case SystemZ::BI__builtin_s390_vclfnls:
4256   case SystemZ::BI__builtin_s390_vcfn:
4257   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4258   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4259   }
4260   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4261 }
4262 
4263 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4264 /// This checks that the target supports __builtin_cpu_supports and
4265 /// that the string argument is constant and valid.
4266 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4267                                    CallExpr *TheCall) {
4268   Expr *Arg = TheCall->getArg(0);
4269 
4270   // Check if the argument is a string literal.
4271   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4272     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4273            << Arg->getSourceRange();
4274 
4275   // Check the contents of the string.
4276   StringRef Feature =
4277       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4278   if (!TI.validateCpuSupports(Feature))
4279     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4280            << Arg->getSourceRange();
4281   return false;
4282 }
4283 
4284 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4285 /// This checks that the target supports __builtin_cpu_is and
4286 /// that the string argument is constant and valid.
4287 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4288   Expr *Arg = TheCall->getArg(0);
4289 
4290   // Check if the argument is a string literal.
4291   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4292     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4293            << Arg->getSourceRange();
4294 
4295   // Check the contents of the string.
4296   StringRef Feature =
4297       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4298   if (!TI.validateCpuIs(Feature))
4299     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4300            << Arg->getSourceRange();
4301   return false;
4302 }
4303 
4304 // Check if the rounding mode is legal.
4305 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4306   // Indicates if this instruction has rounding control or just SAE.
4307   bool HasRC = false;
4308 
4309   unsigned ArgNum = 0;
4310   switch (BuiltinID) {
4311   default:
4312     return false;
4313   case X86::BI__builtin_ia32_vcvttsd2si32:
4314   case X86::BI__builtin_ia32_vcvttsd2si64:
4315   case X86::BI__builtin_ia32_vcvttsd2usi32:
4316   case X86::BI__builtin_ia32_vcvttsd2usi64:
4317   case X86::BI__builtin_ia32_vcvttss2si32:
4318   case X86::BI__builtin_ia32_vcvttss2si64:
4319   case X86::BI__builtin_ia32_vcvttss2usi32:
4320   case X86::BI__builtin_ia32_vcvttss2usi64:
4321   case X86::BI__builtin_ia32_vcvttsh2si32:
4322   case X86::BI__builtin_ia32_vcvttsh2si64:
4323   case X86::BI__builtin_ia32_vcvttsh2usi32:
4324   case X86::BI__builtin_ia32_vcvttsh2usi64:
4325     ArgNum = 1;
4326     break;
4327   case X86::BI__builtin_ia32_maxpd512:
4328   case X86::BI__builtin_ia32_maxps512:
4329   case X86::BI__builtin_ia32_minpd512:
4330   case X86::BI__builtin_ia32_minps512:
4331   case X86::BI__builtin_ia32_maxph512:
4332   case X86::BI__builtin_ia32_minph512:
4333     ArgNum = 2;
4334     break;
4335   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4336   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4337   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4338   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4339   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4340   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4341   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4342   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4343   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4344   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4345   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4346   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4347   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4348   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4349   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4350   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4351   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4352   case X86::BI__builtin_ia32_exp2pd_mask:
4353   case X86::BI__builtin_ia32_exp2ps_mask:
4354   case X86::BI__builtin_ia32_getexppd512_mask:
4355   case X86::BI__builtin_ia32_getexpps512_mask:
4356   case X86::BI__builtin_ia32_getexpph512_mask:
4357   case X86::BI__builtin_ia32_rcp28pd_mask:
4358   case X86::BI__builtin_ia32_rcp28ps_mask:
4359   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4360   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4361   case X86::BI__builtin_ia32_vcomisd:
4362   case X86::BI__builtin_ia32_vcomiss:
4363   case X86::BI__builtin_ia32_vcomish:
4364   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4365     ArgNum = 3;
4366     break;
4367   case X86::BI__builtin_ia32_cmppd512_mask:
4368   case X86::BI__builtin_ia32_cmpps512_mask:
4369   case X86::BI__builtin_ia32_cmpsd_mask:
4370   case X86::BI__builtin_ia32_cmpss_mask:
4371   case X86::BI__builtin_ia32_cmpsh_mask:
4372   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4373   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4374   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4375   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4376   case X86::BI__builtin_ia32_getexpss128_round_mask:
4377   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4378   case X86::BI__builtin_ia32_getmantpd512_mask:
4379   case X86::BI__builtin_ia32_getmantps512_mask:
4380   case X86::BI__builtin_ia32_getmantph512_mask:
4381   case X86::BI__builtin_ia32_maxsd_round_mask:
4382   case X86::BI__builtin_ia32_maxss_round_mask:
4383   case X86::BI__builtin_ia32_maxsh_round_mask:
4384   case X86::BI__builtin_ia32_minsd_round_mask:
4385   case X86::BI__builtin_ia32_minss_round_mask:
4386   case X86::BI__builtin_ia32_minsh_round_mask:
4387   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4388   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4389   case X86::BI__builtin_ia32_reducepd512_mask:
4390   case X86::BI__builtin_ia32_reduceps512_mask:
4391   case X86::BI__builtin_ia32_reduceph512_mask:
4392   case X86::BI__builtin_ia32_rndscalepd_mask:
4393   case X86::BI__builtin_ia32_rndscaleps_mask:
4394   case X86::BI__builtin_ia32_rndscaleph_mask:
4395   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4396   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4397     ArgNum = 4;
4398     break;
4399   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4400   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4401   case X86::BI__builtin_ia32_fixupimmps512_mask:
4402   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4403   case X86::BI__builtin_ia32_fixupimmsd_mask:
4404   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4405   case X86::BI__builtin_ia32_fixupimmss_mask:
4406   case X86::BI__builtin_ia32_fixupimmss_maskz:
4407   case X86::BI__builtin_ia32_getmantsd_round_mask:
4408   case X86::BI__builtin_ia32_getmantss_round_mask:
4409   case X86::BI__builtin_ia32_getmantsh_round_mask:
4410   case X86::BI__builtin_ia32_rangepd512_mask:
4411   case X86::BI__builtin_ia32_rangeps512_mask:
4412   case X86::BI__builtin_ia32_rangesd128_round_mask:
4413   case X86::BI__builtin_ia32_rangess128_round_mask:
4414   case X86::BI__builtin_ia32_reducesd_mask:
4415   case X86::BI__builtin_ia32_reducess_mask:
4416   case X86::BI__builtin_ia32_reducesh_mask:
4417   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4418   case X86::BI__builtin_ia32_rndscaless_round_mask:
4419   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4420     ArgNum = 5;
4421     break;
4422   case X86::BI__builtin_ia32_vcvtsd2si64:
4423   case X86::BI__builtin_ia32_vcvtsd2si32:
4424   case X86::BI__builtin_ia32_vcvtsd2usi32:
4425   case X86::BI__builtin_ia32_vcvtsd2usi64:
4426   case X86::BI__builtin_ia32_vcvtss2si32:
4427   case X86::BI__builtin_ia32_vcvtss2si64:
4428   case X86::BI__builtin_ia32_vcvtss2usi32:
4429   case X86::BI__builtin_ia32_vcvtss2usi64:
4430   case X86::BI__builtin_ia32_vcvtsh2si32:
4431   case X86::BI__builtin_ia32_vcvtsh2si64:
4432   case X86::BI__builtin_ia32_vcvtsh2usi32:
4433   case X86::BI__builtin_ia32_vcvtsh2usi64:
4434   case X86::BI__builtin_ia32_sqrtpd512:
4435   case X86::BI__builtin_ia32_sqrtps512:
4436   case X86::BI__builtin_ia32_sqrtph512:
4437     ArgNum = 1;
4438     HasRC = true;
4439     break;
4440   case X86::BI__builtin_ia32_addph512:
4441   case X86::BI__builtin_ia32_divph512:
4442   case X86::BI__builtin_ia32_mulph512:
4443   case X86::BI__builtin_ia32_subph512:
4444   case X86::BI__builtin_ia32_addpd512:
4445   case X86::BI__builtin_ia32_addps512:
4446   case X86::BI__builtin_ia32_divpd512:
4447   case X86::BI__builtin_ia32_divps512:
4448   case X86::BI__builtin_ia32_mulpd512:
4449   case X86::BI__builtin_ia32_mulps512:
4450   case X86::BI__builtin_ia32_subpd512:
4451   case X86::BI__builtin_ia32_subps512:
4452   case X86::BI__builtin_ia32_cvtsi2sd64:
4453   case X86::BI__builtin_ia32_cvtsi2ss32:
4454   case X86::BI__builtin_ia32_cvtsi2ss64:
4455   case X86::BI__builtin_ia32_cvtusi2sd64:
4456   case X86::BI__builtin_ia32_cvtusi2ss32:
4457   case X86::BI__builtin_ia32_cvtusi2ss64:
4458   case X86::BI__builtin_ia32_vcvtusi2sh:
4459   case X86::BI__builtin_ia32_vcvtusi642sh:
4460   case X86::BI__builtin_ia32_vcvtsi2sh:
4461   case X86::BI__builtin_ia32_vcvtsi642sh:
4462     ArgNum = 2;
4463     HasRC = true;
4464     break;
4465   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4466   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4467   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4468   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4469   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4470   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4471   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4472   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4473   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4474   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4475   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4476   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4477   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4478   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4479   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4480   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4481   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4482   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4483   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4484   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4485   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4486   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4487   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4488   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4489   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4490   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4491   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4492   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4493   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4494     ArgNum = 3;
4495     HasRC = true;
4496     break;
4497   case X86::BI__builtin_ia32_addsh_round_mask:
4498   case X86::BI__builtin_ia32_addss_round_mask:
4499   case X86::BI__builtin_ia32_addsd_round_mask:
4500   case X86::BI__builtin_ia32_divsh_round_mask:
4501   case X86::BI__builtin_ia32_divss_round_mask:
4502   case X86::BI__builtin_ia32_divsd_round_mask:
4503   case X86::BI__builtin_ia32_mulsh_round_mask:
4504   case X86::BI__builtin_ia32_mulss_round_mask:
4505   case X86::BI__builtin_ia32_mulsd_round_mask:
4506   case X86::BI__builtin_ia32_subsh_round_mask:
4507   case X86::BI__builtin_ia32_subss_round_mask:
4508   case X86::BI__builtin_ia32_subsd_round_mask:
4509   case X86::BI__builtin_ia32_scalefph512_mask:
4510   case X86::BI__builtin_ia32_scalefpd512_mask:
4511   case X86::BI__builtin_ia32_scalefps512_mask:
4512   case X86::BI__builtin_ia32_scalefsd_round_mask:
4513   case X86::BI__builtin_ia32_scalefss_round_mask:
4514   case X86::BI__builtin_ia32_scalefsh_round_mask:
4515   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4516   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4517   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4518   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4519   case X86::BI__builtin_ia32_sqrtss_round_mask:
4520   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4521   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4522   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4523   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4524   case X86::BI__builtin_ia32_vfmaddss3_mask:
4525   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4526   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4527   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4528   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4529   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4530   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4531   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4532   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4533   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4534   case X86::BI__builtin_ia32_vfmaddps512_mask:
4535   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4536   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4537   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4538   case X86::BI__builtin_ia32_vfmaddph512_mask:
4539   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4540   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4541   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4542   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4543   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4544   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4545   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4546   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4547   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4548   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4549   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4550   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4551   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4552   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4553   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4554   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4555   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4556   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4557   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4558   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4559   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4560   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4561   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4562   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4563   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4564   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4565   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4566   case X86::BI__builtin_ia32_vfmulcsh_mask:
4567   case X86::BI__builtin_ia32_vfmulcph512_mask:
4568   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4569   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4570     ArgNum = 4;
4571     HasRC = true;
4572     break;
4573   }
4574 
4575   llvm::APSInt Result;
4576 
4577   // We can't check the value of a dependent argument.
4578   Expr *Arg = TheCall->getArg(ArgNum);
4579   if (Arg->isTypeDependent() || Arg->isValueDependent())
4580     return false;
4581 
4582   // Check constant-ness first.
4583   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4584     return true;
4585 
4586   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4587   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4588   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4589   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4590   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4591       Result == 8/*ROUND_NO_EXC*/ ||
4592       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4593       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4594     return false;
4595 
4596   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4597          << Arg->getSourceRange();
4598 }
4599 
4600 // Check if the gather/scatter scale is legal.
4601 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4602                                              CallExpr *TheCall) {
4603   unsigned ArgNum = 0;
4604   switch (BuiltinID) {
4605   default:
4606     return false;
4607   case X86::BI__builtin_ia32_gatherpfdpd:
4608   case X86::BI__builtin_ia32_gatherpfdps:
4609   case X86::BI__builtin_ia32_gatherpfqpd:
4610   case X86::BI__builtin_ia32_gatherpfqps:
4611   case X86::BI__builtin_ia32_scatterpfdpd:
4612   case X86::BI__builtin_ia32_scatterpfdps:
4613   case X86::BI__builtin_ia32_scatterpfqpd:
4614   case X86::BI__builtin_ia32_scatterpfqps:
4615     ArgNum = 3;
4616     break;
4617   case X86::BI__builtin_ia32_gatherd_pd:
4618   case X86::BI__builtin_ia32_gatherd_pd256:
4619   case X86::BI__builtin_ia32_gatherq_pd:
4620   case X86::BI__builtin_ia32_gatherq_pd256:
4621   case X86::BI__builtin_ia32_gatherd_ps:
4622   case X86::BI__builtin_ia32_gatherd_ps256:
4623   case X86::BI__builtin_ia32_gatherq_ps:
4624   case X86::BI__builtin_ia32_gatherq_ps256:
4625   case X86::BI__builtin_ia32_gatherd_q:
4626   case X86::BI__builtin_ia32_gatherd_q256:
4627   case X86::BI__builtin_ia32_gatherq_q:
4628   case X86::BI__builtin_ia32_gatherq_q256:
4629   case X86::BI__builtin_ia32_gatherd_d:
4630   case X86::BI__builtin_ia32_gatherd_d256:
4631   case X86::BI__builtin_ia32_gatherq_d:
4632   case X86::BI__builtin_ia32_gatherq_d256:
4633   case X86::BI__builtin_ia32_gather3div2df:
4634   case X86::BI__builtin_ia32_gather3div2di:
4635   case X86::BI__builtin_ia32_gather3div4df:
4636   case X86::BI__builtin_ia32_gather3div4di:
4637   case X86::BI__builtin_ia32_gather3div4sf:
4638   case X86::BI__builtin_ia32_gather3div4si:
4639   case X86::BI__builtin_ia32_gather3div8sf:
4640   case X86::BI__builtin_ia32_gather3div8si:
4641   case X86::BI__builtin_ia32_gather3siv2df:
4642   case X86::BI__builtin_ia32_gather3siv2di:
4643   case X86::BI__builtin_ia32_gather3siv4df:
4644   case X86::BI__builtin_ia32_gather3siv4di:
4645   case X86::BI__builtin_ia32_gather3siv4sf:
4646   case X86::BI__builtin_ia32_gather3siv4si:
4647   case X86::BI__builtin_ia32_gather3siv8sf:
4648   case X86::BI__builtin_ia32_gather3siv8si:
4649   case X86::BI__builtin_ia32_gathersiv8df:
4650   case X86::BI__builtin_ia32_gathersiv16sf:
4651   case X86::BI__builtin_ia32_gatherdiv8df:
4652   case X86::BI__builtin_ia32_gatherdiv16sf:
4653   case X86::BI__builtin_ia32_gathersiv8di:
4654   case X86::BI__builtin_ia32_gathersiv16si:
4655   case X86::BI__builtin_ia32_gatherdiv8di:
4656   case X86::BI__builtin_ia32_gatherdiv16si:
4657   case X86::BI__builtin_ia32_scatterdiv2df:
4658   case X86::BI__builtin_ia32_scatterdiv2di:
4659   case X86::BI__builtin_ia32_scatterdiv4df:
4660   case X86::BI__builtin_ia32_scatterdiv4di:
4661   case X86::BI__builtin_ia32_scatterdiv4sf:
4662   case X86::BI__builtin_ia32_scatterdiv4si:
4663   case X86::BI__builtin_ia32_scatterdiv8sf:
4664   case X86::BI__builtin_ia32_scatterdiv8si:
4665   case X86::BI__builtin_ia32_scattersiv2df:
4666   case X86::BI__builtin_ia32_scattersiv2di:
4667   case X86::BI__builtin_ia32_scattersiv4df:
4668   case X86::BI__builtin_ia32_scattersiv4di:
4669   case X86::BI__builtin_ia32_scattersiv4sf:
4670   case X86::BI__builtin_ia32_scattersiv4si:
4671   case X86::BI__builtin_ia32_scattersiv8sf:
4672   case X86::BI__builtin_ia32_scattersiv8si:
4673   case X86::BI__builtin_ia32_scattersiv8df:
4674   case X86::BI__builtin_ia32_scattersiv16sf:
4675   case X86::BI__builtin_ia32_scatterdiv8df:
4676   case X86::BI__builtin_ia32_scatterdiv16sf:
4677   case X86::BI__builtin_ia32_scattersiv8di:
4678   case X86::BI__builtin_ia32_scattersiv16si:
4679   case X86::BI__builtin_ia32_scatterdiv8di:
4680   case X86::BI__builtin_ia32_scatterdiv16si:
4681     ArgNum = 4;
4682     break;
4683   }
4684 
4685   llvm::APSInt Result;
4686 
4687   // We can't check the value of a dependent argument.
4688   Expr *Arg = TheCall->getArg(ArgNum);
4689   if (Arg->isTypeDependent() || Arg->isValueDependent())
4690     return false;
4691 
4692   // Check constant-ness first.
4693   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4694     return true;
4695 
4696   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4697     return false;
4698 
4699   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4700          << Arg->getSourceRange();
4701 }
4702 
4703 enum { TileRegLow = 0, TileRegHigh = 7 };
4704 
4705 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4706                                              ArrayRef<int> ArgNums) {
4707   for (int ArgNum : ArgNums) {
4708     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4709       return true;
4710   }
4711   return false;
4712 }
4713 
4714 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4715                                         ArrayRef<int> ArgNums) {
4716   // Because the max number of tile register is TileRegHigh + 1, so here we use
4717   // each bit to represent the usage of them in bitset.
4718   std::bitset<TileRegHigh + 1> ArgValues;
4719   for (int ArgNum : ArgNums) {
4720     Expr *Arg = TheCall->getArg(ArgNum);
4721     if (Arg->isTypeDependent() || Arg->isValueDependent())
4722       continue;
4723 
4724     llvm::APSInt Result;
4725     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4726       return true;
4727     int ArgExtValue = Result.getExtValue();
4728     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4729            "Incorrect tile register num.");
4730     if (ArgValues.test(ArgExtValue))
4731       return Diag(TheCall->getBeginLoc(),
4732                   diag::err_x86_builtin_tile_arg_duplicate)
4733              << TheCall->getArg(ArgNum)->getSourceRange();
4734     ArgValues.set(ArgExtValue);
4735   }
4736   return false;
4737 }
4738 
4739 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4740                                                 ArrayRef<int> ArgNums) {
4741   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4742          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4743 }
4744 
4745 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4746   switch (BuiltinID) {
4747   default:
4748     return false;
4749   case X86::BI__builtin_ia32_tileloadd64:
4750   case X86::BI__builtin_ia32_tileloaddt164:
4751   case X86::BI__builtin_ia32_tilestored64:
4752   case X86::BI__builtin_ia32_tilezero:
4753     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4754   case X86::BI__builtin_ia32_tdpbssd:
4755   case X86::BI__builtin_ia32_tdpbsud:
4756   case X86::BI__builtin_ia32_tdpbusd:
4757   case X86::BI__builtin_ia32_tdpbuud:
4758   case X86::BI__builtin_ia32_tdpbf16ps:
4759     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4760   }
4761 }
4762 static bool isX86_32Builtin(unsigned BuiltinID) {
4763   // These builtins only work on x86-32 targets.
4764   switch (BuiltinID) {
4765   case X86::BI__builtin_ia32_readeflags_u32:
4766   case X86::BI__builtin_ia32_writeeflags_u32:
4767     return true;
4768   }
4769 
4770   return false;
4771 }
4772 
4773 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4774                                        CallExpr *TheCall) {
4775   if (BuiltinID == X86::BI__builtin_cpu_supports)
4776     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4777 
4778   if (BuiltinID == X86::BI__builtin_cpu_is)
4779     return SemaBuiltinCpuIs(*this, TI, TheCall);
4780 
4781   // Check for 32-bit only builtins on a 64-bit target.
4782   const llvm::Triple &TT = TI.getTriple();
4783   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4784     return Diag(TheCall->getCallee()->getBeginLoc(),
4785                 diag::err_32_bit_builtin_64_bit_tgt);
4786 
4787   // If the intrinsic has rounding or SAE make sure its valid.
4788   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4789     return true;
4790 
4791   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4792   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4793     return true;
4794 
4795   // If the intrinsic has a tile arguments, make sure they are valid.
4796   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4797     return true;
4798 
4799   // For intrinsics which take an immediate value as part of the instruction,
4800   // range check them here.
4801   int i = 0, l = 0, u = 0;
4802   switch (BuiltinID) {
4803   default:
4804     return false;
4805   case X86::BI__builtin_ia32_vec_ext_v2si:
4806   case X86::BI__builtin_ia32_vec_ext_v2di:
4807   case X86::BI__builtin_ia32_vextractf128_pd256:
4808   case X86::BI__builtin_ia32_vextractf128_ps256:
4809   case X86::BI__builtin_ia32_vextractf128_si256:
4810   case X86::BI__builtin_ia32_extract128i256:
4811   case X86::BI__builtin_ia32_extractf64x4_mask:
4812   case X86::BI__builtin_ia32_extracti64x4_mask:
4813   case X86::BI__builtin_ia32_extractf32x8_mask:
4814   case X86::BI__builtin_ia32_extracti32x8_mask:
4815   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4816   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4817   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4818   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4819     i = 1; l = 0; u = 1;
4820     break;
4821   case X86::BI__builtin_ia32_vec_set_v2di:
4822   case X86::BI__builtin_ia32_vinsertf128_pd256:
4823   case X86::BI__builtin_ia32_vinsertf128_ps256:
4824   case X86::BI__builtin_ia32_vinsertf128_si256:
4825   case X86::BI__builtin_ia32_insert128i256:
4826   case X86::BI__builtin_ia32_insertf32x8:
4827   case X86::BI__builtin_ia32_inserti32x8:
4828   case X86::BI__builtin_ia32_insertf64x4:
4829   case X86::BI__builtin_ia32_inserti64x4:
4830   case X86::BI__builtin_ia32_insertf64x2_256:
4831   case X86::BI__builtin_ia32_inserti64x2_256:
4832   case X86::BI__builtin_ia32_insertf32x4_256:
4833   case X86::BI__builtin_ia32_inserti32x4_256:
4834     i = 2; l = 0; u = 1;
4835     break;
4836   case X86::BI__builtin_ia32_vpermilpd:
4837   case X86::BI__builtin_ia32_vec_ext_v4hi:
4838   case X86::BI__builtin_ia32_vec_ext_v4si:
4839   case X86::BI__builtin_ia32_vec_ext_v4sf:
4840   case X86::BI__builtin_ia32_vec_ext_v4di:
4841   case X86::BI__builtin_ia32_extractf32x4_mask:
4842   case X86::BI__builtin_ia32_extracti32x4_mask:
4843   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4844   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4845     i = 1; l = 0; u = 3;
4846     break;
4847   case X86::BI_mm_prefetch:
4848   case X86::BI__builtin_ia32_vec_ext_v8hi:
4849   case X86::BI__builtin_ia32_vec_ext_v8si:
4850     i = 1; l = 0; u = 7;
4851     break;
4852   case X86::BI__builtin_ia32_sha1rnds4:
4853   case X86::BI__builtin_ia32_blendpd:
4854   case X86::BI__builtin_ia32_shufpd:
4855   case X86::BI__builtin_ia32_vec_set_v4hi:
4856   case X86::BI__builtin_ia32_vec_set_v4si:
4857   case X86::BI__builtin_ia32_vec_set_v4di:
4858   case X86::BI__builtin_ia32_shuf_f32x4_256:
4859   case X86::BI__builtin_ia32_shuf_f64x2_256:
4860   case X86::BI__builtin_ia32_shuf_i32x4_256:
4861   case X86::BI__builtin_ia32_shuf_i64x2_256:
4862   case X86::BI__builtin_ia32_insertf64x2_512:
4863   case X86::BI__builtin_ia32_inserti64x2_512:
4864   case X86::BI__builtin_ia32_insertf32x4:
4865   case X86::BI__builtin_ia32_inserti32x4:
4866     i = 2; l = 0; u = 3;
4867     break;
4868   case X86::BI__builtin_ia32_vpermil2pd:
4869   case X86::BI__builtin_ia32_vpermil2pd256:
4870   case X86::BI__builtin_ia32_vpermil2ps:
4871   case X86::BI__builtin_ia32_vpermil2ps256:
4872     i = 3; l = 0; u = 3;
4873     break;
4874   case X86::BI__builtin_ia32_cmpb128_mask:
4875   case X86::BI__builtin_ia32_cmpw128_mask:
4876   case X86::BI__builtin_ia32_cmpd128_mask:
4877   case X86::BI__builtin_ia32_cmpq128_mask:
4878   case X86::BI__builtin_ia32_cmpb256_mask:
4879   case X86::BI__builtin_ia32_cmpw256_mask:
4880   case X86::BI__builtin_ia32_cmpd256_mask:
4881   case X86::BI__builtin_ia32_cmpq256_mask:
4882   case X86::BI__builtin_ia32_cmpb512_mask:
4883   case X86::BI__builtin_ia32_cmpw512_mask:
4884   case X86::BI__builtin_ia32_cmpd512_mask:
4885   case X86::BI__builtin_ia32_cmpq512_mask:
4886   case X86::BI__builtin_ia32_ucmpb128_mask:
4887   case X86::BI__builtin_ia32_ucmpw128_mask:
4888   case X86::BI__builtin_ia32_ucmpd128_mask:
4889   case X86::BI__builtin_ia32_ucmpq128_mask:
4890   case X86::BI__builtin_ia32_ucmpb256_mask:
4891   case X86::BI__builtin_ia32_ucmpw256_mask:
4892   case X86::BI__builtin_ia32_ucmpd256_mask:
4893   case X86::BI__builtin_ia32_ucmpq256_mask:
4894   case X86::BI__builtin_ia32_ucmpb512_mask:
4895   case X86::BI__builtin_ia32_ucmpw512_mask:
4896   case X86::BI__builtin_ia32_ucmpd512_mask:
4897   case X86::BI__builtin_ia32_ucmpq512_mask:
4898   case X86::BI__builtin_ia32_vpcomub:
4899   case X86::BI__builtin_ia32_vpcomuw:
4900   case X86::BI__builtin_ia32_vpcomud:
4901   case X86::BI__builtin_ia32_vpcomuq:
4902   case X86::BI__builtin_ia32_vpcomb:
4903   case X86::BI__builtin_ia32_vpcomw:
4904   case X86::BI__builtin_ia32_vpcomd:
4905   case X86::BI__builtin_ia32_vpcomq:
4906   case X86::BI__builtin_ia32_vec_set_v8hi:
4907   case X86::BI__builtin_ia32_vec_set_v8si:
4908     i = 2; l = 0; u = 7;
4909     break;
4910   case X86::BI__builtin_ia32_vpermilpd256:
4911   case X86::BI__builtin_ia32_roundps:
4912   case X86::BI__builtin_ia32_roundpd:
4913   case X86::BI__builtin_ia32_roundps256:
4914   case X86::BI__builtin_ia32_roundpd256:
4915   case X86::BI__builtin_ia32_getmantpd128_mask:
4916   case X86::BI__builtin_ia32_getmantpd256_mask:
4917   case X86::BI__builtin_ia32_getmantps128_mask:
4918   case X86::BI__builtin_ia32_getmantps256_mask:
4919   case X86::BI__builtin_ia32_getmantpd512_mask:
4920   case X86::BI__builtin_ia32_getmantps512_mask:
4921   case X86::BI__builtin_ia32_getmantph128_mask:
4922   case X86::BI__builtin_ia32_getmantph256_mask:
4923   case X86::BI__builtin_ia32_getmantph512_mask:
4924   case X86::BI__builtin_ia32_vec_ext_v16qi:
4925   case X86::BI__builtin_ia32_vec_ext_v16hi:
4926     i = 1; l = 0; u = 15;
4927     break;
4928   case X86::BI__builtin_ia32_pblendd128:
4929   case X86::BI__builtin_ia32_blendps:
4930   case X86::BI__builtin_ia32_blendpd256:
4931   case X86::BI__builtin_ia32_shufpd256:
4932   case X86::BI__builtin_ia32_roundss:
4933   case X86::BI__builtin_ia32_roundsd:
4934   case X86::BI__builtin_ia32_rangepd128_mask:
4935   case X86::BI__builtin_ia32_rangepd256_mask:
4936   case X86::BI__builtin_ia32_rangepd512_mask:
4937   case X86::BI__builtin_ia32_rangeps128_mask:
4938   case X86::BI__builtin_ia32_rangeps256_mask:
4939   case X86::BI__builtin_ia32_rangeps512_mask:
4940   case X86::BI__builtin_ia32_getmantsd_round_mask:
4941   case X86::BI__builtin_ia32_getmantss_round_mask:
4942   case X86::BI__builtin_ia32_getmantsh_round_mask:
4943   case X86::BI__builtin_ia32_vec_set_v16qi:
4944   case X86::BI__builtin_ia32_vec_set_v16hi:
4945     i = 2; l = 0; u = 15;
4946     break;
4947   case X86::BI__builtin_ia32_vec_ext_v32qi:
4948     i = 1; l = 0; u = 31;
4949     break;
4950   case X86::BI__builtin_ia32_cmpps:
4951   case X86::BI__builtin_ia32_cmpss:
4952   case X86::BI__builtin_ia32_cmppd:
4953   case X86::BI__builtin_ia32_cmpsd:
4954   case X86::BI__builtin_ia32_cmpps256:
4955   case X86::BI__builtin_ia32_cmppd256:
4956   case X86::BI__builtin_ia32_cmpps128_mask:
4957   case X86::BI__builtin_ia32_cmppd128_mask:
4958   case X86::BI__builtin_ia32_cmpps256_mask:
4959   case X86::BI__builtin_ia32_cmppd256_mask:
4960   case X86::BI__builtin_ia32_cmpps512_mask:
4961   case X86::BI__builtin_ia32_cmppd512_mask:
4962   case X86::BI__builtin_ia32_cmpsd_mask:
4963   case X86::BI__builtin_ia32_cmpss_mask:
4964   case X86::BI__builtin_ia32_vec_set_v32qi:
4965     i = 2; l = 0; u = 31;
4966     break;
4967   case X86::BI__builtin_ia32_permdf256:
4968   case X86::BI__builtin_ia32_permdi256:
4969   case X86::BI__builtin_ia32_permdf512:
4970   case X86::BI__builtin_ia32_permdi512:
4971   case X86::BI__builtin_ia32_vpermilps:
4972   case X86::BI__builtin_ia32_vpermilps256:
4973   case X86::BI__builtin_ia32_vpermilpd512:
4974   case X86::BI__builtin_ia32_vpermilps512:
4975   case X86::BI__builtin_ia32_pshufd:
4976   case X86::BI__builtin_ia32_pshufd256:
4977   case X86::BI__builtin_ia32_pshufd512:
4978   case X86::BI__builtin_ia32_pshufhw:
4979   case X86::BI__builtin_ia32_pshufhw256:
4980   case X86::BI__builtin_ia32_pshufhw512:
4981   case X86::BI__builtin_ia32_pshuflw:
4982   case X86::BI__builtin_ia32_pshuflw256:
4983   case X86::BI__builtin_ia32_pshuflw512:
4984   case X86::BI__builtin_ia32_vcvtps2ph:
4985   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4986   case X86::BI__builtin_ia32_vcvtps2ph256:
4987   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4988   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4989   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4990   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4991   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4992   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4993   case X86::BI__builtin_ia32_rndscaleps_mask:
4994   case X86::BI__builtin_ia32_rndscalepd_mask:
4995   case X86::BI__builtin_ia32_rndscaleph_mask:
4996   case X86::BI__builtin_ia32_reducepd128_mask:
4997   case X86::BI__builtin_ia32_reducepd256_mask:
4998   case X86::BI__builtin_ia32_reducepd512_mask:
4999   case X86::BI__builtin_ia32_reduceps128_mask:
5000   case X86::BI__builtin_ia32_reduceps256_mask:
5001   case X86::BI__builtin_ia32_reduceps512_mask:
5002   case X86::BI__builtin_ia32_reduceph128_mask:
5003   case X86::BI__builtin_ia32_reduceph256_mask:
5004   case X86::BI__builtin_ia32_reduceph512_mask:
5005   case X86::BI__builtin_ia32_prold512:
5006   case X86::BI__builtin_ia32_prolq512:
5007   case X86::BI__builtin_ia32_prold128:
5008   case X86::BI__builtin_ia32_prold256:
5009   case X86::BI__builtin_ia32_prolq128:
5010   case X86::BI__builtin_ia32_prolq256:
5011   case X86::BI__builtin_ia32_prord512:
5012   case X86::BI__builtin_ia32_prorq512:
5013   case X86::BI__builtin_ia32_prord128:
5014   case X86::BI__builtin_ia32_prord256:
5015   case X86::BI__builtin_ia32_prorq128:
5016   case X86::BI__builtin_ia32_prorq256:
5017   case X86::BI__builtin_ia32_fpclasspd128_mask:
5018   case X86::BI__builtin_ia32_fpclasspd256_mask:
5019   case X86::BI__builtin_ia32_fpclassps128_mask:
5020   case X86::BI__builtin_ia32_fpclassps256_mask:
5021   case X86::BI__builtin_ia32_fpclassps512_mask:
5022   case X86::BI__builtin_ia32_fpclasspd512_mask:
5023   case X86::BI__builtin_ia32_fpclassph128_mask:
5024   case X86::BI__builtin_ia32_fpclassph256_mask:
5025   case X86::BI__builtin_ia32_fpclassph512_mask:
5026   case X86::BI__builtin_ia32_fpclasssd_mask:
5027   case X86::BI__builtin_ia32_fpclassss_mask:
5028   case X86::BI__builtin_ia32_fpclasssh_mask:
5029   case X86::BI__builtin_ia32_pslldqi128_byteshift:
5030   case X86::BI__builtin_ia32_pslldqi256_byteshift:
5031   case X86::BI__builtin_ia32_pslldqi512_byteshift:
5032   case X86::BI__builtin_ia32_psrldqi128_byteshift:
5033   case X86::BI__builtin_ia32_psrldqi256_byteshift:
5034   case X86::BI__builtin_ia32_psrldqi512_byteshift:
5035   case X86::BI__builtin_ia32_kshiftliqi:
5036   case X86::BI__builtin_ia32_kshiftlihi:
5037   case X86::BI__builtin_ia32_kshiftlisi:
5038   case X86::BI__builtin_ia32_kshiftlidi:
5039   case X86::BI__builtin_ia32_kshiftriqi:
5040   case X86::BI__builtin_ia32_kshiftrihi:
5041   case X86::BI__builtin_ia32_kshiftrisi:
5042   case X86::BI__builtin_ia32_kshiftridi:
5043     i = 1; l = 0; u = 255;
5044     break;
5045   case X86::BI__builtin_ia32_vperm2f128_pd256:
5046   case X86::BI__builtin_ia32_vperm2f128_ps256:
5047   case X86::BI__builtin_ia32_vperm2f128_si256:
5048   case X86::BI__builtin_ia32_permti256:
5049   case X86::BI__builtin_ia32_pblendw128:
5050   case X86::BI__builtin_ia32_pblendw256:
5051   case X86::BI__builtin_ia32_blendps256:
5052   case X86::BI__builtin_ia32_pblendd256:
5053   case X86::BI__builtin_ia32_palignr128:
5054   case X86::BI__builtin_ia32_palignr256:
5055   case X86::BI__builtin_ia32_palignr512:
5056   case X86::BI__builtin_ia32_alignq512:
5057   case X86::BI__builtin_ia32_alignd512:
5058   case X86::BI__builtin_ia32_alignd128:
5059   case X86::BI__builtin_ia32_alignd256:
5060   case X86::BI__builtin_ia32_alignq128:
5061   case X86::BI__builtin_ia32_alignq256:
5062   case X86::BI__builtin_ia32_vcomisd:
5063   case X86::BI__builtin_ia32_vcomiss:
5064   case X86::BI__builtin_ia32_shuf_f32x4:
5065   case X86::BI__builtin_ia32_shuf_f64x2:
5066   case X86::BI__builtin_ia32_shuf_i32x4:
5067   case X86::BI__builtin_ia32_shuf_i64x2:
5068   case X86::BI__builtin_ia32_shufpd512:
5069   case X86::BI__builtin_ia32_shufps:
5070   case X86::BI__builtin_ia32_shufps256:
5071   case X86::BI__builtin_ia32_shufps512:
5072   case X86::BI__builtin_ia32_dbpsadbw128:
5073   case X86::BI__builtin_ia32_dbpsadbw256:
5074   case X86::BI__builtin_ia32_dbpsadbw512:
5075   case X86::BI__builtin_ia32_vpshldd128:
5076   case X86::BI__builtin_ia32_vpshldd256:
5077   case X86::BI__builtin_ia32_vpshldd512:
5078   case X86::BI__builtin_ia32_vpshldq128:
5079   case X86::BI__builtin_ia32_vpshldq256:
5080   case X86::BI__builtin_ia32_vpshldq512:
5081   case X86::BI__builtin_ia32_vpshldw128:
5082   case X86::BI__builtin_ia32_vpshldw256:
5083   case X86::BI__builtin_ia32_vpshldw512:
5084   case X86::BI__builtin_ia32_vpshrdd128:
5085   case X86::BI__builtin_ia32_vpshrdd256:
5086   case X86::BI__builtin_ia32_vpshrdd512:
5087   case X86::BI__builtin_ia32_vpshrdq128:
5088   case X86::BI__builtin_ia32_vpshrdq256:
5089   case X86::BI__builtin_ia32_vpshrdq512:
5090   case X86::BI__builtin_ia32_vpshrdw128:
5091   case X86::BI__builtin_ia32_vpshrdw256:
5092   case X86::BI__builtin_ia32_vpshrdw512:
5093     i = 2; l = 0; u = 255;
5094     break;
5095   case X86::BI__builtin_ia32_fixupimmpd512_mask:
5096   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
5097   case X86::BI__builtin_ia32_fixupimmps512_mask:
5098   case X86::BI__builtin_ia32_fixupimmps512_maskz:
5099   case X86::BI__builtin_ia32_fixupimmsd_mask:
5100   case X86::BI__builtin_ia32_fixupimmsd_maskz:
5101   case X86::BI__builtin_ia32_fixupimmss_mask:
5102   case X86::BI__builtin_ia32_fixupimmss_maskz:
5103   case X86::BI__builtin_ia32_fixupimmpd128_mask:
5104   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
5105   case X86::BI__builtin_ia32_fixupimmpd256_mask:
5106   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
5107   case X86::BI__builtin_ia32_fixupimmps128_mask:
5108   case X86::BI__builtin_ia32_fixupimmps128_maskz:
5109   case X86::BI__builtin_ia32_fixupimmps256_mask:
5110   case X86::BI__builtin_ia32_fixupimmps256_maskz:
5111   case X86::BI__builtin_ia32_pternlogd512_mask:
5112   case X86::BI__builtin_ia32_pternlogd512_maskz:
5113   case X86::BI__builtin_ia32_pternlogq512_mask:
5114   case X86::BI__builtin_ia32_pternlogq512_maskz:
5115   case X86::BI__builtin_ia32_pternlogd128_mask:
5116   case X86::BI__builtin_ia32_pternlogd128_maskz:
5117   case X86::BI__builtin_ia32_pternlogd256_mask:
5118   case X86::BI__builtin_ia32_pternlogd256_maskz:
5119   case X86::BI__builtin_ia32_pternlogq128_mask:
5120   case X86::BI__builtin_ia32_pternlogq128_maskz:
5121   case X86::BI__builtin_ia32_pternlogq256_mask:
5122   case X86::BI__builtin_ia32_pternlogq256_maskz:
5123     i = 3; l = 0; u = 255;
5124     break;
5125   case X86::BI__builtin_ia32_gatherpfdpd:
5126   case X86::BI__builtin_ia32_gatherpfdps:
5127   case X86::BI__builtin_ia32_gatherpfqpd:
5128   case X86::BI__builtin_ia32_gatherpfqps:
5129   case X86::BI__builtin_ia32_scatterpfdpd:
5130   case X86::BI__builtin_ia32_scatterpfdps:
5131   case X86::BI__builtin_ia32_scatterpfqpd:
5132   case X86::BI__builtin_ia32_scatterpfqps:
5133     i = 4; l = 2; u = 3;
5134     break;
5135   case X86::BI__builtin_ia32_reducesd_mask:
5136   case X86::BI__builtin_ia32_reducess_mask:
5137   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5138   case X86::BI__builtin_ia32_rndscaless_round_mask:
5139   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5140   case X86::BI__builtin_ia32_reducesh_mask:
5141     i = 4; l = 0; u = 255;
5142     break;
5143   }
5144 
5145   // Note that we don't force a hard error on the range check here, allowing
5146   // template-generated or macro-generated dead code to potentially have out-of-
5147   // range values. These need to code generate, but don't need to necessarily
5148   // make any sense. We use a warning that defaults to an error.
5149   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5150 }
5151 
5152 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5153 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5154 /// Returns true when the format fits the function and the FormatStringInfo has
5155 /// been populated.
5156 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5157                                FormatStringInfo *FSI) {
5158   FSI->HasVAListArg = Format->getFirstArg() == 0;
5159   FSI->FormatIdx = Format->getFormatIdx() - 1;
5160   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5161 
5162   // The way the format attribute works in GCC, the implicit this argument
5163   // of member functions is counted. However, it doesn't appear in our own
5164   // lists, so decrement format_idx in that case.
5165   if (IsCXXMember) {
5166     if(FSI->FormatIdx == 0)
5167       return false;
5168     --FSI->FormatIdx;
5169     if (FSI->FirstDataArg != 0)
5170       --FSI->FirstDataArg;
5171   }
5172   return true;
5173 }
5174 
5175 /// Checks if a the given expression evaluates to null.
5176 ///
5177 /// Returns true if the value evaluates to null.
5178 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5179   // If the expression has non-null type, it doesn't evaluate to null.
5180   if (auto nullability
5181         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5182     if (*nullability == NullabilityKind::NonNull)
5183       return false;
5184   }
5185 
5186   // As a special case, transparent unions initialized with zero are
5187   // considered null for the purposes of the nonnull attribute.
5188   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5189     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5190       if (const CompoundLiteralExpr *CLE =
5191           dyn_cast<CompoundLiteralExpr>(Expr))
5192         if (const InitListExpr *ILE =
5193             dyn_cast<InitListExpr>(CLE->getInitializer()))
5194           Expr = ILE->getInit(0);
5195   }
5196 
5197   bool Result;
5198   return (!Expr->isValueDependent() &&
5199           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5200           !Result);
5201 }
5202 
5203 static void CheckNonNullArgument(Sema &S,
5204                                  const Expr *ArgExpr,
5205                                  SourceLocation CallSiteLoc) {
5206   if (CheckNonNullExpr(S, ArgExpr))
5207     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5208                           S.PDiag(diag::warn_null_arg)
5209                               << ArgExpr->getSourceRange());
5210 }
5211 
5212 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5213   FormatStringInfo FSI;
5214   if ((GetFormatStringType(Format) == FST_NSString) &&
5215       getFormatStringInfo(Format, false, &FSI)) {
5216     Idx = FSI.FormatIdx;
5217     return true;
5218   }
5219   return false;
5220 }
5221 
5222 /// Diagnose use of %s directive in an NSString which is being passed
5223 /// as formatting string to formatting method.
5224 static void
5225 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5226                                         const NamedDecl *FDecl,
5227                                         Expr **Args,
5228                                         unsigned NumArgs) {
5229   unsigned Idx = 0;
5230   bool Format = false;
5231   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5232   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5233     Idx = 2;
5234     Format = true;
5235   }
5236   else
5237     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5238       if (S.GetFormatNSStringIdx(I, Idx)) {
5239         Format = true;
5240         break;
5241       }
5242     }
5243   if (!Format || NumArgs <= Idx)
5244     return;
5245   const Expr *FormatExpr = Args[Idx];
5246   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5247     FormatExpr = CSCE->getSubExpr();
5248   const StringLiteral *FormatString;
5249   if (const ObjCStringLiteral *OSL =
5250       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5251     FormatString = OSL->getString();
5252   else
5253     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5254   if (!FormatString)
5255     return;
5256   if (S.FormatStringHasSArg(FormatString)) {
5257     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5258       << "%s" << 1 << 1;
5259     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5260       << FDecl->getDeclName();
5261   }
5262 }
5263 
5264 /// Determine whether the given type has a non-null nullability annotation.
5265 static bool isNonNullType(ASTContext &ctx, QualType type) {
5266   if (auto nullability = type->getNullability(ctx))
5267     return *nullability == NullabilityKind::NonNull;
5268 
5269   return false;
5270 }
5271 
5272 static void CheckNonNullArguments(Sema &S,
5273                                   const NamedDecl *FDecl,
5274                                   const FunctionProtoType *Proto,
5275                                   ArrayRef<const Expr *> Args,
5276                                   SourceLocation CallSiteLoc) {
5277   assert((FDecl || Proto) && "Need a function declaration or prototype");
5278 
5279   // Already checked by by constant evaluator.
5280   if (S.isConstantEvaluated())
5281     return;
5282   // Check the attributes attached to the method/function itself.
5283   llvm::SmallBitVector NonNullArgs;
5284   if (FDecl) {
5285     // Handle the nonnull attribute on the function/method declaration itself.
5286     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5287       if (!NonNull->args_size()) {
5288         // Easy case: all pointer arguments are nonnull.
5289         for (const auto *Arg : Args)
5290           if (S.isValidPointerAttrType(Arg->getType()))
5291             CheckNonNullArgument(S, Arg, CallSiteLoc);
5292         return;
5293       }
5294 
5295       for (const ParamIdx &Idx : NonNull->args()) {
5296         unsigned IdxAST = Idx.getASTIndex();
5297         if (IdxAST >= Args.size())
5298           continue;
5299         if (NonNullArgs.empty())
5300           NonNullArgs.resize(Args.size());
5301         NonNullArgs.set(IdxAST);
5302       }
5303     }
5304   }
5305 
5306   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5307     // Handle the nonnull attribute on the parameters of the
5308     // function/method.
5309     ArrayRef<ParmVarDecl*> parms;
5310     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5311       parms = FD->parameters();
5312     else
5313       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5314 
5315     unsigned ParamIndex = 0;
5316     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5317          I != E; ++I, ++ParamIndex) {
5318       const ParmVarDecl *PVD = *I;
5319       if (PVD->hasAttr<NonNullAttr>() ||
5320           isNonNullType(S.Context, PVD->getType())) {
5321         if (NonNullArgs.empty())
5322           NonNullArgs.resize(Args.size());
5323 
5324         NonNullArgs.set(ParamIndex);
5325       }
5326     }
5327   } else {
5328     // If we have a non-function, non-method declaration but no
5329     // function prototype, try to dig out the function prototype.
5330     if (!Proto) {
5331       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5332         QualType type = VD->getType().getNonReferenceType();
5333         if (auto pointerType = type->getAs<PointerType>())
5334           type = pointerType->getPointeeType();
5335         else if (auto blockType = type->getAs<BlockPointerType>())
5336           type = blockType->getPointeeType();
5337         // FIXME: data member pointers?
5338 
5339         // Dig out the function prototype, if there is one.
5340         Proto = type->getAs<FunctionProtoType>();
5341       }
5342     }
5343 
5344     // Fill in non-null argument information from the nullability
5345     // information on the parameter types (if we have them).
5346     if (Proto) {
5347       unsigned Index = 0;
5348       for (auto paramType : Proto->getParamTypes()) {
5349         if (isNonNullType(S.Context, paramType)) {
5350           if (NonNullArgs.empty())
5351             NonNullArgs.resize(Args.size());
5352 
5353           NonNullArgs.set(Index);
5354         }
5355 
5356         ++Index;
5357       }
5358     }
5359   }
5360 
5361   // Check for non-null arguments.
5362   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5363        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5364     if (NonNullArgs[ArgIndex])
5365       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5366   }
5367 }
5368 
5369 /// Warn if a pointer or reference argument passed to a function points to an
5370 /// object that is less aligned than the parameter. This can happen when
5371 /// creating a typedef with a lower alignment than the original type and then
5372 /// calling functions defined in terms of the original type.
5373 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5374                              StringRef ParamName, QualType ArgTy,
5375                              QualType ParamTy) {
5376 
5377   // If a function accepts a pointer or reference type
5378   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5379     return;
5380 
5381   // If the parameter is a pointer type, get the pointee type for the
5382   // argument too. If the parameter is a reference type, don't try to get
5383   // the pointee type for the argument.
5384   if (ParamTy->isPointerType())
5385     ArgTy = ArgTy->getPointeeType();
5386 
5387   // Remove reference or pointer
5388   ParamTy = ParamTy->getPointeeType();
5389 
5390   // Find expected alignment, and the actual alignment of the passed object.
5391   // getTypeAlignInChars requires complete types
5392   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5393       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5394       ArgTy->isUndeducedType())
5395     return;
5396 
5397   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5398   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5399 
5400   // If the argument is less aligned than the parameter, there is a
5401   // potential alignment issue.
5402   if (ArgAlign < ParamAlign)
5403     Diag(Loc, diag::warn_param_mismatched_alignment)
5404         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5405         << ParamName << (FDecl != nullptr) << FDecl;
5406 }
5407 
5408 /// Handles the checks for format strings, non-POD arguments to vararg
5409 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5410 /// attributes.
5411 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5412                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5413                      bool IsMemberFunction, SourceLocation Loc,
5414                      SourceRange Range, VariadicCallType CallType) {
5415   // FIXME: We should check as much as we can in the template definition.
5416   if (CurContext->isDependentContext())
5417     return;
5418 
5419   // Printf and scanf checking.
5420   llvm::SmallBitVector CheckedVarArgs;
5421   if (FDecl) {
5422     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5423       // Only create vector if there are format attributes.
5424       CheckedVarArgs.resize(Args.size());
5425 
5426       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5427                            CheckedVarArgs);
5428     }
5429   }
5430 
5431   // Refuse POD arguments that weren't caught by the format string
5432   // checks above.
5433   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5434   if (CallType != VariadicDoesNotApply &&
5435       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5436     unsigned NumParams = Proto ? Proto->getNumParams()
5437                        : FDecl && isa<FunctionDecl>(FDecl)
5438                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5439                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5440                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5441                        : 0;
5442 
5443     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5444       // Args[ArgIdx] can be null in malformed code.
5445       if (const Expr *Arg = Args[ArgIdx]) {
5446         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5447           checkVariadicArgument(Arg, CallType);
5448       }
5449     }
5450   }
5451 
5452   if (FDecl || Proto) {
5453     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5454 
5455     // Type safety checking.
5456     if (FDecl) {
5457       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5458         CheckArgumentWithTypeTag(I, Args, Loc);
5459     }
5460   }
5461 
5462   // Check that passed arguments match the alignment of original arguments.
5463   // Try to get the missing prototype from the declaration.
5464   if (!Proto && FDecl) {
5465     const auto *FT = FDecl->getFunctionType();
5466     if (isa_and_nonnull<FunctionProtoType>(FT))
5467       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5468   }
5469   if (Proto) {
5470     // For variadic functions, we may have more args than parameters.
5471     // For some K&R functions, we may have less args than parameters.
5472     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5473     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5474       // Args[ArgIdx] can be null in malformed code.
5475       if (const Expr *Arg = Args[ArgIdx]) {
5476         if (Arg->containsErrors())
5477           continue;
5478 
5479         QualType ParamTy = Proto->getParamType(ArgIdx);
5480         QualType ArgTy = Arg->getType();
5481         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5482                           ArgTy, ParamTy);
5483       }
5484     }
5485   }
5486 
5487   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5488     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5489     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5490     if (!Arg->isValueDependent()) {
5491       Expr::EvalResult Align;
5492       if (Arg->EvaluateAsInt(Align, Context)) {
5493         const llvm::APSInt &I = Align.Val.getInt();
5494         if (!I.isPowerOf2())
5495           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5496               << Arg->getSourceRange();
5497 
5498         if (I > Sema::MaximumAlignment)
5499           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5500               << Arg->getSourceRange() << Sema::MaximumAlignment;
5501       }
5502     }
5503   }
5504 
5505   if (FD)
5506     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5507 }
5508 
5509 /// CheckConstructorCall - Check a constructor call for correctness and safety
5510 /// properties not enforced by the C type system.
5511 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5512                                 ArrayRef<const Expr *> Args,
5513                                 const FunctionProtoType *Proto,
5514                                 SourceLocation Loc) {
5515   VariadicCallType CallType =
5516       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5517 
5518   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5519   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5520                     Context.getPointerType(Ctor->getThisObjectType()));
5521 
5522   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5523             Loc, SourceRange(), CallType);
5524 }
5525 
5526 /// CheckFunctionCall - Check a direct function call for various correctness
5527 /// and safety properties not strictly enforced by the C type system.
5528 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5529                              const FunctionProtoType *Proto) {
5530   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5531                               isa<CXXMethodDecl>(FDecl);
5532   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5533                           IsMemberOperatorCall;
5534   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5535                                                   TheCall->getCallee());
5536   Expr** Args = TheCall->getArgs();
5537   unsigned NumArgs = TheCall->getNumArgs();
5538 
5539   Expr *ImplicitThis = nullptr;
5540   if (IsMemberOperatorCall) {
5541     // If this is a call to a member operator, hide the first argument
5542     // from checkCall.
5543     // FIXME: Our choice of AST representation here is less than ideal.
5544     ImplicitThis = Args[0];
5545     ++Args;
5546     --NumArgs;
5547   } else if (IsMemberFunction)
5548     ImplicitThis =
5549         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5550 
5551   if (ImplicitThis) {
5552     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5553     // used.
5554     QualType ThisType = ImplicitThis->getType();
5555     if (!ThisType->isPointerType()) {
5556       assert(!ThisType->isReferenceType());
5557       ThisType = Context.getPointerType(ThisType);
5558     }
5559 
5560     QualType ThisTypeFromDecl =
5561         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5562 
5563     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5564                       ThisTypeFromDecl);
5565   }
5566 
5567   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5568             IsMemberFunction, TheCall->getRParenLoc(),
5569             TheCall->getCallee()->getSourceRange(), CallType);
5570 
5571   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5572   // None of the checks below are needed for functions that don't have
5573   // simple names (e.g., C++ conversion functions).
5574   if (!FnInfo)
5575     return false;
5576 
5577   // Enforce TCB except for builtin calls, which are always allowed.
5578   if (FDecl->getBuiltinID() == 0)
5579     CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
5580 
5581   CheckAbsoluteValueFunction(TheCall, FDecl);
5582   CheckMaxUnsignedZero(TheCall, FDecl);
5583 
5584   if (getLangOpts().ObjC)
5585     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5586 
5587   unsigned CMId = FDecl->getMemoryFunctionKind();
5588 
5589   // Handle memory setting and copying functions.
5590   switch (CMId) {
5591   case 0:
5592     return false;
5593   case Builtin::BIstrlcpy: // fallthrough
5594   case Builtin::BIstrlcat:
5595     CheckStrlcpycatArguments(TheCall, FnInfo);
5596     break;
5597   case Builtin::BIstrncat:
5598     CheckStrncatArguments(TheCall, FnInfo);
5599     break;
5600   case Builtin::BIfree:
5601     CheckFreeArguments(TheCall);
5602     break;
5603   default:
5604     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5605   }
5606 
5607   return false;
5608 }
5609 
5610 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5611                                ArrayRef<const Expr *> Args) {
5612   VariadicCallType CallType =
5613       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5614 
5615   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5616             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5617             CallType);
5618 
5619   CheckTCBEnforcement(lbrac, Method);
5620 
5621   return false;
5622 }
5623 
5624 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5625                             const FunctionProtoType *Proto) {
5626   QualType Ty;
5627   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5628     Ty = V->getType().getNonReferenceType();
5629   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5630     Ty = F->getType().getNonReferenceType();
5631   else
5632     return false;
5633 
5634   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5635       !Ty->isFunctionProtoType())
5636     return false;
5637 
5638   VariadicCallType CallType;
5639   if (!Proto || !Proto->isVariadic()) {
5640     CallType = VariadicDoesNotApply;
5641   } else if (Ty->isBlockPointerType()) {
5642     CallType = VariadicBlock;
5643   } else { // Ty->isFunctionPointerType()
5644     CallType = VariadicFunction;
5645   }
5646 
5647   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5648             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5649             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5650             TheCall->getCallee()->getSourceRange(), CallType);
5651 
5652   return false;
5653 }
5654 
5655 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5656 /// such as function pointers returned from functions.
5657 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5658   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5659                                                   TheCall->getCallee());
5660   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5661             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5662             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5663             TheCall->getCallee()->getSourceRange(), CallType);
5664 
5665   return false;
5666 }
5667 
5668 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5669   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5670     return false;
5671 
5672   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5673   switch (Op) {
5674   case AtomicExpr::AO__c11_atomic_init:
5675   case AtomicExpr::AO__opencl_atomic_init:
5676     llvm_unreachable("There is no ordering argument for an init");
5677 
5678   case AtomicExpr::AO__c11_atomic_load:
5679   case AtomicExpr::AO__opencl_atomic_load:
5680   case AtomicExpr::AO__hip_atomic_load:
5681   case AtomicExpr::AO__atomic_load_n:
5682   case AtomicExpr::AO__atomic_load:
5683     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5684            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5685 
5686   case AtomicExpr::AO__c11_atomic_store:
5687   case AtomicExpr::AO__opencl_atomic_store:
5688   case AtomicExpr::AO__hip_atomic_store:
5689   case AtomicExpr::AO__atomic_store:
5690   case AtomicExpr::AO__atomic_store_n:
5691     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5692            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5693            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5694 
5695   default:
5696     return true;
5697   }
5698 }
5699 
5700 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5701                                          AtomicExpr::AtomicOp Op) {
5702   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5703   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5704   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5705   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5706                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5707                          Op);
5708 }
5709 
5710 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5711                                  SourceLocation RParenLoc, MultiExprArg Args,
5712                                  AtomicExpr::AtomicOp Op,
5713                                  AtomicArgumentOrder ArgOrder) {
5714   // All the non-OpenCL operations take one of the following forms.
5715   // The OpenCL operations take the __c11 forms with one extra argument for
5716   // synchronization scope.
5717   enum {
5718     // C    __c11_atomic_init(A *, C)
5719     Init,
5720 
5721     // C    __c11_atomic_load(A *, int)
5722     Load,
5723 
5724     // void __atomic_load(A *, CP, int)
5725     LoadCopy,
5726 
5727     // void __atomic_store(A *, CP, int)
5728     Copy,
5729 
5730     // C    __c11_atomic_add(A *, M, int)
5731     Arithmetic,
5732 
5733     // C    __atomic_exchange_n(A *, CP, int)
5734     Xchg,
5735 
5736     // void __atomic_exchange(A *, C *, CP, int)
5737     GNUXchg,
5738 
5739     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5740     C11CmpXchg,
5741 
5742     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5743     GNUCmpXchg
5744   } Form = Init;
5745 
5746   const unsigned NumForm = GNUCmpXchg + 1;
5747   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5748   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5749   // where:
5750   //   C is an appropriate type,
5751   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5752   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5753   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5754   //   the int parameters are for orderings.
5755 
5756   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5757       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5758       "need to update code for modified forms");
5759   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5760                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5761                         AtomicExpr::AO__atomic_load,
5762                 "need to update code for modified C11 atomics");
5763   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5764                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5765   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5766                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5767   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5768                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5769                IsOpenCL;
5770   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5771              Op == AtomicExpr::AO__atomic_store_n ||
5772              Op == AtomicExpr::AO__atomic_exchange_n ||
5773              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5774   bool IsAddSub = false;
5775 
5776   switch (Op) {
5777   case AtomicExpr::AO__c11_atomic_init:
5778   case AtomicExpr::AO__opencl_atomic_init:
5779     Form = Init;
5780     break;
5781 
5782   case AtomicExpr::AO__c11_atomic_load:
5783   case AtomicExpr::AO__opencl_atomic_load:
5784   case AtomicExpr::AO__hip_atomic_load:
5785   case AtomicExpr::AO__atomic_load_n:
5786     Form = Load;
5787     break;
5788 
5789   case AtomicExpr::AO__atomic_load:
5790     Form = LoadCopy;
5791     break;
5792 
5793   case AtomicExpr::AO__c11_atomic_store:
5794   case AtomicExpr::AO__opencl_atomic_store:
5795   case AtomicExpr::AO__hip_atomic_store:
5796   case AtomicExpr::AO__atomic_store:
5797   case AtomicExpr::AO__atomic_store_n:
5798     Form = Copy;
5799     break;
5800   case AtomicExpr::AO__hip_atomic_fetch_add:
5801   case AtomicExpr::AO__hip_atomic_fetch_min:
5802   case AtomicExpr::AO__hip_atomic_fetch_max:
5803   case AtomicExpr::AO__c11_atomic_fetch_add:
5804   case AtomicExpr::AO__c11_atomic_fetch_sub:
5805   case AtomicExpr::AO__opencl_atomic_fetch_add:
5806   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5807   case AtomicExpr::AO__atomic_fetch_add:
5808   case AtomicExpr::AO__atomic_fetch_sub:
5809   case AtomicExpr::AO__atomic_add_fetch:
5810   case AtomicExpr::AO__atomic_sub_fetch:
5811     IsAddSub = true;
5812     Form = Arithmetic;
5813     break;
5814   case AtomicExpr::AO__c11_atomic_fetch_and:
5815   case AtomicExpr::AO__c11_atomic_fetch_or:
5816   case AtomicExpr::AO__c11_atomic_fetch_xor:
5817   case AtomicExpr::AO__hip_atomic_fetch_and:
5818   case AtomicExpr::AO__hip_atomic_fetch_or:
5819   case AtomicExpr::AO__hip_atomic_fetch_xor:
5820   case AtomicExpr::AO__c11_atomic_fetch_nand:
5821   case AtomicExpr::AO__opencl_atomic_fetch_and:
5822   case AtomicExpr::AO__opencl_atomic_fetch_or:
5823   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5824   case AtomicExpr::AO__atomic_fetch_and:
5825   case AtomicExpr::AO__atomic_fetch_or:
5826   case AtomicExpr::AO__atomic_fetch_xor:
5827   case AtomicExpr::AO__atomic_fetch_nand:
5828   case AtomicExpr::AO__atomic_and_fetch:
5829   case AtomicExpr::AO__atomic_or_fetch:
5830   case AtomicExpr::AO__atomic_xor_fetch:
5831   case AtomicExpr::AO__atomic_nand_fetch:
5832     Form = Arithmetic;
5833     break;
5834   case AtomicExpr::AO__c11_atomic_fetch_min:
5835   case AtomicExpr::AO__c11_atomic_fetch_max:
5836   case AtomicExpr::AO__opencl_atomic_fetch_min:
5837   case AtomicExpr::AO__opencl_atomic_fetch_max:
5838   case AtomicExpr::AO__atomic_min_fetch:
5839   case AtomicExpr::AO__atomic_max_fetch:
5840   case AtomicExpr::AO__atomic_fetch_min:
5841   case AtomicExpr::AO__atomic_fetch_max:
5842     Form = Arithmetic;
5843     break;
5844 
5845   case AtomicExpr::AO__c11_atomic_exchange:
5846   case AtomicExpr::AO__hip_atomic_exchange:
5847   case AtomicExpr::AO__opencl_atomic_exchange:
5848   case AtomicExpr::AO__atomic_exchange_n:
5849     Form = Xchg;
5850     break;
5851 
5852   case AtomicExpr::AO__atomic_exchange:
5853     Form = GNUXchg;
5854     break;
5855 
5856   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5857   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5858   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5859   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5860   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5861   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5862     Form = C11CmpXchg;
5863     break;
5864 
5865   case AtomicExpr::AO__atomic_compare_exchange:
5866   case AtomicExpr::AO__atomic_compare_exchange_n:
5867     Form = GNUCmpXchg;
5868     break;
5869   }
5870 
5871   unsigned AdjustedNumArgs = NumArgs[Form];
5872   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5873     ++AdjustedNumArgs;
5874   // Check we have the right number of arguments.
5875   if (Args.size() < AdjustedNumArgs) {
5876     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5877         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5878         << ExprRange;
5879     return ExprError();
5880   } else if (Args.size() > AdjustedNumArgs) {
5881     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5882          diag::err_typecheck_call_too_many_args)
5883         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5884         << ExprRange;
5885     return ExprError();
5886   }
5887 
5888   // Inspect the first argument of the atomic operation.
5889   Expr *Ptr = Args[0];
5890   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5891   if (ConvertedPtr.isInvalid())
5892     return ExprError();
5893 
5894   Ptr = ConvertedPtr.get();
5895   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5896   if (!pointerType) {
5897     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5898         << Ptr->getType() << Ptr->getSourceRange();
5899     return ExprError();
5900   }
5901 
5902   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5903   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5904   QualType ValType = AtomTy; // 'C'
5905   if (IsC11) {
5906     if (!AtomTy->isAtomicType()) {
5907       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5908           << Ptr->getType() << Ptr->getSourceRange();
5909       return ExprError();
5910     }
5911     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5912         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5913       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5914           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5915           << Ptr->getSourceRange();
5916       return ExprError();
5917     }
5918     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5919   } else if (Form != Load && Form != LoadCopy) {
5920     if (ValType.isConstQualified()) {
5921       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5922           << Ptr->getType() << Ptr->getSourceRange();
5923       return ExprError();
5924     }
5925   }
5926 
5927   // For an arithmetic operation, the implied arithmetic must be well-formed.
5928   if (Form == Arithmetic) {
5929     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5930     // trivial type errors.
5931     auto IsAllowedValueType = [&](QualType ValType) {
5932       if (ValType->isIntegerType())
5933         return true;
5934       if (ValType->isPointerType())
5935         return true;
5936       if (!ValType->isFloatingType())
5937         return false;
5938       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5939       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5940           &Context.getTargetInfo().getLongDoubleFormat() ==
5941               &llvm::APFloat::x87DoubleExtended())
5942         return false;
5943       return true;
5944     };
5945     if (IsAddSub && !IsAllowedValueType(ValType)) {
5946       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5947           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5948       return ExprError();
5949     }
5950     if (!IsAddSub && !ValType->isIntegerType()) {
5951       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5952           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5953       return ExprError();
5954     }
5955     if (IsC11 && ValType->isPointerType() &&
5956         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5957                             diag::err_incomplete_type)) {
5958       return ExprError();
5959     }
5960   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5961     // For __atomic_*_n operations, the value type must be a scalar integral or
5962     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5963     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5964         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5965     return ExprError();
5966   }
5967 
5968   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5969       !AtomTy->isScalarType()) {
5970     // For GNU atomics, require a trivially-copyable type. This is not part of
5971     // the GNU atomics specification but we enforce it for consistency with
5972     // other atomics which generally all require a trivially-copyable type. This
5973     // is because atomics just copy bits.
5974     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5975         << Ptr->getType() << Ptr->getSourceRange();
5976     return ExprError();
5977   }
5978 
5979   switch (ValType.getObjCLifetime()) {
5980   case Qualifiers::OCL_None:
5981   case Qualifiers::OCL_ExplicitNone:
5982     // okay
5983     break;
5984 
5985   case Qualifiers::OCL_Weak:
5986   case Qualifiers::OCL_Strong:
5987   case Qualifiers::OCL_Autoreleasing:
5988     // FIXME: Can this happen? By this point, ValType should be known
5989     // to be trivially copyable.
5990     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5991         << ValType << Ptr->getSourceRange();
5992     return ExprError();
5993   }
5994 
5995   // All atomic operations have an overload which takes a pointer to a volatile
5996   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5997   // into the result or the other operands. Similarly atomic_load takes a
5998   // pointer to a const 'A'.
5999   ValType.removeLocalVolatile();
6000   ValType.removeLocalConst();
6001   QualType ResultType = ValType;
6002   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
6003       Form == Init)
6004     ResultType = Context.VoidTy;
6005   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
6006     ResultType = Context.BoolTy;
6007 
6008   // The type of a parameter passed 'by value'. In the GNU atomics, such
6009   // arguments are actually passed as pointers.
6010   QualType ByValType = ValType; // 'CP'
6011   bool IsPassedByAddress = false;
6012   if (!IsC11 && !IsHIP && !IsN) {
6013     ByValType = Ptr->getType();
6014     IsPassedByAddress = true;
6015   }
6016 
6017   SmallVector<Expr *, 5> APIOrderedArgs;
6018   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
6019     APIOrderedArgs.push_back(Args[0]);
6020     switch (Form) {
6021     case Init:
6022     case Load:
6023       APIOrderedArgs.push_back(Args[1]); // Val1/Order
6024       break;
6025     case LoadCopy:
6026     case Copy:
6027     case Arithmetic:
6028     case Xchg:
6029       APIOrderedArgs.push_back(Args[2]); // Val1
6030       APIOrderedArgs.push_back(Args[1]); // Order
6031       break;
6032     case GNUXchg:
6033       APIOrderedArgs.push_back(Args[2]); // Val1
6034       APIOrderedArgs.push_back(Args[3]); // Val2
6035       APIOrderedArgs.push_back(Args[1]); // Order
6036       break;
6037     case C11CmpXchg:
6038       APIOrderedArgs.push_back(Args[2]); // Val1
6039       APIOrderedArgs.push_back(Args[4]); // Val2
6040       APIOrderedArgs.push_back(Args[1]); // Order
6041       APIOrderedArgs.push_back(Args[3]); // OrderFail
6042       break;
6043     case GNUCmpXchg:
6044       APIOrderedArgs.push_back(Args[2]); // Val1
6045       APIOrderedArgs.push_back(Args[4]); // Val2
6046       APIOrderedArgs.push_back(Args[5]); // Weak
6047       APIOrderedArgs.push_back(Args[1]); // Order
6048       APIOrderedArgs.push_back(Args[3]); // OrderFail
6049       break;
6050     }
6051   } else
6052     APIOrderedArgs.append(Args.begin(), Args.end());
6053 
6054   // The first argument's non-CV pointer type is used to deduce the type of
6055   // subsequent arguments, except for:
6056   //  - weak flag (always converted to bool)
6057   //  - memory order (always converted to int)
6058   //  - scope  (always converted to int)
6059   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
6060     QualType Ty;
6061     if (i < NumVals[Form] + 1) {
6062       switch (i) {
6063       case 0:
6064         // The first argument is always a pointer. It has a fixed type.
6065         // It is always dereferenced, a nullptr is undefined.
6066         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6067         // Nothing else to do: we already know all we want about this pointer.
6068         continue;
6069       case 1:
6070         // The second argument is the non-atomic operand. For arithmetic, this
6071         // is always passed by value, and for a compare_exchange it is always
6072         // passed by address. For the rest, GNU uses by-address and C11 uses
6073         // by-value.
6074         assert(Form != Load);
6075         if (Form == Arithmetic && ValType->isPointerType())
6076           Ty = Context.getPointerDiffType();
6077         else if (Form == Init || Form == Arithmetic)
6078           Ty = ValType;
6079         else if (Form == Copy || Form == Xchg) {
6080           if (IsPassedByAddress) {
6081             // The value pointer is always dereferenced, a nullptr is undefined.
6082             CheckNonNullArgument(*this, APIOrderedArgs[i],
6083                                  ExprRange.getBegin());
6084           }
6085           Ty = ByValType;
6086         } else {
6087           Expr *ValArg = APIOrderedArgs[i];
6088           // The value pointer is always dereferenced, a nullptr is undefined.
6089           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
6090           LangAS AS = LangAS::Default;
6091           // Keep address space of non-atomic pointer type.
6092           if (const PointerType *PtrTy =
6093                   ValArg->getType()->getAs<PointerType>()) {
6094             AS = PtrTy->getPointeeType().getAddressSpace();
6095           }
6096           Ty = Context.getPointerType(
6097               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
6098         }
6099         break;
6100       case 2:
6101         // The third argument to compare_exchange / GNU exchange is the desired
6102         // value, either by-value (for the C11 and *_n variant) or as a pointer.
6103         if (IsPassedByAddress)
6104           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6105         Ty = ByValType;
6106         break;
6107       case 3:
6108         // The fourth argument to GNU compare_exchange is a 'weak' flag.
6109         Ty = Context.BoolTy;
6110         break;
6111       }
6112     } else {
6113       // The order(s) and scope are always converted to int.
6114       Ty = Context.IntTy;
6115     }
6116 
6117     InitializedEntity Entity =
6118         InitializedEntity::InitializeParameter(Context, Ty, false);
6119     ExprResult Arg = APIOrderedArgs[i];
6120     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6121     if (Arg.isInvalid())
6122       return true;
6123     APIOrderedArgs[i] = Arg.get();
6124   }
6125 
6126   // Permute the arguments into a 'consistent' order.
6127   SmallVector<Expr*, 5> SubExprs;
6128   SubExprs.push_back(Ptr);
6129   switch (Form) {
6130   case Init:
6131     // Note, AtomicExpr::getVal1() has a special case for this atomic.
6132     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6133     break;
6134   case Load:
6135     SubExprs.push_back(APIOrderedArgs[1]); // Order
6136     break;
6137   case LoadCopy:
6138   case Copy:
6139   case Arithmetic:
6140   case Xchg:
6141     SubExprs.push_back(APIOrderedArgs[2]); // Order
6142     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6143     break;
6144   case GNUXchg:
6145     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6146     SubExprs.push_back(APIOrderedArgs[3]); // Order
6147     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6148     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6149     break;
6150   case C11CmpXchg:
6151     SubExprs.push_back(APIOrderedArgs[3]); // Order
6152     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6153     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6154     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6155     break;
6156   case GNUCmpXchg:
6157     SubExprs.push_back(APIOrderedArgs[4]); // Order
6158     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6159     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6160     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6161     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6162     break;
6163   }
6164 
6165   if (SubExprs.size() >= 2 && Form != Init) {
6166     if (Optional<llvm::APSInt> Result =
6167             SubExprs[1]->getIntegerConstantExpr(Context))
6168       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6169         Diag(SubExprs[1]->getBeginLoc(),
6170              diag::warn_atomic_op_has_invalid_memory_order)
6171             << SubExprs[1]->getSourceRange();
6172   }
6173 
6174   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6175     auto *Scope = Args[Args.size() - 1];
6176     if (Optional<llvm::APSInt> Result =
6177             Scope->getIntegerConstantExpr(Context)) {
6178       if (!ScopeModel->isValid(Result->getZExtValue()))
6179         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6180             << Scope->getSourceRange();
6181     }
6182     SubExprs.push_back(Scope);
6183   }
6184 
6185   AtomicExpr *AE = new (Context)
6186       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6187 
6188   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6189        Op == AtomicExpr::AO__c11_atomic_store ||
6190        Op == AtomicExpr::AO__opencl_atomic_load ||
6191        Op == AtomicExpr::AO__hip_atomic_load ||
6192        Op == AtomicExpr::AO__opencl_atomic_store ||
6193        Op == AtomicExpr::AO__hip_atomic_store) &&
6194       Context.AtomicUsesUnsupportedLibcall(AE))
6195     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6196         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6197              Op == AtomicExpr::AO__opencl_atomic_load ||
6198              Op == AtomicExpr::AO__hip_atomic_load)
6199                 ? 0
6200                 : 1);
6201 
6202   if (ValType->isBitIntType()) {
6203     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6204     return ExprError();
6205   }
6206 
6207   return AE;
6208 }
6209 
6210 /// checkBuiltinArgument - Given a call to a builtin function, perform
6211 /// normal type-checking on the given argument, updating the call in
6212 /// place.  This is useful when a builtin function requires custom
6213 /// type-checking for some of its arguments but not necessarily all of
6214 /// them.
6215 ///
6216 /// Returns true on error.
6217 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6218   FunctionDecl *Fn = E->getDirectCallee();
6219   assert(Fn && "builtin call without direct callee!");
6220 
6221   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6222   InitializedEntity Entity =
6223     InitializedEntity::InitializeParameter(S.Context, Param);
6224 
6225   ExprResult Arg = E->getArg(0);
6226   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6227   if (Arg.isInvalid())
6228     return true;
6229 
6230   E->setArg(ArgIndex, Arg.get());
6231   return false;
6232 }
6233 
6234 /// We have a call to a function like __sync_fetch_and_add, which is an
6235 /// overloaded function based on the pointer type of its first argument.
6236 /// The main BuildCallExpr routines have already promoted the types of
6237 /// arguments because all of these calls are prototyped as void(...).
6238 ///
6239 /// This function goes through and does final semantic checking for these
6240 /// builtins, as well as generating any warnings.
6241 ExprResult
6242 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6243   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6244   Expr *Callee = TheCall->getCallee();
6245   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6246   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6247 
6248   // Ensure that we have at least one argument to do type inference from.
6249   if (TheCall->getNumArgs() < 1) {
6250     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6251         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6252     return ExprError();
6253   }
6254 
6255   // Inspect the first argument of the atomic builtin.  This should always be
6256   // a pointer type, whose element is an integral scalar or pointer type.
6257   // Because it is a pointer type, we don't have to worry about any implicit
6258   // casts here.
6259   // FIXME: We don't allow floating point scalars as input.
6260   Expr *FirstArg = TheCall->getArg(0);
6261   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6262   if (FirstArgResult.isInvalid())
6263     return ExprError();
6264   FirstArg = FirstArgResult.get();
6265   TheCall->setArg(0, FirstArg);
6266 
6267   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6268   if (!pointerType) {
6269     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6270         << FirstArg->getType() << FirstArg->getSourceRange();
6271     return ExprError();
6272   }
6273 
6274   QualType ValType = pointerType->getPointeeType();
6275   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6276       !ValType->isBlockPointerType()) {
6277     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6278         << FirstArg->getType() << FirstArg->getSourceRange();
6279     return ExprError();
6280   }
6281 
6282   if (ValType.isConstQualified()) {
6283     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6284         << FirstArg->getType() << FirstArg->getSourceRange();
6285     return ExprError();
6286   }
6287 
6288   switch (ValType.getObjCLifetime()) {
6289   case Qualifiers::OCL_None:
6290   case Qualifiers::OCL_ExplicitNone:
6291     // okay
6292     break;
6293 
6294   case Qualifiers::OCL_Weak:
6295   case Qualifiers::OCL_Strong:
6296   case Qualifiers::OCL_Autoreleasing:
6297     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6298         << ValType << FirstArg->getSourceRange();
6299     return ExprError();
6300   }
6301 
6302   // Strip any qualifiers off ValType.
6303   ValType = ValType.getUnqualifiedType();
6304 
6305   // The majority of builtins return a value, but a few have special return
6306   // types, so allow them to override appropriately below.
6307   QualType ResultType = ValType;
6308 
6309   // We need to figure out which concrete builtin this maps onto.  For example,
6310   // __sync_fetch_and_add with a 2 byte object turns into
6311   // __sync_fetch_and_add_2.
6312 #define BUILTIN_ROW(x) \
6313   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6314     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6315 
6316   static const unsigned BuiltinIndices[][5] = {
6317     BUILTIN_ROW(__sync_fetch_and_add),
6318     BUILTIN_ROW(__sync_fetch_and_sub),
6319     BUILTIN_ROW(__sync_fetch_and_or),
6320     BUILTIN_ROW(__sync_fetch_and_and),
6321     BUILTIN_ROW(__sync_fetch_and_xor),
6322     BUILTIN_ROW(__sync_fetch_and_nand),
6323 
6324     BUILTIN_ROW(__sync_add_and_fetch),
6325     BUILTIN_ROW(__sync_sub_and_fetch),
6326     BUILTIN_ROW(__sync_and_and_fetch),
6327     BUILTIN_ROW(__sync_or_and_fetch),
6328     BUILTIN_ROW(__sync_xor_and_fetch),
6329     BUILTIN_ROW(__sync_nand_and_fetch),
6330 
6331     BUILTIN_ROW(__sync_val_compare_and_swap),
6332     BUILTIN_ROW(__sync_bool_compare_and_swap),
6333     BUILTIN_ROW(__sync_lock_test_and_set),
6334     BUILTIN_ROW(__sync_lock_release),
6335     BUILTIN_ROW(__sync_swap)
6336   };
6337 #undef BUILTIN_ROW
6338 
6339   // Determine the index of the size.
6340   unsigned SizeIndex;
6341   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6342   case 1: SizeIndex = 0; break;
6343   case 2: SizeIndex = 1; break;
6344   case 4: SizeIndex = 2; break;
6345   case 8: SizeIndex = 3; break;
6346   case 16: SizeIndex = 4; break;
6347   default:
6348     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6349         << FirstArg->getType() << FirstArg->getSourceRange();
6350     return ExprError();
6351   }
6352 
6353   // Each of these builtins has one pointer argument, followed by some number of
6354   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6355   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6356   // as the number of fixed args.
6357   unsigned BuiltinID = FDecl->getBuiltinID();
6358   unsigned BuiltinIndex, NumFixed = 1;
6359   bool WarnAboutSemanticsChange = false;
6360   switch (BuiltinID) {
6361   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6362   case Builtin::BI__sync_fetch_and_add:
6363   case Builtin::BI__sync_fetch_and_add_1:
6364   case Builtin::BI__sync_fetch_and_add_2:
6365   case Builtin::BI__sync_fetch_and_add_4:
6366   case Builtin::BI__sync_fetch_and_add_8:
6367   case Builtin::BI__sync_fetch_and_add_16:
6368     BuiltinIndex = 0;
6369     break;
6370 
6371   case Builtin::BI__sync_fetch_and_sub:
6372   case Builtin::BI__sync_fetch_and_sub_1:
6373   case Builtin::BI__sync_fetch_and_sub_2:
6374   case Builtin::BI__sync_fetch_and_sub_4:
6375   case Builtin::BI__sync_fetch_and_sub_8:
6376   case Builtin::BI__sync_fetch_and_sub_16:
6377     BuiltinIndex = 1;
6378     break;
6379 
6380   case Builtin::BI__sync_fetch_and_or:
6381   case Builtin::BI__sync_fetch_and_or_1:
6382   case Builtin::BI__sync_fetch_and_or_2:
6383   case Builtin::BI__sync_fetch_and_or_4:
6384   case Builtin::BI__sync_fetch_and_or_8:
6385   case Builtin::BI__sync_fetch_and_or_16:
6386     BuiltinIndex = 2;
6387     break;
6388 
6389   case Builtin::BI__sync_fetch_and_and:
6390   case Builtin::BI__sync_fetch_and_and_1:
6391   case Builtin::BI__sync_fetch_and_and_2:
6392   case Builtin::BI__sync_fetch_and_and_4:
6393   case Builtin::BI__sync_fetch_and_and_8:
6394   case Builtin::BI__sync_fetch_and_and_16:
6395     BuiltinIndex = 3;
6396     break;
6397 
6398   case Builtin::BI__sync_fetch_and_xor:
6399   case Builtin::BI__sync_fetch_and_xor_1:
6400   case Builtin::BI__sync_fetch_and_xor_2:
6401   case Builtin::BI__sync_fetch_and_xor_4:
6402   case Builtin::BI__sync_fetch_and_xor_8:
6403   case Builtin::BI__sync_fetch_and_xor_16:
6404     BuiltinIndex = 4;
6405     break;
6406 
6407   case Builtin::BI__sync_fetch_and_nand:
6408   case Builtin::BI__sync_fetch_and_nand_1:
6409   case Builtin::BI__sync_fetch_and_nand_2:
6410   case Builtin::BI__sync_fetch_and_nand_4:
6411   case Builtin::BI__sync_fetch_and_nand_8:
6412   case Builtin::BI__sync_fetch_and_nand_16:
6413     BuiltinIndex = 5;
6414     WarnAboutSemanticsChange = true;
6415     break;
6416 
6417   case Builtin::BI__sync_add_and_fetch:
6418   case Builtin::BI__sync_add_and_fetch_1:
6419   case Builtin::BI__sync_add_and_fetch_2:
6420   case Builtin::BI__sync_add_and_fetch_4:
6421   case Builtin::BI__sync_add_and_fetch_8:
6422   case Builtin::BI__sync_add_and_fetch_16:
6423     BuiltinIndex = 6;
6424     break;
6425 
6426   case Builtin::BI__sync_sub_and_fetch:
6427   case Builtin::BI__sync_sub_and_fetch_1:
6428   case Builtin::BI__sync_sub_and_fetch_2:
6429   case Builtin::BI__sync_sub_and_fetch_4:
6430   case Builtin::BI__sync_sub_and_fetch_8:
6431   case Builtin::BI__sync_sub_and_fetch_16:
6432     BuiltinIndex = 7;
6433     break;
6434 
6435   case Builtin::BI__sync_and_and_fetch:
6436   case Builtin::BI__sync_and_and_fetch_1:
6437   case Builtin::BI__sync_and_and_fetch_2:
6438   case Builtin::BI__sync_and_and_fetch_4:
6439   case Builtin::BI__sync_and_and_fetch_8:
6440   case Builtin::BI__sync_and_and_fetch_16:
6441     BuiltinIndex = 8;
6442     break;
6443 
6444   case Builtin::BI__sync_or_and_fetch:
6445   case Builtin::BI__sync_or_and_fetch_1:
6446   case Builtin::BI__sync_or_and_fetch_2:
6447   case Builtin::BI__sync_or_and_fetch_4:
6448   case Builtin::BI__sync_or_and_fetch_8:
6449   case Builtin::BI__sync_or_and_fetch_16:
6450     BuiltinIndex = 9;
6451     break;
6452 
6453   case Builtin::BI__sync_xor_and_fetch:
6454   case Builtin::BI__sync_xor_and_fetch_1:
6455   case Builtin::BI__sync_xor_and_fetch_2:
6456   case Builtin::BI__sync_xor_and_fetch_4:
6457   case Builtin::BI__sync_xor_and_fetch_8:
6458   case Builtin::BI__sync_xor_and_fetch_16:
6459     BuiltinIndex = 10;
6460     break;
6461 
6462   case Builtin::BI__sync_nand_and_fetch:
6463   case Builtin::BI__sync_nand_and_fetch_1:
6464   case Builtin::BI__sync_nand_and_fetch_2:
6465   case Builtin::BI__sync_nand_and_fetch_4:
6466   case Builtin::BI__sync_nand_and_fetch_8:
6467   case Builtin::BI__sync_nand_and_fetch_16:
6468     BuiltinIndex = 11;
6469     WarnAboutSemanticsChange = true;
6470     break;
6471 
6472   case Builtin::BI__sync_val_compare_and_swap:
6473   case Builtin::BI__sync_val_compare_and_swap_1:
6474   case Builtin::BI__sync_val_compare_and_swap_2:
6475   case Builtin::BI__sync_val_compare_and_swap_4:
6476   case Builtin::BI__sync_val_compare_and_swap_8:
6477   case Builtin::BI__sync_val_compare_and_swap_16:
6478     BuiltinIndex = 12;
6479     NumFixed = 2;
6480     break;
6481 
6482   case Builtin::BI__sync_bool_compare_and_swap:
6483   case Builtin::BI__sync_bool_compare_and_swap_1:
6484   case Builtin::BI__sync_bool_compare_and_swap_2:
6485   case Builtin::BI__sync_bool_compare_and_swap_4:
6486   case Builtin::BI__sync_bool_compare_and_swap_8:
6487   case Builtin::BI__sync_bool_compare_and_swap_16:
6488     BuiltinIndex = 13;
6489     NumFixed = 2;
6490     ResultType = Context.BoolTy;
6491     break;
6492 
6493   case Builtin::BI__sync_lock_test_and_set:
6494   case Builtin::BI__sync_lock_test_and_set_1:
6495   case Builtin::BI__sync_lock_test_and_set_2:
6496   case Builtin::BI__sync_lock_test_and_set_4:
6497   case Builtin::BI__sync_lock_test_and_set_8:
6498   case Builtin::BI__sync_lock_test_and_set_16:
6499     BuiltinIndex = 14;
6500     break;
6501 
6502   case Builtin::BI__sync_lock_release:
6503   case Builtin::BI__sync_lock_release_1:
6504   case Builtin::BI__sync_lock_release_2:
6505   case Builtin::BI__sync_lock_release_4:
6506   case Builtin::BI__sync_lock_release_8:
6507   case Builtin::BI__sync_lock_release_16:
6508     BuiltinIndex = 15;
6509     NumFixed = 0;
6510     ResultType = Context.VoidTy;
6511     break;
6512 
6513   case Builtin::BI__sync_swap:
6514   case Builtin::BI__sync_swap_1:
6515   case Builtin::BI__sync_swap_2:
6516   case Builtin::BI__sync_swap_4:
6517   case Builtin::BI__sync_swap_8:
6518   case Builtin::BI__sync_swap_16:
6519     BuiltinIndex = 16;
6520     break;
6521   }
6522 
6523   // Now that we know how many fixed arguments we expect, first check that we
6524   // have at least that many.
6525   if (TheCall->getNumArgs() < 1+NumFixed) {
6526     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6527         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6528         << Callee->getSourceRange();
6529     return ExprError();
6530   }
6531 
6532   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6533       << Callee->getSourceRange();
6534 
6535   if (WarnAboutSemanticsChange) {
6536     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6537         << Callee->getSourceRange();
6538   }
6539 
6540   // Get the decl for the concrete builtin from this, we can tell what the
6541   // concrete integer type we should convert to is.
6542   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6543   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6544   FunctionDecl *NewBuiltinDecl;
6545   if (NewBuiltinID == BuiltinID)
6546     NewBuiltinDecl = FDecl;
6547   else {
6548     // Perform builtin lookup to avoid redeclaring it.
6549     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6550     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6551     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6552     assert(Res.getFoundDecl());
6553     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6554     if (!NewBuiltinDecl)
6555       return ExprError();
6556   }
6557 
6558   // The first argument --- the pointer --- has a fixed type; we
6559   // deduce the types of the rest of the arguments accordingly.  Walk
6560   // the remaining arguments, converting them to the deduced value type.
6561   for (unsigned i = 0; i != NumFixed; ++i) {
6562     ExprResult Arg = TheCall->getArg(i+1);
6563 
6564     // GCC does an implicit conversion to the pointer or integer ValType.  This
6565     // can fail in some cases (1i -> int**), check for this error case now.
6566     // Initialize the argument.
6567     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6568                                                    ValType, /*consume*/ false);
6569     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6570     if (Arg.isInvalid())
6571       return ExprError();
6572 
6573     // Okay, we have something that *can* be converted to the right type.  Check
6574     // to see if there is a potentially weird extension going on here.  This can
6575     // happen when you do an atomic operation on something like an char* and
6576     // pass in 42.  The 42 gets converted to char.  This is even more strange
6577     // for things like 45.123 -> char, etc.
6578     // FIXME: Do this check.
6579     TheCall->setArg(i+1, Arg.get());
6580   }
6581 
6582   // Create a new DeclRefExpr to refer to the new decl.
6583   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6584       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6585       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6586       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6587 
6588   // Set the callee in the CallExpr.
6589   // FIXME: This loses syntactic information.
6590   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6591   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6592                                               CK_BuiltinFnToFnPtr);
6593   TheCall->setCallee(PromotedCall.get());
6594 
6595   // Change the result type of the call to match the original value type. This
6596   // is arbitrary, but the codegen for these builtins ins design to handle it
6597   // gracefully.
6598   TheCall->setType(ResultType);
6599 
6600   // Prohibit problematic uses of bit-precise integer types with atomic
6601   // builtins. The arguments would have already been converted to the first
6602   // argument's type, so only need to check the first argument.
6603   const auto *BitIntValType = ValType->getAs<BitIntType>();
6604   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6605     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6606     return ExprError();
6607   }
6608 
6609   return TheCallResult;
6610 }
6611 
6612 /// SemaBuiltinNontemporalOverloaded - We have a call to
6613 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6614 /// overloaded function based on the pointer type of its last argument.
6615 ///
6616 /// This function goes through and does final semantic checking for these
6617 /// builtins.
6618 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6619   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6620   DeclRefExpr *DRE =
6621       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6622   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6623   unsigned BuiltinID = FDecl->getBuiltinID();
6624   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6625           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6626          "Unexpected nontemporal load/store builtin!");
6627   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6628   unsigned numArgs = isStore ? 2 : 1;
6629 
6630   // Ensure that we have the proper number of arguments.
6631   if (checkArgCount(*this, TheCall, numArgs))
6632     return ExprError();
6633 
6634   // Inspect the last argument of the nontemporal builtin.  This should always
6635   // be a pointer type, from which we imply the type of the memory access.
6636   // Because it is a pointer type, we don't have to worry about any implicit
6637   // casts here.
6638   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6639   ExprResult PointerArgResult =
6640       DefaultFunctionArrayLvalueConversion(PointerArg);
6641 
6642   if (PointerArgResult.isInvalid())
6643     return ExprError();
6644   PointerArg = PointerArgResult.get();
6645   TheCall->setArg(numArgs - 1, PointerArg);
6646 
6647   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6648   if (!pointerType) {
6649     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6650         << PointerArg->getType() << PointerArg->getSourceRange();
6651     return ExprError();
6652   }
6653 
6654   QualType ValType = pointerType->getPointeeType();
6655 
6656   // Strip any qualifiers off ValType.
6657   ValType = ValType.getUnqualifiedType();
6658   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6659       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6660       !ValType->isVectorType()) {
6661     Diag(DRE->getBeginLoc(),
6662          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6663         << PointerArg->getType() << PointerArg->getSourceRange();
6664     return ExprError();
6665   }
6666 
6667   if (!isStore) {
6668     TheCall->setType(ValType);
6669     return TheCallResult;
6670   }
6671 
6672   ExprResult ValArg = TheCall->getArg(0);
6673   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6674       Context, ValType, /*consume*/ false);
6675   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6676   if (ValArg.isInvalid())
6677     return ExprError();
6678 
6679   TheCall->setArg(0, ValArg.get());
6680   TheCall->setType(Context.VoidTy);
6681   return TheCallResult;
6682 }
6683 
6684 /// CheckObjCString - Checks that the argument to the builtin
6685 /// CFString constructor is correct
6686 /// Note: It might also make sense to do the UTF-16 conversion here (would
6687 /// simplify the backend).
6688 bool Sema::CheckObjCString(Expr *Arg) {
6689   Arg = Arg->IgnoreParenCasts();
6690   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6691 
6692   if (!Literal || !Literal->isAscii()) {
6693     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6694         << Arg->getSourceRange();
6695     return true;
6696   }
6697 
6698   if (Literal->containsNonAsciiOrNull()) {
6699     StringRef String = Literal->getString();
6700     unsigned NumBytes = String.size();
6701     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6702     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6703     llvm::UTF16 *ToPtr = &ToBuf[0];
6704 
6705     llvm::ConversionResult Result =
6706         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6707                                  ToPtr + NumBytes, llvm::strictConversion);
6708     // Check for conversion failure.
6709     if (Result != llvm::conversionOK)
6710       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6711           << Arg->getSourceRange();
6712   }
6713   return false;
6714 }
6715 
6716 /// CheckObjCString - Checks that the format string argument to the os_log()
6717 /// and os_trace() functions is correct, and converts it to const char *.
6718 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6719   Arg = Arg->IgnoreParenCasts();
6720   auto *Literal = dyn_cast<StringLiteral>(Arg);
6721   if (!Literal) {
6722     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6723       Literal = ObjcLiteral->getString();
6724     }
6725   }
6726 
6727   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6728     return ExprError(
6729         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6730         << Arg->getSourceRange());
6731   }
6732 
6733   ExprResult Result(Literal);
6734   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6735   InitializedEntity Entity =
6736       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6737   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6738   return Result;
6739 }
6740 
6741 /// Check that the user is calling the appropriate va_start builtin for the
6742 /// target and calling convention.
6743 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6744   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6745   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6746   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6747                     TT.getArch() == llvm::Triple::aarch64_32);
6748   bool IsWindows = TT.isOSWindows();
6749   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6750   if (IsX64 || IsAArch64) {
6751     CallingConv CC = CC_C;
6752     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6753       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6754     if (IsMSVAStart) {
6755       // Don't allow this in System V ABI functions.
6756       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6757         return S.Diag(Fn->getBeginLoc(),
6758                       diag::err_ms_va_start_used_in_sysv_function);
6759     } else {
6760       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6761       // On x64 Windows, don't allow this in System V ABI functions.
6762       // (Yes, that means there's no corresponding way to support variadic
6763       // System V ABI functions on Windows.)
6764       if ((IsWindows && CC == CC_X86_64SysV) ||
6765           (!IsWindows && CC == CC_Win64))
6766         return S.Diag(Fn->getBeginLoc(),
6767                       diag::err_va_start_used_in_wrong_abi_function)
6768                << !IsWindows;
6769     }
6770     return false;
6771   }
6772 
6773   if (IsMSVAStart)
6774     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6775   return false;
6776 }
6777 
6778 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6779                                              ParmVarDecl **LastParam = nullptr) {
6780   // Determine whether the current function, block, or obj-c method is variadic
6781   // and get its parameter list.
6782   bool IsVariadic = false;
6783   ArrayRef<ParmVarDecl *> Params;
6784   DeclContext *Caller = S.CurContext;
6785   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6786     IsVariadic = Block->isVariadic();
6787     Params = Block->parameters();
6788   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6789     IsVariadic = FD->isVariadic();
6790     Params = FD->parameters();
6791   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6792     IsVariadic = MD->isVariadic();
6793     // FIXME: This isn't correct for methods (results in bogus warning).
6794     Params = MD->parameters();
6795   } else if (isa<CapturedDecl>(Caller)) {
6796     // We don't support va_start in a CapturedDecl.
6797     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6798     return true;
6799   } else {
6800     // This must be some other declcontext that parses exprs.
6801     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6802     return true;
6803   }
6804 
6805   if (!IsVariadic) {
6806     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6807     return true;
6808   }
6809 
6810   if (LastParam)
6811     *LastParam = Params.empty() ? nullptr : Params.back();
6812 
6813   return false;
6814 }
6815 
6816 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6817 /// for validity.  Emit an error and return true on failure; return false
6818 /// on success.
6819 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6820   Expr *Fn = TheCall->getCallee();
6821 
6822   if (checkVAStartABI(*this, BuiltinID, Fn))
6823     return true;
6824 
6825   if (checkArgCount(*this, TheCall, 2))
6826     return true;
6827 
6828   // Type-check the first argument normally.
6829   if (checkBuiltinArgument(*this, TheCall, 0))
6830     return true;
6831 
6832   // Check that the current function is variadic, and get its last parameter.
6833   ParmVarDecl *LastParam;
6834   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6835     return true;
6836 
6837   // Verify that the second argument to the builtin is the last argument of the
6838   // current function or method.
6839   bool SecondArgIsLastNamedArgument = false;
6840   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6841 
6842   // These are valid if SecondArgIsLastNamedArgument is false after the next
6843   // block.
6844   QualType Type;
6845   SourceLocation ParamLoc;
6846   bool IsCRegister = false;
6847 
6848   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6849     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6850       SecondArgIsLastNamedArgument = PV == LastParam;
6851 
6852       Type = PV->getType();
6853       ParamLoc = PV->getLocation();
6854       IsCRegister =
6855           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6856     }
6857   }
6858 
6859   if (!SecondArgIsLastNamedArgument)
6860     Diag(TheCall->getArg(1)->getBeginLoc(),
6861          diag::warn_second_arg_of_va_start_not_last_named_param);
6862   else if (IsCRegister || Type->isReferenceType() ||
6863            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6864              // Promotable integers are UB, but enumerations need a bit of
6865              // extra checking to see what their promotable type actually is.
6866              if (!Type->isPromotableIntegerType())
6867                return false;
6868              if (!Type->isEnumeralType())
6869                return true;
6870              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6871              return !(ED &&
6872                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6873            }()) {
6874     unsigned Reason = 0;
6875     if (Type->isReferenceType())  Reason = 1;
6876     else if (IsCRegister)         Reason = 2;
6877     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6878     Diag(ParamLoc, diag::note_parameter_type) << Type;
6879   }
6880 
6881   TheCall->setType(Context.VoidTy);
6882   return false;
6883 }
6884 
6885 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6886   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6887     const LangOptions &LO = getLangOpts();
6888 
6889     if (LO.CPlusPlus)
6890       return Arg->getType()
6891                  .getCanonicalType()
6892                  .getTypePtr()
6893                  ->getPointeeType()
6894                  .withoutLocalFastQualifiers() == Context.CharTy;
6895 
6896     // In C, allow aliasing through `char *`, this is required for AArch64 at
6897     // least.
6898     return true;
6899   };
6900 
6901   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6902   //                 const char *named_addr);
6903 
6904   Expr *Func = Call->getCallee();
6905 
6906   if (Call->getNumArgs() < 3)
6907     return Diag(Call->getEndLoc(),
6908                 diag::err_typecheck_call_too_few_args_at_least)
6909            << 0 /*function call*/ << 3 << Call->getNumArgs();
6910 
6911   // Type-check the first argument normally.
6912   if (checkBuiltinArgument(*this, Call, 0))
6913     return true;
6914 
6915   // Check that the current function is variadic.
6916   if (checkVAStartIsInVariadicFunction(*this, Func))
6917     return true;
6918 
6919   // __va_start on Windows does not validate the parameter qualifiers
6920 
6921   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6922   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6923 
6924   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6925   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6926 
6927   const QualType &ConstCharPtrTy =
6928       Context.getPointerType(Context.CharTy.withConst());
6929   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6930     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6931         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6932         << 0                                      /* qualifier difference */
6933         << 3                                      /* parameter mismatch */
6934         << 2 << Arg1->getType() << ConstCharPtrTy;
6935 
6936   const QualType SizeTy = Context.getSizeType();
6937   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6938     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6939         << Arg2->getType() << SizeTy << 1 /* different class */
6940         << 0                              /* qualifier difference */
6941         << 3                              /* parameter mismatch */
6942         << 3 << Arg2->getType() << SizeTy;
6943 
6944   return false;
6945 }
6946 
6947 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6948 /// friends.  This is declared to take (...), so we have to check everything.
6949 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6950   if (checkArgCount(*this, TheCall, 2))
6951     return true;
6952 
6953   ExprResult OrigArg0 = TheCall->getArg(0);
6954   ExprResult OrigArg1 = TheCall->getArg(1);
6955 
6956   // Do standard promotions between the two arguments, returning their common
6957   // type.
6958   QualType Res = UsualArithmeticConversions(
6959       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6960   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6961     return true;
6962 
6963   // Make sure any conversions are pushed back into the call; this is
6964   // type safe since unordered compare builtins are declared as "_Bool
6965   // foo(...)".
6966   TheCall->setArg(0, OrigArg0.get());
6967   TheCall->setArg(1, OrigArg1.get());
6968 
6969   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6970     return false;
6971 
6972   // If the common type isn't a real floating type, then the arguments were
6973   // invalid for this operation.
6974   if (Res.isNull() || !Res->isRealFloatingType())
6975     return Diag(OrigArg0.get()->getBeginLoc(),
6976                 diag::err_typecheck_call_invalid_ordered_compare)
6977            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6978            << SourceRange(OrigArg0.get()->getBeginLoc(),
6979                           OrigArg1.get()->getEndLoc());
6980 
6981   return false;
6982 }
6983 
6984 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6985 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6986 /// to check everything. We expect the last argument to be a floating point
6987 /// value.
6988 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6989   if (checkArgCount(*this, TheCall, NumArgs))
6990     return true;
6991 
6992   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6993   // on all preceding parameters just being int.  Try all of those.
6994   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6995     Expr *Arg = TheCall->getArg(i);
6996 
6997     if (Arg->isTypeDependent())
6998       return false;
6999 
7000     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
7001 
7002     if (Res.isInvalid())
7003       return true;
7004     TheCall->setArg(i, Res.get());
7005   }
7006 
7007   Expr *OrigArg = TheCall->getArg(NumArgs-1);
7008 
7009   if (OrigArg->isTypeDependent())
7010     return false;
7011 
7012   // Usual Unary Conversions will convert half to float, which we want for
7013   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
7014   // type how it is, but do normal L->Rvalue conversions.
7015   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
7016     OrigArg = UsualUnaryConversions(OrigArg).get();
7017   else
7018     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
7019   TheCall->setArg(NumArgs - 1, OrigArg);
7020 
7021   // This operation requires a non-_Complex floating-point number.
7022   if (!OrigArg->getType()->isRealFloatingType())
7023     return Diag(OrigArg->getBeginLoc(),
7024                 diag::err_typecheck_call_invalid_unary_fp)
7025            << OrigArg->getType() << OrigArg->getSourceRange();
7026 
7027   return false;
7028 }
7029 
7030 /// Perform semantic analysis for a call to __builtin_complex.
7031 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
7032   if (checkArgCount(*this, TheCall, 2))
7033     return true;
7034 
7035   bool Dependent = false;
7036   for (unsigned I = 0; I != 2; ++I) {
7037     Expr *Arg = TheCall->getArg(I);
7038     QualType T = Arg->getType();
7039     if (T->isDependentType()) {
7040       Dependent = true;
7041       continue;
7042     }
7043 
7044     // Despite supporting _Complex int, GCC requires a real floating point type
7045     // for the operands of __builtin_complex.
7046     if (!T->isRealFloatingType()) {
7047       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
7048              << Arg->getType() << Arg->getSourceRange();
7049     }
7050 
7051     ExprResult Converted = DefaultLvalueConversion(Arg);
7052     if (Converted.isInvalid())
7053       return true;
7054     TheCall->setArg(I, Converted.get());
7055   }
7056 
7057   if (Dependent) {
7058     TheCall->setType(Context.DependentTy);
7059     return false;
7060   }
7061 
7062   Expr *Real = TheCall->getArg(0);
7063   Expr *Imag = TheCall->getArg(1);
7064   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
7065     return Diag(Real->getBeginLoc(),
7066                 diag::err_typecheck_call_different_arg_types)
7067            << Real->getType() << Imag->getType()
7068            << Real->getSourceRange() << Imag->getSourceRange();
7069   }
7070 
7071   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
7072   // don't allow this builtin to form those types either.
7073   // FIXME: Should we allow these types?
7074   if (Real->getType()->isFloat16Type())
7075     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7076            << "_Float16";
7077   if (Real->getType()->isHalfType())
7078     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7079            << "half";
7080 
7081   TheCall->setType(Context.getComplexType(Real->getType()));
7082   return false;
7083 }
7084 
7085 // Customized Sema Checking for VSX builtins that have the following signature:
7086 // vector [...] builtinName(vector [...], vector [...], const int);
7087 // Which takes the same type of vectors (any legal vector type) for the first
7088 // two arguments and takes compile time constant for the third argument.
7089 // Example builtins are :
7090 // vector double vec_xxpermdi(vector double, vector double, int);
7091 // vector short vec_xxsldwi(vector short, vector short, int);
7092 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
7093   unsigned ExpectedNumArgs = 3;
7094   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
7095     return true;
7096 
7097   // Check the third argument is a compile time constant
7098   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
7099     return Diag(TheCall->getBeginLoc(),
7100                 diag::err_vsx_builtin_nonconstant_argument)
7101            << 3 /* argument index */ << TheCall->getDirectCallee()
7102            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
7103                           TheCall->getArg(2)->getEndLoc());
7104 
7105   QualType Arg1Ty = TheCall->getArg(0)->getType();
7106   QualType Arg2Ty = TheCall->getArg(1)->getType();
7107 
7108   // Check the type of argument 1 and argument 2 are vectors.
7109   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
7110   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
7111       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
7112     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
7113            << TheCall->getDirectCallee()
7114            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7115                           TheCall->getArg(1)->getEndLoc());
7116   }
7117 
7118   // Check the first two arguments are the same type.
7119   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
7120     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
7121            << TheCall->getDirectCallee()
7122            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7123                           TheCall->getArg(1)->getEndLoc());
7124   }
7125 
7126   // When default clang type checking is turned off and the customized type
7127   // checking is used, the returning type of the function must be explicitly
7128   // set. Otherwise it is _Bool by default.
7129   TheCall->setType(Arg1Ty);
7130 
7131   return false;
7132 }
7133 
7134 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
7135 // This is declared to take (...), so we have to check everything.
7136 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
7137   if (TheCall->getNumArgs() < 2)
7138     return ExprError(Diag(TheCall->getEndLoc(),
7139                           diag::err_typecheck_call_too_few_args_at_least)
7140                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7141                      << TheCall->getSourceRange());
7142 
7143   // Determine which of the following types of shufflevector we're checking:
7144   // 1) unary, vector mask: (lhs, mask)
7145   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7146   QualType resType = TheCall->getArg(0)->getType();
7147   unsigned numElements = 0;
7148 
7149   if (!TheCall->getArg(0)->isTypeDependent() &&
7150       !TheCall->getArg(1)->isTypeDependent()) {
7151     QualType LHSType = TheCall->getArg(0)->getType();
7152     QualType RHSType = TheCall->getArg(1)->getType();
7153 
7154     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7155       return ExprError(
7156           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7157           << TheCall->getDirectCallee()
7158           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7159                          TheCall->getArg(1)->getEndLoc()));
7160 
7161     numElements = LHSType->castAs<VectorType>()->getNumElements();
7162     unsigned numResElements = TheCall->getNumArgs() - 2;
7163 
7164     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7165     // with mask.  If so, verify that RHS is an integer vector type with the
7166     // same number of elts as lhs.
7167     if (TheCall->getNumArgs() == 2) {
7168       if (!RHSType->hasIntegerRepresentation() ||
7169           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7170         return ExprError(Diag(TheCall->getBeginLoc(),
7171                               diag::err_vec_builtin_incompatible_vector)
7172                          << TheCall->getDirectCallee()
7173                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7174                                         TheCall->getArg(1)->getEndLoc()));
7175     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7176       return ExprError(Diag(TheCall->getBeginLoc(),
7177                             diag::err_vec_builtin_incompatible_vector)
7178                        << TheCall->getDirectCallee()
7179                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7180                                       TheCall->getArg(1)->getEndLoc()));
7181     } else if (numElements != numResElements) {
7182       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7183       resType = Context.getVectorType(eltType, numResElements,
7184                                       VectorType::GenericVector);
7185     }
7186   }
7187 
7188   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7189     if (TheCall->getArg(i)->isTypeDependent() ||
7190         TheCall->getArg(i)->isValueDependent())
7191       continue;
7192 
7193     Optional<llvm::APSInt> Result;
7194     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7195       return ExprError(Diag(TheCall->getBeginLoc(),
7196                             diag::err_shufflevector_nonconstant_argument)
7197                        << TheCall->getArg(i)->getSourceRange());
7198 
7199     // Allow -1 which will be translated to undef in the IR.
7200     if (Result->isSigned() && Result->isAllOnes())
7201       continue;
7202 
7203     if (Result->getActiveBits() > 64 ||
7204         Result->getZExtValue() >= numElements * 2)
7205       return ExprError(Diag(TheCall->getBeginLoc(),
7206                             diag::err_shufflevector_argument_too_large)
7207                        << TheCall->getArg(i)->getSourceRange());
7208   }
7209 
7210   SmallVector<Expr*, 32> exprs;
7211 
7212   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7213     exprs.push_back(TheCall->getArg(i));
7214     TheCall->setArg(i, nullptr);
7215   }
7216 
7217   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7218                                          TheCall->getCallee()->getBeginLoc(),
7219                                          TheCall->getRParenLoc());
7220 }
7221 
7222 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7223 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7224                                        SourceLocation BuiltinLoc,
7225                                        SourceLocation RParenLoc) {
7226   ExprValueKind VK = VK_PRValue;
7227   ExprObjectKind OK = OK_Ordinary;
7228   QualType DstTy = TInfo->getType();
7229   QualType SrcTy = E->getType();
7230 
7231   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7232     return ExprError(Diag(BuiltinLoc,
7233                           diag::err_convertvector_non_vector)
7234                      << E->getSourceRange());
7235   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7236     return ExprError(Diag(BuiltinLoc,
7237                           diag::err_convertvector_non_vector_type));
7238 
7239   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7240     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7241     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7242     if (SrcElts != DstElts)
7243       return ExprError(Diag(BuiltinLoc,
7244                             diag::err_convertvector_incompatible_vector)
7245                        << E->getSourceRange());
7246   }
7247 
7248   return new (Context)
7249       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7250 }
7251 
7252 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7253 // This is declared to take (const void*, ...) and can take two
7254 // optional constant int args.
7255 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7256   unsigned NumArgs = TheCall->getNumArgs();
7257 
7258   if (NumArgs > 3)
7259     return Diag(TheCall->getEndLoc(),
7260                 diag::err_typecheck_call_too_many_args_at_most)
7261            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7262 
7263   // Argument 0 is checked for us and the remaining arguments must be
7264   // constant integers.
7265   for (unsigned i = 1; i != NumArgs; ++i)
7266     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7267       return true;
7268 
7269   return false;
7270 }
7271 
7272 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7273 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7274   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7275     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7276            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7277   if (checkArgCount(*this, TheCall, 1))
7278     return true;
7279   Expr *Arg = TheCall->getArg(0);
7280   if (Arg->isInstantiationDependent())
7281     return false;
7282 
7283   QualType ArgTy = Arg->getType();
7284   if (!ArgTy->hasFloatingRepresentation())
7285     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7286            << ArgTy;
7287   if (Arg->isLValue()) {
7288     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7289     TheCall->setArg(0, FirstArg.get());
7290   }
7291   TheCall->setType(TheCall->getArg(0)->getType());
7292   return false;
7293 }
7294 
7295 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7296 // __assume does not evaluate its arguments, and should warn if its argument
7297 // has side effects.
7298 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7299   Expr *Arg = TheCall->getArg(0);
7300   if (Arg->isInstantiationDependent()) return false;
7301 
7302   if (Arg->HasSideEffects(Context))
7303     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7304         << Arg->getSourceRange()
7305         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7306 
7307   return false;
7308 }
7309 
7310 /// Handle __builtin_alloca_with_align. This is declared
7311 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7312 /// than 8.
7313 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7314   // The alignment must be a constant integer.
7315   Expr *Arg = TheCall->getArg(1);
7316 
7317   // We can't check the value of a dependent argument.
7318   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7319     if (const auto *UE =
7320             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7321       if (UE->getKind() == UETT_AlignOf ||
7322           UE->getKind() == UETT_PreferredAlignOf)
7323         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7324             << Arg->getSourceRange();
7325 
7326     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7327 
7328     if (!Result.isPowerOf2())
7329       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7330              << Arg->getSourceRange();
7331 
7332     if (Result < Context.getCharWidth())
7333       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7334              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7335 
7336     if (Result > std::numeric_limits<int32_t>::max())
7337       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7338              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7339   }
7340 
7341   return false;
7342 }
7343 
7344 /// Handle __builtin_assume_aligned. This is declared
7345 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7346 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7347   unsigned NumArgs = TheCall->getNumArgs();
7348 
7349   if (NumArgs > 3)
7350     return Diag(TheCall->getEndLoc(),
7351                 diag::err_typecheck_call_too_many_args_at_most)
7352            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7353 
7354   // The alignment must be a constant integer.
7355   Expr *Arg = TheCall->getArg(1);
7356 
7357   // We can't check the value of a dependent argument.
7358   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7359     llvm::APSInt Result;
7360     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7361       return true;
7362 
7363     if (!Result.isPowerOf2())
7364       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7365              << Arg->getSourceRange();
7366 
7367     if (Result > Sema::MaximumAlignment)
7368       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7369           << Arg->getSourceRange() << Sema::MaximumAlignment;
7370   }
7371 
7372   if (NumArgs > 2) {
7373     ExprResult Arg(TheCall->getArg(2));
7374     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7375       Context.getSizeType(), false);
7376     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7377     if (Arg.isInvalid()) return true;
7378     TheCall->setArg(2, Arg.get());
7379   }
7380 
7381   return false;
7382 }
7383 
7384 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7385   unsigned BuiltinID =
7386       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7387   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7388 
7389   unsigned NumArgs = TheCall->getNumArgs();
7390   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7391   if (NumArgs < NumRequiredArgs) {
7392     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7393            << 0 /* function call */ << NumRequiredArgs << NumArgs
7394            << TheCall->getSourceRange();
7395   }
7396   if (NumArgs >= NumRequiredArgs + 0x100) {
7397     return Diag(TheCall->getEndLoc(),
7398                 diag::err_typecheck_call_too_many_args_at_most)
7399            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7400            << TheCall->getSourceRange();
7401   }
7402   unsigned i = 0;
7403 
7404   // For formatting call, check buffer arg.
7405   if (!IsSizeCall) {
7406     ExprResult Arg(TheCall->getArg(i));
7407     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7408         Context, Context.VoidPtrTy, false);
7409     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7410     if (Arg.isInvalid())
7411       return true;
7412     TheCall->setArg(i, Arg.get());
7413     i++;
7414   }
7415 
7416   // Check string literal arg.
7417   unsigned FormatIdx = i;
7418   {
7419     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7420     if (Arg.isInvalid())
7421       return true;
7422     TheCall->setArg(i, Arg.get());
7423     i++;
7424   }
7425 
7426   // Make sure variadic args are scalar.
7427   unsigned FirstDataArg = i;
7428   while (i < NumArgs) {
7429     ExprResult Arg = DefaultVariadicArgumentPromotion(
7430         TheCall->getArg(i), VariadicFunction, nullptr);
7431     if (Arg.isInvalid())
7432       return true;
7433     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7434     if (ArgSize.getQuantity() >= 0x100) {
7435       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7436              << i << (int)ArgSize.getQuantity() << 0xff
7437              << TheCall->getSourceRange();
7438     }
7439     TheCall->setArg(i, Arg.get());
7440     i++;
7441   }
7442 
7443   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7444   // call to avoid duplicate diagnostics.
7445   if (!IsSizeCall) {
7446     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7447     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7448     bool Success = CheckFormatArguments(
7449         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7450         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7451         CheckedVarArgs);
7452     if (!Success)
7453       return true;
7454   }
7455 
7456   if (IsSizeCall) {
7457     TheCall->setType(Context.getSizeType());
7458   } else {
7459     TheCall->setType(Context.VoidPtrTy);
7460   }
7461   return false;
7462 }
7463 
7464 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7465 /// TheCall is a constant expression.
7466 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7467                                   llvm::APSInt &Result) {
7468   Expr *Arg = TheCall->getArg(ArgNum);
7469   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7470   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7471 
7472   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7473 
7474   Optional<llvm::APSInt> R;
7475   if (!(R = Arg->getIntegerConstantExpr(Context)))
7476     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7477            << FDecl->getDeclName() << Arg->getSourceRange();
7478   Result = *R;
7479   return false;
7480 }
7481 
7482 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7483 /// TheCall is a constant expression in the range [Low, High].
7484 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7485                                        int Low, int High, bool RangeIsError) {
7486   if (isConstantEvaluated())
7487     return false;
7488   llvm::APSInt Result;
7489 
7490   // We can't check the value of a dependent argument.
7491   Expr *Arg = TheCall->getArg(ArgNum);
7492   if (Arg->isTypeDependent() || Arg->isValueDependent())
7493     return false;
7494 
7495   // Check constant-ness first.
7496   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7497     return true;
7498 
7499   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7500     if (RangeIsError)
7501       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7502              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7503     else
7504       // Defer the warning until we know if the code will be emitted so that
7505       // dead code can ignore this.
7506       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7507                           PDiag(diag::warn_argument_invalid_range)
7508                               << toString(Result, 10) << Low << High
7509                               << Arg->getSourceRange());
7510   }
7511 
7512   return false;
7513 }
7514 
7515 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7516 /// TheCall is a constant expression is a multiple of Num..
7517 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7518                                           unsigned Num) {
7519   llvm::APSInt Result;
7520 
7521   // We can't check the value of a dependent argument.
7522   Expr *Arg = TheCall->getArg(ArgNum);
7523   if (Arg->isTypeDependent() || Arg->isValueDependent())
7524     return false;
7525 
7526   // Check constant-ness first.
7527   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7528     return true;
7529 
7530   if (Result.getSExtValue() % Num != 0)
7531     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7532            << Num << Arg->getSourceRange();
7533 
7534   return false;
7535 }
7536 
7537 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7538 /// constant expression representing a power of 2.
7539 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7540   llvm::APSInt Result;
7541 
7542   // We can't check the value of a dependent argument.
7543   Expr *Arg = TheCall->getArg(ArgNum);
7544   if (Arg->isTypeDependent() || Arg->isValueDependent())
7545     return false;
7546 
7547   // Check constant-ness first.
7548   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7549     return true;
7550 
7551   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7552   // and only if x is a power of 2.
7553   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7554     return false;
7555 
7556   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7557          << Arg->getSourceRange();
7558 }
7559 
7560 static bool IsShiftedByte(llvm::APSInt Value) {
7561   if (Value.isNegative())
7562     return false;
7563 
7564   // Check if it's a shifted byte, by shifting it down
7565   while (true) {
7566     // If the value fits in the bottom byte, the check passes.
7567     if (Value < 0x100)
7568       return true;
7569 
7570     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7571     // fails.
7572     if ((Value & 0xFF) != 0)
7573       return false;
7574 
7575     // If the bottom 8 bits are all 0, but something above that is nonzero,
7576     // then shifting the value right by 8 bits won't affect whether it's a
7577     // shifted byte or not. So do that, and go round again.
7578     Value >>= 8;
7579   }
7580 }
7581 
7582 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7583 /// a constant expression representing an arbitrary byte value shifted left by
7584 /// a multiple of 8 bits.
7585 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7586                                              unsigned ArgBits) {
7587   llvm::APSInt Result;
7588 
7589   // We can't check the value of a dependent argument.
7590   Expr *Arg = TheCall->getArg(ArgNum);
7591   if (Arg->isTypeDependent() || Arg->isValueDependent())
7592     return false;
7593 
7594   // Check constant-ness first.
7595   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7596     return true;
7597 
7598   // Truncate to the given size.
7599   Result = Result.getLoBits(ArgBits);
7600   Result.setIsUnsigned(true);
7601 
7602   if (IsShiftedByte(Result))
7603     return false;
7604 
7605   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7606          << Arg->getSourceRange();
7607 }
7608 
7609 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7610 /// TheCall is a constant expression representing either a shifted byte value,
7611 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7612 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7613 /// Arm MVE intrinsics.
7614 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7615                                                    int ArgNum,
7616                                                    unsigned ArgBits) {
7617   llvm::APSInt Result;
7618 
7619   // We can't check the value of a dependent argument.
7620   Expr *Arg = TheCall->getArg(ArgNum);
7621   if (Arg->isTypeDependent() || Arg->isValueDependent())
7622     return false;
7623 
7624   // Check constant-ness first.
7625   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7626     return true;
7627 
7628   // Truncate to the given size.
7629   Result = Result.getLoBits(ArgBits);
7630   Result.setIsUnsigned(true);
7631 
7632   // Check to see if it's in either of the required forms.
7633   if (IsShiftedByte(Result) ||
7634       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7635     return false;
7636 
7637   return Diag(TheCall->getBeginLoc(),
7638               diag::err_argument_not_shifted_byte_or_xxff)
7639          << Arg->getSourceRange();
7640 }
7641 
7642 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7643 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7644   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7645     if (checkArgCount(*this, TheCall, 2))
7646       return true;
7647     Expr *Arg0 = TheCall->getArg(0);
7648     Expr *Arg1 = TheCall->getArg(1);
7649 
7650     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7651     if (FirstArg.isInvalid())
7652       return true;
7653     QualType FirstArgType = FirstArg.get()->getType();
7654     if (!FirstArgType->isAnyPointerType())
7655       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7656                << "first" << FirstArgType << Arg0->getSourceRange();
7657     TheCall->setArg(0, FirstArg.get());
7658 
7659     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7660     if (SecArg.isInvalid())
7661       return true;
7662     QualType SecArgType = SecArg.get()->getType();
7663     if (!SecArgType->isIntegerType())
7664       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7665                << "second" << SecArgType << Arg1->getSourceRange();
7666 
7667     // Derive the return type from the pointer argument.
7668     TheCall->setType(FirstArgType);
7669     return false;
7670   }
7671 
7672   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7673     if (checkArgCount(*this, TheCall, 2))
7674       return true;
7675 
7676     Expr *Arg0 = TheCall->getArg(0);
7677     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7678     if (FirstArg.isInvalid())
7679       return true;
7680     QualType FirstArgType = FirstArg.get()->getType();
7681     if (!FirstArgType->isAnyPointerType())
7682       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7683                << "first" << FirstArgType << Arg0->getSourceRange();
7684     TheCall->setArg(0, FirstArg.get());
7685 
7686     // Derive the return type from the pointer argument.
7687     TheCall->setType(FirstArgType);
7688 
7689     // Second arg must be an constant in range [0,15]
7690     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7691   }
7692 
7693   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7694     if (checkArgCount(*this, TheCall, 2))
7695       return true;
7696     Expr *Arg0 = TheCall->getArg(0);
7697     Expr *Arg1 = TheCall->getArg(1);
7698 
7699     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7700     if (FirstArg.isInvalid())
7701       return true;
7702     QualType FirstArgType = FirstArg.get()->getType();
7703     if (!FirstArgType->isAnyPointerType())
7704       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7705                << "first" << FirstArgType << Arg0->getSourceRange();
7706 
7707     QualType SecArgType = Arg1->getType();
7708     if (!SecArgType->isIntegerType())
7709       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7710                << "second" << SecArgType << Arg1->getSourceRange();
7711     TheCall->setType(Context.IntTy);
7712     return false;
7713   }
7714 
7715   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7716       BuiltinID == AArch64::BI__builtin_arm_stg) {
7717     if (checkArgCount(*this, TheCall, 1))
7718       return true;
7719     Expr *Arg0 = TheCall->getArg(0);
7720     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7721     if (FirstArg.isInvalid())
7722       return true;
7723 
7724     QualType FirstArgType = FirstArg.get()->getType();
7725     if (!FirstArgType->isAnyPointerType())
7726       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7727                << "first" << FirstArgType << Arg0->getSourceRange();
7728     TheCall->setArg(0, FirstArg.get());
7729 
7730     // Derive the return type from the pointer argument.
7731     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7732       TheCall->setType(FirstArgType);
7733     return false;
7734   }
7735 
7736   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7737     Expr *ArgA = TheCall->getArg(0);
7738     Expr *ArgB = TheCall->getArg(1);
7739 
7740     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7741     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7742 
7743     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7744       return true;
7745 
7746     QualType ArgTypeA = ArgExprA.get()->getType();
7747     QualType ArgTypeB = ArgExprB.get()->getType();
7748 
7749     auto isNull = [&] (Expr *E) -> bool {
7750       return E->isNullPointerConstant(
7751                         Context, Expr::NPC_ValueDependentIsNotNull); };
7752 
7753     // argument should be either a pointer or null
7754     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7755       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7756         << "first" << ArgTypeA << ArgA->getSourceRange();
7757 
7758     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7759       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7760         << "second" << ArgTypeB << ArgB->getSourceRange();
7761 
7762     // Ensure Pointee types are compatible
7763     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7764         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7765       QualType pointeeA = ArgTypeA->getPointeeType();
7766       QualType pointeeB = ArgTypeB->getPointeeType();
7767       if (!Context.typesAreCompatible(
7768              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7769              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7770         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7771           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7772           << ArgB->getSourceRange();
7773       }
7774     }
7775 
7776     // at least one argument should be pointer type
7777     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7778       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7779         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7780 
7781     if (isNull(ArgA)) // adopt type of the other pointer
7782       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7783 
7784     if (isNull(ArgB))
7785       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7786 
7787     TheCall->setArg(0, ArgExprA.get());
7788     TheCall->setArg(1, ArgExprB.get());
7789     TheCall->setType(Context.LongLongTy);
7790     return false;
7791   }
7792   assert(false && "Unhandled ARM MTE intrinsic");
7793   return true;
7794 }
7795 
7796 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7797 /// TheCall is an ARM/AArch64 special register string literal.
7798 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7799                                     int ArgNum, unsigned ExpectedFieldNum,
7800                                     bool AllowName) {
7801   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7802                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7803                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7804                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7805                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7806                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7807   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7808                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7809                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7810                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7811                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7812                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7813   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7814 
7815   // We can't check the value of a dependent argument.
7816   Expr *Arg = TheCall->getArg(ArgNum);
7817   if (Arg->isTypeDependent() || Arg->isValueDependent())
7818     return false;
7819 
7820   // Check if the argument is a string literal.
7821   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7822     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7823            << Arg->getSourceRange();
7824 
7825   // Check the type of special register given.
7826   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7827   SmallVector<StringRef, 6> Fields;
7828   Reg.split(Fields, ":");
7829 
7830   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7831     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7832            << Arg->getSourceRange();
7833 
7834   // If the string is the name of a register then we cannot check that it is
7835   // valid here but if the string is of one the forms described in ACLE then we
7836   // can check that the supplied fields are integers and within the valid
7837   // ranges.
7838   if (Fields.size() > 1) {
7839     bool FiveFields = Fields.size() == 5;
7840 
7841     bool ValidString = true;
7842     if (IsARMBuiltin) {
7843       ValidString &= Fields[0].startswith_insensitive("cp") ||
7844                      Fields[0].startswith_insensitive("p");
7845       if (ValidString)
7846         Fields[0] = Fields[0].drop_front(
7847             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7848 
7849       ValidString &= Fields[2].startswith_insensitive("c");
7850       if (ValidString)
7851         Fields[2] = Fields[2].drop_front(1);
7852 
7853       if (FiveFields) {
7854         ValidString &= Fields[3].startswith_insensitive("c");
7855         if (ValidString)
7856           Fields[3] = Fields[3].drop_front(1);
7857       }
7858     }
7859 
7860     SmallVector<int, 5> Ranges;
7861     if (FiveFields)
7862       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7863     else
7864       Ranges.append({15, 7, 15});
7865 
7866     for (unsigned i=0; i<Fields.size(); ++i) {
7867       int IntField;
7868       ValidString &= !Fields[i].getAsInteger(10, IntField);
7869       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7870     }
7871 
7872     if (!ValidString)
7873       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7874              << Arg->getSourceRange();
7875   } else if (IsAArch64Builtin && Fields.size() == 1) {
7876     // If the register name is one of those that appear in the condition below
7877     // and the special register builtin being used is one of the write builtins,
7878     // then we require that the argument provided for writing to the register
7879     // is an integer constant expression. This is because it will be lowered to
7880     // an MSR (immediate) instruction, so we need to know the immediate at
7881     // compile time.
7882     if (TheCall->getNumArgs() != 2)
7883       return false;
7884 
7885     std::string RegLower = Reg.lower();
7886     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7887         RegLower != "pan" && RegLower != "uao")
7888       return false;
7889 
7890     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7891   }
7892 
7893   return false;
7894 }
7895 
7896 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7897 /// Emit an error and return true on failure; return false on success.
7898 /// TypeStr is a string containing the type descriptor of the value returned by
7899 /// the builtin and the descriptors of the expected type of the arguments.
7900 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7901                                  const char *TypeStr) {
7902 
7903   assert((TypeStr[0] != '\0') &&
7904          "Invalid types in PPC MMA builtin declaration");
7905 
7906   switch (BuiltinID) {
7907   default:
7908     // This function is called in CheckPPCBuiltinFunctionCall where the
7909     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7910     // we are isolating the pair vector memop builtins that can be used with mma
7911     // off so the default case is every builtin that requires mma and paired
7912     // vector memops.
7913     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7914                          diag::err_ppc_builtin_only_on_arch, "10") ||
7915         SemaFeatureCheck(*this, TheCall, "mma",
7916                          diag::err_ppc_builtin_only_on_arch, "10"))
7917       return true;
7918     break;
7919   case PPC::BI__builtin_vsx_lxvp:
7920   case PPC::BI__builtin_vsx_stxvp:
7921   case PPC::BI__builtin_vsx_assemble_pair:
7922   case PPC::BI__builtin_vsx_disassemble_pair:
7923     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7924                          diag::err_ppc_builtin_only_on_arch, "10"))
7925       return true;
7926     break;
7927   }
7928 
7929   unsigned Mask = 0;
7930   unsigned ArgNum = 0;
7931 
7932   // The first type in TypeStr is the type of the value returned by the
7933   // builtin. So we first read that type and change the type of TheCall.
7934   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7935   TheCall->setType(type);
7936 
7937   while (*TypeStr != '\0') {
7938     Mask = 0;
7939     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7940     if (ArgNum >= TheCall->getNumArgs()) {
7941       ArgNum++;
7942       break;
7943     }
7944 
7945     Expr *Arg = TheCall->getArg(ArgNum);
7946     QualType PassedType = Arg->getType();
7947     QualType StrippedRVType = PassedType.getCanonicalType();
7948 
7949     // Strip Restrict/Volatile qualifiers.
7950     if (StrippedRVType.isRestrictQualified() ||
7951         StrippedRVType.isVolatileQualified())
7952       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7953 
7954     // The only case where the argument type and expected type are allowed to
7955     // mismatch is if the argument type is a non-void pointer (or array) and
7956     // expected type is a void pointer.
7957     if (StrippedRVType != ExpectedType)
7958       if (!(ExpectedType->isVoidPointerType() &&
7959             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7960         return Diag(Arg->getBeginLoc(),
7961                     diag::err_typecheck_convert_incompatible)
7962                << PassedType << ExpectedType << 1 << 0 << 0;
7963 
7964     // If the value of the Mask is not 0, we have a constraint in the size of
7965     // the integer argument so here we ensure the argument is a constant that
7966     // is in the valid range.
7967     if (Mask != 0 &&
7968         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7969       return true;
7970 
7971     ArgNum++;
7972   }
7973 
7974   // In case we exited early from the previous loop, there are other types to
7975   // read from TypeStr. So we need to read them all to ensure we have the right
7976   // number of arguments in TheCall and if it is not the case, to display a
7977   // better error message.
7978   while (*TypeStr != '\0') {
7979     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7980     ArgNum++;
7981   }
7982   if (checkArgCount(*this, TheCall, ArgNum))
7983     return true;
7984 
7985   return false;
7986 }
7987 
7988 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7989 /// This checks that the target supports __builtin_longjmp and
7990 /// that val is a constant 1.
7991 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7992   if (!Context.getTargetInfo().hasSjLjLowering())
7993     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7994            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7995 
7996   Expr *Arg = TheCall->getArg(1);
7997   llvm::APSInt Result;
7998 
7999   // TODO: This is less than ideal. Overload this to take a value.
8000   if (SemaBuiltinConstantArg(TheCall, 1, Result))
8001     return true;
8002 
8003   if (Result != 1)
8004     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
8005            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
8006 
8007   return false;
8008 }
8009 
8010 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
8011 /// This checks that the target supports __builtin_setjmp.
8012 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
8013   if (!Context.getTargetInfo().hasSjLjLowering())
8014     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
8015            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
8016   return false;
8017 }
8018 
8019 namespace {
8020 
8021 class UncoveredArgHandler {
8022   enum { Unknown = -1, AllCovered = -2 };
8023 
8024   signed FirstUncoveredArg = Unknown;
8025   SmallVector<const Expr *, 4> DiagnosticExprs;
8026 
8027 public:
8028   UncoveredArgHandler() = default;
8029 
8030   bool hasUncoveredArg() const {
8031     return (FirstUncoveredArg >= 0);
8032   }
8033 
8034   unsigned getUncoveredArg() const {
8035     assert(hasUncoveredArg() && "no uncovered argument");
8036     return FirstUncoveredArg;
8037   }
8038 
8039   void setAllCovered() {
8040     // A string has been found with all arguments covered, so clear out
8041     // the diagnostics.
8042     DiagnosticExprs.clear();
8043     FirstUncoveredArg = AllCovered;
8044   }
8045 
8046   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
8047     assert(NewFirstUncoveredArg >= 0 && "Outside range");
8048 
8049     // Don't update if a previous string covers all arguments.
8050     if (FirstUncoveredArg == AllCovered)
8051       return;
8052 
8053     // UncoveredArgHandler tracks the highest uncovered argument index
8054     // and with it all the strings that match this index.
8055     if (NewFirstUncoveredArg == FirstUncoveredArg)
8056       DiagnosticExprs.push_back(StrExpr);
8057     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
8058       DiagnosticExprs.clear();
8059       DiagnosticExprs.push_back(StrExpr);
8060       FirstUncoveredArg = NewFirstUncoveredArg;
8061     }
8062   }
8063 
8064   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
8065 };
8066 
8067 enum StringLiteralCheckType {
8068   SLCT_NotALiteral,
8069   SLCT_UncheckedLiteral,
8070   SLCT_CheckedLiteral
8071 };
8072 
8073 } // namespace
8074 
8075 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
8076                                      BinaryOperatorKind BinOpKind,
8077                                      bool AddendIsRight) {
8078   unsigned BitWidth = Offset.getBitWidth();
8079   unsigned AddendBitWidth = Addend.getBitWidth();
8080   // There might be negative interim results.
8081   if (Addend.isUnsigned()) {
8082     Addend = Addend.zext(++AddendBitWidth);
8083     Addend.setIsSigned(true);
8084   }
8085   // Adjust the bit width of the APSInts.
8086   if (AddendBitWidth > BitWidth) {
8087     Offset = Offset.sext(AddendBitWidth);
8088     BitWidth = AddendBitWidth;
8089   } else if (BitWidth > AddendBitWidth) {
8090     Addend = Addend.sext(BitWidth);
8091   }
8092 
8093   bool Ov = false;
8094   llvm::APSInt ResOffset = Offset;
8095   if (BinOpKind == BO_Add)
8096     ResOffset = Offset.sadd_ov(Addend, Ov);
8097   else {
8098     assert(AddendIsRight && BinOpKind == BO_Sub &&
8099            "operator must be add or sub with addend on the right");
8100     ResOffset = Offset.ssub_ov(Addend, Ov);
8101   }
8102 
8103   // We add an offset to a pointer here so we should support an offset as big as
8104   // possible.
8105   if (Ov) {
8106     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
8107            "index (intermediate) result too big");
8108     Offset = Offset.sext(2 * BitWidth);
8109     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
8110     return;
8111   }
8112 
8113   Offset = ResOffset;
8114 }
8115 
8116 namespace {
8117 
8118 // This is a wrapper class around StringLiteral to support offsetted string
8119 // literals as format strings. It takes the offset into account when returning
8120 // the string and its length or the source locations to display notes correctly.
8121 class FormatStringLiteral {
8122   const StringLiteral *FExpr;
8123   int64_t Offset;
8124 
8125  public:
8126   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
8127       : FExpr(fexpr), Offset(Offset) {}
8128 
8129   StringRef getString() const {
8130     return FExpr->getString().drop_front(Offset);
8131   }
8132 
8133   unsigned getByteLength() const {
8134     return FExpr->getByteLength() - getCharByteWidth() * Offset;
8135   }
8136 
8137   unsigned getLength() const { return FExpr->getLength() - Offset; }
8138   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
8139 
8140   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8141 
8142   QualType getType() const { return FExpr->getType(); }
8143 
8144   bool isAscii() const { return FExpr->isAscii(); }
8145   bool isWide() const { return FExpr->isWide(); }
8146   bool isUTF8() const { return FExpr->isUTF8(); }
8147   bool isUTF16() const { return FExpr->isUTF16(); }
8148   bool isUTF32() const { return FExpr->isUTF32(); }
8149   bool isPascal() const { return FExpr->isPascal(); }
8150 
8151   SourceLocation getLocationOfByte(
8152       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8153       const TargetInfo &Target, unsigned *StartToken = nullptr,
8154       unsigned *StartTokenByteOffset = nullptr) const {
8155     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8156                                     StartToken, StartTokenByteOffset);
8157   }
8158 
8159   SourceLocation getBeginLoc() const LLVM_READONLY {
8160     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8161   }
8162 
8163   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8164 };
8165 
8166 }  // namespace
8167 
8168 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8169                               const Expr *OrigFormatExpr,
8170                               ArrayRef<const Expr *> Args,
8171                               bool HasVAListArg, unsigned format_idx,
8172                               unsigned firstDataArg,
8173                               Sema::FormatStringType Type,
8174                               bool inFunctionCall,
8175                               Sema::VariadicCallType CallType,
8176                               llvm::SmallBitVector &CheckedVarArgs,
8177                               UncoveredArgHandler &UncoveredArg,
8178                               bool IgnoreStringsWithoutSpecifiers);
8179 
8180 // Determine if an expression is a string literal or constant string.
8181 // If this function returns false on the arguments to a function expecting a
8182 // format string, we will usually need to emit a warning.
8183 // True string literals are then checked by CheckFormatString.
8184 static StringLiteralCheckType
8185 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8186                       bool HasVAListArg, unsigned format_idx,
8187                       unsigned firstDataArg, Sema::FormatStringType Type,
8188                       Sema::VariadicCallType CallType, bool InFunctionCall,
8189                       llvm::SmallBitVector &CheckedVarArgs,
8190                       UncoveredArgHandler &UncoveredArg,
8191                       llvm::APSInt Offset,
8192                       bool IgnoreStringsWithoutSpecifiers = false) {
8193   if (S.isConstantEvaluated())
8194     return SLCT_NotALiteral;
8195  tryAgain:
8196   assert(Offset.isSigned() && "invalid offset");
8197 
8198   if (E->isTypeDependent() || E->isValueDependent())
8199     return SLCT_NotALiteral;
8200 
8201   E = E->IgnoreParenCasts();
8202 
8203   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8204     // Technically -Wformat-nonliteral does not warn about this case.
8205     // The behavior of printf and friends in this case is implementation
8206     // dependent.  Ideally if the format string cannot be null then
8207     // it should have a 'nonnull' attribute in the function prototype.
8208     return SLCT_UncheckedLiteral;
8209 
8210   switch (E->getStmtClass()) {
8211   case Stmt::BinaryConditionalOperatorClass:
8212   case Stmt::ConditionalOperatorClass: {
8213     // The expression is a literal if both sub-expressions were, and it was
8214     // completely checked only if both sub-expressions were checked.
8215     const AbstractConditionalOperator *C =
8216         cast<AbstractConditionalOperator>(E);
8217 
8218     // Determine whether it is necessary to check both sub-expressions, for
8219     // example, because the condition expression is a constant that can be
8220     // evaluated at compile time.
8221     bool CheckLeft = true, CheckRight = true;
8222 
8223     bool Cond;
8224     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8225                                                  S.isConstantEvaluated())) {
8226       if (Cond)
8227         CheckRight = false;
8228       else
8229         CheckLeft = false;
8230     }
8231 
8232     // We need to maintain the offsets for the right and the left hand side
8233     // separately to check if every possible indexed expression is a valid
8234     // string literal. They might have different offsets for different string
8235     // literals in the end.
8236     StringLiteralCheckType Left;
8237     if (!CheckLeft)
8238       Left = SLCT_UncheckedLiteral;
8239     else {
8240       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8241                                    HasVAListArg, format_idx, firstDataArg,
8242                                    Type, CallType, InFunctionCall,
8243                                    CheckedVarArgs, UncoveredArg, Offset,
8244                                    IgnoreStringsWithoutSpecifiers);
8245       if (Left == SLCT_NotALiteral || !CheckRight) {
8246         return Left;
8247       }
8248     }
8249 
8250     StringLiteralCheckType Right = checkFormatStringExpr(
8251         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8252         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8253         IgnoreStringsWithoutSpecifiers);
8254 
8255     return (CheckLeft && Left < Right) ? Left : Right;
8256   }
8257 
8258   case Stmt::ImplicitCastExprClass:
8259     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8260     goto tryAgain;
8261 
8262   case Stmt::OpaqueValueExprClass:
8263     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8264       E = src;
8265       goto tryAgain;
8266     }
8267     return SLCT_NotALiteral;
8268 
8269   case Stmt::PredefinedExprClass:
8270     // While __func__, etc., are technically not string literals, they
8271     // cannot contain format specifiers and thus are not a security
8272     // liability.
8273     return SLCT_UncheckedLiteral;
8274 
8275   case Stmt::DeclRefExprClass: {
8276     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8277 
8278     // As an exception, do not flag errors for variables binding to
8279     // const string literals.
8280     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8281       bool isConstant = false;
8282       QualType T = DR->getType();
8283 
8284       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8285         isConstant = AT->getElementType().isConstant(S.Context);
8286       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8287         isConstant = T.isConstant(S.Context) &&
8288                      PT->getPointeeType().isConstant(S.Context);
8289       } else if (T->isObjCObjectPointerType()) {
8290         // In ObjC, there is usually no "const ObjectPointer" type,
8291         // so don't check if the pointee type is constant.
8292         isConstant = T.isConstant(S.Context);
8293       }
8294 
8295       if (isConstant) {
8296         if (const Expr *Init = VD->getAnyInitializer()) {
8297           // Look through initializers like const char c[] = { "foo" }
8298           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8299             if (InitList->isStringLiteralInit())
8300               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8301           }
8302           return checkFormatStringExpr(S, Init, Args,
8303                                        HasVAListArg, format_idx,
8304                                        firstDataArg, Type, CallType,
8305                                        /*InFunctionCall*/ false, CheckedVarArgs,
8306                                        UncoveredArg, Offset);
8307         }
8308       }
8309 
8310       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8311       // special check to see if the format string is a function parameter
8312       // of the function calling the printf function.  If the function
8313       // has an attribute indicating it is a printf-like function, then we
8314       // should suppress warnings concerning non-literals being used in a call
8315       // to a vprintf function.  For example:
8316       //
8317       // void
8318       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8319       //      va_list ap;
8320       //      va_start(ap, fmt);
8321       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8322       //      ...
8323       // }
8324       if (HasVAListArg) {
8325         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8326           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8327             int PVIndex = PV->getFunctionScopeIndex() + 1;
8328             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8329               // adjust for implicit parameter
8330               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8331                 if (MD->isInstance())
8332                   ++PVIndex;
8333               // We also check if the formats are compatible.
8334               // We can't pass a 'scanf' string to a 'printf' function.
8335               if (PVIndex == PVFormat->getFormatIdx() &&
8336                   Type == S.GetFormatStringType(PVFormat))
8337                 return SLCT_UncheckedLiteral;
8338             }
8339           }
8340         }
8341       }
8342     }
8343 
8344     return SLCT_NotALiteral;
8345   }
8346 
8347   case Stmt::CallExprClass:
8348   case Stmt::CXXMemberCallExprClass: {
8349     const CallExpr *CE = cast<CallExpr>(E);
8350     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8351       bool IsFirst = true;
8352       StringLiteralCheckType CommonResult;
8353       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8354         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8355         StringLiteralCheckType Result = checkFormatStringExpr(
8356             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8357             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8358             IgnoreStringsWithoutSpecifiers);
8359         if (IsFirst) {
8360           CommonResult = Result;
8361           IsFirst = false;
8362         }
8363       }
8364       if (!IsFirst)
8365         return CommonResult;
8366 
8367       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8368         unsigned BuiltinID = FD->getBuiltinID();
8369         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8370             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8371           const Expr *Arg = CE->getArg(0);
8372           return checkFormatStringExpr(S, Arg, Args,
8373                                        HasVAListArg, format_idx,
8374                                        firstDataArg, Type, CallType,
8375                                        InFunctionCall, CheckedVarArgs,
8376                                        UncoveredArg, Offset,
8377                                        IgnoreStringsWithoutSpecifiers);
8378         }
8379       }
8380     }
8381 
8382     return SLCT_NotALiteral;
8383   }
8384   case Stmt::ObjCMessageExprClass: {
8385     const auto *ME = cast<ObjCMessageExpr>(E);
8386     if (const auto *MD = ME->getMethodDecl()) {
8387       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8388         // As a special case heuristic, if we're using the method -[NSBundle
8389         // localizedStringForKey:value:table:], ignore any key strings that lack
8390         // format specifiers. The idea is that if the key doesn't have any
8391         // format specifiers then its probably just a key to map to the
8392         // localized strings. If it does have format specifiers though, then its
8393         // likely that the text of the key is the format string in the
8394         // programmer's language, and should be checked.
8395         const ObjCInterfaceDecl *IFace;
8396         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8397             IFace->getIdentifier()->isStr("NSBundle") &&
8398             MD->getSelector().isKeywordSelector(
8399                 {"localizedStringForKey", "value", "table"})) {
8400           IgnoreStringsWithoutSpecifiers = true;
8401         }
8402 
8403         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8404         return checkFormatStringExpr(
8405             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8406             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8407             IgnoreStringsWithoutSpecifiers);
8408       }
8409     }
8410 
8411     return SLCT_NotALiteral;
8412   }
8413   case Stmt::ObjCStringLiteralClass:
8414   case Stmt::StringLiteralClass: {
8415     const StringLiteral *StrE = nullptr;
8416 
8417     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8418       StrE = ObjCFExpr->getString();
8419     else
8420       StrE = cast<StringLiteral>(E);
8421 
8422     if (StrE) {
8423       if (Offset.isNegative() || Offset > StrE->getLength()) {
8424         // TODO: It would be better to have an explicit warning for out of
8425         // bounds literals.
8426         return SLCT_NotALiteral;
8427       }
8428       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8429       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8430                         firstDataArg, Type, InFunctionCall, CallType,
8431                         CheckedVarArgs, UncoveredArg,
8432                         IgnoreStringsWithoutSpecifiers);
8433       return SLCT_CheckedLiteral;
8434     }
8435 
8436     return SLCT_NotALiteral;
8437   }
8438   case Stmt::BinaryOperatorClass: {
8439     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8440 
8441     // A string literal + an int offset is still a string literal.
8442     if (BinOp->isAdditiveOp()) {
8443       Expr::EvalResult LResult, RResult;
8444 
8445       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8446           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8447       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8448           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8449 
8450       if (LIsInt != RIsInt) {
8451         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8452 
8453         if (LIsInt) {
8454           if (BinOpKind == BO_Add) {
8455             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8456             E = BinOp->getRHS();
8457             goto tryAgain;
8458           }
8459         } else {
8460           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8461           E = BinOp->getLHS();
8462           goto tryAgain;
8463         }
8464       }
8465     }
8466 
8467     return SLCT_NotALiteral;
8468   }
8469   case Stmt::UnaryOperatorClass: {
8470     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8471     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8472     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8473       Expr::EvalResult IndexResult;
8474       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8475                                        Expr::SE_NoSideEffects,
8476                                        S.isConstantEvaluated())) {
8477         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8478                    /*RHS is int*/ true);
8479         E = ASE->getBase();
8480         goto tryAgain;
8481       }
8482     }
8483 
8484     return SLCT_NotALiteral;
8485   }
8486 
8487   default:
8488     return SLCT_NotALiteral;
8489   }
8490 }
8491 
8492 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8493   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8494       .Case("scanf", FST_Scanf)
8495       .Cases("printf", "printf0", FST_Printf)
8496       .Cases("NSString", "CFString", FST_NSString)
8497       .Case("strftime", FST_Strftime)
8498       .Case("strfmon", FST_Strfmon)
8499       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8500       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8501       .Case("os_trace", FST_OSLog)
8502       .Case("os_log", FST_OSLog)
8503       .Default(FST_Unknown);
8504 }
8505 
8506 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8507 /// functions) for correct use of format strings.
8508 /// Returns true if a format string has been fully checked.
8509 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8510                                 ArrayRef<const Expr *> Args,
8511                                 bool IsCXXMember,
8512                                 VariadicCallType CallType,
8513                                 SourceLocation Loc, SourceRange Range,
8514                                 llvm::SmallBitVector &CheckedVarArgs) {
8515   FormatStringInfo FSI;
8516   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8517     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8518                                 FSI.FirstDataArg, GetFormatStringType(Format),
8519                                 CallType, Loc, Range, CheckedVarArgs);
8520   return false;
8521 }
8522 
8523 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8524                                 bool HasVAListArg, unsigned format_idx,
8525                                 unsigned firstDataArg, FormatStringType Type,
8526                                 VariadicCallType CallType,
8527                                 SourceLocation Loc, SourceRange Range,
8528                                 llvm::SmallBitVector &CheckedVarArgs) {
8529   // CHECK: printf/scanf-like function is called with no format string.
8530   if (format_idx >= Args.size()) {
8531     Diag(Loc, diag::warn_missing_format_string) << Range;
8532     return false;
8533   }
8534 
8535   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8536 
8537   // CHECK: format string is not a string literal.
8538   //
8539   // Dynamically generated format strings are difficult to
8540   // automatically vet at compile time.  Requiring that format strings
8541   // are string literals: (1) permits the checking of format strings by
8542   // the compiler and thereby (2) can practically remove the source of
8543   // many format string exploits.
8544 
8545   // Format string can be either ObjC string (e.g. @"%d") or
8546   // C string (e.g. "%d")
8547   // ObjC string uses the same format specifiers as C string, so we can use
8548   // the same format string checking logic for both ObjC and C strings.
8549   UncoveredArgHandler UncoveredArg;
8550   StringLiteralCheckType CT =
8551       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8552                             format_idx, firstDataArg, Type, CallType,
8553                             /*IsFunctionCall*/ true, CheckedVarArgs,
8554                             UncoveredArg,
8555                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8556 
8557   // Generate a diagnostic where an uncovered argument is detected.
8558   if (UncoveredArg.hasUncoveredArg()) {
8559     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8560     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8561     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8562   }
8563 
8564   if (CT != SLCT_NotALiteral)
8565     // Literal format string found, check done!
8566     return CT == SLCT_CheckedLiteral;
8567 
8568   // Strftime is particular as it always uses a single 'time' argument,
8569   // so it is safe to pass a non-literal string.
8570   if (Type == FST_Strftime)
8571     return false;
8572 
8573   // Do not emit diag when the string param is a macro expansion and the
8574   // format is either NSString or CFString. This is a hack to prevent
8575   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8576   // which are usually used in place of NS and CF string literals.
8577   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8578   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8579     return false;
8580 
8581   // If there are no arguments specified, warn with -Wformat-security, otherwise
8582   // warn only with -Wformat-nonliteral.
8583   if (Args.size() == firstDataArg) {
8584     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8585       << OrigFormatExpr->getSourceRange();
8586     switch (Type) {
8587     default:
8588       break;
8589     case FST_Kprintf:
8590     case FST_FreeBSDKPrintf:
8591     case FST_Printf:
8592       Diag(FormatLoc, diag::note_format_security_fixit)
8593         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8594       break;
8595     case FST_NSString:
8596       Diag(FormatLoc, diag::note_format_security_fixit)
8597         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8598       break;
8599     }
8600   } else {
8601     Diag(FormatLoc, diag::warn_format_nonliteral)
8602       << OrigFormatExpr->getSourceRange();
8603   }
8604   return false;
8605 }
8606 
8607 namespace {
8608 
8609 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8610 protected:
8611   Sema &S;
8612   const FormatStringLiteral *FExpr;
8613   const Expr *OrigFormatExpr;
8614   const Sema::FormatStringType FSType;
8615   const unsigned FirstDataArg;
8616   const unsigned NumDataArgs;
8617   const char *Beg; // Start of format string.
8618   const bool HasVAListArg;
8619   ArrayRef<const Expr *> Args;
8620   unsigned FormatIdx;
8621   llvm::SmallBitVector CoveredArgs;
8622   bool usesPositionalArgs = false;
8623   bool atFirstArg = true;
8624   bool inFunctionCall;
8625   Sema::VariadicCallType CallType;
8626   llvm::SmallBitVector &CheckedVarArgs;
8627   UncoveredArgHandler &UncoveredArg;
8628 
8629 public:
8630   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8631                      const Expr *origFormatExpr,
8632                      const Sema::FormatStringType type, unsigned firstDataArg,
8633                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8634                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8635                      bool inFunctionCall, Sema::VariadicCallType callType,
8636                      llvm::SmallBitVector &CheckedVarArgs,
8637                      UncoveredArgHandler &UncoveredArg)
8638       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8639         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8640         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8641         inFunctionCall(inFunctionCall), CallType(callType),
8642         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8643     CoveredArgs.resize(numDataArgs);
8644     CoveredArgs.reset();
8645   }
8646 
8647   void DoneProcessing();
8648 
8649   void HandleIncompleteSpecifier(const char *startSpecifier,
8650                                  unsigned specifierLen) override;
8651 
8652   void HandleInvalidLengthModifier(
8653                            const analyze_format_string::FormatSpecifier &FS,
8654                            const analyze_format_string::ConversionSpecifier &CS,
8655                            const char *startSpecifier, unsigned specifierLen,
8656                            unsigned DiagID);
8657 
8658   void HandleNonStandardLengthModifier(
8659                     const analyze_format_string::FormatSpecifier &FS,
8660                     const char *startSpecifier, unsigned specifierLen);
8661 
8662   void HandleNonStandardConversionSpecifier(
8663                     const analyze_format_string::ConversionSpecifier &CS,
8664                     const char *startSpecifier, unsigned specifierLen);
8665 
8666   void HandlePosition(const char *startPos, unsigned posLen) override;
8667 
8668   void HandleInvalidPosition(const char *startSpecifier,
8669                              unsigned specifierLen,
8670                              analyze_format_string::PositionContext p) override;
8671 
8672   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8673 
8674   void HandleNullChar(const char *nullCharacter) override;
8675 
8676   template <typename Range>
8677   static void
8678   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8679                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8680                        bool IsStringLocation, Range StringRange,
8681                        ArrayRef<FixItHint> Fixit = None);
8682 
8683 protected:
8684   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8685                                         const char *startSpec,
8686                                         unsigned specifierLen,
8687                                         const char *csStart, unsigned csLen);
8688 
8689   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8690                                          const char *startSpec,
8691                                          unsigned specifierLen);
8692 
8693   SourceRange getFormatStringRange();
8694   CharSourceRange getSpecifierRange(const char *startSpecifier,
8695                                     unsigned specifierLen);
8696   SourceLocation getLocationOfByte(const char *x);
8697 
8698   const Expr *getDataArg(unsigned i) const;
8699 
8700   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8701                     const analyze_format_string::ConversionSpecifier &CS,
8702                     const char *startSpecifier, unsigned specifierLen,
8703                     unsigned argIndex);
8704 
8705   template <typename Range>
8706   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8707                             bool IsStringLocation, Range StringRange,
8708                             ArrayRef<FixItHint> Fixit = None);
8709 };
8710 
8711 } // namespace
8712 
8713 SourceRange CheckFormatHandler::getFormatStringRange() {
8714   return OrigFormatExpr->getSourceRange();
8715 }
8716 
8717 CharSourceRange CheckFormatHandler::
8718 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8719   SourceLocation Start = getLocationOfByte(startSpecifier);
8720   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8721 
8722   // Advance the end SourceLocation by one due to half-open ranges.
8723   End = End.getLocWithOffset(1);
8724 
8725   return CharSourceRange::getCharRange(Start, End);
8726 }
8727 
8728 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8729   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8730                                   S.getLangOpts(), S.Context.getTargetInfo());
8731 }
8732 
8733 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8734                                                    unsigned specifierLen){
8735   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8736                        getLocationOfByte(startSpecifier),
8737                        /*IsStringLocation*/true,
8738                        getSpecifierRange(startSpecifier, specifierLen));
8739 }
8740 
8741 void CheckFormatHandler::HandleInvalidLengthModifier(
8742     const analyze_format_string::FormatSpecifier &FS,
8743     const analyze_format_string::ConversionSpecifier &CS,
8744     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8745   using namespace analyze_format_string;
8746 
8747   const LengthModifier &LM = FS.getLengthModifier();
8748   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8749 
8750   // See if we know how to fix this length modifier.
8751   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8752   if (FixedLM) {
8753     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8754                          getLocationOfByte(LM.getStart()),
8755                          /*IsStringLocation*/true,
8756                          getSpecifierRange(startSpecifier, specifierLen));
8757 
8758     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8759       << FixedLM->toString()
8760       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8761 
8762   } else {
8763     FixItHint Hint;
8764     if (DiagID == diag::warn_format_nonsensical_length)
8765       Hint = FixItHint::CreateRemoval(LMRange);
8766 
8767     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8768                          getLocationOfByte(LM.getStart()),
8769                          /*IsStringLocation*/true,
8770                          getSpecifierRange(startSpecifier, specifierLen),
8771                          Hint);
8772   }
8773 }
8774 
8775 void CheckFormatHandler::HandleNonStandardLengthModifier(
8776     const analyze_format_string::FormatSpecifier &FS,
8777     const char *startSpecifier, unsigned specifierLen) {
8778   using namespace analyze_format_string;
8779 
8780   const LengthModifier &LM = FS.getLengthModifier();
8781   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8782 
8783   // See if we know how to fix this length modifier.
8784   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8785   if (FixedLM) {
8786     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8787                            << LM.toString() << 0,
8788                          getLocationOfByte(LM.getStart()),
8789                          /*IsStringLocation*/true,
8790                          getSpecifierRange(startSpecifier, specifierLen));
8791 
8792     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8793       << FixedLM->toString()
8794       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8795 
8796   } else {
8797     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8798                            << LM.toString() << 0,
8799                          getLocationOfByte(LM.getStart()),
8800                          /*IsStringLocation*/true,
8801                          getSpecifierRange(startSpecifier, specifierLen));
8802   }
8803 }
8804 
8805 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8806     const analyze_format_string::ConversionSpecifier &CS,
8807     const char *startSpecifier, unsigned specifierLen) {
8808   using namespace analyze_format_string;
8809 
8810   // See if we know how to fix this conversion specifier.
8811   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8812   if (FixedCS) {
8813     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8814                           << CS.toString() << /*conversion specifier*/1,
8815                          getLocationOfByte(CS.getStart()),
8816                          /*IsStringLocation*/true,
8817                          getSpecifierRange(startSpecifier, specifierLen));
8818 
8819     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8820     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8821       << FixedCS->toString()
8822       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8823   } else {
8824     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8825                           << CS.toString() << /*conversion specifier*/1,
8826                          getLocationOfByte(CS.getStart()),
8827                          /*IsStringLocation*/true,
8828                          getSpecifierRange(startSpecifier, specifierLen));
8829   }
8830 }
8831 
8832 void CheckFormatHandler::HandlePosition(const char *startPos,
8833                                         unsigned posLen) {
8834   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8835                                getLocationOfByte(startPos),
8836                                /*IsStringLocation*/true,
8837                                getSpecifierRange(startPos, posLen));
8838 }
8839 
8840 void
8841 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8842                                      analyze_format_string::PositionContext p) {
8843   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8844                          << (unsigned) p,
8845                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8846                        getSpecifierRange(startPos, posLen));
8847 }
8848 
8849 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8850                                             unsigned posLen) {
8851   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8852                                getLocationOfByte(startPos),
8853                                /*IsStringLocation*/true,
8854                                getSpecifierRange(startPos, posLen));
8855 }
8856 
8857 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8858   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8859     // The presence of a null character is likely an error.
8860     EmitFormatDiagnostic(
8861       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8862       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8863       getFormatStringRange());
8864   }
8865 }
8866 
8867 // Note that this may return NULL if there was an error parsing or building
8868 // one of the argument expressions.
8869 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8870   return Args[FirstDataArg + i];
8871 }
8872 
8873 void CheckFormatHandler::DoneProcessing() {
8874   // Does the number of data arguments exceed the number of
8875   // format conversions in the format string?
8876   if (!HasVAListArg) {
8877       // Find any arguments that weren't covered.
8878     CoveredArgs.flip();
8879     signed notCoveredArg = CoveredArgs.find_first();
8880     if (notCoveredArg >= 0) {
8881       assert((unsigned)notCoveredArg < NumDataArgs);
8882       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8883     } else {
8884       UncoveredArg.setAllCovered();
8885     }
8886   }
8887 }
8888 
8889 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8890                                    const Expr *ArgExpr) {
8891   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8892          "Invalid state");
8893 
8894   if (!ArgExpr)
8895     return;
8896 
8897   SourceLocation Loc = ArgExpr->getBeginLoc();
8898 
8899   if (S.getSourceManager().isInSystemMacro(Loc))
8900     return;
8901 
8902   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8903   for (auto E : DiagnosticExprs)
8904     PDiag << E->getSourceRange();
8905 
8906   CheckFormatHandler::EmitFormatDiagnostic(
8907                                   S, IsFunctionCall, DiagnosticExprs[0],
8908                                   PDiag, Loc, /*IsStringLocation*/false,
8909                                   DiagnosticExprs[0]->getSourceRange());
8910 }
8911 
8912 bool
8913 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8914                                                      SourceLocation Loc,
8915                                                      const char *startSpec,
8916                                                      unsigned specifierLen,
8917                                                      const char *csStart,
8918                                                      unsigned csLen) {
8919   bool keepGoing = true;
8920   if (argIndex < NumDataArgs) {
8921     // Consider the argument coverered, even though the specifier doesn't
8922     // make sense.
8923     CoveredArgs.set(argIndex);
8924   }
8925   else {
8926     // If argIndex exceeds the number of data arguments we
8927     // don't issue a warning because that is just a cascade of warnings (and
8928     // they may have intended '%%' anyway). We don't want to continue processing
8929     // the format string after this point, however, as we will like just get
8930     // gibberish when trying to match arguments.
8931     keepGoing = false;
8932   }
8933 
8934   StringRef Specifier(csStart, csLen);
8935 
8936   // If the specifier in non-printable, it could be the first byte of a UTF-8
8937   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8938   // hex value.
8939   std::string CodePointStr;
8940   if (!llvm::sys::locale::isPrint(*csStart)) {
8941     llvm::UTF32 CodePoint;
8942     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8943     const llvm::UTF8 *E =
8944         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8945     llvm::ConversionResult Result =
8946         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8947 
8948     if (Result != llvm::conversionOK) {
8949       unsigned char FirstChar = *csStart;
8950       CodePoint = (llvm::UTF32)FirstChar;
8951     }
8952 
8953     llvm::raw_string_ostream OS(CodePointStr);
8954     if (CodePoint < 256)
8955       OS << "\\x" << llvm::format("%02x", CodePoint);
8956     else if (CodePoint <= 0xFFFF)
8957       OS << "\\u" << llvm::format("%04x", CodePoint);
8958     else
8959       OS << "\\U" << llvm::format("%08x", CodePoint);
8960     OS.flush();
8961     Specifier = CodePointStr;
8962   }
8963 
8964   EmitFormatDiagnostic(
8965       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8966       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8967 
8968   return keepGoing;
8969 }
8970 
8971 void
8972 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8973                                                       const char *startSpec,
8974                                                       unsigned specifierLen) {
8975   EmitFormatDiagnostic(
8976     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8977     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8978 }
8979 
8980 bool
8981 CheckFormatHandler::CheckNumArgs(
8982   const analyze_format_string::FormatSpecifier &FS,
8983   const analyze_format_string::ConversionSpecifier &CS,
8984   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8985 
8986   if (argIndex >= NumDataArgs) {
8987     PartialDiagnostic PDiag = FS.usesPositionalArg()
8988       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8989            << (argIndex+1) << NumDataArgs)
8990       : S.PDiag(diag::warn_printf_insufficient_data_args);
8991     EmitFormatDiagnostic(
8992       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8993       getSpecifierRange(startSpecifier, specifierLen));
8994 
8995     // Since more arguments than conversion tokens are given, by extension
8996     // all arguments are covered, so mark this as so.
8997     UncoveredArg.setAllCovered();
8998     return false;
8999   }
9000   return true;
9001 }
9002 
9003 template<typename Range>
9004 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
9005                                               SourceLocation Loc,
9006                                               bool IsStringLocation,
9007                                               Range StringRange,
9008                                               ArrayRef<FixItHint> FixIt) {
9009   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
9010                        Loc, IsStringLocation, StringRange, FixIt);
9011 }
9012 
9013 /// If the format string is not within the function call, emit a note
9014 /// so that the function call and string are in diagnostic messages.
9015 ///
9016 /// \param InFunctionCall if true, the format string is within the function
9017 /// call and only one diagnostic message will be produced.  Otherwise, an
9018 /// extra note will be emitted pointing to location of the format string.
9019 ///
9020 /// \param ArgumentExpr the expression that is passed as the format string
9021 /// argument in the function call.  Used for getting locations when two
9022 /// diagnostics are emitted.
9023 ///
9024 /// \param PDiag the callee should already have provided any strings for the
9025 /// diagnostic message.  This function only adds locations and fixits
9026 /// to diagnostics.
9027 ///
9028 /// \param Loc primary location for diagnostic.  If two diagnostics are
9029 /// required, one will be at Loc and a new SourceLocation will be created for
9030 /// the other one.
9031 ///
9032 /// \param IsStringLocation if true, Loc points to the format string should be
9033 /// used for the note.  Otherwise, Loc points to the argument list and will
9034 /// be used with PDiag.
9035 ///
9036 /// \param StringRange some or all of the string to highlight.  This is
9037 /// templated so it can accept either a CharSourceRange or a SourceRange.
9038 ///
9039 /// \param FixIt optional fix it hint for the format string.
9040 template <typename Range>
9041 void CheckFormatHandler::EmitFormatDiagnostic(
9042     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
9043     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
9044     Range StringRange, ArrayRef<FixItHint> FixIt) {
9045   if (InFunctionCall) {
9046     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
9047     D << StringRange;
9048     D << FixIt;
9049   } else {
9050     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
9051       << ArgumentExpr->getSourceRange();
9052 
9053     const Sema::SemaDiagnosticBuilder &Note =
9054       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
9055              diag::note_format_string_defined);
9056 
9057     Note << StringRange;
9058     Note << FixIt;
9059   }
9060 }
9061 
9062 //===--- CHECK: Printf format string checking ------------------------------===//
9063 
9064 namespace {
9065 
9066 class CheckPrintfHandler : public CheckFormatHandler {
9067 public:
9068   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
9069                      const Expr *origFormatExpr,
9070                      const Sema::FormatStringType type, unsigned firstDataArg,
9071                      unsigned numDataArgs, bool isObjC, const char *beg,
9072                      bool hasVAListArg, ArrayRef<const Expr *> Args,
9073                      unsigned formatIdx, bool inFunctionCall,
9074                      Sema::VariadicCallType CallType,
9075                      llvm::SmallBitVector &CheckedVarArgs,
9076                      UncoveredArgHandler &UncoveredArg)
9077       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9078                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9079                            inFunctionCall, CallType, CheckedVarArgs,
9080                            UncoveredArg) {}
9081 
9082   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
9083 
9084   /// Returns true if '%@' specifiers are allowed in the format string.
9085   bool allowsObjCArg() const {
9086     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
9087            FSType == Sema::FST_OSTrace;
9088   }
9089 
9090   bool HandleInvalidPrintfConversionSpecifier(
9091                                       const analyze_printf::PrintfSpecifier &FS,
9092                                       const char *startSpecifier,
9093                                       unsigned specifierLen) override;
9094 
9095   void handleInvalidMaskType(StringRef MaskType) override;
9096 
9097   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
9098                              const char *startSpecifier, unsigned specifierLen,
9099                              const TargetInfo &Target) override;
9100   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9101                        const char *StartSpecifier,
9102                        unsigned SpecifierLen,
9103                        const Expr *E);
9104 
9105   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
9106                     const char *startSpecifier, unsigned specifierLen);
9107   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
9108                            const analyze_printf::OptionalAmount &Amt,
9109                            unsigned type,
9110                            const char *startSpecifier, unsigned specifierLen);
9111   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9112                   const analyze_printf::OptionalFlag &flag,
9113                   const char *startSpecifier, unsigned specifierLen);
9114   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
9115                          const analyze_printf::OptionalFlag &ignoredFlag,
9116                          const analyze_printf::OptionalFlag &flag,
9117                          const char *startSpecifier, unsigned specifierLen);
9118   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
9119                            const Expr *E);
9120 
9121   void HandleEmptyObjCModifierFlag(const char *startFlag,
9122                                    unsigned flagLen) override;
9123 
9124   void HandleInvalidObjCModifierFlag(const char *startFlag,
9125                                             unsigned flagLen) override;
9126 
9127   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
9128                                            const char *flagsEnd,
9129                                            const char *conversionPosition)
9130                                              override;
9131 };
9132 
9133 } // namespace
9134 
9135 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
9136                                       const analyze_printf::PrintfSpecifier &FS,
9137                                       const char *startSpecifier,
9138                                       unsigned specifierLen) {
9139   const analyze_printf::PrintfConversionSpecifier &CS =
9140     FS.getConversionSpecifier();
9141 
9142   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9143                                           getLocationOfByte(CS.getStart()),
9144                                           startSpecifier, specifierLen,
9145                                           CS.getStart(), CS.getLength());
9146 }
9147 
9148 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9149   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9150 }
9151 
9152 bool CheckPrintfHandler::HandleAmount(
9153                                const analyze_format_string::OptionalAmount &Amt,
9154                                unsigned k, const char *startSpecifier,
9155                                unsigned specifierLen) {
9156   if (Amt.hasDataArgument()) {
9157     if (!HasVAListArg) {
9158       unsigned argIndex = Amt.getArgIndex();
9159       if (argIndex >= NumDataArgs) {
9160         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9161                                << k,
9162                              getLocationOfByte(Amt.getStart()),
9163                              /*IsStringLocation*/true,
9164                              getSpecifierRange(startSpecifier, specifierLen));
9165         // Don't do any more checking.  We will just emit
9166         // spurious errors.
9167         return false;
9168       }
9169 
9170       // Type check the data argument.  It should be an 'int'.
9171       // Although not in conformance with C99, we also allow the argument to be
9172       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9173       // doesn't emit a warning for that case.
9174       CoveredArgs.set(argIndex);
9175       const Expr *Arg = getDataArg(argIndex);
9176       if (!Arg)
9177         return false;
9178 
9179       QualType T = Arg->getType();
9180 
9181       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9182       assert(AT.isValid());
9183 
9184       if (!AT.matchesType(S.Context, T)) {
9185         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9186                                << k << AT.getRepresentativeTypeName(S.Context)
9187                                << T << Arg->getSourceRange(),
9188                              getLocationOfByte(Amt.getStart()),
9189                              /*IsStringLocation*/true,
9190                              getSpecifierRange(startSpecifier, specifierLen));
9191         // Don't do any more checking.  We will just emit
9192         // spurious errors.
9193         return false;
9194       }
9195     }
9196   }
9197   return true;
9198 }
9199 
9200 void CheckPrintfHandler::HandleInvalidAmount(
9201                                       const analyze_printf::PrintfSpecifier &FS,
9202                                       const analyze_printf::OptionalAmount &Amt,
9203                                       unsigned type,
9204                                       const char *startSpecifier,
9205                                       unsigned specifierLen) {
9206   const analyze_printf::PrintfConversionSpecifier &CS =
9207     FS.getConversionSpecifier();
9208 
9209   FixItHint fixit =
9210     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9211       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9212                                  Amt.getConstantLength()))
9213       : FixItHint();
9214 
9215   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9216                          << type << CS.toString(),
9217                        getLocationOfByte(Amt.getStart()),
9218                        /*IsStringLocation*/true,
9219                        getSpecifierRange(startSpecifier, specifierLen),
9220                        fixit);
9221 }
9222 
9223 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9224                                     const analyze_printf::OptionalFlag &flag,
9225                                     const char *startSpecifier,
9226                                     unsigned specifierLen) {
9227   // Warn about pointless flag with a fixit removal.
9228   const analyze_printf::PrintfConversionSpecifier &CS =
9229     FS.getConversionSpecifier();
9230   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9231                          << flag.toString() << CS.toString(),
9232                        getLocationOfByte(flag.getPosition()),
9233                        /*IsStringLocation*/true,
9234                        getSpecifierRange(startSpecifier, specifierLen),
9235                        FixItHint::CreateRemoval(
9236                          getSpecifierRange(flag.getPosition(), 1)));
9237 }
9238 
9239 void CheckPrintfHandler::HandleIgnoredFlag(
9240                                 const analyze_printf::PrintfSpecifier &FS,
9241                                 const analyze_printf::OptionalFlag &ignoredFlag,
9242                                 const analyze_printf::OptionalFlag &flag,
9243                                 const char *startSpecifier,
9244                                 unsigned specifierLen) {
9245   // Warn about ignored flag with a fixit removal.
9246   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9247                          << ignoredFlag.toString() << flag.toString(),
9248                        getLocationOfByte(ignoredFlag.getPosition()),
9249                        /*IsStringLocation*/true,
9250                        getSpecifierRange(startSpecifier, specifierLen),
9251                        FixItHint::CreateRemoval(
9252                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9253 }
9254 
9255 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9256                                                      unsigned flagLen) {
9257   // Warn about an empty flag.
9258   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9259                        getLocationOfByte(startFlag),
9260                        /*IsStringLocation*/true,
9261                        getSpecifierRange(startFlag, flagLen));
9262 }
9263 
9264 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9265                                                        unsigned flagLen) {
9266   // Warn about an invalid flag.
9267   auto Range = getSpecifierRange(startFlag, flagLen);
9268   StringRef flag(startFlag, flagLen);
9269   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9270                       getLocationOfByte(startFlag),
9271                       /*IsStringLocation*/true,
9272                       Range, FixItHint::CreateRemoval(Range));
9273 }
9274 
9275 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9276     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9277     // Warn about using '[...]' without a '@' conversion.
9278     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9279     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9280     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9281                          getLocationOfByte(conversionPosition),
9282                          /*IsStringLocation*/true,
9283                          Range, FixItHint::CreateRemoval(Range));
9284 }
9285 
9286 // Determines if the specified is a C++ class or struct containing
9287 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9288 // "c_str()").
9289 template<typename MemberKind>
9290 static llvm::SmallPtrSet<MemberKind*, 1>
9291 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9292   const RecordType *RT = Ty->getAs<RecordType>();
9293   llvm::SmallPtrSet<MemberKind*, 1> Results;
9294 
9295   if (!RT)
9296     return Results;
9297   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9298   if (!RD || !RD->getDefinition())
9299     return Results;
9300 
9301   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9302                  Sema::LookupMemberName);
9303   R.suppressDiagnostics();
9304 
9305   // We just need to include all members of the right kind turned up by the
9306   // filter, at this point.
9307   if (S.LookupQualifiedName(R, RT->getDecl()))
9308     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9309       NamedDecl *decl = (*I)->getUnderlyingDecl();
9310       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9311         Results.insert(FK);
9312     }
9313   return Results;
9314 }
9315 
9316 /// Check if we could call '.c_str()' on an object.
9317 ///
9318 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9319 /// allow the call, or if it would be ambiguous).
9320 bool Sema::hasCStrMethod(const Expr *E) {
9321   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9322 
9323   MethodSet Results =
9324       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9325   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9326        MI != ME; ++MI)
9327     if ((*MI)->getMinRequiredArguments() == 0)
9328       return true;
9329   return false;
9330 }
9331 
9332 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9333 // better diagnostic if so. AT is assumed to be valid.
9334 // Returns true when a c_str() conversion method is found.
9335 bool CheckPrintfHandler::checkForCStrMembers(
9336     const analyze_printf::ArgType &AT, const Expr *E) {
9337   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9338 
9339   MethodSet Results =
9340       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9341 
9342   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9343        MI != ME; ++MI) {
9344     const CXXMethodDecl *Method = *MI;
9345     if (Method->getMinRequiredArguments() == 0 &&
9346         AT.matchesType(S.Context, Method->getReturnType())) {
9347       // FIXME: Suggest parens if the expression needs them.
9348       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9349       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9350           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9351       return true;
9352     }
9353   }
9354 
9355   return false;
9356 }
9357 
9358 bool CheckPrintfHandler::HandlePrintfSpecifier(
9359     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9360     unsigned specifierLen, const TargetInfo &Target) {
9361   using namespace analyze_format_string;
9362   using namespace analyze_printf;
9363 
9364   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9365 
9366   if (FS.consumesDataArgument()) {
9367     if (atFirstArg) {
9368         atFirstArg = false;
9369         usesPositionalArgs = FS.usesPositionalArg();
9370     }
9371     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9372       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9373                                         startSpecifier, specifierLen);
9374       return false;
9375     }
9376   }
9377 
9378   // First check if the field width, precision, and conversion specifier
9379   // have matching data arguments.
9380   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9381                     startSpecifier, specifierLen)) {
9382     return false;
9383   }
9384 
9385   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9386                     startSpecifier, specifierLen)) {
9387     return false;
9388   }
9389 
9390   if (!CS.consumesDataArgument()) {
9391     // FIXME: Technically specifying a precision or field width here
9392     // makes no sense.  Worth issuing a warning at some point.
9393     return true;
9394   }
9395 
9396   // Consume the argument.
9397   unsigned argIndex = FS.getArgIndex();
9398   if (argIndex < NumDataArgs) {
9399     // The check to see if the argIndex is valid will come later.
9400     // We set the bit here because we may exit early from this
9401     // function if we encounter some other error.
9402     CoveredArgs.set(argIndex);
9403   }
9404 
9405   // FreeBSD kernel extensions.
9406   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9407       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9408     // We need at least two arguments.
9409     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9410       return false;
9411 
9412     // Claim the second argument.
9413     CoveredArgs.set(argIndex + 1);
9414 
9415     // Type check the first argument (int for %b, pointer for %D)
9416     const Expr *Ex = getDataArg(argIndex);
9417     const analyze_printf::ArgType &AT =
9418       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9419         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9420     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9421       EmitFormatDiagnostic(
9422           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9423               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9424               << false << Ex->getSourceRange(),
9425           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9426           getSpecifierRange(startSpecifier, specifierLen));
9427 
9428     // Type check the second argument (char * for both %b and %D)
9429     Ex = getDataArg(argIndex + 1);
9430     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9431     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9432       EmitFormatDiagnostic(
9433           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9434               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9435               << false << Ex->getSourceRange(),
9436           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9437           getSpecifierRange(startSpecifier, specifierLen));
9438 
9439      return true;
9440   }
9441 
9442   // Check for using an Objective-C specific conversion specifier
9443   // in a non-ObjC literal.
9444   if (!allowsObjCArg() && CS.isObjCArg()) {
9445     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9446                                                   specifierLen);
9447   }
9448 
9449   // %P can only be used with os_log.
9450   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9451     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9452                                                   specifierLen);
9453   }
9454 
9455   // %n is not allowed with os_log.
9456   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9457     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9458                          getLocationOfByte(CS.getStart()),
9459                          /*IsStringLocation*/ false,
9460                          getSpecifierRange(startSpecifier, specifierLen));
9461 
9462     return true;
9463   }
9464 
9465   // Only scalars are allowed for os_trace.
9466   if (FSType == Sema::FST_OSTrace &&
9467       (CS.getKind() == ConversionSpecifier::PArg ||
9468        CS.getKind() == ConversionSpecifier::sArg ||
9469        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9470     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9471                                                   specifierLen);
9472   }
9473 
9474   // Check for use of public/private annotation outside of os_log().
9475   if (FSType != Sema::FST_OSLog) {
9476     if (FS.isPublic().isSet()) {
9477       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9478                                << "public",
9479                            getLocationOfByte(FS.isPublic().getPosition()),
9480                            /*IsStringLocation*/ false,
9481                            getSpecifierRange(startSpecifier, specifierLen));
9482     }
9483     if (FS.isPrivate().isSet()) {
9484       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9485                                << "private",
9486                            getLocationOfByte(FS.isPrivate().getPosition()),
9487                            /*IsStringLocation*/ false,
9488                            getSpecifierRange(startSpecifier, specifierLen));
9489     }
9490   }
9491 
9492   const llvm::Triple &Triple = Target.getTriple();
9493   if (CS.getKind() == ConversionSpecifier::nArg &&
9494       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9495     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9496                          getLocationOfByte(CS.getStart()),
9497                          /*IsStringLocation*/ false,
9498                          getSpecifierRange(startSpecifier, specifierLen));
9499   }
9500 
9501   // Check for invalid use of field width
9502   if (!FS.hasValidFieldWidth()) {
9503     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9504         startSpecifier, specifierLen);
9505   }
9506 
9507   // Check for invalid use of precision
9508   if (!FS.hasValidPrecision()) {
9509     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9510         startSpecifier, specifierLen);
9511   }
9512 
9513   // Precision is mandatory for %P specifier.
9514   if (CS.getKind() == ConversionSpecifier::PArg &&
9515       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9516     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9517                          getLocationOfByte(startSpecifier),
9518                          /*IsStringLocation*/ false,
9519                          getSpecifierRange(startSpecifier, specifierLen));
9520   }
9521 
9522   // Check each flag does not conflict with any other component.
9523   if (!FS.hasValidThousandsGroupingPrefix())
9524     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9525   if (!FS.hasValidLeadingZeros())
9526     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9527   if (!FS.hasValidPlusPrefix())
9528     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9529   if (!FS.hasValidSpacePrefix())
9530     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9531   if (!FS.hasValidAlternativeForm())
9532     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9533   if (!FS.hasValidLeftJustified())
9534     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9535 
9536   // Check that flags are not ignored by another flag
9537   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9538     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9539         startSpecifier, specifierLen);
9540   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9541     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9542             startSpecifier, specifierLen);
9543 
9544   // Check the length modifier is valid with the given conversion specifier.
9545   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9546                                  S.getLangOpts()))
9547     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9548                                 diag::warn_format_nonsensical_length);
9549   else if (!FS.hasStandardLengthModifier())
9550     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9551   else if (!FS.hasStandardLengthConversionCombination())
9552     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9553                                 diag::warn_format_non_standard_conversion_spec);
9554 
9555   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9556     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9557 
9558   // The remaining checks depend on the data arguments.
9559   if (HasVAListArg)
9560     return true;
9561 
9562   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9563     return false;
9564 
9565   const Expr *Arg = getDataArg(argIndex);
9566   if (!Arg)
9567     return true;
9568 
9569   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9570 }
9571 
9572 static bool requiresParensToAddCast(const Expr *E) {
9573   // FIXME: We should have a general way to reason about operator
9574   // precedence and whether parens are actually needed here.
9575   // Take care of a few common cases where they aren't.
9576   const Expr *Inside = E->IgnoreImpCasts();
9577   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9578     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9579 
9580   switch (Inside->getStmtClass()) {
9581   case Stmt::ArraySubscriptExprClass:
9582   case Stmt::CallExprClass:
9583   case Stmt::CharacterLiteralClass:
9584   case Stmt::CXXBoolLiteralExprClass:
9585   case Stmt::DeclRefExprClass:
9586   case Stmt::FloatingLiteralClass:
9587   case Stmt::IntegerLiteralClass:
9588   case Stmt::MemberExprClass:
9589   case Stmt::ObjCArrayLiteralClass:
9590   case Stmt::ObjCBoolLiteralExprClass:
9591   case Stmt::ObjCBoxedExprClass:
9592   case Stmt::ObjCDictionaryLiteralClass:
9593   case Stmt::ObjCEncodeExprClass:
9594   case Stmt::ObjCIvarRefExprClass:
9595   case Stmt::ObjCMessageExprClass:
9596   case Stmt::ObjCPropertyRefExprClass:
9597   case Stmt::ObjCStringLiteralClass:
9598   case Stmt::ObjCSubscriptRefExprClass:
9599   case Stmt::ParenExprClass:
9600   case Stmt::StringLiteralClass:
9601   case Stmt::UnaryOperatorClass:
9602     return false;
9603   default:
9604     return true;
9605   }
9606 }
9607 
9608 static std::pair<QualType, StringRef>
9609 shouldNotPrintDirectly(const ASTContext &Context,
9610                        QualType IntendedTy,
9611                        const Expr *E) {
9612   // Use a 'while' to peel off layers of typedefs.
9613   QualType TyTy = IntendedTy;
9614   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9615     StringRef Name = UserTy->getDecl()->getName();
9616     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9617       .Case("CFIndex", Context.getNSIntegerType())
9618       .Case("NSInteger", Context.getNSIntegerType())
9619       .Case("NSUInteger", Context.getNSUIntegerType())
9620       .Case("SInt32", Context.IntTy)
9621       .Case("UInt32", Context.UnsignedIntTy)
9622       .Default(QualType());
9623 
9624     if (!CastTy.isNull())
9625       return std::make_pair(CastTy, Name);
9626 
9627     TyTy = UserTy->desugar();
9628   }
9629 
9630   // Strip parens if necessary.
9631   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9632     return shouldNotPrintDirectly(Context,
9633                                   PE->getSubExpr()->getType(),
9634                                   PE->getSubExpr());
9635 
9636   // If this is a conditional expression, then its result type is constructed
9637   // via usual arithmetic conversions and thus there might be no necessary
9638   // typedef sugar there.  Recurse to operands to check for NSInteger &
9639   // Co. usage condition.
9640   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9641     QualType TrueTy, FalseTy;
9642     StringRef TrueName, FalseName;
9643 
9644     std::tie(TrueTy, TrueName) =
9645       shouldNotPrintDirectly(Context,
9646                              CO->getTrueExpr()->getType(),
9647                              CO->getTrueExpr());
9648     std::tie(FalseTy, FalseName) =
9649       shouldNotPrintDirectly(Context,
9650                              CO->getFalseExpr()->getType(),
9651                              CO->getFalseExpr());
9652 
9653     if (TrueTy == FalseTy)
9654       return std::make_pair(TrueTy, TrueName);
9655     else if (TrueTy.isNull())
9656       return std::make_pair(FalseTy, FalseName);
9657     else if (FalseTy.isNull())
9658       return std::make_pair(TrueTy, TrueName);
9659   }
9660 
9661   return std::make_pair(QualType(), StringRef());
9662 }
9663 
9664 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9665 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9666 /// type do not count.
9667 static bool
9668 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9669   QualType From = ICE->getSubExpr()->getType();
9670   QualType To = ICE->getType();
9671   // It's an integer promotion if the destination type is the promoted
9672   // source type.
9673   if (ICE->getCastKind() == CK_IntegralCast &&
9674       From->isPromotableIntegerType() &&
9675       S.Context.getPromotedIntegerType(From) == To)
9676     return true;
9677   // Look through vector types, since we do default argument promotion for
9678   // those in OpenCL.
9679   if (const auto *VecTy = From->getAs<ExtVectorType>())
9680     From = VecTy->getElementType();
9681   if (const auto *VecTy = To->getAs<ExtVectorType>())
9682     To = VecTy->getElementType();
9683   // It's a floating promotion if the source type is a lower rank.
9684   return ICE->getCastKind() == CK_FloatingCast &&
9685          S.Context.getFloatingTypeOrder(From, To) < 0;
9686 }
9687 
9688 bool
9689 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9690                                     const char *StartSpecifier,
9691                                     unsigned SpecifierLen,
9692                                     const Expr *E) {
9693   using namespace analyze_format_string;
9694   using namespace analyze_printf;
9695 
9696   // Now type check the data expression that matches the
9697   // format specifier.
9698   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9699   if (!AT.isValid())
9700     return true;
9701 
9702   QualType ExprTy = E->getType();
9703   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9704     ExprTy = TET->getUnderlyingExpr()->getType();
9705   }
9706 
9707   // Diagnose attempts to print a boolean value as a character. Unlike other
9708   // -Wformat diagnostics, this is fine from a type perspective, but it still
9709   // doesn't make sense.
9710   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9711       E->isKnownToHaveBooleanValue()) {
9712     const CharSourceRange &CSR =
9713         getSpecifierRange(StartSpecifier, SpecifierLen);
9714     SmallString<4> FSString;
9715     llvm::raw_svector_ostream os(FSString);
9716     FS.toString(os);
9717     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9718                              << FSString,
9719                          E->getExprLoc(), false, CSR);
9720     return true;
9721   }
9722 
9723   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9724   if (Match == analyze_printf::ArgType::Match)
9725     return true;
9726 
9727   // Look through argument promotions for our error message's reported type.
9728   // This includes the integral and floating promotions, but excludes array
9729   // and function pointer decay (seeing that an argument intended to be a
9730   // string has type 'char [6]' is probably more confusing than 'char *') and
9731   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9732   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9733     if (isArithmeticArgumentPromotion(S, ICE)) {
9734       E = ICE->getSubExpr();
9735       ExprTy = E->getType();
9736 
9737       // Check if we didn't match because of an implicit cast from a 'char'
9738       // or 'short' to an 'int'.  This is done because printf is a varargs
9739       // function.
9740       if (ICE->getType() == S.Context.IntTy ||
9741           ICE->getType() == S.Context.UnsignedIntTy) {
9742         // All further checking is done on the subexpression
9743         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9744             AT.matchesType(S.Context, ExprTy);
9745         if (ImplicitMatch == analyze_printf::ArgType::Match)
9746           return true;
9747         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9748             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9749           Match = ImplicitMatch;
9750       }
9751     }
9752   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9753     // Special case for 'a', which has type 'int' in C.
9754     // Note, however, that we do /not/ want to treat multibyte constants like
9755     // 'MooV' as characters! This form is deprecated but still exists. In
9756     // addition, don't treat expressions as of type 'char' if one byte length
9757     // modifier is provided.
9758     if (ExprTy == S.Context.IntTy &&
9759         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9760       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9761         ExprTy = S.Context.CharTy;
9762   }
9763 
9764   // Look through enums to their underlying type.
9765   bool IsEnum = false;
9766   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9767     ExprTy = EnumTy->getDecl()->getIntegerType();
9768     IsEnum = true;
9769   }
9770 
9771   // %C in an Objective-C context prints a unichar, not a wchar_t.
9772   // If the argument is an integer of some kind, believe the %C and suggest
9773   // a cast instead of changing the conversion specifier.
9774   QualType IntendedTy = ExprTy;
9775   if (isObjCContext() &&
9776       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9777     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9778         !ExprTy->isCharType()) {
9779       // 'unichar' is defined as a typedef of unsigned short, but we should
9780       // prefer using the typedef if it is visible.
9781       IntendedTy = S.Context.UnsignedShortTy;
9782 
9783       // While we are here, check if the value is an IntegerLiteral that happens
9784       // to be within the valid range.
9785       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9786         const llvm::APInt &V = IL->getValue();
9787         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9788           return true;
9789       }
9790 
9791       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9792                           Sema::LookupOrdinaryName);
9793       if (S.LookupName(Result, S.getCurScope())) {
9794         NamedDecl *ND = Result.getFoundDecl();
9795         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9796           if (TD->getUnderlyingType() == IntendedTy)
9797             IntendedTy = S.Context.getTypedefType(TD);
9798       }
9799     }
9800   }
9801 
9802   // Special-case some of Darwin's platform-independence types by suggesting
9803   // casts to primitive types that are known to be large enough.
9804   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9805   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9806     QualType CastTy;
9807     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9808     if (!CastTy.isNull()) {
9809       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9810       // (long in ASTContext). Only complain to pedants.
9811       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9812           (AT.isSizeT() || AT.isPtrdiffT()) &&
9813           AT.matchesType(S.Context, CastTy))
9814         Match = ArgType::NoMatchPedantic;
9815       IntendedTy = CastTy;
9816       ShouldNotPrintDirectly = true;
9817     }
9818   }
9819 
9820   // We may be able to offer a FixItHint if it is a supported type.
9821   PrintfSpecifier fixedFS = FS;
9822   bool Success =
9823       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9824 
9825   if (Success) {
9826     // Get the fix string from the fixed format specifier
9827     SmallString<16> buf;
9828     llvm::raw_svector_ostream os(buf);
9829     fixedFS.toString(os);
9830 
9831     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9832 
9833     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9834       unsigned Diag;
9835       switch (Match) {
9836       case ArgType::Match: llvm_unreachable("expected non-matching");
9837       case ArgType::NoMatchPedantic:
9838         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9839         break;
9840       case ArgType::NoMatchTypeConfusion:
9841         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9842         break;
9843       case ArgType::NoMatch:
9844         Diag = diag::warn_format_conversion_argument_type_mismatch;
9845         break;
9846       }
9847 
9848       // In this case, the specifier is wrong and should be changed to match
9849       // the argument.
9850       EmitFormatDiagnostic(S.PDiag(Diag)
9851                                << AT.getRepresentativeTypeName(S.Context)
9852                                << IntendedTy << IsEnum << E->getSourceRange(),
9853                            E->getBeginLoc(),
9854                            /*IsStringLocation*/ false, SpecRange,
9855                            FixItHint::CreateReplacement(SpecRange, os.str()));
9856     } else {
9857       // The canonical type for formatting this value is different from the
9858       // actual type of the expression. (This occurs, for example, with Darwin's
9859       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9860       // should be printed as 'long' for 64-bit compatibility.)
9861       // Rather than emitting a normal format/argument mismatch, we want to
9862       // add a cast to the recommended type (and correct the format string
9863       // if necessary).
9864       SmallString<16> CastBuf;
9865       llvm::raw_svector_ostream CastFix(CastBuf);
9866       CastFix << "(";
9867       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9868       CastFix << ")";
9869 
9870       SmallVector<FixItHint,4> Hints;
9871       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9872         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9873 
9874       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9875         // If there's already a cast present, just replace it.
9876         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9877         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9878 
9879       } else if (!requiresParensToAddCast(E)) {
9880         // If the expression has high enough precedence,
9881         // just write the C-style cast.
9882         Hints.push_back(
9883             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9884       } else {
9885         // Otherwise, add parens around the expression as well as the cast.
9886         CastFix << "(";
9887         Hints.push_back(
9888             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9889 
9890         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9891         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9892       }
9893 
9894       if (ShouldNotPrintDirectly) {
9895         // The expression has a type that should not be printed directly.
9896         // We extract the name from the typedef because we don't want to show
9897         // the underlying type in the diagnostic.
9898         StringRef Name;
9899         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9900           Name = TypedefTy->getDecl()->getName();
9901         else
9902           Name = CastTyName;
9903         unsigned Diag = Match == ArgType::NoMatchPedantic
9904                             ? diag::warn_format_argument_needs_cast_pedantic
9905                             : diag::warn_format_argument_needs_cast;
9906         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9907                                            << E->getSourceRange(),
9908                              E->getBeginLoc(), /*IsStringLocation=*/false,
9909                              SpecRange, Hints);
9910       } else {
9911         // In this case, the expression could be printed using a different
9912         // specifier, but we've decided that the specifier is probably correct
9913         // and we should cast instead. Just use the normal warning message.
9914         EmitFormatDiagnostic(
9915             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9916                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9917                 << E->getSourceRange(),
9918             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9919       }
9920     }
9921   } else {
9922     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9923                                                    SpecifierLen);
9924     // Since the warning for passing non-POD types to variadic functions
9925     // was deferred until now, we emit a warning for non-POD
9926     // arguments here.
9927     switch (S.isValidVarArgType(ExprTy)) {
9928     case Sema::VAK_Valid:
9929     case Sema::VAK_ValidInCXX11: {
9930       unsigned Diag;
9931       switch (Match) {
9932       case ArgType::Match: llvm_unreachable("expected non-matching");
9933       case ArgType::NoMatchPedantic:
9934         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9935         break;
9936       case ArgType::NoMatchTypeConfusion:
9937         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9938         break;
9939       case ArgType::NoMatch:
9940         Diag = diag::warn_format_conversion_argument_type_mismatch;
9941         break;
9942       }
9943 
9944       EmitFormatDiagnostic(
9945           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9946                         << IsEnum << CSR << E->getSourceRange(),
9947           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9948       break;
9949     }
9950     case Sema::VAK_Undefined:
9951     case Sema::VAK_MSVCUndefined:
9952       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9953                                << S.getLangOpts().CPlusPlus11 << ExprTy
9954                                << CallType
9955                                << AT.getRepresentativeTypeName(S.Context) << CSR
9956                                << E->getSourceRange(),
9957                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9958       checkForCStrMembers(AT, E);
9959       break;
9960 
9961     case Sema::VAK_Invalid:
9962       if (ExprTy->isObjCObjectType())
9963         EmitFormatDiagnostic(
9964             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9965                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9966                 << AT.getRepresentativeTypeName(S.Context) << CSR
9967                 << E->getSourceRange(),
9968             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9969       else
9970         // FIXME: If this is an initializer list, suggest removing the braces
9971         // or inserting a cast to the target type.
9972         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9973             << isa<InitListExpr>(E) << ExprTy << CallType
9974             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9975       break;
9976     }
9977 
9978     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9979            "format string specifier index out of range");
9980     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9981   }
9982 
9983   return true;
9984 }
9985 
9986 //===--- CHECK: Scanf format string checking ------------------------------===//
9987 
9988 namespace {
9989 
9990 class CheckScanfHandler : public CheckFormatHandler {
9991 public:
9992   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9993                     const Expr *origFormatExpr, Sema::FormatStringType type,
9994                     unsigned firstDataArg, unsigned numDataArgs,
9995                     const char *beg, bool hasVAListArg,
9996                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9997                     bool inFunctionCall, Sema::VariadicCallType CallType,
9998                     llvm::SmallBitVector &CheckedVarArgs,
9999                     UncoveredArgHandler &UncoveredArg)
10000       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10001                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
10002                            inFunctionCall, CallType, CheckedVarArgs,
10003                            UncoveredArg) {}
10004 
10005   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10006                             const char *startSpecifier,
10007                             unsigned specifierLen) override;
10008 
10009   bool HandleInvalidScanfConversionSpecifier(
10010           const analyze_scanf::ScanfSpecifier &FS,
10011           const char *startSpecifier,
10012           unsigned specifierLen) override;
10013 
10014   void HandleIncompleteScanList(const char *start, const char *end) override;
10015 };
10016 
10017 } // namespace
10018 
10019 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10020                                                  const char *end) {
10021   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
10022                        getLocationOfByte(end), /*IsStringLocation*/true,
10023                        getSpecifierRange(start, end - start));
10024 }
10025 
10026 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10027                                         const analyze_scanf::ScanfSpecifier &FS,
10028                                         const char *startSpecifier,
10029                                         unsigned specifierLen) {
10030   const analyze_scanf::ScanfConversionSpecifier &CS =
10031     FS.getConversionSpecifier();
10032 
10033   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
10034                                           getLocationOfByte(CS.getStart()),
10035                                           startSpecifier, specifierLen,
10036                                           CS.getStart(), CS.getLength());
10037 }
10038 
10039 bool CheckScanfHandler::HandleScanfSpecifier(
10040                                        const analyze_scanf::ScanfSpecifier &FS,
10041                                        const char *startSpecifier,
10042                                        unsigned specifierLen) {
10043   using namespace analyze_scanf;
10044   using namespace analyze_format_string;
10045 
10046   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10047 
10048   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
10049   // be used to decide if we are using positional arguments consistently.
10050   if (FS.consumesDataArgument()) {
10051     if (atFirstArg) {
10052       atFirstArg = false;
10053       usesPositionalArgs = FS.usesPositionalArg();
10054     }
10055     else if (usesPositionalArgs != FS.usesPositionalArg()) {
10056       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
10057                                         startSpecifier, specifierLen);
10058       return false;
10059     }
10060   }
10061 
10062   // Check if the field with is non-zero.
10063   const OptionalAmount &Amt = FS.getFieldWidth();
10064   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
10065     if (Amt.getConstantAmount() == 0) {
10066       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
10067                                                    Amt.getConstantLength());
10068       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
10069                            getLocationOfByte(Amt.getStart()),
10070                            /*IsStringLocation*/true, R,
10071                            FixItHint::CreateRemoval(R));
10072     }
10073   }
10074 
10075   if (!FS.consumesDataArgument()) {
10076     // FIXME: Technically specifying a precision or field width here
10077     // makes no sense.  Worth issuing a warning at some point.
10078     return true;
10079   }
10080 
10081   // Consume the argument.
10082   unsigned argIndex = FS.getArgIndex();
10083   if (argIndex < NumDataArgs) {
10084       // The check to see if the argIndex is valid will come later.
10085       // We set the bit here because we may exit early from this
10086       // function if we encounter some other error.
10087     CoveredArgs.set(argIndex);
10088   }
10089 
10090   // Check the length modifier is valid with the given conversion specifier.
10091   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
10092                                  S.getLangOpts()))
10093     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10094                                 diag::warn_format_nonsensical_length);
10095   else if (!FS.hasStandardLengthModifier())
10096     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10097   else if (!FS.hasStandardLengthConversionCombination())
10098     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10099                                 diag::warn_format_non_standard_conversion_spec);
10100 
10101   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
10102     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10103 
10104   // The remaining checks depend on the data arguments.
10105   if (HasVAListArg)
10106     return true;
10107 
10108   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10109     return false;
10110 
10111   // Check that the argument type matches the format specifier.
10112   const Expr *Ex = getDataArg(argIndex);
10113   if (!Ex)
10114     return true;
10115 
10116   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
10117 
10118   if (!AT.isValid()) {
10119     return true;
10120   }
10121 
10122   analyze_format_string::ArgType::MatchKind Match =
10123       AT.matchesType(S.Context, Ex->getType());
10124   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10125   if (Match == analyze_format_string::ArgType::Match)
10126     return true;
10127 
10128   ScanfSpecifier fixedFS = FS;
10129   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10130                                  S.getLangOpts(), S.Context);
10131 
10132   unsigned Diag =
10133       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10134                : diag::warn_format_conversion_argument_type_mismatch;
10135 
10136   if (Success) {
10137     // Get the fix string from the fixed format specifier.
10138     SmallString<128> buf;
10139     llvm::raw_svector_ostream os(buf);
10140     fixedFS.toString(os);
10141 
10142     EmitFormatDiagnostic(
10143         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10144                       << Ex->getType() << false << Ex->getSourceRange(),
10145         Ex->getBeginLoc(),
10146         /*IsStringLocation*/ false,
10147         getSpecifierRange(startSpecifier, specifierLen),
10148         FixItHint::CreateReplacement(
10149             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10150   } else {
10151     EmitFormatDiagnostic(S.PDiag(Diag)
10152                              << AT.getRepresentativeTypeName(S.Context)
10153                              << Ex->getType() << false << Ex->getSourceRange(),
10154                          Ex->getBeginLoc(),
10155                          /*IsStringLocation*/ false,
10156                          getSpecifierRange(startSpecifier, specifierLen));
10157   }
10158 
10159   return true;
10160 }
10161 
10162 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10163                               const Expr *OrigFormatExpr,
10164                               ArrayRef<const Expr *> Args,
10165                               bool HasVAListArg, unsigned format_idx,
10166                               unsigned firstDataArg,
10167                               Sema::FormatStringType Type,
10168                               bool inFunctionCall,
10169                               Sema::VariadicCallType CallType,
10170                               llvm::SmallBitVector &CheckedVarArgs,
10171                               UncoveredArgHandler &UncoveredArg,
10172                               bool IgnoreStringsWithoutSpecifiers) {
10173   // CHECK: is the format string a wide literal?
10174   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10175     CheckFormatHandler::EmitFormatDiagnostic(
10176         S, inFunctionCall, Args[format_idx],
10177         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10178         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10179     return;
10180   }
10181 
10182   // Str - The format string.  NOTE: this is NOT null-terminated!
10183   StringRef StrRef = FExpr->getString();
10184   const char *Str = StrRef.data();
10185   // Account for cases where the string literal is truncated in a declaration.
10186   const ConstantArrayType *T =
10187     S.Context.getAsConstantArrayType(FExpr->getType());
10188   assert(T && "String literal not of constant array type!");
10189   size_t TypeSize = T->getSize().getZExtValue();
10190   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10191   const unsigned numDataArgs = Args.size() - firstDataArg;
10192 
10193   if (IgnoreStringsWithoutSpecifiers &&
10194       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10195           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10196     return;
10197 
10198   // Emit a warning if the string literal is truncated and does not contain an
10199   // embedded null character.
10200   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10201     CheckFormatHandler::EmitFormatDiagnostic(
10202         S, inFunctionCall, Args[format_idx],
10203         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10204         FExpr->getBeginLoc(),
10205         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10206     return;
10207   }
10208 
10209   // CHECK: empty format string?
10210   if (StrLen == 0 && numDataArgs > 0) {
10211     CheckFormatHandler::EmitFormatDiagnostic(
10212         S, inFunctionCall, Args[format_idx],
10213         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10214         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10215     return;
10216   }
10217 
10218   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10219       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10220       Type == Sema::FST_OSTrace) {
10221     CheckPrintfHandler H(
10222         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10223         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10224         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10225         CheckedVarArgs, UncoveredArg);
10226 
10227     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10228                                                   S.getLangOpts(),
10229                                                   S.Context.getTargetInfo(),
10230                                             Type == Sema::FST_FreeBSDKPrintf))
10231       H.DoneProcessing();
10232   } else if (Type == Sema::FST_Scanf) {
10233     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10234                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10235                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10236 
10237     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10238                                                  S.getLangOpts(),
10239                                                  S.Context.getTargetInfo()))
10240       H.DoneProcessing();
10241   } // TODO: handle other formats
10242 }
10243 
10244 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10245   // Str - The format string.  NOTE: this is NOT null-terminated!
10246   StringRef StrRef = FExpr->getString();
10247   const char *Str = StrRef.data();
10248   // Account for cases where the string literal is truncated in a declaration.
10249   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10250   assert(T && "String literal not of constant array type!");
10251   size_t TypeSize = T->getSize().getZExtValue();
10252   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10253   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10254                                                          getLangOpts(),
10255                                                          Context.getTargetInfo());
10256 }
10257 
10258 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10259 
10260 // Returns the related absolute value function that is larger, of 0 if one
10261 // does not exist.
10262 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10263   switch (AbsFunction) {
10264   default:
10265     return 0;
10266 
10267   case Builtin::BI__builtin_abs:
10268     return Builtin::BI__builtin_labs;
10269   case Builtin::BI__builtin_labs:
10270     return Builtin::BI__builtin_llabs;
10271   case Builtin::BI__builtin_llabs:
10272     return 0;
10273 
10274   case Builtin::BI__builtin_fabsf:
10275     return Builtin::BI__builtin_fabs;
10276   case Builtin::BI__builtin_fabs:
10277     return Builtin::BI__builtin_fabsl;
10278   case Builtin::BI__builtin_fabsl:
10279     return 0;
10280 
10281   case Builtin::BI__builtin_cabsf:
10282     return Builtin::BI__builtin_cabs;
10283   case Builtin::BI__builtin_cabs:
10284     return Builtin::BI__builtin_cabsl;
10285   case Builtin::BI__builtin_cabsl:
10286     return 0;
10287 
10288   case Builtin::BIabs:
10289     return Builtin::BIlabs;
10290   case Builtin::BIlabs:
10291     return Builtin::BIllabs;
10292   case Builtin::BIllabs:
10293     return 0;
10294 
10295   case Builtin::BIfabsf:
10296     return Builtin::BIfabs;
10297   case Builtin::BIfabs:
10298     return Builtin::BIfabsl;
10299   case Builtin::BIfabsl:
10300     return 0;
10301 
10302   case Builtin::BIcabsf:
10303    return Builtin::BIcabs;
10304   case Builtin::BIcabs:
10305     return Builtin::BIcabsl;
10306   case Builtin::BIcabsl:
10307     return 0;
10308   }
10309 }
10310 
10311 // Returns the argument type of the absolute value function.
10312 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10313                                              unsigned AbsType) {
10314   if (AbsType == 0)
10315     return QualType();
10316 
10317   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10318   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10319   if (Error != ASTContext::GE_None)
10320     return QualType();
10321 
10322   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10323   if (!FT)
10324     return QualType();
10325 
10326   if (FT->getNumParams() != 1)
10327     return QualType();
10328 
10329   return FT->getParamType(0);
10330 }
10331 
10332 // Returns the best absolute value function, or zero, based on type and
10333 // current absolute value function.
10334 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10335                                    unsigned AbsFunctionKind) {
10336   unsigned BestKind = 0;
10337   uint64_t ArgSize = Context.getTypeSize(ArgType);
10338   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10339        Kind = getLargerAbsoluteValueFunction(Kind)) {
10340     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10341     if (Context.getTypeSize(ParamType) >= ArgSize) {
10342       if (BestKind == 0)
10343         BestKind = Kind;
10344       else if (Context.hasSameType(ParamType, ArgType)) {
10345         BestKind = Kind;
10346         break;
10347       }
10348     }
10349   }
10350   return BestKind;
10351 }
10352 
10353 enum AbsoluteValueKind {
10354   AVK_Integer,
10355   AVK_Floating,
10356   AVK_Complex
10357 };
10358 
10359 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10360   if (T->isIntegralOrEnumerationType())
10361     return AVK_Integer;
10362   if (T->isRealFloatingType())
10363     return AVK_Floating;
10364   if (T->isAnyComplexType())
10365     return AVK_Complex;
10366 
10367   llvm_unreachable("Type not integer, floating, or complex");
10368 }
10369 
10370 // Changes the absolute value function to a different type.  Preserves whether
10371 // the function is a builtin.
10372 static unsigned changeAbsFunction(unsigned AbsKind,
10373                                   AbsoluteValueKind ValueKind) {
10374   switch (ValueKind) {
10375   case AVK_Integer:
10376     switch (AbsKind) {
10377     default:
10378       return 0;
10379     case Builtin::BI__builtin_fabsf:
10380     case Builtin::BI__builtin_fabs:
10381     case Builtin::BI__builtin_fabsl:
10382     case Builtin::BI__builtin_cabsf:
10383     case Builtin::BI__builtin_cabs:
10384     case Builtin::BI__builtin_cabsl:
10385       return Builtin::BI__builtin_abs;
10386     case Builtin::BIfabsf:
10387     case Builtin::BIfabs:
10388     case Builtin::BIfabsl:
10389     case Builtin::BIcabsf:
10390     case Builtin::BIcabs:
10391     case Builtin::BIcabsl:
10392       return Builtin::BIabs;
10393     }
10394   case AVK_Floating:
10395     switch (AbsKind) {
10396     default:
10397       return 0;
10398     case Builtin::BI__builtin_abs:
10399     case Builtin::BI__builtin_labs:
10400     case Builtin::BI__builtin_llabs:
10401     case Builtin::BI__builtin_cabsf:
10402     case Builtin::BI__builtin_cabs:
10403     case Builtin::BI__builtin_cabsl:
10404       return Builtin::BI__builtin_fabsf;
10405     case Builtin::BIabs:
10406     case Builtin::BIlabs:
10407     case Builtin::BIllabs:
10408     case Builtin::BIcabsf:
10409     case Builtin::BIcabs:
10410     case Builtin::BIcabsl:
10411       return Builtin::BIfabsf;
10412     }
10413   case AVK_Complex:
10414     switch (AbsKind) {
10415     default:
10416       return 0;
10417     case Builtin::BI__builtin_abs:
10418     case Builtin::BI__builtin_labs:
10419     case Builtin::BI__builtin_llabs:
10420     case Builtin::BI__builtin_fabsf:
10421     case Builtin::BI__builtin_fabs:
10422     case Builtin::BI__builtin_fabsl:
10423       return Builtin::BI__builtin_cabsf;
10424     case Builtin::BIabs:
10425     case Builtin::BIlabs:
10426     case Builtin::BIllabs:
10427     case Builtin::BIfabsf:
10428     case Builtin::BIfabs:
10429     case Builtin::BIfabsl:
10430       return Builtin::BIcabsf;
10431     }
10432   }
10433   llvm_unreachable("Unable to convert function");
10434 }
10435 
10436 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10437   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10438   if (!FnInfo)
10439     return 0;
10440 
10441   switch (FDecl->getBuiltinID()) {
10442   default:
10443     return 0;
10444   case Builtin::BI__builtin_abs:
10445   case Builtin::BI__builtin_fabs:
10446   case Builtin::BI__builtin_fabsf:
10447   case Builtin::BI__builtin_fabsl:
10448   case Builtin::BI__builtin_labs:
10449   case Builtin::BI__builtin_llabs:
10450   case Builtin::BI__builtin_cabs:
10451   case Builtin::BI__builtin_cabsf:
10452   case Builtin::BI__builtin_cabsl:
10453   case Builtin::BIabs:
10454   case Builtin::BIlabs:
10455   case Builtin::BIllabs:
10456   case Builtin::BIfabs:
10457   case Builtin::BIfabsf:
10458   case Builtin::BIfabsl:
10459   case Builtin::BIcabs:
10460   case Builtin::BIcabsf:
10461   case Builtin::BIcabsl:
10462     return FDecl->getBuiltinID();
10463   }
10464   llvm_unreachable("Unknown Builtin type");
10465 }
10466 
10467 // If the replacement is valid, emit a note with replacement function.
10468 // Additionally, suggest including the proper header if not already included.
10469 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10470                             unsigned AbsKind, QualType ArgType) {
10471   bool EmitHeaderHint = true;
10472   const char *HeaderName = nullptr;
10473   const char *FunctionName = nullptr;
10474   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10475     FunctionName = "std::abs";
10476     if (ArgType->isIntegralOrEnumerationType()) {
10477       HeaderName = "cstdlib";
10478     } else if (ArgType->isRealFloatingType()) {
10479       HeaderName = "cmath";
10480     } else {
10481       llvm_unreachable("Invalid Type");
10482     }
10483 
10484     // Lookup all std::abs
10485     if (NamespaceDecl *Std = S.getStdNamespace()) {
10486       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10487       R.suppressDiagnostics();
10488       S.LookupQualifiedName(R, Std);
10489 
10490       for (const auto *I : R) {
10491         const FunctionDecl *FDecl = nullptr;
10492         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10493           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10494         } else {
10495           FDecl = dyn_cast<FunctionDecl>(I);
10496         }
10497         if (!FDecl)
10498           continue;
10499 
10500         // Found std::abs(), check that they are the right ones.
10501         if (FDecl->getNumParams() != 1)
10502           continue;
10503 
10504         // Check that the parameter type can handle the argument.
10505         QualType ParamType = FDecl->getParamDecl(0)->getType();
10506         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10507             S.Context.getTypeSize(ArgType) <=
10508                 S.Context.getTypeSize(ParamType)) {
10509           // Found a function, don't need the header hint.
10510           EmitHeaderHint = false;
10511           break;
10512         }
10513       }
10514     }
10515   } else {
10516     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10517     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10518 
10519     if (HeaderName) {
10520       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10521       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10522       R.suppressDiagnostics();
10523       S.LookupName(R, S.getCurScope());
10524 
10525       if (R.isSingleResult()) {
10526         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10527         if (FD && FD->getBuiltinID() == AbsKind) {
10528           EmitHeaderHint = false;
10529         } else {
10530           return;
10531         }
10532       } else if (!R.empty()) {
10533         return;
10534       }
10535     }
10536   }
10537 
10538   S.Diag(Loc, diag::note_replace_abs_function)
10539       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10540 
10541   if (!HeaderName)
10542     return;
10543 
10544   if (!EmitHeaderHint)
10545     return;
10546 
10547   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10548                                                     << FunctionName;
10549 }
10550 
10551 template <std::size_t StrLen>
10552 static bool IsStdFunction(const FunctionDecl *FDecl,
10553                           const char (&Str)[StrLen]) {
10554   if (!FDecl)
10555     return false;
10556   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10557     return false;
10558   if (!FDecl->isInStdNamespace())
10559     return false;
10560 
10561   return true;
10562 }
10563 
10564 // Warn when using the wrong abs() function.
10565 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10566                                       const FunctionDecl *FDecl) {
10567   if (Call->getNumArgs() != 1)
10568     return;
10569 
10570   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10571   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10572   if (AbsKind == 0 && !IsStdAbs)
10573     return;
10574 
10575   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10576   QualType ParamType = Call->getArg(0)->getType();
10577 
10578   // Unsigned types cannot be negative.  Suggest removing the absolute value
10579   // function call.
10580   if (ArgType->isUnsignedIntegerType()) {
10581     const char *FunctionName =
10582         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10583     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10584     Diag(Call->getExprLoc(), diag::note_remove_abs)
10585         << FunctionName
10586         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10587     return;
10588   }
10589 
10590   // Taking the absolute value of a pointer is very suspicious, they probably
10591   // wanted to index into an array, dereference a pointer, call a function, etc.
10592   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10593     unsigned DiagType = 0;
10594     if (ArgType->isFunctionType())
10595       DiagType = 1;
10596     else if (ArgType->isArrayType())
10597       DiagType = 2;
10598 
10599     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10600     return;
10601   }
10602 
10603   // std::abs has overloads which prevent most of the absolute value problems
10604   // from occurring.
10605   if (IsStdAbs)
10606     return;
10607 
10608   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10609   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10610 
10611   // The argument and parameter are the same kind.  Check if they are the right
10612   // size.
10613   if (ArgValueKind == ParamValueKind) {
10614     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10615       return;
10616 
10617     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10618     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10619         << FDecl << ArgType << ParamType;
10620 
10621     if (NewAbsKind == 0)
10622       return;
10623 
10624     emitReplacement(*this, Call->getExprLoc(),
10625                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10626     return;
10627   }
10628 
10629   // ArgValueKind != ParamValueKind
10630   // The wrong type of absolute value function was used.  Attempt to find the
10631   // proper one.
10632   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10633   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10634   if (NewAbsKind == 0)
10635     return;
10636 
10637   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10638       << FDecl << ParamValueKind << ArgValueKind;
10639 
10640   emitReplacement(*this, Call->getExprLoc(),
10641                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10642 }
10643 
10644 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10645 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10646                                 const FunctionDecl *FDecl) {
10647   if (!Call || !FDecl) return;
10648 
10649   // Ignore template specializations and macros.
10650   if (inTemplateInstantiation()) return;
10651   if (Call->getExprLoc().isMacroID()) return;
10652 
10653   // Only care about the one template argument, two function parameter std::max
10654   if (Call->getNumArgs() != 2) return;
10655   if (!IsStdFunction(FDecl, "max")) return;
10656   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10657   if (!ArgList) return;
10658   if (ArgList->size() != 1) return;
10659 
10660   // Check that template type argument is unsigned integer.
10661   const auto& TA = ArgList->get(0);
10662   if (TA.getKind() != TemplateArgument::Type) return;
10663   QualType ArgType = TA.getAsType();
10664   if (!ArgType->isUnsignedIntegerType()) return;
10665 
10666   // See if either argument is a literal zero.
10667   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10668     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10669     if (!MTE) return false;
10670     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10671     if (!Num) return false;
10672     if (Num->getValue() != 0) return false;
10673     return true;
10674   };
10675 
10676   const Expr *FirstArg = Call->getArg(0);
10677   const Expr *SecondArg = Call->getArg(1);
10678   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10679   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10680 
10681   // Only warn when exactly one argument is zero.
10682   if (IsFirstArgZero == IsSecondArgZero) return;
10683 
10684   SourceRange FirstRange = FirstArg->getSourceRange();
10685   SourceRange SecondRange = SecondArg->getSourceRange();
10686 
10687   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10688 
10689   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10690       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10691 
10692   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10693   SourceRange RemovalRange;
10694   if (IsFirstArgZero) {
10695     RemovalRange = SourceRange(FirstRange.getBegin(),
10696                                SecondRange.getBegin().getLocWithOffset(-1));
10697   } else {
10698     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10699                                SecondRange.getEnd());
10700   }
10701 
10702   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10703         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10704         << FixItHint::CreateRemoval(RemovalRange);
10705 }
10706 
10707 //===--- CHECK: Standard memory functions ---------------------------------===//
10708 
10709 /// Takes the expression passed to the size_t parameter of functions
10710 /// such as memcmp, strncat, etc and warns if it's a comparison.
10711 ///
10712 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10713 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10714                                            IdentifierInfo *FnName,
10715                                            SourceLocation FnLoc,
10716                                            SourceLocation RParenLoc) {
10717   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10718   if (!Size)
10719     return false;
10720 
10721   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10722   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10723     return false;
10724 
10725   SourceRange SizeRange = Size->getSourceRange();
10726   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10727       << SizeRange << FnName;
10728   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10729       << FnName
10730       << FixItHint::CreateInsertion(
10731              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10732       << FixItHint::CreateRemoval(RParenLoc);
10733   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10734       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10735       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10736                                     ")");
10737 
10738   return true;
10739 }
10740 
10741 /// Determine whether the given type is or contains a dynamic class type
10742 /// (e.g., whether it has a vtable).
10743 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10744                                                      bool &IsContained) {
10745   // Look through array types while ignoring qualifiers.
10746   const Type *Ty = T->getBaseElementTypeUnsafe();
10747   IsContained = false;
10748 
10749   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10750   RD = RD ? RD->getDefinition() : nullptr;
10751   if (!RD || RD->isInvalidDecl())
10752     return nullptr;
10753 
10754   if (RD->isDynamicClass())
10755     return RD;
10756 
10757   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10758   // It's impossible for a class to transitively contain itself by value, so
10759   // infinite recursion is impossible.
10760   for (auto *FD : RD->fields()) {
10761     bool SubContained;
10762     if (const CXXRecordDecl *ContainedRD =
10763             getContainedDynamicClass(FD->getType(), SubContained)) {
10764       IsContained = true;
10765       return ContainedRD;
10766     }
10767   }
10768 
10769   return nullptr;
10770 }
10771 
10772 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10773   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10774     if (Unary->getKind() == UETT_SizeOf)
10775       return Unary;
10776   return nullptr;
10777 }
10778 
10779 /// If E is a sizeof expression, returns its argument expression,
10780 /// otherwise returns NULL.
10781 static const Expr *getSizeOfExprArg(const Expr *E) {
10782   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10783     if (!SizeOf->isArgumentType())
10784       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10785   return nullptr;
10786 }
10787 
10788 /// If E is a sizeof expression, returns its argument type.
10789 static QualType getSizeOfArgType(const Expr *E) {
10790   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10791     return SizeOf->getTypeOfArgument();
10792   return QualType();
10793 }
10794 
10795 namespace {
10796 
10797 struct SearchNonTrivialToInitializeField
10798     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10799   using Super =
10800       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10801 
10802   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10803 
10804   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10805                      SourceLocation SL) {
10806     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10807       asDerived().visitArray(PDIK, AT, SL);
10808       return;
10809     }
10810 
10811     Super::visitWithKind(PDIK, FT, SL);
10812   }
10813 
10814   void visitARCStrong(QualType FT, SourceLocation SL) {
10815     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10816   }
10817   void visitARCWeak(QualType FT, SourceLocation SL) {
10818     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10819   }
10820   void visitStruct(QualType FT, SourceLocation SL) {
10821     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10822       visit(FD->getType(), FD->getLocation());
10823   }
10824   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10825                   const ArrayType *AT, SourceLocation SL) {
10826     visit(getContext().getBaseElementType(AT), SL);
10827   }
10828   void visitTrivial(QualType FT, SourceLocation SL) {}
10829 
10830   static void diag(QualType RT, const Expr *E, Sema &S) {
10831     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10832   }
10833 
10834   ASTContext &getContext() { return S.getASTContext(); }
10835 
10836   const Expr *E;
10837   Sema &S;
10838 };
10839 
10840 struct SearchNonTrivialToCopyField
10841     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10842   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10843 
10844   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10845 
10846   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10847                      SourceLocation SL) {
10848     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10849       asDerived().visitArray(PCK, AT, SL);
10850       return;
10851     }
10852 
10853     Super::visitWithKind(PCK, FT, SL);
10854   }
10855 
10856   void visitARCStrong(QualType FT, SourceLocation SL) {
10857     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10858   }
10859   void visitARCWeak(QualType FT, SourceLocation SL) {
10860     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10861   }
10862   void visitStruct(QualType FT, SourceLocation SL) {
10863     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10864       visit(FD->getType(), FD->getLocation());
10865   }
10866   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10867                   SourceLocation SL) {
10868     visit(getContext().getBaseElementType(AT), SL);
10869   }
10870   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10871                 SourceLocation SL) {}
10872   void visitTrivial(QualType FT, SourceLocation SL) {}
10873   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10874 
10875   static void diag(QualType RT, const Expr *E, Sema &S) {
10876     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10877   }
10878 
10879   ASTContext &getContext() { return S.getASTContext(); }
10880 
10881   const Expr *E;
10882   Sema &S;
10883 };
10884 
10885 }
10886 
10887 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10888 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10889   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10890 
10891   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10892     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10893       return false;
10894 
10895     return doesExprLikelyComputeSize(BO->getLHS()) ||
10896            doesExprLikelyComputeSize(BO->getRHS());
10897   }
10898 
10899   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10900 }
10901 
10902 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10903 ///
10904 /// \code
10905 ///   #define MACRO 0
10906 ///   foo(MACRO);
10907 ///   foo(0);
10908 /// \endcode
10909 ///
10910 /// This should return true for the first call to foo, but not for the second
10911 /// (regardless of whether foo is a macro or function).
10912 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10913                                         SourceLocation CallLoc,
10914                                         SourceLocation ArgLoc) {
10915   if (!CallLoc.isMacroID())
10916     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10917 
10918   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10919          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10920 }
10921 
10922 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10923 /// last two arguments transposed.
10924 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10925   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10926     return;
10927 
10928   const Expr *SizeArg =
10929     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10930 
10931   auto isLiteralZero = [](const Expr *E) {
10932     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10933   };
10934 
10935   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10936   SourceLocation CallLoc = Call->getRParenLoc();
10937   SourceManager &SM = S.getSourceManager();
10938   if (isLiteralZero(SizeArg) &&
10939       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10940 
10941     SourceLocation DiagLoc = SizeArg->getExprLoc();
10942 
10943     // Some platforms #define bzero to __builtin_memset. See if this is the
10944     // case, and if so, emit a better diagnostic.
10945     if (BId == Builtin::BIbzero ||
10946         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10947                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10948       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10949       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10950     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10951       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10952       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10953     }
10954     return;
10955   }
10956 
10957   // If the second argument to a memset is a sizeof expression and the third
10958   // isn't, this is also likely an error. This should catch
10959   // 'memset(buf, sizeof(buf), 0xff)'.
10960   if (BId == Builtin::BImemset &&
10961       doesExprLikelyComputeSize(Call->getArg(1)) &&
10962       !doesExprLikelyComputeSize(Call->getArg(2))) {
10963     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10964     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10965     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10966     return;
10967   }
10968 }
10969 
10970 /// Check for dangerous or invalid arguments to memset().
10971 ///
10972 /// This issues warnings on known problematic, dangerous or unspecified
10973 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10974 /// function calls.
10975 ///
10976 /// \param Call The call expression to diagnose.
10977 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10978                                    unsigned BId,
10979                                    IdentifierInfo *FnName) {
10980   assert(BId != 0);
10981 
10982   // It is possible to have a non-standard definition of memset.  Validate
10983   // we have enough arguments, and if not, abort further checking.
10984   unsigned ExpectedNumArgs =
10985       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10986   if (Call->getNumArgs() < ExpectedNumArgs)
10987     return;
10988 
10989   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10990                       BId == Builtin::BIstrndup ? 1 : 2);
10991   unsigned LenArg =
10992       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10993   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10994 
10995   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10996                                      Call->getBeginLoc(), Call->getRParenLoc()))
10997     return;
10998 
10999   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11000   CheckMemaccessSize(*this, BId, Call);
11001 
11002   // We have special checking when the length is a sizeof expression.
11003   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11004   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11005   llvm::FoldingSetNodeID SizeOfArgID;
11006 
11007   // Although widely used, 'bzero' is not a standard function. Be more strict
11008   // with the argument types before allowing diagnostics and only allow the
11009   // form bzero(ptr, sizeof(...)).
11010   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11011   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11012     return;
11013 
11014   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11015     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11016     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11017 
11018     QualType DestTy = Dest->getType();
11019     QualType PointeeTy;
11020     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11021       PointeeTy = DestPtrTy->getPointeeType();
11022 
11023       // Never warn about void type pointers. This can be used to suppress
11024       // false positives.
11025       if (PointeeTy->isVoidType())
11026         continue;
11027 
11028       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11029       // actually comparing the expressions for equality. Because computing the
11030       // expression IDs can be expensive, we only do this if the diagnostic is
11031       // enabled.
11032       if (SizeOfArg &&
11033           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11034                            SizeOfArg->getExprLoc())) {
11035         // We only compute IDs for expressions if the warning is enabled, and
11036         // cache the sizeof arg's ID.
11037         if (SizeOfArgID == llvm::FoldingSetNodeID())
11038           SizeOfArg->Profile(SizeOfArgID, Context, true);
11039         llvm::FoldingSetNodeID DestID;
11040         Dest->Profile(DestID, Context, true);
11041         if (DestID == SizeOfArgID) {
11042           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11043           //       over sizeof(src) as well.
11044           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11045           StringRef ReadableName = FnName->getName();
11046 
11047           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
11048             if (UnaryOp->getOpcode() == UO_AddrOf)
11049               ActionIdx = 1; // If its an address-of operator, just remove it.
11050           if (!PointeeTy->isIncompleteType() &&
11051               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11052             ActionIdx = 2; // If the pointee's size is sizeof(char),
11053                            // suggest an explicit length.
11054 
11055           // If the function is defined as a builtin macro, do not show macro
11056           // expansion.
11057           SourceLocation SL = SizeOfArg->getExprLoc();
11058           SourceRange DSR = Dest->getSourceRange();
11059           SourceRange SSR = SizeOfArg->getSourceRange();
11060           SourceManager &SM = getSourceManager();
11061 
11062           if (SM.isMacroArgExpansion(SL)) {
11063             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11064             SL = SM.getSpellingLoc(SL);
11065             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11066                              SM.getSpellingLoc(DSR.getEnd()));
11067             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11068                              SM.getSpellingLoc(SSR.getEnd()));
11069           }
11070 
11071           DiagRuntimeBehavior(SL, SizeOfArg,
11072                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11073                                 << ReadableName
11074                                 << PointeeTy
11075                                 << DestTy
11076                                 << DSR
11077                                 << SSR);
11078           DiagRuntimeBehavior(SL, SizeOfArg,
11079                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11080                                 << ActionIdx
11081                                 << SSR);
11082 
11083           break;
11084         }
11085       }
11086 
11087       // Also check for cases where the sizeof argument is the exact same
11088       // type as the memory argument, and where it points to a user-defined
11089       // record type.
11090       if (SizeOfArgTy != QualType()) {
11091         if (PointeeTy->isRecordType() &&
11092             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11093           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11094                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
11095                                 << FnName << SizeOfArgTy << ArgIdx
11096                                 << PointeeTy << Dest->getSourceRange()
11097                                 << LenExpr->getSourceRange());
11098           break;
11099         }
11100       }
11101     } else if (DestTy->isArrayType()) {
11102       PointeeTy = DestTy;
11103     }
11104 
11105     if (PointeeTy == QualType())
11106       continue;
11107 
11108     // Always complain about dynamic classes.
11109     bool IsContained;
11110     if (const CXXRecordDecl *ContainedRD =
11111             getContainedDynamicClass(PointeeTy, IsContained)) {
11112 
11113       unsigned OperationType = 0;
11114       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11115       // "overwritten" if we're warning about the destination for any call
11116       // but memcmp; otherwise a verb appropriate to the call.
11117       if (ArgIdx != 0 || IsCmp) {
11118         if (BId == Builtin::BImemcpy)
11119           OperationType = 1;
11120         else if(BId == Builtin::BImemmove)
11121           OperationType = 2;
11122         else if (IsCmp)
11123           OperationType = 3;
11124       }
11125 
11126       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11127                           PDiag(diag::warn_dyn_class_memaccess)
11128                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11129                               << IsContained << ContainedRD << OperationType
11130                               << Call->getCallee()->getSourceRange());
11131     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11132              BId != Builtin::BImemset)
11133       DiagRuntimeBehavior(
11134         Dest->getExprLoc(), Dest,
11135         PDiag(diag::warn_arc_object_memaccess)
11136           << ArgIdx << FnName << PointeeTy
11137           << Call->getCallee()->getSourceRange());
11138     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
11139       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11140           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11141         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11142                             PDiag(diag::warn_cstruct_memaccess)
11143                                 << ArgIdx << FnName << PointeeTy << 0);
11144         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11145       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11146                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11147         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11148                             PDiag(diag::warn_cstruct_memaccess)
11149                                 << ArgIdx << FnName << PointeeTy << 1);
11150         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11151       } else {
11152         continue;
11153       }
11154     } else
11155       continue;
11156 
11157     DiagRuntimeBehavior(
11158       Dest->getExprLoc(), Dest,
11159       PDiag(diag::note_bad_memaccess_silence)
11160         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11161     break;
11162   }
11163 }
11164 
11165 // A little helper routine: ignore addition and subtraction of integer literals.
11166 // This intentionally does not ignore all integer constant expressions because
11167 // we don't want to remove sizeof().
11168 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11169   Ex = Ex->IgnoreParenCasts();
11170 
11171   while (true) {
11172     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11173     if (!BO || !BO->isAdditiveOp())
11174       break;
11175 
11176     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11177     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11178 
11179     if (isa<IntegerLiteral>(RHS))
11180       Ex = LHS;
11181     else if (isa<IntegerLiteral>(LHS))
11182       Ex = RHS;
11183     else
11184       break;
11185   }
11186 
11187   return Ex;
11188 }
11189 
11190 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11191                                                       ASTContext &Context) {
11192   // Only handle constant-sized or VLAs, but not flexible members.
11193   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11194     // Only issue the FIXIT for arrays of size > 1.
11195     if (CAT->getSize().getSExtValue() <= 1)
11196       return false;
11197   } else if (!Ty->isVariableArrayType()) {
11198     return false;
11199   }
11200   return true;
11201 }
11202 
11203 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11204 // be the size of the source, instead of the destination.
11205 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11206                                     IdentifierInfo *FnName) {
11207 
11208   // Don't crash if the user has the wrong number of arguments
11209   unsigned NumArgs = Call->getNumArgs();
11210   if ((NumArgs != 3) && (NumArgs != 4))
11211     return;
11212 
11213   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11214   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11215   const Expr *CompareWithSrc = nullptr;
11216 
11217   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11218                                      Call->getBeginLoc(), Call->getRParenLoc()))
11219     return;
11220 
11221   // Look for 'strlcpy(dst, x, sizeof(x))'
11222   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11223     CompareWithSrc = Ex;
11224   else {
11225     // Look for 'strlcpy(dst, x, strlen(x))'
11226     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11227       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11228           SizeCall->getNumArgs() == 1)
11229         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11230     }
11231   }
11232 
11233   if (!CompareWithSrc)
11234     return;
11235 
11236   // Determine if the argument to sizeof/strlen is equal to the source
11237   // argument.  In principle there's all kinds of things you could do
11238   // here, for instance creating an == expression and evaluating it with
11239   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11240   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11241   if (!SrcArgDRE)
11242     return;
11243 
11244   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11245   if (!CompareWithSrcDRE ||
11246       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11247     return;
11248 
11249   const Expr *OriginalSizeArg = Call->getArg(2);
11250   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11251       << OriginalSizeArg->getSourceRange() << FnName;
11252 
11253   // Output a FIXIT hint if the destination is an array (rather than a
11254   // pointer to an array).  This could be enhanced to handle some
11255   // pointers if we know the actual size, like if DstArg is 'array+2'
11256   // we could say 'sizeof(array)-2'.
11257   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11258   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11259     return;
11260 
11261   SmallString<128> sizeString;
11262   llvm::raw_svector_ostream OS(sizeString);
11263   OS << "sizeof(";
11264   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11265   OS << ")";
11266 
11267   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11268       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11269                                       OS.str());
11270 }
11271 
11272 /// Check if two expressions refer to the same declaration.
11273 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11274   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11275     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11276       return D1->getDecl() == D2->getDecl();
11277   return false;
11278 }
11279 
11280 static const Expr *getStrlenExprArg(const Expr *E) {
11281   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11282     const FunctionDecl *FD = CE->getDirectCallee();
11283     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11284       return nullptr;
11285     return CE->getArg(0)->IgnoreParenCasts();
11286   }
11287   return nullptr;
11288 }
11289 
11290 // Warn on anti-patterns as the 'size' argument to strncat.
11291 // The correct size argument should look like following:
11292 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11293 void Sema::CheckStrncatArguments(const CallExpr *CE,
11294                                  IdentifierInfo *FnName) {
11295   // Don't crash if the user has the wrong number of arguments.
11296   if (CE->getNumArgs() < 3)
11297     return;
11298   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11299   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11300   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11301 
11302   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11303                                      CE->getRParenLoc()))
11304     return;
11305 
11306   // Identify common expressions, which are wrongly used as the size argument
11307   // to strncat and may lead to buffer overflows.
11308   unsigned PatternType = 0;
11309   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11310     // - sizeof(dst)
11311     if (referToTheSameDecl(SizeOfArg, DstArg))
11312       PatternType = 1;
11313     // - sizeof(src)
11314     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11315       PatternType = 2;
11316   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11317     if (BE->getOpcode() == BO_Sub) {
11318       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11319       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11320       // - sizeof(dst) - strlen(dst)
11321       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11322           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11323         PatternType = 1;
11324       // - sizeof(src) - (anything)
11325       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11326         PatternType = 2;
11327     }
11328   }
11329 
11330   if (PatternType == 0)
11331     return;
11332 
11333   // Generate the diagnostic.
11334   SourceLocation SL = LenArg->getBeginLoc();
11335   SourceRange SR = LenArg->getSourceRange();
11336   SourceManager &SM = getSourceManager();
11337 
11338   // If the function is defined as a builtin macro, do not show macro expansion.
11339   if (SM.isMacroArgExpansion(SL)) {
11340     SL = SM.getSpellingLoc(SL);
11341     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11342                      SM.getSpellingLoc(SR.getEnd()));
11343   }
11344 
11345   // Check if the destination is an array (rather than a pointer to an array).
11346   QualType DstTy = DstArg->getType();
11347   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11348                                                                     Context);
11349   if (!isKnownSizeArray) {
11350     if (PatternType == 1)
11351       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11352     else
11353       Diag(SL, diag::warn_strncat_src_size) << SR;
11354     return;
11355   }
11356 
11357   if (PatternType == 1)
11358     Diag(SL, diag::warn_strncat_large_size) << SR;
11359   else
11360     Diag(SL, diag::warn_strncat_src_size) << SR;
11361 
11362   SmallString<128> sizeString;
11363   llvm::raw_svector_ostream OS(sizeString);
11364   OS << "sizeof(";
11365   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11366   OS << ") - ";
11367   OS << "strlen(";
11368   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11369   OS << ") - 1";
11370 
11371   Diag(SL, diag::note_strncat_wrong_size)
11372     << FixItHint::CreateReplacement(SR, OS.str());
11373 }
11374 
11375 namespace {
11376 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11377                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11378   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11379     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11380         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11381     return;
11382   }
11383 }
11384 
11385 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11386                                  const UnaryOperator *UnaryExpr) {
11387   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11388     const Decl *D = Lvalue->getDecl();
11389     if (isa<DeclaratorDecl>(D))
11390       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11391         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11392   }
11393 
11394   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11395     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11396                                       Lvalue->getMemberDecl());
11397 }
11398 
11399 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11400                             const UnaryOperator *UnaryExpr) {
11401   const auto *Lambda = dyn_cast<LambdaExpr>(
11402       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11403   if (!Lambda)
11404     return;
11405 
11406   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11407       << CalleeName << 2 /*object: lambda expression*/;
11408 }
11409 
11410 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11411                                   const DeclRefExpr *Lvalue) {
11412   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11413   if (Var == nullptr)
11414     return;
11415 
11416   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11417       << CalleeName << 0 /*object: */ << Var;
11418 }
11419 
11420 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11421                             const CastExpr *Cast) {
11422   SmallString<128> SizeString;
11423   llvm::raw_svector_ostream OS(SizeString);
11424 
11425   clang::CastKind Kind = Cast->getCastKind();
11426   if (Kind == clang::CK_BitCast &&
11427       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11428     return;
11429   if (Kind == clang::CK_IntegralToPointer &&
11430       !isa<IntegerLiteral>(
11431           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11432     return;
11433 
11434   switch (Cast->getCastKind()) {
11435   case clang::CK_BitCast:
11436   case clang::CK_IntegralToPointer:
11437   case clang::CK_FunctionToPointerDecay:
11438     OS << '\'';
11439     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11440     OS << '\'';
11441     break;
11442   default:
11443     return;
11444   }
11445 
11446   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11447       << CalleeName << 0 /*object: */ << OS.str();
11448 }
11449 } // namespace
11450 
11451 /// Alerts the user that they are attempting to free a non-malloc'd object.
11452 void Sema::CheckFreeArguments(const CallExpr *E) {
11453   const std::string CalleeName =
11454       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11455 
11456   { // Prefer something that doesn't involve a cast to make things simpler.
11457     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11458     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11459       switch (UnaryExpr->getOpcode()) {
11460       case UnaryOperator::Opcode::UO_AddrOf:
11461         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11462       case UnaryOperator::Opcode::UO_Plus:
11463         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11464       default:
11465         break;
11466       }
11467 
11468     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11469       if (Lvalue->getType()->isArrayType())
11470         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11471 
11472     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11473       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11474           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11475       return;
11476     }
11477 
11478     if (isa<BlockExpr>(Arg)) {
11479       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11480           << CalleeName << 1 /*object: block*/;
11481       return;
11482     }
11483   }
11484   // Maybe the cast was important, check after the other cases.
11485   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11486     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11487 }
11488 
11489 void
11490 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11491                          SourceLocation ReturnLoc,
11492                          bool isObjCMethod,
11493                          const AttrVec *Attrs,
11494                          const FunctionDecl *FD) {
11495   // Check if the return value is null but should not be.
11496   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11497        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11498       CheckNonNullExpr(*this, RetValExp))
11499     Diag(ReturnLoc, diag::warn_null_ret)
11500       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11501 
11502   // C++11 [basic.stc.dynamic.allocation]p4:
11503   //   If an allocation function declared with a non-throwing
11504   //   exception-specification fails to allocate storage, it shall return
11505   //   a null pointer. Any other allocation function that fails to allocate
11506   //   storage shall indicate failure only by throwing an exception [...]
11507   if (FD) {
11508     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11509     if (Op == OO_New || Op == OO_Array_New) {
11510       const FunctionProtoType *Proto
11511         = FD->getType()->castAs<FunctionProtoType>();
11512       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11513           CheckNonNullExpr(*this, RetValExp))
11514         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11515           << FD << getLangOpts().CPlusPlus11;
11516     }
11517   }
11518 
11519   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11520   // here prevent the user from using a PPC MMA type as trailing return type.
11521   if (Context.getTargetInfo().getTriple().isPPC64())
11522     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11523 }
11524 
11525 /// Check for comparisons of floating-point values using == and !=. Issue a
11526 /// warning if the comparison is not likely to do what the programmer intended.
11527 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
11528                                 BinaryOperatorKind Opcode) {
11529   // Match and capture subexpressions such as "(float) X == 0.1".
11530   FloatingLiteral *FPLiteral;
11531   CastExpr *FPCast;
11532   auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
11533     FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11534     FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11535     return FPLiteral && FPCast;
11536   };
11537 
11538   if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11539     auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11540     auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11541     if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11542         TargetTy->isFloatingPoint()) {
11543       bool Lossy;
11544       llvm::APFloat TargetC = FPLiteral->getValue();
11545       TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11546                       llvm::APFloat::rmNearestTiesToEven, &Lossy);
11547       if (Lossy) {
11548         // If the literal cannot be represented in the source type, then a
11549         // check for == is always false and check for != is always true.
11550         Diag(Loc, diag::warn_float_compare_literal)
11551             << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11552             << LHS->getSourceRange() << RHS->getSourceRange();
11553         return;
11554       }
11555     }
11556   }
11557 
11558   // Match a more general floating-point equality comparison (-Wfloat-equal).
11559   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11560   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11561 
11562   // Special case: check for x == x (which is OK).
11563   // Do not emit warnings for such cases.
11564   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11565     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11566       if (DRL->getDecl() == DRR->getDecl())
11567         return;
11568 
11569   // Special case: check for comparisons against literals that can be exactly
11570   //  represented by APFloat.  In such cases, do not emit a warning.  This
11571   //  is a heuristic: often comparison against such literals are used to
11572   //  detect if a value in a variable has not changed.  This clearly can
11573   //  lead to false negatives.
11574   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11575     if (FLL->isExact())
11576       return;
11577   } else
11578     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11579       if (FLR->isExact())
11580         return;
11581 
11582   // Check for comparisons with builtin types.
11583   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11584     if (CL->getBuiltinCallee())
11585       return;
11586 
11587   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11588     if (CR->getBuiltinCallee())
11589       return;
11590 
11591   // Emit the diagnostic.
11592   Diag(Loc, diag::warn_floatingpoint_eq)
11593     << LHS->getSourceRange() << RHS->getSourceRange();
11594 }
11595 
11596 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11597 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11598 
11599 namespace {
11600 
11601 /// Structure recording the 'active' range of an integer-valued
11602 /// expression.
11603 struct IntRange {
11604   /// The number of bits active in the int. Note that this includes exactly one
11605   /// sign bit if !NonNegative.
11606   unsigned Width;
11607 
11608   /// True if the int is known not to have negative values. If so, all leading
11609   /// bits before Width are known zero, otherwise they are known to be the
11610   /// same as the MSB within Width.
11611   bool NonNegative;
11612 
11613   IntRange(unsigned Width, bool NonNegative)
11614       : Width(Width), NonNegative(NonNegative) {}
11615 
11616   /// Number of bits excluding the sign bit.
11617   unsigned valueBits() const {
11618     return NonNegative ? Width : Width - 1;
11619   }
11620 
11621   /// Returns the range of the bool type.
11622   static IntRange forBoolType() {
11623     return IntRange(1, true);
11624   }
11625 
11626   /// Returns the range of an opaque value of the given integral type.
11627   static IntRange forValueOfType(ASTContext &C, QualType T) {
11628     return forValueOfCanonicalType(C,
11629                           T->getCanonicalTypeInternal().getTypePtr());
11630   }
11631 
11632   /// Returns the range of an opaque value of a canonical integral type.
11633   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11634     assert(T->isCanonicalUnqualified());
11635 
11636     if (const VectorType *VT = dyn_cast<VectorType>(T))
11637       T = VT->getElementType().getTypePtr();
11638     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11639       T = CT->getElementType().getTypePtr();
11640     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11641       T = AT->getValueType().getTypePtr();
11642 
11643     if (!C.getLangOpts().CPlusPlus) {
11644       // For enum types in C code, use the underlying datatype.
11645       if (const EnumType *ET = dyn_cast<EnumType>(T))
11646         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11647     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11648       // For enum types in C++, use the known bit width of the enumerators.
11649       EnumDecl *Enum = ET->getDecl();
11650       // In C++11, enums can have a fixed underlying type. Use this type to
11651       // compute the range.
11652       if (Enum->isFixed()) {
11653         return IntRange(C.getIntWidth(QualType(T, 0)),
11654                         !ET->isSignedIntegerOrEnumerationType());
11655       }
11656 
11657       unsigned NumPositive = Enum->getNumPositiveBits();
11658       unsigned NumNegative = Enum->getNumNegativeBits();
11659 
11660       if (NumNegative == 0)
11661         return IntRange(NumPositive, true/*NonNegative*/);
11662       else
11663         return IntRange(std::max(NumPositive + 1, NumNegative),
11664                         false/*NonNegative*/);
11665     }
11666 
11667     if (const auto *EIT = dyn_cast<BitIntType>(T))
11668       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11669 
11670     const BuiltinType *BT = cast<BuiltinType>(T);
11671     assert(BT->isInteger());
11672 
11673     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11674   }
11675 
11676   /// Returns the "target" range of a canonical integral type, i.e.
11677   /// the range of values expressible in the type.
11678   ///
11679   /// This matches forValueOfCanonicalType except that enums have the
11680   /// full range of their type, not the range of their enumerators.
11681   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11682     assert(T->isCanonicalUnqualified());
11683 
11684     if (const VectorType *VT = dyn_cast<VectorType>(T))
11685       T = VT->getElementType().getTypePtr();
11686     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11687       T = CT->getElementType().getTypePtr();
11688     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11689       T = AT->getValueType().getTypePtr();
11690     if (const EnumType *ET = dyn_cast<EnumType>(T))
11691       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11692 
11693     if (const auto *EIT = dyn_cast<BitIntType>(T))
11694       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11695 
11696     const BuiltinType *BT = cast<BuiltinType>(T);
11697     assert(BT->isInteger());
11698 
11699     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11700   }
11701 
11702   /// Returns the supremum of two ranges: i.e. their conservative merge.
11703   static IntRange join(IntRange L, IntRange R) {
11704     bool Unsigned = L.NonNegative && R.NonNegative;
11705     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11706                     L.NonNegative && R.NonNegative);
11707   }
11708 
11709   /// Return the range of a bitwise-AND of the two ranges.
11710   static IntRange bit_and(IntRange L, IntRange R) {
11711     unsigned Bits = std::max(L.Width, R.Width);
11712     bool NonNegative = false;
11713     if (L.NonNegative) {
11714       Bits = std::min(Bits, L.Width);
11715       NonNegative = true;
11716     }
11717     if (R.NonNegative) {
11718       Bits = std::min(Bits, R.Width);
11719       NonNegative = true;
11720     }
11721     return IntRange(Bits, NonNegative);
11722   }
11723 
11724   /// Return the range of a sum of the two ranges.
11725   static IntRange sum(IntRange L, IntRange R) {
11726     bool Unsigned = L.NonNegative && R.NonNegative;
11727     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11728                     Unsigned);
11729   }
11730 
11731   /// Return the range of a difference of the two ranges.
11732   static IntRange difference(IntRange L, IntRange R) {
11733     // We need a 1-bit-wider range if:
11734     //   1) LHS can be negative: least value can be reduced.
11735     //   2) RHS can be negative: greatest value can be increased.
11736     bool CanWiden = !L.NonNegative || !R.NonNegative;
11737     bool Unsigned = L.NonNegative && R.Width == 0;
11738     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11739                         !Unsigned,
11740                     Unsigned);
11741   }
11742 
11743   /// Return the range of a product of the two ranges.
11744   static IntRange product(IntRange L, IntRange R) {
11745     // If both LHS and RHS can be negative, we can form
11746     //   -2^L * -2^R = 2^(L + R)
11747     // which requires L + R + 1 value bits to represent.
11748     bool CanWiden = !L.NonNegative && !R.NonNegative;
11749     bool Unsigned = L.NonNegative && R.NonNegative;
11750     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11751                     Unsigned);
11752   }
11753 
11754   /// Return the range of a remainder operation between the two ranges.
11755   static IntRange rem(IntRange L, IntRange R) {
11756     // The result of a remainder can't be larger than the result of
11757     // either side. The sign of the result is the sign of the LHS.
11758     bool Unsigned = L.NonNegative;
11759     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11760                     Unsigned);
11761   }
11762 };
11763 
11764 } // namespace
11765 
11766 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11767                               unsigned MaxWidth) {
11768   if (value.isSigned() && value.isNegative())
11769     return IntRange(value.getMinSignedBits(), false);
11770 
11771   if (value.getBitWidth() > MaxWidth)
11772     value = value.trunc(MaxWidth);
11773 
11774   // isNonNegative() just checks the sign bit without considering
11775   // signedness.
11776   return IntRange(value.getActiveBits(), true);
11777 }
11778 
11779 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11780                               unsigned MaxWidth) {
11781   if (result.isInt())
11782     return GetValueRange(C, result.getInt(), MaxWidth);
11783 
11784   if (result.isVector()) {
11785     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11786     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11787       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11788       R = IntRange::join(R, El);
11789     }
11790     return R;
11791   }
11792 
11793   if (result.isComplexInt()) {
11794     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11795     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11796     return IntRange::join(R, I);
11797   }
11798 
11799   // This can happen with lossless casts to intptr_t of "based" lvalues.
11800   // Assume it might use arbitrary bits.
11801   // FIXME: The only reason we need to pass the type in here is to get
11802   // the sign right on this one case.  It would be nice if APValue
11803   // preserved this.
11804   assert(result.isLValue() || result.isAddrLabelDiff());
11805   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11806 }
11807 
11808 static QualType GetExprType(const Expr *E) {
11809   QualType Ty = E->getType();
11810   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11811     Ty = AtomicRHS->getValueType();
11812   return Ty;
11813 }
11814 
11815 /// Pseudo-evaluate the given integer expression, estimating the
11816 /// range of values it might take.
11817 ///
11818 /// \param MaxWidth The width to which the value will be truncated.
11819 /// \param Approximate If \c true, return a likely range for the result: in
11820 ///        particular, assume that arithmetic on narrower types doesn't leave
11821 ///        those types. If \c false, return a range including all possible
11822 ///        result values.
11823 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11824                              bool InConstantContext, bool Approximate) {
11825   E = E->IgnoreParens();
11826 
11827   // Try a full evaluation first.
11828   Expr::EvalResult result;
11829   if (E->EvaluateAsRValue(result, C, InConstantContext))
11830     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11831 
11832   // I think we only want to look through implicit casts here; if the
11833   // user has an explicit widening cast, we should treat the value as
11834   // being of the new, wider type.
11835   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11836     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11837       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11838                           Approximate);
11839 
11840     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11841 
11842     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11843                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11844 
11845     // Assume that non-integer casts can span the full range of the type.
11846     if (!isIntegerCast)
11847       return OutputTypeRange;
11848 
11849     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11850                                      std::min(MaxWidth, OutputTypeRange.Width),
11851                                      InConstantContext, Approximate);
11852 
11853     // Bail out if the subexpr's range is as wide as the cast type.
11854     if (SubRange.Width >= OutputTypeRange.Width)
11855       return OutputTypeRange;
11856 
11857     // Otherwise, we take the smaller width, and we're non-negative if
11858     // either the output type or the subexpr is.
11859     return IntRange(SubRange.Width,
11860                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11861   }
11862 
11863   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11864     // If we can fold the condition, just take that operand.
11865     bool CondResult;
11866     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11867       return GetExprRange(C,
11868                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11869                           MaxWidth, InConstantContext, Approximate);
11870 
11871     // Otherwise, conservatively merge.
11872     // GetExprRange requires an integer expression, but a throw expression
11873     // results in a void type.
11874     Expr *E = CO->getTrueExpr();
11875     IntRange L = E->getType()->isVoidType()
11876                      ? IntRange{0, true}
11877                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11878     E = CO->getFalseExpr();
11879     IntRange R = E->getType()->isVoidType()
11880                      ? IntRange{0, true}
11881                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11882     return IntRange::join(L, R);
11883   }
11884 
11885   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11886     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11887 
11888     switch (BO->getOpcode()) {
11889     case BO_Cmp:
11890       llvm_unreachable("builtin <=> should have class type");
11891 
11892     // Boolean-valued operations are single-bit and positive.
11893     case BO_LAnd:
11894     case BO_LOr:
11895     case BO_LT:
11896     case BO_GT:
11897     case BO_LE:
11898     case BO_GE:
11899     case BO_EQ:
11900     case BO_NE:
11901       return IntRange::forBoolType();
11902 
11903     // The type of the assignments is the type of the LHS, so the RHS
11904     // is not necessarily the same type.
11905     case BO_MulAssign:
11906     case BO_DivAssign:
11907     case BO_RemAssign:
11908     case BO_AddAssign:
11909     case BO_SubAssign:
11910     case BO_XorAssign:
11911     case BO_OrAssign:
11912       // TODO: bitfields?
11913       return IntRange::forValueOfType(C, GetExprType(E));
11914 
11915     // Simple assignments just pass through the RHS, which will have
11916     // been coerced to the LHS type.
11917     case BO_Assign:
11918       // TODO: bitfields?
11919       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11920                           Approximate);
11921 
11922     // Operations with opaque sources are black-listed.
11923     case BO_PtrMemD:
11924     case BO_PtrMemI:
11925       return IntRange::forValueOfType(C, GetExprType(E));
11926 
11927     // Bitwise-and uses the *infinum* of the two source ranges.
11928     case BO_And:
11929     case BO_AndAssign:
11930       Combine = IntRange::bit_and;
11931       break;
11932 
11933     // Left shift gets black-listed based on a judgement call.
11934     case BO_Shl:
11935       // ...except that we want to treat '1 << (blah)' as logically
11936       // positive.  It's an important idiom.
11937       if (IntegerLiteral *I
11938             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11939         if (I->getValue() == 1) {
11940           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11941           return IntRange(R.Width, /*NonNegative*/ true);
11942         }
11943       }
11944       LLVM_FALLTHROUGH;
11945 
11946     case BO_ShlAssign:
11947       return IntRange::forValueOfType(C, GetExprType(E));
11948 
11949     // Right shift by a constant can narrow its left argument.
11950     case BO_Shr:
11951     case BO_ShrAssign: {
11952       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11953                                 Approximate);
11954 
11955       // If the shift amount is a positive constant, drop the width by
11956       // that much.
11957       if (Optional<llvm::APSInt> shift =
11958               BO->getRHS()->getIntegerConstantExpr(C)) {
11959         if (shift->isNonNegative()) {
11960           unsigned zext = shift->getZExtValue();
11961           if (zext >= L.Width)
11962             L.Width = (L.NonNegative ? 0 : 1);
11963           else
11964             L.Width -= zext;
11965         }
11966       }
11967 
11968       return L;
11969     }
11970 
11971     // Comma acts as its right operand.
11972     case BO_Comma:
11973       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11974                           Approximate);
11975 
11976     case BO_Add:
11977       if (!Approximate)
11978         Combine = IntRange::sum;
11979       break;
11980 
11981     case BO_Sub:
11982       if (BO->getLHS()->getType()->isPointerType())
11983         return IntRange::forValueOfType(C, GetExprType(E));
11984       if (!Approximate)
11985         Combine = IntRange::difference;
11986       break;
11987 
11988     case BO_Mul:
11989       if (!Approximate)
11990         Combine = IntRange::product;
11991       break;
11992 
11993     // The width of a division result is mostly determined by the size
11994     // of the LHS.
11995     case BO_Div: {
11996       // Don't 'pre-truncate' the operands.
11997       unsigned opWidth = C.getIntWidth(GetExprType(E));
11998       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11999                                 Approximate);
12000 
12001       // If the divisor is constant, use that.
12002       if (Optional<llvm::APSInt> divisor =
12003               BO->getRHS()->getIntegerConstantExpr(C)) {
12004         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12005         if (log2 >= L.Width)
12006           L.Width = (L.NonNegative ? 0 : 1);
12007         else
12008           L.Width = std::min(L.Width - log2, MaxWidth);
12009         return L;
12010       }
12011 
12012       // Otherwise, just use the LHS's width.
12013       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12014       // could be -1.
12015       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
12016                                 Approximate);
12017       return IntRange(L.Width, L.NonNegative && R.NonNegative);
12018     }
12019 
12020     case BO_Rem:
12021       Combine = IntRange::rem;
12022       break;
12023 
12024     // The default behavior is okay for these.
12025     case BO_Xor:
12026     case BO_Or:
12027       break;
12028     }
12029 
12030     // Combine the two ranges, but limit the result to the type in which we
12031     // performed the computation.
12032     QualType T = GetExprType(E);
12033     unsigned opWidth = C.getIntWidth(T);
12034     IntRange L =
12035         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12036     IntRange R =
12037         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12038     IntRange C = Combine(L, R);
12039     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12040     C.Width = std::min(C.Width, MaxWidth);
12041     return C;
12042   }
12043 
12044   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12045     switch (UO->getOpcode()) {
12046     // Boolean-valued operations are white-listed.
12047     case UO_LNot:
12048       return IntRange::forBoolType();
12049 
12050     // Operations with opaque sources are black-listed.
12051     case UO_Deref:
12052     case UO_AddrOf: // should be impossible
12053       return IntRange::forValueOfType(C, GetExprType(E));
12054 
12055     default:
12056       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12057                           Approximate);
12058     }
12059   }
12060 
12061   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12062     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
12063                         Approximate);
12064 
12065   if (const auto *BitField = E->getSourceBitField())
12066     return IntRange(BitField->getBitWidthValue(C),
12067                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
12068 
12069   return IntRange::forValueOfType(C, GetExprType(E));
12070 }
12071 
12072 static IntRange GetExprRange(ASTContext &C, const Expr *E,
12073                              bool InConstantContext, bool Approximate) {
12074   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12075                       Approximate);
12076 }
12077 
12078 /// Checks whether the given value, which currently has the given
12079 /// source semantics, has the same value when coerced through the
12080 /// target semantics.
12081 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12082                                  const llvm::fltSemantics &Src,
12083                                  const llvm::fltSemantics &Tgt) {
12084   llvm::APFloat truncated = value;
12085 
12086   bool ignored;
12087   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12088   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12089 
12090   return truncated.bitwiseIsEqual(value);
12091 }
12092 
12093 /// Checks whether the given value, which currently has the given
12094 /// source semantics, has the same value when coerced through the
12095 /// target semantics.
12096 ///
12097 /// The value might be a vector of floats (or a complex number).
12098 static bool IsSameFloatAfterCast(const APValue &value,
12099                                  const llvm::fltSemantics &Src,
12100                                  const llvm::fltSemantics &Tgt) {
12101   if (value.isFloat())
12102     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12103 
12104   if (value.isVector()) {
12105     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12106       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12107         return false;
12108     return true;
12109   }
12110 
12111   assert(value.isComplexFloat());
12112   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12113           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12114 }
12115 
12116 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12117                                        bool IsListInit = false);
12118 
12119 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
12120   // Suppress cases where we are comparing against an enum constant.
12121   if (const DeclRefExpr *DR =
12122       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12123     if (isa<EnumConstantDecl>(DR->getDecl()))
12124       return true;
12125 
12126   // Suppress cases where the value is expanded from a macro, unless that macro
12127   // is how a language represents a boolean literal. This is the case in both C
12128   // and Objective-C.
12129   SourceLocation BeginLoc = E->getBeginLoc();
12130   if (BeginLoc.isMacroID()) {
12131     StringRef MacroName = Lexer::getImmediateMacroName(
12132         BeginLoc, S.getSourceManager(), S.getLangOpts());
12133     return MacroName != "YES" && MacroName != "NO" &&
12134            MacroName != "true" && MacroName != "false";
12135   }
12136 
12137   return false;
12138 }
12139 
12140 static bool isKnownToHaveUnsignedValue(Expr *E) {
12141   return E->getType()->isIntegerType() &&
12142          (!E->getType()->isSignedIntegerType() ||
12143           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12144 }
12145 
12146 namespace {
12147 /// The promoted range of values of a type. In general this has the
12148 /// following structure:
12149 ///
12150 ///     |-----------| . . . |-----------|
12151 ///     ^           ^       ^           ^
12152 ///    Min       HoleMin  HoleMax      Max
12153 ///
12154 /// ... where there is only a hole if a signed type is promoted to unsigned
12155 /// (in which case Min and Max are the smallest and largest representable
12156 /// values).
12157 struct PromotedRange {
12158   // Min, or HoleMax if there is a hole.
12159   llvm::APSInt PromotedMin;
12160   // Max, or HoleMin if there is a hole.
12161   llvm::APSInt PromotedMax;
12162 
12163   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12164     if (R.Width == 0)
12165       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12166     else if (R.Width >= BitWidth && !Unsigned) {
12167       // Promotion made the type *narrower*. This happens when promoting
12168       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12169       // Treat all values of 'signed int' as being in range for now.
12170       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12171       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12172     } else {
12173       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12174                         .extOrTrunc(BitWidth);
12175       PromotedMin.setIsUnsigned(Unsigned);
12176 
12177       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12178                         .extOrTrunc(BitWidth);
12179       PromotedMax.setIsUnsigned(Unsigned);
12180     }
12181   }
12182 
12183   // Determine whether this range is contiguous (has no hole).
12184   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12185 
12186   // Where a constant value is within the range.
12187   enum ComparisonResult {
12188     LT = 0x1,
12189     LE = 0x2,
12190     GT = 0x4,
12191     GE = 0x8,
12192     EQ = 0x10,
12193     NE = 0x20,
12194     InRangeFlag = 0x40,
12195 
12196     Less = LE | LT | NE,
12197     Min = LE | InRangeFlag,
12198     InRange = InRangeFlag,
12199     Max = GE | InRangeFlag,
12200     Greater = GE | GT | NE,
12201 
12202     OnlyValue = LE | GE | EQ | InRangeFlag,
12203     InHole = NE
12204   };
12205 
12206   ComparisonResult compare(const llvm::APSInt &Value) const {
12207     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12208            Value.isUnsigned() == PromotedMin.isUnsigned());
12209     if (!isContiguous()) {
12210       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12211       if (Value.isMinValue()) return Min;
12212       if (Value.isMaxValue()) return Max;
12213       if (Value >= PromotedMin) return InRange;
12214       if (Value <= PromotedMax) return InRange;
12215       return InHole;
12216     }
12217 
12218     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12219     case -1: return Less;
12220     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12221     case 1:
12222       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12223       case -1: return InRange;
12224       case 0: return Max;
12225       case 1: return Greater;
12226       }
12227     }
12228 
12229     llvm_unreachable("impossible compare result");
12230   }
12231 
12232   static llvm::Optional<StringRef>
12233   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12234     if (Op == BO_Cmp) {
12235       ComparisonResult LTFlag = LT, GTFlag = GT;
12236       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12237 
12238       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12239       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12240       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12241       return llvm::None;
12242     }
12243 
12244     ComparisonResult TrueFlag, FalseFlag;
12245     if (Op == BO_EQ) {
12246       TrueFlag = EQ;
12247       FalseFlag = NE;
12248     } else if (Op == BO_NE) {
12249       TrueFlag = NE;
12250       FalseFlag = EQ;
12251     } else {
12252       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12253         TrueFlag = LT;
12254         FalseFlag = GE;
12255       } else {
12256         TrueFlag = GT;
12257         FalseFlag = LE;
12258       }
12259       if (Op == BO_GE || Op == BO_LE)
12260         std::swap(TrueFlag, FalseFlag);
12261     }
12262     if (R & TrueFlag)
12263       return StringRef("true");
12264     if (R & FalseFlag)
12265       return StringRef("false");
12266     return llvm::None;
12267   }
12268 };
12269 }
12270 
12271 static bool HasEnumType(Expr *E) {
12272   // Strip off implicit integral promotions.
12273   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12274     if (ICE->getCastKind() != CK_IntegralCast &&
12275         ICE->getCastKind() != CK_NoOp)
12276       break;
12277     E = ICE->getSubExpr();
12278   }
12279 
12280   return E->getType()->isEnumeralType();
12281 }
12282 
12283 static int classifyConstantValue(Expr *Constant) {
12284   // The values of this enumeration are used in the diagnostics
12285   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12286   enum ConstantValueKind {
12287     Miscellaneous = 0,
12288     LiteralTrue,
12289     LiteralFalse
12290   };
12291   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12292     return BL->getValue() ? ConstantValueKind::LiteralTrue
12293                           : ConstantValueKind::LiteralFalse;
12294   return ConstantValueKind::Miscellaneous;
12295 }
12296 
12297 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12298                                         Expr *Constant, Expr *Other,
12299                                         const llvm::APSInt &Value,
12300                                         bool RhsConstant) {
12301   if (S.inTemplateInstantiation())
12302     return false;
12303 
12304   Expr *OriginalOther = Other;
12305 
12306   Constant = Constant->IgnoreParenImpCasts();
12307   Other = Other->IgnoreParenImpCasts();
12308 
12309   // Suppress warnings on tautological comparisons between values of the same
12310   // enumeration type. There are only two ways we could warn on this:
12311   //  - If the constant is outside the range of representable values of
12312   //    the enumeration. In such a case, we should warn about the cast
12313   //    to enumeration type, not about the comparison.
12314   //  - If the constant is the maximum / minimum in-range value. For an
12315   //    enumeratin type, such comparisons can be meaningful and useful.
12316   if (Constant->getType()->isEnumeralType() &&
12317       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12318     return false;
12319 
12320   IntRange OtherValueRange = GetExprRange(
12321       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12322 
12323   QualType OtherT = Other->getType();
12324   if (const auto *AT = OtherT->getAs<AtomicType>())
12325     OtherT = AT->getValueType();
12326   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12327 
12328   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12329   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12330   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12331                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12332                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12333 
12334   // Whether we're treating Other as being a bool because of the form of
12335   // expression despite it having another type (typically 'int' in C).
12336   bool OtherIsBooleanDespiteType =
12337       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12338   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12339     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12340 
12341   // Check if all values in the range of possible values of this expression
12342   // lead to the same comparison outcome.
12343   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12344                                         Value.isUnsigned());
12345   auto Cmp = OtherPromotedValueRange.compare(Value);
12346   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12347   if (!Result)
12348     return false;
12349 
12350   // Also consider the range determined by the type alone. This allows us to
12351   // classify the warning under the proper diagnostic group.
12352   bool TautologicalTypeCompare = false;
12353   {
12354     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12355                                          Value.isUnsigned());
12356     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12357     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12358                                                        RhsConstant)) {
12359       TautologicalTypeCompare = true;
12360       Cmp = TypeCmp;
12361       Result = TypeResult;
12362     }
12363   }
12364 
12365   // Don't warn if the non-constant operand actually always evaluates to the
12366   // same value.
12367   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12368     return false;
12369 
12370   // Suppress the diagnostic for an in-range comparison if the constant comes
12371   // from a macro or enumerator. We don't want to diagnose
12372   //
12373   //   some_long_value <= INT_MAX
12374   //
12375   // when sizeof(int) == sizeof(long).
12376   bool InRange = Cmp & PromotedRange::InRangeFlag;
12377   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12378     return false;
12379 
12380   // A comparison of an unsigned bit-field against 0 is really a type problem,
12381   // even though at the type level the bit-field might promote to 'signed int'.
12382   if (Other->refersToBitField() && InRange && Value == 0 &&
12383       Other->getType()->isUnsignedIntegerOrEnumerationType())
12384     TautologicalTypeCompare = true;
12385 
12386   // If this is a comparison to an enum constant, include that
12387   // constant in the diagnostic.
12388   const EnumConstantDecl *ED = nullptr;
12389   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12390     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12391 
12392   // Should be enough for uint128 (39 decimal digits)
12393   SmallString<64> PrettySourceValue;
12394   llvm::raw_svector_ostream OS(PrettySourceValue);
12395   if (ED) {
12396     OS << '\'' << *ED << "' (" << Value << ")";
12397   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12398                Constant->IgnoreParenImpCasts())) {
12399     OS << (BL->getValue() ? "YES" : "NO");
12400   } else {
12401     OS << Value;
12402   }
12403 
12404   if (!TautologicalTypeCompare) {
12405     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12406         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12407         << E->getOpcodeStr() << OS.str() << *Result
12408         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12409     return true;
12410   }
12411 
12412   if (IsObjCSignedCharBool) {
12413     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12414                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12415                               << OS.str() << *Result);
12416     return true;
12417   }
12418 
12419   // FIXME: We use a somewhat different formatting for the in-range cases and
12420   // cases involving boolean values for historical reasons. We should pick a
12421   // consistent way of presenting these diagnostics.
12422   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12423 
12424     S.DiagRuntimeBehavior(
12425         E->getOperatorLoc(), E,
12426         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12427                          : diag::warn_tautological_bool_compare)
12428             << OS.str() << classifyConstantValue(Constant) << OtherT
12429             << OtherIsBooleanDespiteType << *Result
12430             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12431   } else {
12432     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12433     unsigned Diag =
12434         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12435             ? (HasEnumType(OriginalOther)
12436                    ? diag::warn_unsigned_enum_always_true_comparison
12437                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12438                               : diag::warn_unsigned_always_true_comparison)
12439             : diag::warn_tautological_constant_compare;
12440 
12441     S.Diag(E->getOperatorLoc(), Diag)
12442         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12443         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12444   }
12445 
12446   return true;
12447 }
12448 
12449 /// Analyze the operands of the given comparison.  Implements the
12450 /// fallback case from AnalyzeComparison.
12451 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12452   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12453   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12454 }
12455 
12456 /// Implements -Wsign-compare.
12457 ///
12458 /// \param E the binary operator to check for warnings
12459 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12460   // The type the comparison is being performed in.
12461   QualType T = E->getLHS()->getType();
12462 
12463   // Only analyze comparison operators where both sides have been converted to
12464   // the same type.
12465   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12466     return AnalyzeImpConvsInComparison(S, E);
12467 
12468   // Don't analyze value-dependent comparisons directly.
12469   if (E->isValueDependent())
12470     return AnalyzeImpConvsInComparison(S, E);
12471 
12472   Expr *LHS = E->getLHS();
12473   Expr *RHS = E->getRHS();
12474 
12475   if (T->isIntegralType(S.Context)) {
12476     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12477     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12478 
12479     // We don't care about expressions whose result is a constant.
12480     if (RHSValue && LHSValue)
12481       return AnalyzeImpConvsInComparison(S, E);
12482 
12483     // We only care about expressions where just one side is literal
12484     if ((bool)RHSValue ^ (bool)LHSValue) {
12485       // Is the constant on the RHS or LHS?
12486       const bool RhsConstant = (bool)RHSValue;
12487       Expr *Const = RhsConstant ? RHS : LHS;
12488       Expr *Other = RhsConstant ? LHS : RHS;
12489       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12490 
12491       // Check whether an integer constant comparison results in a value
12492       // of 'true' or 'false'.
12493       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12494         return AnalyzeImpConvsInComparison(S, E);
12495     }
12496   }
12497 
12498   if (!T->hasUnsignedIntegerRepresentation()) {
12499     // We don't do anything special if this isn't an unsigned integral
12500     // comparison:  we're only interested in integral comparisons, and
12501     // signed comparisons only happen in cases we don't care to warn about.
12502     return AnalyzeImpConvsInComparison(S, E);
12503   }
12504 
12505   LHS = LHS->IgnoreParenImpCasts();
12506   RHS = RHS->IgnoreParenImpCasts();
12507 
12508   if (!S.getLangOpts().CPlusPlus) {
12509     // Avoid warning about comparison of integers with different signs when
12510     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12511     // the type of `E`.
12512     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12513       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12514     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12515       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12516   }
12517 
12518   // Check to see if one of the (unmodified) operands is of different
12519   // signedness.
12520   Expr *signedOperand, *unsignedOperand;
12521   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12522     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12523            "unsigned comparison between two signed integer expressions?");
12524     signedOperand = LHS;
12525     unsignedOperand = RHS;
12526   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12527     signedOperand = RHS;
12528     unsignedOperand = LHS;
12529   } else {
12530     return AnalyzeImpConvsInComparison(S, E);
12531   }
12532 
12533   // Otherwise, calculate the effective range of the signed operand.
12534   IntRange signedRange = GetExprRange(
12535       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12536 
12537   // Go ahead and analyze implicit conversions in the operands.  Note
12538   // that we skip the implicit conversions on both sides.
12539   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12540   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12541 
12542   // If the signed range is non-negative, -Wsign-compare won't fire.
12543   if (signedRange.NonNegative)
12544     return;
12545 
12546   // For (in)equality comparisons, if the unsigned operand is a
12547   // constant which cannot collide with a overflowed signed operand,
12548   // then reinterpreting the signed operand as unsigned will not
12549   // change the result of the comparison.
12550   if (E->isEqualityOp()) {
12551     unsigned comparisonWidth = S.Context.getIntWidth(T);
12552     IntRange unsignedRange =
12553         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12554                      /*Approximate*/ true);
12555 
12556     // We should never be unable to prove that the unsigned operand is
12557     // non-negative.
12558     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12559 
12560     if (unsignedRange.Width < comparisonWidth)
12561       return;
12562   }
12563 
12564   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12565                         S.PDiag(diag::warn_mixed_sign_comparison)
12566                             << LHS->getType() << RHS->getType()
12567                             << LHS->getSourceRange() << RHS->getSourceRange());
12568 }
12569 
12570 /// Analyzes an attempt to assign the given value to a bitfield.
12571 ///
12572 /// Returns true if there was something fishy about the attempt.
12573 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12574                                       SourceLocation InitLoc) {
12575   assert(Bitfield->isBitField());
12576   if (Bitfield->isInvalidDecl())
12577     return false;
12578 
12579   // White-list bool bitfields.
12580   QualType BitfieldType = Bitfield->getType();
12581   if (BitfieldType->isBooleanType())
12582      return false;
12583 
12584   if (BitfieldType->isEnumeralType()) {
12585     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12586     // If the underlying enum type was not explicitly specified as an unsigned
12587     // type and the enum contain only positive values, MSVC++ will cause an
12588     // inconsistency by storing this as a signed type.
12589     if (S.getLangOpts().CPlusPlus11 &&
12590         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12591         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12592         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12593       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12594           << BitfieldEnumDecl;
12595     }
12596   }
12597 
12598   if (Bitfield->getType()->isBooleanType())
12599     return false;
12600 
12601   // Ignore value- or type-dependent expressions.
12602   if (Bitfield->getBitWidth()->isValueDependent() ||
12603       Bitfield->getBitWidth()->isTypeDependent() ||
12604       Init->isValueDependent() ||
12605       Init->isTypeDependent())
12606     return false;
12607 
12608   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12609   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12610 
12611   Expr::EvalResult Result;
12612   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12613                                    Expr::SE_AllowSideEffects)) {
12614     // The RHS is not constant.  If the RHS has an enum type, make sure the
12615     // bitfield is wide enough to hold all the values of the enum without
12616     // truncation.
12617     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12618       EnumDecl *ED = EnumTy->getDecl();
12619       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12620 
12621       // Enum types are implicitly signed on Windows, so check if there are any
12622       // negative enumerators to see if the enum was intended to be signed or
12623       // not.
12624       bool SignedEnum = ED->getNumNegativeBits() > 0;
12625 
12626       // Check for surprising sign changes when assigning enum values to a
12627       // bitfield of different signedness.  If the bitfield is signed and we
12628       // have exactly the right number of bits to store this unsigned enum,
12629       // suggest changing the enum to an unsigned type. This typically happens
12630       // on Windows where unfixed enums always use an underlying type of 'int'.
12631       unsigned DiagID = 0;
12632       if (SignedEnum && !SignedBitfield) {
12633         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12634       } else if (SignedBitfield && !SignedEnum &&
12635                  ED->getNumPositiveBits() == FieldWidth) {
12636         DiagID = diag::warn_signed_bitfield_enum_conversion;
12637       }
12638 
12639       if (DiagID) {
12640         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12641         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12642         SourceRange TypeRange =
12643             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12644         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12645             << SignedEnum << TypeRange;
12646       }
12647 
12648       // Compute the required bitwidth. If the enum has negative values, we need
12649       // one more bit than the normal number of positive bits to represent the
12650       // sign bit.
12651       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12652                                                   ED->getNumNegativeBits())
12653                                        : ED->getNumPositiveBits();
12654 
12655       // Check the bitwidth.
12656       if (BitsNeeded > FieldWidth) {
12657         Expr *WidthExpr = Bitfield->getBitWidth();
12658         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12659             << Bitfield << ED;
12660         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12661             << BitsNeeded << ED << WidthExpr->getSourceRange();
12662       }
12663     }
12664 
12665     return false;
12666   }
12667 
12668   llvm::APSInt Value = Result.Val.getInt();
12669 
12670   unsigned OriginalWidth = Value.getBitWidth();
12671 
12672   if (!Value.isSigned() || Value.isNegative())
12673     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12674       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12675         OriginalWidth = Value.getMinSignedBits();
12676 
12677   if (OriginalWidth <= FieldWidth)
12678     return false;
12679 
12680   // Compute the value which the bitfield will contain.
12681   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12682   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12683 
12684   // Check whether the stored value is equal to the original value.
12685   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12686   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12687     return false;
12688 
12689   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12690   // therefore don't strictly fit into a signed bitfield of width 1.
12691   if (FieldWidth == 1 && Value == 1)
12692     return false;
12693 
12694   std::string PrettyValue = toString(Value, 10);
12695   std::string PrettyTrunc = toString(TruncatedValue, 10);
12696 
12697   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12698     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12699     << Init->getSourceRange();
12700 
12701   return true;
12702 }
12703 
12704 /// Analyze the given simple or compound assignment for warning-worthy
12705 /// operations.
12706 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12707   // Just recurse on the LHS.
12708   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12709 
12710   // We want to recurse on the RHS as normal unless we're assigning to
12711   // a bitfield.
12712   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12713     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12714                                   E->getOperatorLoc())) {
12715       // Recurse, ignoring any implicit conversions on the RHS.
12716       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12717                                         E->getOperatorLoc());
12718     }
12719   }
12720 
12721   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12722 
12723   // Diagnose implicitly sequentially-consistent atomic assignment.
12724   if (E->getLHS()->getType()->isAtomicType())
12725     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12726 }
12727 
12728 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12729 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12730                             SourceLocation CContext, unsigned diag,
12731                             bool pruneControlFlow = false) {
12732   if (pruneControlFlow) {
12733     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12734                           S.PDiag(diag)
12735                               << SourceType << T << E->getSourceRange()
12736                               << SourceRange(CContext));
12737     return;
12738   }
12739   S.Diag(E->getExprLoc(), diag)
12740     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12741 }
12742 
12743 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12744 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12745                             SourceLocation CContext,
12746                             unsigned diag, bool pruneControlFlow = false) {
12747   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12748 }
12749 
12750 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12751   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12752       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12753 }
12754 
12755 static void adornObjCBoolConversionDiagWithTernaryFixit(
12756     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12757   Expr *Ignored = SourceExpr->IgnoreImplicit();
12758   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12759     Ignored = OVE->getSourceExpr();
12760   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12761                      isa<BinaryOperator>(Ignored) ||
12762                      isa<CXXOperatorCallExpr>(Ignored);
12763   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12764   if (NeedsParens)
12765     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12766             << FixItHint::CreateInsertion(EndLoc, ")");
12767   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12768 }
12769 
12770 /// Diagnose an implicit cast from a floating point value to an integer value.
12771 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12772                                     SourceLocation CContext) {
12773   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12774   const bool PruneWarnings = S.inTemplateInstantiation();
12775 
12776   Expr *InnerE = E->IgnoreParenImpCasts();
12777   // We also want to warn on, e.g., "int i = -1.234"
12778   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12779     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12780       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12781 
12782   const bool IsLiteral =
12783       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12784 
12785   llvm::APFloat Value(0.0);
12786   bool IsConstant =
12787     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12788   if (!IsConstant) {
12789     if (isObjCSignedCharBool(S, T)) {
12790       return adornObjCBoolConversionDiagWithTernaryFixit(
12791           S, E,
12792           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12793               << E->getType());
12794     }
12795 
12796     return DiagnoseImpCast(S, E, T, CContext,
12797                            diag::warn_impcast_float_integer, PruneWarnings);
12798   }
12799 
12800   bool isExact = false;
12801 
12802   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12803                             T->hasUnsignedIntegerRepresentation());
12804   llvm::APFloat::opStatus Result = Value.convertToInteger(
12805       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12806 
12807   // FIXME: Force the precision of the source value down so we don't print
12808   // digits which are usually useless (we don't really care here if we
12809   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12810   // would automatically print the shortest representation, but it's a bit
12811   // tricky to implement.
12812   SmallString<16> PrettySourceValue;
12813   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12814   precision = (precision * 59 + 195) / 196;
12815   Value.toString(PrettySourceValue, precision);
12816 
12817   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12818     return adornObjCBoolConversionDiagWithTernaryFixit(
12819         S, E,
12820         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12821             << PrettySourceValue);
12822   }
12823 
12824   if (Result == llvm::APFloat::opOK && isExact) {
12825     if (IsLiteral) return;
12826     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12827                            PruneWarnings);
12828   }
12829 
12830   // Conversion of a floating-point value to a non-bool integer where the
12831   // integral part cannot be represented by the integer type is undefined.
12832   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12833     return DiagnoseImpCast(
12834         S, E, T, CContext,
12835         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12836                   : diag::warn_impcast_float_to_integer_out_of_range,
12837         PruneWarnings);
12838 
12839   unsigned DiagID = 0;
12840   if (IsLiteral) {
12841     // Warn on floating point literal to integer.
12842     DiagID = diag::warn_impcast_literal_float_to_integer;
12843   } else if (IntegerValue == 0) {
12844     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12845       return DiagnoseImpCast(S, E, T, CContext,
12846                              diag::warn_impcast_float_integer, PruneWarnings);
12847     }
12848     // Warn on non-zero to zero conversion.
12849     DiagID = diag::warn_impcast_float_to_integer_zero;
12850   } else {
12851     if (IntegerValue.isUnsigned()) {
12852       if (!IntegerValue.isMaxValue()) {
12853         return DiagnoseImpCast(S, E, T, CContext,
12854                                diag::warn_impcast_float_integer, PruneWarnings);
12855       }
12856     } else {  // IntegerValue.isSigned()
12857       if (!IntegerValue.isMaxSignedValue() &&
12858           !IntegerValue.isMinSignedValue()) {
12859         return DiagnoseImpCast(S, E, T, CContext,
12860                                diag::warn_impcast_float_integer, PruneWarnings);
12861       }
12862     }
12863     // Warn on evaluatable floating point expression to integer conversion.
12864     DiagID = diag::warn_impcast_float_to_integer;
12865   }
12866 
12867   SmallString<16> PrettyTargetValue;
12868   if (IsBool)
12869     PrettyTargetValue = Value.isZero() ? "false" : "true";
12870   else
12871     IntegerValue.toString(PrettyTargetValue);
12872 
12873   if (PruneWarnings) {
12874     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12875                           S.PDiag(DiagID)
12876                               << E->getType() << T.getUnqualifiedType()
12877                               << PrettySourceValue << PrettyTargetValue
12878                               << E->getSourceRange() << SourceRange(CContext));
12879   } else {
12880     S.Diag(E->getExprLoc(), DiagID)
12881         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12882         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12883   }
12884 }
12885 
12886 /// Analyze the given compound assignment for the possible losing of
12887 /// floating-point precision.
12888 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12889   assert(isa<CompoundAssignOperator>(E) &&
12890          "Must be compound assignment operation");
12891   // Recurse on the LHS and RHS in here
12892   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12893   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12894 
12895   if (E->getLHS()->getType()->isAtomicType())
12896     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12897 
12898   // Now check the outermost expression
12899   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12900   const auto *RBT = cast<CompoundAssignOperator>(E)
12901                         ->getComputationResultType()
12902                         ->getAs<BuiltinType>();
12903 
12904   // The below checks assume source is floating point.
12905   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12906 
12907   // If source is floating point but target is an integer.
12908   if (ResultBT->isInteger())
12909     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12910                            E->getExprLoc(), diag::warn_impcast_float_integer);
12911 
12912   if (!ResultBT->isFloatingPoint())
12913     return;
12914 
12915   // If both source and target are floating points, warn about losing precision.
12916   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12917       QualType(ResultBT, 0), QualType(RBT, 0));
12918   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12919     // warn about dropping FP rank.
12920     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12921                     diag::warn_impcast_float_result_precision);
12922 }
12923 
12924 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12925                                       IntRange Range) {
12926   if (!Range.Width) return "0";
12927 
12928   llvm::APSInt ValueInRange = Value;
12929   ValueInRange.setIsSigned(!Range.NonNegative);
12930   ValueInRange = ValueInRange.trunc(Range.Width);
12931   return toString(ValueInRange, 10);
12932 }
12933 
12934 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12935   if (!isa<ImplicitCastExpr>(Ex))
12936     return false;
12937 
12938   Expr *InnerE = Ex->IgnoreParenImpCasts();
12939   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12940   const Type *Source =
12941     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12942   if (Target->isDependentType())
12943     return false;
12944 
12945   const BuiltinType *FloatCandidateBT =
12946     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12947   const Type *BoolCandidateType = ToBool ? Target : Source;
12948 
12949   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12950           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12951 }
12952 
12953 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12954                                              SourceLocation CC) {
12955   unsigned NumArgs = TheCall->getNumArgs();
12956   for (unsigned i = 0; i < NumArgs; ++i) {
12957     Expr *CurrA = TheCall->getArg(i);
12958     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12959       continue;
12960 
12961     bool IsSwapped = ((i > 0) &&
12962         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12963     IsSwapped |= ((i < (NumArgs - 1)) &&
12964         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12965     if (IsSwapped) {
12966       // Warn on this floating-point to bool conversion.
12967       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12968                       CurrA->getType(), CC,
12969                       diag::warn_impcast_floating_point_to_bool);
12970     }
12971   }
12972 }
12973 
12974 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12975                                    SourceLocation CC) {
12976   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12977                         E->getExprLoc()))
12978     return;
12979 
12980   // Don't warn on functions which have return type nullptr_t.
12981   if (isa<CallExpr>(E))
12982     return;
12983 
12984   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12985   const Expr::NullPointerConstantKind NullKind =
12986       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12987   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12988     return;
12989 
12990   // Return if target type is a safe conversion.
12991   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12992       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12993     return;
12994 
12995   SourceLocation Loc = E->getSourceRange().getBegin();
12996 
12997   // Venture through the macro stacks to get to the source of macro arguments.
12998   // The new location is a better location than the complete location that was
12999   // passed in.
13000   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13001   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
13002 
13003   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
13004   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
13005     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13006         Loc, S.SourceMgr, S.getLangOpts());
13007     if (MacroName == "NULL")
13008       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13009   }
13010 
13011   // Only warn if the null and context location are in the same macro expansion.
13012   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13013     return;
13014 
13015   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13016       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
13017       << FixItHint::CreateReplacement(Loc,
13018                                       S.getFixItZeroLiteralForType(T, Loc));
13019 }
13020 
13021 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
13022                                   ObjCArrayLiteral *ArrayLiteral);
13023 
13024 static void
13025 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13026                            ObjCDictionaryLiteral *DictionaryLiteral);
13027 
13028 /// Check a single element within a collection literal against the
13029 /// target element type.
13030 static void checkObjCCollectionLiteralElement(Sema &S,
13031                                               QualType TargetElementType,
13032                                               Expr *Element,
13033                                               unsigned ElementKind) {
13034   // Skip a bitcast to 'id' or qualified 'id'.
13035   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
13036     if (ICE->getCastKind() == CK_BitCast &&
13037         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
13038       Element = ICE->getSubExpr();
13039   }
13040 
13041   QualType ElementType = Element->getType();
13042   ExprResult ElementResult(Element);
13043   if (ElementType->getAs<ObjCObjectPointerType>() &&
13044       S.CheckSingleAssignmentConstraints(TargetElementType,
13045                                          ElementResult,
13046                                          false, false)
13047         != Sema::Compatible) {
13048     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
13049         << ElementType << ElementKind << TargetElementType
13050         << Element->getSourceRange();
13051   }
13052 
13053   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
13054     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
13055   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
13056     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
13057 }
13058 
13059 /// Check an Objective-C array literal being converted to the given
13060 /// target type.
13061 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
13062                                   ObjCArrayLiteral *ArrayLiteral) {
13063   if (!S.NSArrayDecl)
13064     return;
13065 
13066   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13067   if (!TargetObjCPtr)
13068     return;
13069 
13070   if (TargetObjCPtr->isUnspecialized() ||
13071       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13072         != S.NSArrayDecl->getCanonicalDecl())
13073     return;
13074 
13075   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13076   if (TypeArgs.size() != 1)
13077     return;
13078 
13079   QualType TargetElementType = TypeArgs[0];
13080   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
13081     checkObjCCollectionLiteralElement(S, TargetElementType,
13082                                       ArrayLiteral->getElement(I),
13083                                       0);
13084   }
13085 }
13086 
13087 /// Check an Objective-C dictionary literal being converted to the given
13088 /// target type.
13089 static void
13090 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13091                            ObjCDictionaryLiteral *DictionaryLiteral) {
13092   if (!S.NSDictionaryDecl)
13093     return;
13094 
13095   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13096   if (!TargetObjCPtr)
13097     return;
13098 
13099   if (TargetObjCPtr->isUnspecialized() ||
13100       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13101         != S.NSDictionaryDecl->getCanonicalDecl())
13102     return;
13103 
13104   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13105   if (TypeArgs.size() != 2)
13106     return;
13107 
13108   QualType TargetKeyType = TypeArgs[0];
13109   QualType TargetObjectType = TypeArgs[1];
13110   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
13111     auto Element = DictionaryLiteral->getKeyValueElement(I);
13112     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
13113     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
13114   }
13115 }
13116 
13117 // Helper function to filter out cases for constant width constant conversion.
13118 // Don't warn on char array initialization or for non-decimal values.
13119 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13120                                           SourceLocation CC) {
13121   // If initializing from a constant, and the constant starts with '0',
13122   // then it is a binary, octal, or hexadecimal.  Allow these constants
13123   // to fill all the bits, even if there is a sign change.
13124   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13125     const char FirstLiteralCharacter =
13126         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13127     if (FirstLiteralCharacter == '0')
13128       return false;
13129   }
13130 
13131   // If the CC location points to a '{', and the type is char, then assume
13132   // assume it is an array initialization.
13133   if (CC.isValid() && T->isCharType()) {
13134     const char FirstContextCharacter =
13135         S.getSourceManager().getCharacterData(CC)[0];
13136     if (FirstContextCharacter == '{')
13137       return false;
13138   }
13139 
13140   return true;
13141 }
13142 
13143 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13144   const auto *IL = dyn_cast<IntegerLiteral>(E);
13145   if (!IL) {
13146     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13147       if (UO->getOpcode() == UO_Minus)
13148         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13149     }
13150   }
13151 
13152   return IL;
13153 }
13154 
13155 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13156   E = E->IgnoreParenImpCasts();
13157   SourceLocation ExprLoc = E->getExprLoc();
13158 
13159   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13160     BinaryOperator::Opcode Opc = BO->getOpcode();
13161     Expr::EvalResult Result;
13162     // Do not diagnose unsigned shifts.
13163     if (Opc == BO_Shl) {
13164       const auto *LHS = getIntegerLiteral(BO->getLHS());
13165       const auto *RHS = getIntegerLiteral(BO->getRHS());
13166       if (LHS && LHS->getValue() == 0)
13167         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13168       else if (!E->isValueDependent() && LHS && RHS &&
13169                RHS->getValue().isNonNegative() &&
13170                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13171         S.Diag(ExprLoc, diag::warn_left_shift_always)
13172             << (Result.Val.getInt() != 0);
13173       else if (E->getType()->isSignedIntegerType())
13174         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13175     }
13176   }
13177 
13178   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13179     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13180     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13181     if (!LHS || !RHS)
13182       return;
13183     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13184         (RHS->getValue() == 0 || RHS->getValue() == 1))
13185       // Do not diagnose common idioms.
13186       return;
13187     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13188       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13189   }
13190 }
13191 
13192 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13193                                     SourceLocation CC,
13194                                     bool *ICContext = nullptr,
13195                                     bool IsListInit = false) {
13196   if (E->isTypeDependent() || E->isValueDependent()) return;
13197 
13198   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13199   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13200   if (Source == Target) return;
13201   if (Target->isDependentType()) return;
13202 
13203   // If the conversion context location is invalid don't complain. We also
13204   // don't want to emit a warning if the issue occurs from the expansion of
13205   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13206   // delay this check as long as possible. Once we detect we are in that
13207   // scenario, we just return.
13208   if (CC.isInvalid())
13209     return;
13210 
13211   if (Source->isAtomicType())
13212     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13213 
13214   // Diagnose implicit casts to bool.
13215   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13216     if (isa<StringLiteral>(E))
13217       // Warn on string literal to bool.  Checks for string literals in logical
13218       // and expressions, for instance, assert(0 && "error here"), are
13219       // prevented by a check in AnalyzeImplicitConversions().
13220       return DiagnoseImpCast(S, E, T, CC,
13221                              diag::warn_impcast_string_literal_to_bool);
13222     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13223         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13224       // This covers the literal expressions that evaluate to Objective-C
13225       // objects.
13226       return DiagnoseImpCast(S, E, T, CC,
13227                              diag::warn_impcast_objective_c_literal_to_bool);
13228     }
13229     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13230       // Warn on pointer to bool conversion that is always true.
13231       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13232                                      SourceRange(CC));
13233     }
13234   }
13235 
13236   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13237   // is a typedef for signed char (macOS), then that constant value has to be 1
13238   // or 0.
13239   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13240     Expr::EvalResult Result;
13241     if (E->EvaluateAsInt(Result, S.getASTContext(),
13242                          Expr::SE_AllowSideEffects)) {
13243       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13244         adornObjCBoolConversionDiagWithTernaryFixit(
13245             S, E,
13246             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13247                 << toString(Result.Val.getInt(), 10));
13248       }
13249       return;
13250     }
13251   }
13252 
13253   // Check implicit casts from Objective-C collection literals to specialized
13254   // collection types, e.g., NSArray<NSString *> *.
13255   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13256     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13257   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13258     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13259 
13260   // Strip vector types.
13261   if (isa<VectorType>(Source)) {
13262     if (Target->isVLSTBuiltinType() &&
13263         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13264                                          QualType(Source, 0)) ||
13265          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13266                                             QualType(Source, 0))))
13267       return;
13268 
13269     if (!isa<VectorType>(Target)) {
13270       if (S.SourceMgr.isInSystemMacro(CC))
13271         return;
13272       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13273     }
13274 
13275     // If the vector cast is cast between two vectors of the same size, it is
13276     // a bitcast, not a conversion.
13277     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13278       return;
13279 
13280     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13281     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13282   }
13283   if (auto VecTy = dyn_cast<VectorType>(Target))
13284     Target = VecTy->getElementType().getTypePtr();
13285 
13286   // Strip complex types.
13287   if (isa<ComplexType>(Source)) {
13288     if (!isa<ComplexType>(Target)) {
13289       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13290         return;
13291 
13292       return DiagnoseImpCast(S, E, T, CC,
13293                              S.getLangOpts().CPlusPlus
13294                                  ? diag::err_impcast_complex_scalar
13295                                  : diag::warn_impcast_complex_scalar);
13296     }
13297 
13298     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13299     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13300   }
13301 
13302   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13303   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13304 
13305   // If the source is floating point...
13306   if (SourceBT && SourceBT->isFloatingPoint()) {
13307     // ...and the target is floating point...
13308     if (TargetBT && TargetBT->isFloatingPoint()) {
13309       // ...then warn if we're dropping FP rank.
13310 
13311       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13312           QualType(SourceBT, 0), QualType(TargetBT, 0));
13313       if (Order > 0) {
13314         // Don't warn about float constants that are precisely
13315         // representable in the target type.
13316         Expr::EvalResult result;
13317         if (E->EvaluateAsRValue(result, S.Context)) {
13318           // Value might be a float, a float vector, or a float complex.
13319           if (IsSameFloatAfterCast(result.Val,
13320                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13321                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13322             return;
13323         }
13324 
13325         if (S.SourceMgr.isInSystemMacro(CC))
13326           return;
13327 
13328         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13329       }
13330       // ... or possibly if we're increasing rank, too
13331       else if (Order < 0) {
13332         if (S.SourceMgr.isInSystemMacro(CC))
13333           return;
13334 
13335         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13336       }
13337       return;
13338     }
13339 
13340     // If the target is integral, always warn.
13341     if (TargetBT && TargetBT->isInteger()) {
13342       if (S.SourceMgr.isInSystemMacro(CC))
13343         return;
13344 
13345       DiagnoseFloatingImpCast(S, E, T, CC);
13346     }
13347 
13348     // Detect the case where a call result is converted from floating-point to
13349     // to bool, and the final argument to the call is converted from bool, to
13350     // discover this typo:
13351     //
13352     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13353     //
13354     // FIXME: This is an incredibly special case; is there some more general
13355     // way to detect this class of misplaced-parentheses bug?
13356     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13357       // Check last argument of function call to see if it is an
13358       // implicit cast from a type matching the type the result
13359       // is being cast to.
13360       CallExpr *CEx = cast<CallExpr>(E);
13361       if (unsigned NumArgs = CEx->getNumArgs()) {
13362         Expr *LastA = CEx->getArg(NumArgs - 1);
13363         Expr *InnerE = LastA->IgnoreParenImpCasts();
13364         if (isa<ImplicitCastExpr>(LastA) &&
13365             InnerE->getType()->isBooleanType()) {
13366           // Warn on this floating-point to bool conversion
13367           DiagnoseImpCast(S, E, T, CC,
13368                           diag::warn_impcast_floating_point_to_bool);
13369         }
13370       }
13371     }
13372     return;
13373   }
13374 
13375   // Valid casts involving fixed point types should be accounted for here.
13376   if (Source->isFixedPointType()) {
13377     if (Target->isUnsaturatedFixedPointType()) {
13378       Expr::EvalResult Result;
13379       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13380                                   S.isConstantEvaluated())) {
13381         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13382         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13383         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13384         if (Value > MaxVal || Value < MinVal) {
13385           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13386                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13387                                     << Value.toString() << T
13388                                     << E->getSourceRange()
13389                                     << clang::SourceRange(CC));
13390           return;
13391         }
13392       }
13393     } else if (Target->isIntegerType()) {
13394       Expr::EvalResult Result;
13395       if (!S.isConstantEvaluated() &&
13396           E->EvaluateAsFixedPoint(Result, S.Context,
13397                                   Expr::SE_AllowSideEffects)) {
13398         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13399 
13400         bool Overflowed;
13401         llvm::APSInt IntResult = FXResult.convertToInt(
13402             S.Context.getIntWidth(T),
13403             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13404 
13405         if (Overflowed) {
13406           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13407                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13408                                     << FXResult.toString() << T
13409                                     << E->getSourceRange()
13410                                     << clang::SourceRange(CC));
13411           return;
13412         }
13413       }
13414     }
13415   } else if (Target->isUnsaturatedFixedPointType()) {
13416     if (Source->isIntegerType()) {
13417       Expr::EvalResult Result;
13418       if (!S.isConstantEvaluated() &&
13419           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13420         llvm::APSInt Value = Result.Val.getInt();
13421 
13422         bool Overflowed;
13423         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13424             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13425 
13426         if (Overflowed) {
13427           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13428                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13429                                     << toString(Value, /*Radix=*/10) << T
13430                                     << E->getSourceRange()
13431                                     << clang::SourceRange(CC));
13432           return;
13433         }
13434       }
13435     }
13436   }
13437 
13438   // If we are casting an integer type to a floating point type without
13439   // initialization-list syntax, we might lose accuracy if the floating
13440   // point type has a narrower significand than the integer type.
13441   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13442       TargetBT->isFloatingType() && !IsListInit) {
13443     // Determine the number of precision bits in the source integer type.
13444     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13445                                         /*Approximate*/ true);
13446     unsigned int SourcePrecision = SourceRange.Width;
13447 
13448     // Determine the number of precision bits in the
13449     // target floating point type.
13450     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13451         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13452 
13453     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13454         SourcePrecision > TargetPrecision) {
13455 
13456       if (Optional<llvm::APSInt> SourceInt =
13457               E->getIntegerConstantExpr(S.Context)) {
13458         // If the source integer is a constant, convert it to the target
13459         // floating point type. Issue a warning if the value changes
13460         // during the whole conversion.
13461         llvm::APFloat TargetFloatValue(
13462             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13463         llvm::APFloat::opStatus ConversionStatus =
13464             TargetFloatValue.convertFromAPInt(
13465                 *SourceInt, SourceBT->isSignedInteger(),
13466                 llvm::APFloat::rmNearestTiesToEven);
13467 
13468         if (ConversionStatus != llvm::APFloat::opOK) {
13469           SmallString<32> PrettySourceValue;
13470           SourceInt->toString(PrettySourceValue, 10);
13471           SmallString<32> PrettyTargetValue;
13472           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13473 
13474           S.DiagRuntimeBehavior(
13475               E->getExprLoc(), E,
13476               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13477                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13478                   << E->getSourceRange() << clang::SourceRange(CC));
13479         }
13480       } else {
13481         // Otherwise, the implicit conversion may lose precision.
13482         DiagnoseImpCast(S, E, T, CC,
13483                         diag::warn_impcast_integer_float_precision);
13484       }
13485     }
13486   }
13487 
13488   DiagnoseNullConversion(S, E, T, CC);
13489 
13490   S.DiscardMisalignedMemberAddress(Target, E);
13491 
13492   if (Target->isBooleanType())
13493     DiagnoseIntInBoolContext(S, E);
13494 
13495   if (!Source->isIntegerType() || !Target->isIntegerType())
13496     return;
13497 
13498   // TODO: remove this early return once the false positives for constant->bool
13499   // in templates, macros, etc, are reduced or removed.
13500   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13501     return;
13502 
13503   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13504       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13505     return adornObjCBoolConversionDiagWithTernaryFixit(
13506         S, E,
13507         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13508             << E->getType());
13509   }
13510 
13511   IntRange SourceTypeRange =
13512       IntRange::forTargetOfCanonicalType(S.Context, Source);
13513   IntRange LikelySourceRange =
13514       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13515   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13516 
13517   if (LikelySourceRange.Width > TargetRange.Width) {
13518     // If the source is a constant, use a default-on diagnostic.
13519     // TODO: this should happen for bitfield stores, too.
13520     Expr::EvalResult Result;
13521     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13522                          S.isConstantEvaluated())) {
13523       llvm::APSInt Value(32);
13524       Value = Result.Val.getInt();
13525 
13526       if (S.SourceMgr.isInSystemMacro(CC))
13527         return;
13528 
13529       std::string PrettySourceValue = toString(Value, 10);
13530       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13531 
13532       S.DiagRuntimeBehavior(
13533           E->getExprLoc(), E,
13534           S.PDiag(diag::warn_impcast_integer_precision_constant)
13535               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13536               << E->getSourceRange() << SourceRange(CC));
13537       return;
13538     }
13539 
13540     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13541     if (S.SourceMgr.isInSystemMacro(CC))
13542       return;
13543 
13544     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13545       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13546                              /* pruneControlFlow */ true);
13547     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13548   }
13549 
13550   if (TargetRange.Width > SourceTypeRange.Width) {
13551     if (auto *UO = dyn_cast<UnaryOperator>(E))
13552       if (UO->getOpcode() == UO_Minus)
13553         if (Source->isUnsignedIntegerType()) {
13554           if (Target->isUnsignedIntegerType())
13555             return DiagnoseImpCast(S, E, T, CC,
13556                                    diag::warn_impcast_high_order_zero_bits);
13557           if (Target->isSignedIntegerType())
13558             return DiagnoseImpCast(S, E, T, CC,
13559                                    diag::warn_impcast_nonnegative_result);
13560         }
13561   }
13562 
13563   if (TargetRange.Width == LikelySourceRange.Width &&
13564       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13565       Source->isSignedIntegerType()) {
13566     // Warn when doing a signed to signed conversion, warn if the positive
13567     // source value is exactly the width of the target type, which will
13568     // cause a negative value to be stored.
13569 
13570     Expr::EvalResult Result;
13571     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13572         !S.SourceMgr.isInSystemMacro(CC)) {
13573       llvm::APSInt Value = Result.Val.getInt();
13574       if (isSameWidthConstantConversion(S, E, T, CC)) {
13575         std::string PrettySourceValue = toString(Value, 10);
13576         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13577 
13578         S.DiagRuntimeBehavior(
13579             E->getExprLoc(), E,
13580             S.PDiag(diag::warn_impcast_integer_precision_constant)
13581                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13582                 << E->getSourceRange() << SourceRange(CC));
13583         return;
13584       }
13585     }
13586 
13587     // Fall through for non-constants to give a sign conversion warning.
13588   }
13589 
13590   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13591       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13592        LikelySourceRange.Width == TargetRange.Width)) {
13593     if (S.SourceMgr.isInSystemMacro(CC))
13594       return;
13595 
13596     unsigned DiagID = diag::warn_impcast_integer_sign;
13597 
13598     // Traditionally, gcc has warned about this under -Wsign-compare.
13599     // We also want to warn about it in -Wconversion.
13600     // So if -Wconversion is off, use a completely identical diagnostic
13601     // in the sign-compare group.
13602     // The conditional-checking code will
13603     if (ICContext) {
13604       DiagID = diag::warn_impcast_integer_sign_conditional;
13605       *ICContext = true;
13606     }
13607 
13608     return DiagnoseImpCast(S, E, T, CC, DiagID);
13609   }
13610 
13611   // Diagnose conversions between different enumeration types.
13612   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13613   // type, to give us better diagnostics.
13614   QualType SourceType = E->getType();
13615   if (!S.getLangOpts().CPlusPlus) {
13616     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13617       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13618         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13619         SourceType = S.Context.getTypeDeclType(Enum);
13620         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13621       }
13622   }
13623 
13624   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13625     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13626       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13627           TargetEnum->getDecl()->hasNameForLinkage() &&
13628           SourceEnum != TargetEnum) {
13629         if (S.SourceMgr.isInSystemMacro(CC))
13630           return;
13631 
13632         return DiagnoseImpCast(S, E, SourceType, T, CC,
13633                                diag::warn_impcast_different_enum_types);
13634       }
13635 }
13636 
13637 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13638                                      SourceLocation CC, QualType T);
13639 
13640 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13641                                     SourceLocation CC, bool &ICContext) {
13642   E = E->IgnoreParenImpCasts();
13643 
13644   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13645     return CheckConditionalOperator(S, CO, CC, T);
13646 
13647   AnalyzeImplicitConversions(S, E, CC);
13648   if (E->getType() != T)
13649     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13650 }
13651 
13652 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13653                                      SourceLocation CC, QualType T) {
13654   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13655 
13656   Expr *TrueExpr = E->getTrueExpr();
13657   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13658     TrueExpr = BCO->getCommon();
13659 
13660   bool Suspicious = false;
13661   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13662   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13663 
13664   if (T->isBooleanType())
13665     DiagnoseIntInBoolContext(S, E);
13666 
13667   // If -Wconversion would have warned about either of the candidates
13668   // for a signedness conversion to the context type...
13669   if (!Suspicious) return;
13670 
13671   // ...but it's currently ignored...
13672   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13673     return;
13674 
13675   // ...then check whether it would have warned about either of the
13676   // candidates for a signedness conversion to the condition type.
13677   if (E->getType() == T) return;
13678 
13679   Suspicious = false;
13680   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13681                           E->getType(), CC, &Suspicious);
13682   if (!Suspicious)
13683     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13684                             E->getType(), CC, &Suspicious);
13685 }
13686 
13687 /// Check conversion of given expression to boolean.
13688 /// Input argument E is a logical expression.
13689 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13690   if (S.getLangOpts().Bool)
13691     return;
13692   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13693     return;
13694   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13695 }
13696 
13697 namespace {
13698 struct AnalyzeImplicitConversionsWorkItem {
13699   Expr *E;
13700   SourceLocation CC;
13701   bool IsListInit;
13702 };
13703 }
13704 
13705 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13706 /// that should be visited are added to WorkList.
13707 static void AnalyzeImplicitConversions(
13708     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13709     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13710   Expr *OrigE = Item.E;
13711   SourceLocation CC = Item.CC;
13712 
13713   QualType T = OrigE->getType();
13714   Expr *E = OrigE->IgnoreParenImpCasts();
13715 
13716   // Propagate whether we are in a C++ list initialization expression.
13717   // If so, we do not issue warnings for implicit int-float conversion
13718   // precision loss, because C++11 narrowing already handles it.
13719   bool IsListInit = Item.IsListInit ||
13720                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13721 
13722   if (E->isTypeDependent() || E->isValueDependent())
13723     return;
13724 
13725   Expr *SourceExpr = E;
13726   // Examine, but don't traverse into the source expression of an
13727   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13728   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13729   // evaluate it in the context of checking the specific conversion to T though.
13730   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13731     if (auto *Src = OVE->getSourceExpr())
13732       SourceExpr = Src;
13733 
13734   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13735     if (UO->getOpcode() == UO_Not &&
13736         UO->getSubExpr()->isKnownToHaveBooleanValue())
13737       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13738           << OrigE->getSourceRange() << T->isBooleanType()
13739           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13740 
13741   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13742     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13743         BO->getLHS()->isKnownToHaveBooleanValue() &&
13744         BO->getRHS()->isKnownToHaveBooleanValue() &&
13745         BO->getLHS()->HasSideEffects(S.Context) &&
13746         BO->getRHS()->HasSideEffects(S.Context)) {
13747       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13748           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13749           << FixItHint::CreateReplacement(
13750                  BO->getOperatorLoc(),
13751                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13752       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13753     }
13754 
13755   // For conditional operators, we analyze the arguments as if they
13756   // were being fed directly into the output.
13757   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13758     CheckConditionalOperator(S, CO, CC, T);
13759     return;
13760   }
13761 
13762   // Check implicit argument conversions for function calls.
13763   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13764     CheckImplicitArgumentConversions(S, Call, CC);
13765 
13766   // Go ahead and check any implicit conversions we might have skipped.
13767   // The non-canonical typecheck is just an optimization;
13768   // CheckImplicitConversion will filter out dead implicit conversions.
13769   if (SourceExpr->getType() != T)
13770     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13771 
13772   // Now continue drilling into this expression.
13773 
13774   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13775     // The bound subexpressions in a PseudoObjectExpr are not reachable
13776     // as transitive children.
13777     // FIXME: Use a more uniform representation for this.
13778     for (auto *SE : POE->semantics())
13779       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13780         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13781   }
13782 
13783   // Skip past explicit casts.
13784   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13785     E = CE->getSubExpr()->IgnoreParenImpCasts();
13786     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13787       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13788     WorkList.push_back({E, CC, IsListInit});
13789     return;
13790   }
13791 
13792   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13793     // Do a somewhat different check with comparison operators.
13794     if (BO->isComparisonOp())
13795       return AnalyzeComparison(S, BO);
13796 
13797     // And with simple assignments.
13798     if (BO->getOpcode() == BO_Assign)
13799       return AnalyzeAssignment(S, BO);
13800     // And with compound assignments.
13801     if (BO->isAssignmentOp())
13802       return AnalyzeCompoundAssignment(S, BO);
13803   }
13804 
13805   // These break the otherwise-useful invariant below.  Fortunately,
13806   // we don't really need to recurse into them, because any internal
13807   // expressions should have been analyzed already when they were
13808   // built into statements.
13809   if (isa<StmtExpr>(E)) return;
13810 
13811   // Don't descend into unevaluated contexts.
13812   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13813 
13814   // Now just recurse over the expression's children.
13815   CC = E->getExprLoc();
13816   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13817   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13818   for (Stmt *SubStmt : E->children()) {
13819     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13820     if (!ChildExpr)
13821       continue;
13822 
13823     if (IsLogicalAndOperator &&
13824         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13825       // Ignore checking string literals that are in logical and operators.
13826       // This is a common pattern for asserts.
13827       continue;
13828     WorkList.push_back({ChildExpr, CC, IsListInit});
13829   }
13830 
13831   if (BO && BO->isLogicalOp()) {
13832     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13833     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13834       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13835 
13836     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13837     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13838       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13839   }
13840 
13841   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13842     if (U->getOpcode() == UO_LNot) {
13843       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13844     } else if (U->getOpcode() != UO_AddrOf) {
13845       if (U->getSubExpr()->getType()->isAtomicType())
13846         S.Diag(U->getSubExpr()->getBeginLoc(),
13847                diag::warn_atomic_implicit_seq_cst);
13848     }
13849   }
13850 }
13851 
13852 /// AnalyzeImplicitConversions - Find and report any interesting
13853 /// implicit conversions in the given expression.  There are a couple
13854 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13855 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13856                                        bool IsListInit/*= false*/) {
13857   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13858   WorkList.push_back({OrigE, CC, IsListInit});
13859   while (!WorkList.empty())
13860     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13861 }
13862 
13863 /// Diagnose integer type and any valid implicit conversion to it.
13864 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13865   // Taking into account implicit conversions,
13866   // allow any integer.
13867   if (!E->getType()->isIntegerType()) {
13868     S.Diag(E->getBeginLoc(),
13869            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13870     return true;
13871   }
13872   // Potentially emit standard warnings for implicit conversions if enabled
13873   // using -Wconversion.
13874   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13875   return false;
13876 }
13877 
13878 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13879 // Returns true when emitting a warning about taking the address of a reference.
13880 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13881                               const PartialDiagnostic &PD) {
13882   E = E->IgnoreParenImpCasts();
13883 
13884   const FunctionDecl *FD = nullptr;
13885 
13886   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13887     if (!DRE->getDecl()->getType()->isReferenceType())
13888       return false;
13889   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13890     if (!M->getMemberDecl()->getType()->isReferenceType())
13891       return false;
13892   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13893     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13894       return false;
13895     FD = Call->getDirectCallee();
13896   } else {
13897     return false;
13898   }
13899 
13900   SemaRef.Diag(E->getExprLoc(), PD);
13901 
13902   // If possible, point to location of function.
13903   if (FD) {
13904     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13905   }
13906 
13907   return true;
13908 }
13909 
13910 // Returns true if the SourceLocation is expanded from any macro body.
13911 // Returns false if the SourceLocation is invalid, is from not in a macro
13912 // expansion, or is from expanded from a top-level macro argument.
13913 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13914   if (Loc.isInvalid())
13915     return false;
13916 
13917   while (Loc.isMacroID()) {
13918     if (SM.isMacroBodyExpansion(Loc))
13919       return true;
13920     Loc = SM.getImmediateMacroCallerLoc(Loc);
13921   }
13922 
13923   return false;
13924 }
13925 
13926 /// Diagnose pointers that are always non-null.
13927 /// \param E the expression containing the pointer
13928 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13929 /// compared to a null pointer
13930 /// \param IsEqual True when the comparison is equal to a null pointer
13931 /// \param Range Extra SourceRange to highlight in the diagnostic
13932 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13933                                         Expr::NullPointerConstantKind NullKind,
13934                                         bool IsEqual, SourceRange Range) {
13935   if (!E)
13936     return;
13937 
13938   // Don't warn inside macros.
13939   if (E->getExprLoc().isMacroID()) {
13940     const SourceManager &SM = getSourceManager();
13941     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13942         IsInAnyMacroBody(SM, Range.getBegin()))
13943       return;
13944   }
13945   E = E->IgnoreImpCasts();
13946 
13947   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13948 
13949   if (isa<CXXThisExpr>(E)) {
13950     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13951                                 : diag::warn_this_bool_conversion;
13952     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13953     return;
13954   }
13955 
13956   bool IsAddressOf = false;
13957 
13958   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13959     if (UO->getOpcode() != UO_AddrOf)
13960       return;
13961     IsAddressOf = true;
13962     E = UO->getSubExpr();
13963   }
13964 
13965   if (IsAddressOf) {
13966     unsigned DiagID = IsCompare
13967                           ? diag::warn_address_of_reference_null_compare
13968                           : diag::warn_address_of_reference_bool_conversion;
13969     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13970                                          << IsEqual;
13971     if (CheckForReference(*this, E, PD)) {
13972       return;
13973     }
13974   }
13975 
13976   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13977     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13978     std::string Str;
13979     llvm::raw_string_ostream S(Str);
13980     E->printPretty(S, nullptr, getPrintingPolicy());
13981     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13982                                 : diag::warn_cast_nonnull_to_bool;
13983     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13984       << E->getSourceRange() << Range << IsEqual;
13985     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13986   };
13987 
13988   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13989   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13990     if (auto *Callee = Call->getDirectCallee()) {
13991       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13992         ComplainAboutNonnullParamOrCall(A);
13993         return;
13994       }
13995     }
13996   }
13997 
13998   // Expect to find a single Decl.  Skip anything more complicated.
13999   ValueDecl *D = nullptr;
14000   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14001     D = R->getDecl();
14002   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14003     D = M->getMemberDecl();
14004   }
14005 
14006   // Weak Decls can be null.
14007   if (!D || D->isWeak())
14008     return;
14009 
14010   // Check for parameter decl with nonnull attribute
14011   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14012     if (getCurFunction() &&
14013         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14014       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14015         ComplainAboutNonnullParamOrCall(A);
14016         return;
14017       }
14018 
14019       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14020         // Skip function template not specialized yet.
14021         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14022           return;
14023         auto ParamIter = llvm::find(FD->parameters(), PV);
14024         assert(ParamIter != FD->param_end());
14025         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14026 
14027         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14028           if (!NonNull->args_size()) {
14029               ComplainAboutNonnullParamOrCall(NonNull);
14030               return;
14031           }
14032 
14033           for (const ParamIdx &ArgNo : NonNull->args()) {
14034             if (ArgNo.getASTIndex() == ParamNo) {
14035               ComplainAboutNonnullParamOrCall(NonNull);
14036               return;
14037             }
14038           }
14039         }
14040       }
14041     }
14042   }
14043 
14044   QualType T = D->getType();
14045   const bool IsArray = T->isArrayType();
14046   const bool IsFunction = T->isFunctionType();
14047 
14048   // Address of function is used to silence the function warning.
14049   if (IsAddressOf && IsFunction) {
14050     return;
14051   }
14052 
14053   // Found nothing.
14054   if (!IsAddressOf && !IsFunction && !IsArray)
14055     return;
14056 
14057   // Pretty print the expression for the diagnostic.
14058   std::string Str;
14059   llvm::raw_string_ostream S(Str);
14060   E->printPretty(S, nullptr, getPrintingPolicy());
14061 
14062   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14063                               : diag::warn_impcast_pointer_to_bool;
14064   enum {
14065     AddressOf,
14066     FunctionPointer,
14067     ArrayPointer
14068   } DiagType;
14069   if (IsAddressOf)
14070     DiagType = AddressOf;
14071   else if (IsFunction)
14072     DiagType = FunctionPointer;
14073   else if (IsArray)
14074     DiagType = ArrayPointer;
14075   else
14076     llvm_unreachable("Could not determine diagnostic.");
14077   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14078                                 << Range << IsEqual;
14079 
14080   if (!IsFunction)
14081     return;
14082 
14083   // Suggest '&' to silence the function warning.
14084   Diag(E->getExprLoc(), diag::note_function_warning_silence)
14085       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
14086 
14087   // Check to see if '()' fixit should be emitted.
14088   QualType ReturnType;
14089   UnresolvedSet<4> NonTemplateOverloads;
14090   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14091   if (ReturnType.isNull())
14092     return;
14093 
14094   if (IsCompare) {
14095     // There are two cases here.  If there is null constant, the only suggest
14096     // for a pointer return type.  If the null is 0, then suggest if the return
14097     // type is a pointer or an integer type.
14098     if (!ReturnType->isPointerType()) {
14099       if (NullKind == Expr::NPCK_ZeroExpression ||
14100           NullKind == Expr::NPCK_ZeroLiteral) {
14101         if (!ReturnType->isIntegerType())
14102           return;
14103       } else {
14104         return;
14105       }
14106     }
14107   } else { // !IsCompare
14108     // For function to bool, only suggest if the function pointer has bool
14109     // return type.
14110     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14111       return;
14112   }
14113   Diag(E->getExprLoc(), diag::note_function_to_function_call)
14114       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
14115 }
14116 
14117 /// Diagnoses "dangerous" implicit conversions within the given
14118 /// expression (which is a full expression).  Implements -Wconversion
14119 /// and -Wsign-compare.
14120 ///
14121 /// \param CC the "context" location of the implicit conversion, i.e.
14122 ///   the most location of the syntactic entity requiring the implicit
14123 ///   conversion
14124 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14125   // Don't diagnose in unevaluated contexts.
14126   if (isUnevaluatedContext())
14127     return;
14128 
14129   // Don't diagnose for value- or type-dependent expressions.
14130   if (E->isTypeDependent() || E->isValueDependent())
14131     return;
14132 
14133   // Check for array bounds violations in cases where the check isn't triggered
14134   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14135   // ArraySubscriptExpr is on the RHS of a variable initialization.
14136   CheckArrayAccess(E);
14137 
14138   // This is not the right CC for (e.g.) a variable initialization.
14139   AnalyzeImplicitConversions(*this, E, CC);
14140 }
14141 
14142 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
14143 /// Input argument E is a logical expression.
14144 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14145   ::CheckBoolLikeConversion(*this, E, CC);
14146 }
14147 
14148 /// Diagnose when expression is an integer constant expression and its evaluation
14149 /// results in integer overflow
14150 void Sema::CheckForIntOverflow (Expr *E) {
14151   // Use a work list to deal with nested struct initializers.
14152   SmallVector<Expr *, 2> Exprs(1, E);
14153 
14154   do {
14155     Expr *OriginalE = Exprs.pop_back_val();
14156     Expr *E = OriginalE->IgnoreParenCasts();
14157 
14158     if (isa<BinaryOperator>(E)) {
14159       E->EvaluateForOverflow(Context);
14160       continue;
14161     }
14162 
14163     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14164       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14165     else if (isa<ObjCBoxedExpr>(OriginalE))
14166       E->EvaluateForOverflow(Context);
14167     else if (auto Call = dyn_cast<CallExpr>(E))
14168       Exprs.append(Call->arg_begin(), Call->arg_end());
14169     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14170       Exprs.append(Message->arg_begin(), Message->arg_end());
14171   } while (!Exprs.empty());
14172 }
14173 
14174 namespace {
14175 
14176 /// Visitor for expressions which looks for unsequenced operations on the
14177 /// same object.
14178 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14179   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14180 
14181   /// A tree of sequenced regions within an expression. Two regions are
14182   /// unsequenced if one is an ancestor or a descendent of the other. When we
14183   /// finish processing an expression with sequencing, such as a comma
14184   /// expression, we fold its tree nodes into its parent, since they are
14185   /// unsequenced with respect to nodes we will visit later.
14186   class SequenceTree {
14187     struct Value {
14188       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14189       unsigned Parent : 31;
14190       unsigned Merged : 1;
14191     };
14192     SmallVector<Value, 8> Values;
14193 
14194   public:
14195     /// A region within an expression which may be sequenced with respect
14196     /// to some other region.
14197     class Seq {
14198       friend class SequenceTree;
14199 
14200       unsigned Index;
14201 
14202       explicit Seq(unsigned N) : Index(N) {}
14203 
14204     public:
14205       Seq() : Index(0) {}
14206     };
14207 
14208     SequenceTree() { Values.push_back(Value(0)); }
14209     Seq root() const { return Seq(0); }
14210 
14211     /// Create a new sequence of operations, which is an unsequenced
14212     /// subset of \p Parent. This sequence of operations is sequenced with
14213     /// respect to other children of \p Parent.
14214     Seq allocate(Seq Parent) {
14215       Values.push_back(Value(Parent.Index));
14216       return Seq(Values.size() - 1);
14217     }
14218 
14219     /// Merge a sequence of operations into its parent.
14220     void merge(Seq S) {
14221       Values[S.Index].Merged = true;
14222     }
14223 
14224     /// Determine whether two operations are unsequenced. This operation
14225     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14226     /// should have been merged into its parent as appropriate.
14227     bool isUnsequenced(Seq Cur, Seq Old) {
14228       unsigned C = representative(Cur.Index);
14229       unsigned Target = representative(Old.Index);
14230       while (C >= Target) {
14231         if (C == Target)
14232           return true;
14233         C = Values[C].Parent;
14234       }
14235       return false;
14236     }
14237 
14238   private:
14239     /// Pick a representative for a sequence.
14240     unsigned representative(unsigned K) {
14241       if (Values[K].Merged)
14242         // Perform path compression as we go.
14243         return Values[K].Parent = representative(Values[K].Parent);
14244       return K;
14245     }
14246   };
14247 
14248   /// An object for which we can track unsequenced uses.
14249   using Object = const NamedDecl *;
14250 
14251   /// Different flavors of object usage which we track. We only track the
14252   /// least-sequenced usage of each kind.
14253   enum UsageKind {
14254     /// A read of an object. Multiple unsequenced reads are OK.
14255     UK_Use,
14256 
14257     /// A modification of an object which is sequenced before the value
14258     /// computation of the expression, such as ++n in C++.
14259     UK_ModAsValue,
14260 
14261     /// A modification of an object which is not sequenced before the value
14262     /// computation of the expression, such as n++.
14263     UK_ModAsSideEffect,
14264 
14265     UK_Count = UK_ModAsSideEffect + 1
14266   };
14267 
14268   /// Bundle together a sequencing region and the expression corresponding
14269   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14270   struct Usage {
14271     const Expr *UsageExpr;
14272     SequenceTree::Seq Seq;
14273 
14274     Usage() : UsageExpr(nullptr) {}
14275   };
14276 
14277   struct UsageInfo {
14278     Usage Uses[UK_Count];
14279 
14280     /// Have we issued a diagnostic for this object already?
14281     bool Diagnosed;
14282 
14283     UsageInfo() : Diagnosed(false) {}
14284   };
14285   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14286 
14287   Sema &SemaRef;
14288 
14289   /// Sequenced regions within the expression.
14290   SequenceTree Tree;
14291 
14292   /// Declaration modifications and references which we have seen.
14293   UsageInfoMap UsageMap;
14294 
14295   /// The region we are currently within.
14296   SequenceTree::Seq Region;
14297 
14298   /// Filled in with declarations which were modified as a side-effect
14299   /// (that is, post-increment operations).
14300   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14301 
14302   /// Expressions to check later. We defer checking these to reduce
14303   /// stack usage.
14304   SmallVectorImpl<const Expr *> &WorkList;
14305 
14306   /// RAII object wrapping the visitation of a sequenced subexpression of an
14307   /// expression. At the end of this process, the side-effects of the evaluation
14308   /// become sequenced with respect to the value computation of the result, so
14309   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14310   /// UK_ModAsValue.
14311   struct SequencedSubexpression {
14312     SequencedSubexpression(SequenceChecker &Self)
14313       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14314       Self.ModAsSideEffect = &ModAsSideEffect;
14315     }
14316 
14317     ~SequencedSubexpression() {
14318       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14319         // Add a new usage with usage kind UK_ModAsValue, and then restore
14320         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14321         // the previous one was empty).
14322         UsageInfo &UI = Self.UsageMap[M.first];
14323         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14324         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14325         SideEffectUsage = M.second;
14326       }
14327       Self.ModAsSideEffect = OldModAsSideEffect;
14328     }
14329 
14330     SequenceChecker &Self;
14331     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14332     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14333   };
14334 
14335   /// RAII object wrapping the visitation of a subexpression which we might
14336   /// choose to evaluate as a constant. If any subexpression is evaluated and
14337   /// found to be non-constant, this allows us to suppress the evaluation of
14338   /// the outer expression.
14339   class EvaluationTracker {
14340   public:
14341     EvaluationTracker(SequenceChecker &Self)
14342         : Self(Self), Prev(Self.EvalTracker) {
14343       Self.EvalTracker = this;
14344     }
14345 
14346     ~EvaluationTracker() {
14347       Self.EvalTracker = Prev;
14348       if (Prev)
14349         Prev->EvalOK &= EvalOK;
14350     }
14351 
14352     bool evaluate(const Expr *E, bool &Result) {
14353       if (!EvalOK || E->isValueDependent())
14354         return false;
14355       EvalOK = E->EvaluateAsBooleanCondition(
14356           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14357       return EvalOK;
14358     }
14359 
14360   private:
14361     SequenceChecker &Self;
14362     EvaluationTracker *Prev;
14363     bool EvalOK = true;
14364   } *EvalTracker = nullptr;
14365 
14366   /// Find the object which is produced by the specified expression,
14367   /// if any.
14368   Object getObject(const Expr *E, bool Mod) const {
14369     E = E->IgnoreParenCasts();
14370     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14371       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14372         return getObject(UO->getSubExpr(), Mod);
14373     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14374       if (BO->getOpcode() == BO_Comma)
14375         return getObject(BO->getRHS(), Mod);
14376       if (Mod && BO->isAssignmentOp())
14377         return getObject(BO->getLHS(), Mod);
14378     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14379       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14380       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14381         return ME->getMemberDecl();
14382     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14383       // FIXME: If this is a reference, map through to its value.
14384       return DRE->getDecl();
14385     return nullptr;
14386   }
14387 
14388   /// Note that an object \p O was modified or used by an expression
14389   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14390   /// the object \p O as obtained via the \p UsageMap.
14391   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14392     // Get the old usage for the given object and usage kind.
14393     Usage &U = UI.Uses[UK];
14394     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14395       // If we have a modification as side effect and are in a sequenced
14396       // subexpression, save the old Usage so that we can restore it later
14397       // in SequencedSubexpression::~SequencedSubexpression.
14398       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14399         ModAsSideEffect->push_back(std::make_pair(O, U));
14400       // Then record the new usage with the current sequencing region.
14401       U.UsageExpr = UsageExpr;
14402       U.Seq = Region;
14403     }
14404   }
14405 
14406   /// Check whether a modification or use of an object \p O in an expression
14407   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14408   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14409   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14410   /// usage and false we are checking for a mod-use unsequenced usage.
14411   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14412                   UsageKind OtherKind, bool IsModMod) {
14413     if (UI.Diagnosed)
14414       return;
14415 
14416     const Usage &U = UI.Uses[OtherKind];
14417     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14418       return;
14419 
14420     const Expr *Mod = U.UsageExpr;
14421     const Expr *ModOrUse = UsageExpr;
14422     if (OtherKind == UK_Use)
14423       std::swap(Mod, ModOrUse);
14424 
14425     SemaRef.DiagRuntimeBehavior(
14426         Mod->getExprLoc(), {Mod, ModOrUse},
14427         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14428                                : diag::warn_unsequenced_mod_use)
14429             << O << SourceRange(ModOrUse->getExprLoc()));
14430     UI.Diagnosed = true;
14431   }
14432 
14433   // A note on note{Pre, Post}{Use, Mod}:
14434   //
14435   // (It helps to follow the algorithm with an expression such as
14436   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14437   //  operations before C++17 and both are well-defined in C++17).
14438   //
14439   // When visiting a node which uses/modify an object we first call notePreUse
14440   // or notePreMod before visiting its sub-expression(s). At this point the
14441   // children of the current node have not yet been visited and so the eventual
14442   // uses/modifications resulting from the children of the current node have not
14443   // been recorded yet.
14444   //
14445   // We then visit the children of the current node. After that notePostUse or
14446   // notePostMod is called. These will 1) detect an unsequenced modification
14447   // as side effect (as in "k++ + k") and 2) add a new usage with the
14448   // appropriate usage kind.
14449   //
14450   // We also have to be careful that some operation sequences modification as
14451   // side effect as well (for example: || or ,). To account for this we wrap
14452   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14453   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14454   // which record usages which are modifications as side effect, and then
14455   // downgrade them (or more accurately restore the previous usage which was a
14456   // modification as side effect) when exiting the scope of the sequenced
14457   // subexpression.
14458 
14459   void notePreUse(Object O, const Expr *UseExpr) {
14460     UsageInfo &UI = UsageMap[O];
14461     // Uses conflict with other modifications.
14462     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14463   }
14464 
14465   void notePostUse(Object O, const Expr *UseExpr) {
14466     UsageInfo &UI = UsageMap[O];
14467     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14468                /*IsModMod=*/false);
14469     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14470   }
14471 
14472   void notePreMod(Object O, const Expr *ModExpr) {
14473     UsageInfo &UI = UsageMap[O];
14474     // Modifications conflict with other modifications and with uses.
14475     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14476     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14477   }
14478 
14479   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14480     UsageInfo &UI = UsageMap[O];
14481     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14482                /*IsModMod=*/true);
14483     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14484   }
14485 
14486 public:
14487   SequenceChecker(Sema &S, const Expr *E,
14488                   SmallVectorImpl<const Expr *> &WorkList)
14489       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14490     Visit(E);
14491     // Silence a -Wunused-private-field since WorkList is now unused.
14492     // TODO: Evaluate if it can be used, and if not remove it.
14493     (void)this->WorkList;
14494   }
14495 
14496   void VisitStmt(const Stmt *S) {
14497     // Skip all statements which aren't expressions for now.
14498   }
14499 
14500   void VisitExpr(const Expr *E) {
14501     // By default, just recurse to evaluated subexpressions.
14502     Base::VisitStmt(E);
14503   }
14504 
14505   void VisitCastExpr(const CastExpr *E) {
14506     Object O = Object();
14507     if (E->getCastKind() == CK_LValueToRValue)
14508       O = getObject(E->getSubExpr(), false);
14509 
14510     if (O)
14511       notePreUse(O, E);
14512     VisitExpr(E);
14513     if (O)
14514       notePostUse(O, E);
14515   }
14516 
14517   void VisitSequencedExpressions(const Expr *SequencedBefore,
14518                                  const Expr *SequencedAfter) {
14519     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14520     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14521     SequenceTree::Seq OldRegion = Region;
14522 
14523     {
14524       SequencedSubexpression SeqBefore(*this);
14525       Region = BeforeRegion;
14526       Visit(SequencedBefore);
14527     }
14528 
14529     Region = AfterRegion;
14530     Visit(SequencedAfter);
14531 
14532     Region = OldRegion;
14533 
14534     Tree.merge(BeforeRegion);
14535     Tree.merge(AfterRegion);
14536   }
14537 
14538   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14539     // C++17 [expr.sub]p1:
14540     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14541     //   expression E1 is sequenced before the expression E2.
14542     if (SemaRef.getLangOpts().CPlusPlus17)
14543       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14544     else {
14545       Visit(ASE->getLHS());
14546       Visit(ASE->getRHS());
14547     }
14548   }
14549 
14550   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14551   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14552   void VisitBinPtrMem(const BinaryOperator *BO) {
14553     // C++17 [expr.mptr.oper]p4:
14554     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14555     //  the expression E1 is sequenced before the expression E2.
14556     if (SemaRef.getLangOpts().CPlusPlus17)
14557       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14558     else {
14559       Visit(BO->getLHS());
14560       Visit(BO->getRHS());
14561     }
14562   }
14563 
14564   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14565   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14566   void VisitBinShlShr(const BinaryOperator *BO) {
14567     // C++17 [expr.shift]p4:
14568     //  The expression E1 is sequenced before the expression E2.
14569     if (SemaRef.getLangOpts().CPlusPlus17)
14570       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14571     else {
14572       Visit(BO->getLHS());
14573       Visit(BO->getRHS());
14574     }
14575   }
14576 
14577   void VisitBinComma(const BinaryOperator *BO) {
14578     // C++11 [expr.comma]p1:
14579     //   Every value computation and side effect associated with the left
14580     //   expression is sequenced before every value computation and side
14581     //   effect associated with the right expression.
14582     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14583   }
14584 
14585   void VisitBinAssign(const BinaryOperator *BO) {
14586     SequenceTree::Seq RHSRegion;
14587     SequenceTree::Seq LHSRegion;
14588     if (SemaRef.getLangOpts().CPlusPlus17) {
14589       RHSRegion = Tree.allocate(Region);
14590       LHSRegion = Tree.allocate(Region);
14591     } else {
14592       RHSRegion = Region;
14593       LHSRegion = Region;
14594     }
14595     SequenceTree::Seq OldRegion = Region;
14596 
14597     // C++11 [expr.ass]p1:
14598     //  [...] the assignment is sequenced after the value computation
14599     //  of the right and left operands, [...]
14600     //
14601     // so check it before inspecting the operands and update the
14602     // map afterwards.
14603     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14604     if (O)
14605       notePreMod(O, BO);
14606 
14607     if (SemaRef.getLangOpts().CPlusPlus17) {
14608       // C++17 [expr.ass]p1:
14609       //  [...] The right operand is sequenced before the left operand. [...]
14610       {
14611         SequencedSubexpression SeqBefore(*this);
14612         Region = RHSRegion;
14613         Visit(BO->getRHS());
14614       }
14615 
14616       Region = LHSRegion;
14617       Visit(BO->getLHS());
14618 
14619       if (O && isa<CompoundAssignOperator>(BO))
14620         notePostUse(O, BO);
14621 
14622     } else {
14623       // C++11 does not specify any sequencing between the LHS and RHS.
14624       Region = LHSRegion;
14625       Visit(BO->getLHS());
14626 
14627       if (O && isa<CompoundAssignOperator>(BO))
14628         notePostUse(O, BO);
14629 
14630       Region = RHSRegion;
14631       Visit(BO->getRHS());
14632     }
14633 
14634     // C++11 [expr.ass]p1:
14635     //  the assignment is sequenced [...] before the value computation of the
14636     //  assignment expression.
14637     // C11 6.5.16/3 has no such rule.
14638     Region = OldRegion;
14639     if (O)
14640       notePostMod(O, BO,
14641                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14642                                                   : UK_ModAsSideEffect);
14643     if (SemaRef.getLangOpts().CPlusPlus17) {
14644       Tree.merge(RHSRegion);
14645       Tree.merge(LHSRegion);
14646     }
14647   }
14648 
14649   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14650     VisitBinAssign(CAO);
14651   }
14652 
14653   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14654   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14655   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14656     Object O = getObject(UO->getSubExpr(), true);
14657     if (!O)
14658       return VisitExpr(UO);
14659 
14660     notePreMod(O, UO);
14661     Visit(UO->getSubExpr());
14662     // C++11 [expr.pre.incr]p1:
14663     //   the expression ++x is equivalent to x+=1
14664     notePostMod(O, UO,
14665                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14666                                                 : UK_ModAsSideEffect);
14667   }
14668 
14669   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14670   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14671   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14672     Object O = getObject(UO->getSubExpr(), true);
14673     if (!O)
14674       return VisitExpr(UO);
14675 
14676     notePreMod(O, UO);
14677     Visit(UO->getSubExpr());
14678     notePostMod(O, UO, UK_ModAsSideEffect);
14679   }
14680 
14681   void VisitBinLOr(const BinaryOperator *BO) {
14682     // C++11 [expr.log.or]p2:
14683     //  If the second expression is evaluated, every value computation and
14684     //  side effect associated with the first expression is sequenced before
14685     //  every value computation and side effect associated with the
14686     //  second expression.
14687     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14688     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14689     SequenceTree::Seq OldRegion = Region;
14690 
14691     EvaluationTracker Eval(*this);
14692     {
14693       SequencedSubexpression Sequenced(*this);
14694       Region = LHSRegion;
14695       Visit(BO->getLHS());
14696     }
14697 
14698     // C++11 [expr.log.or]p1:
14699     //  [...] the second operand is not evaluated if the first operand
14700     //  evaluates to true.
14701     bool EvalResult = false;
14702     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14703     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14704     if (ShouldVisitRHS) {
14705       Region = RHSRegion;
14706       Visit(BO->getRHS());
14707     }
14708 
14709     Region = OldRegion;
14710     Tree.merge(LHSRegion);
14711     Tree.merge(RHSRegion);
14712   }
14713 
14714   void VisitBinLAnd(const BinaryOperator *BO) {
14715     // C++11 [expr.log.and]p2:
14716     //  If the second expression is evaluated, every value computation and
14717     //  side effect associated with the first expression is sequenced before
14718     //  every value computation and side effect associated with the
14719     //  second expression.
14720     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14721     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14722     SequenceTree::Seq OldRegion = Region;
14723 
14724     EvaluationTracker Eval(*this);
14725     {
14726       SequencedSubexpression Sequenced(*this);
14727       Region = LHSRegion;
14728       Visit(BO->getLHS());
14729     }
14730 
14731     // C++11 [expr.log.and]p1:
14732     //  [...] the second operand is not evaluated if the first operand is false.
14733     bool EvalResult = false;
14734     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14735     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14736     if (ShouldVisitRHS) {
14737       Region = RHSRegion;
14738       Visit(BO->getRHS());
14739     }
14740 
14741     Region = OldRegion;
14742     Tree.merge(LHSRegion);
14743     Tree.merge(RHSRegion);
14744   }
14745 
14746   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14747     // C++11 [expr.cond]p1:
14748     //  [...] Every value computation and side effect associated with the first
14749     //  expression is sequenced before every value computation and side effect
14750     //  associated with the second or third expression.
14751     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14752 
14753     // No sequencing is specified between the true and false expression.
14754     // However since exactly one of both is going to be evaluated we can
14755     // consider them to be sequenced. This is needed to avoid warning on
14756     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14757     // both the true and false expressions because we can't evaluate x.
14758     // This will still allow us to detect an expression like (pre C++17)
14759     // "(x ? y += 1 : y += 2) = y".
14760     //
14761     // We don't wrap the visitation of the true and false expression with
14762     // SequencedSubexpression because we don't want to downgrade modifications
14763     // as side effect in the true and false expressions after the visition
14764     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14765     // not warn between the two "y++", but we should warn between the "y++"
14766     // and the "y".
14767     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14768     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14769     SequenceTree::Seq OldRegion = Region;
14770 
14771     EvaluationTracker Eval(*this);
14772     {
14773       SequencedSubexpression Sequenced(*this);
14774       Region = ConditionRegion;
14775       Visit(CO->getCond());
14776     }
14777 
14778     // C++11 [expr.cond]p1:
14779     // [...] The first expression is contextually converted to bool (Clause 4).
14780     // It is evaluated and if it is true, the result of the conditional
14781     // expression is the value of the second expression, otherwise that of the
14782     // third expression. Only one of the second and third expressions is
14783     // evaluated. [...]
14784     bool EvalResult = false;
14785     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14786     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14787     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14788     if (ShouldVisitTrueExpr) {
14789       Region = TrueRegion;
14790       Visit(CO->getTrueExpr());
14791     }
14792     if (ShouldVisitFalseExpr) {
14793       Region = FalseRegion;
14794       Visit(CO->getFalseExpr());
14795     }
14796 
14797     Region = OldRegion;
14798     Tree.merge(ConditionRegion);
14799     Tree.merge(TrueRegion);
14800     Tree.merge(FalseRegion);
14801   }
14802 
14803   void VisitCallExpr(const CallExpr *CE) {
14804     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14805 
14806     if (CE->isUnevaluatedBuiltinCall(Context))
14807       return;
14808 
14809     // C++11 [intro.execution]p15:
14810     //   When calling a function [...], every value computation and side effect
14811     //   associated with any argument expression, or with the postfix expression
14812     //   designating the called function, is sequenced before execution of every
14813     //   expression or statement in the body of the function [and thus before
14814     //   the value computation of its result].
14815     SequencedSubexpression Sequenced(*this);
14816     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14817       // C++17 [expr.call]p5
14818       //   The postfix-expression is sequenced before each expression in the
14819       //   expression-list and any default argument. [...]
14820       SequenceTree::Seq CalleeRegion;
14821       SequenceTree::Seq OtherRegion;
14822       if (SemaRef.getLangOpts().CPlusPlus17) {
14823         CalleeRegion = Tree.allocate(Region);
14824         OtherRegion = Tree.allocate(Region);
14825       } else {
14826         CalleeRegion = Region;
14827         OtherRegion = Region;
14828       }
14829       SequenceTree::Seq OldRegion = Region;
14830 
14831       // Visit the callee expression first.
14832       Region = CalleeRegion;
14833       if (SemaRef.getLangOpts().CPlusPlus17) {
14834         SequencedSubexpression Sequenced(*this);
14835         Visit(CE->getCallee());
14836       } else {
14837         Visit(CE->getCallee());
14838       }
14839 
14840       // Then visit the argument expressions.
14841       Region = OtherRegion;
14842       for (const Expr *Argument : CE->arguments())
14843         Visit(Argument);
14844 
14845       Region = OldRegion;
14846       if (SemaRef.getLangOpts().CPlusPlus17) {
14847         Tree.merge(CalleeRegion);
14848         Tree.merge(OtherRegion);
14849       }
14850     });
14851   }
14852 
14853   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14854     // C++17 [over.match.oper]p2:
14855     //   [...] the operator notation is first transformed to the equivalent
14856     //   function-call notation as summarized in Table 12 (where @ denotes one
14857     //   of the operators covered in the specified subclause). However, the
14858     //   operands are sequenced in the order prescribed for the built-in
14859     //   operator (Clause 8).
14860     //
14861     // From the above only overloaded binary operators and overloaded call
14862     // operators have sequencing rules in C++17 that we need to handle
14863     // separately.
14864     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14865         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14866       return VisitCallExpr(CXXOCE);
14867 
14868     enum {
14869       NoSequencing,
14870       LHSBeforeRHS,
14871       RHSBeforeLHS,
14872       LHSBeforeRest
14873     } SequencingKind;
14874     switch (CXXOCE->getOperator()) {
14875     case OO_Equal:
14876     case OO_PlusEqual:
14877     case OO_MinusEqual:
14878     case OO_StarEqual:
14879     case OO_SlashEqual:
14880     case OO_PercentEqual:
14881     case OO_CaretEqual:
14882     case OO_AmpEqual:
14883     case OO_PipeEqual:
14884     case OO_LessLessEqual:
14885     case OO_GreaterGreaterEqual:
14886       SequencingKind = RHSBeforeLHS;
14887       break;
14888 
14889     case OO_LessLess:
14890     case OO_GreaterGreater:
14891     case OO_AmpAmp:
14892     case OO_PipePipe:
14893     case OO_Comma:
14894     case OO_ArrowStar:
14895     case OO_Subscript:
14896       SequencingKind = LHSBeforeRHS;
14897       break;
14898 
14899     case OO_Call:
14900       SequencingKind = LHSBeforeRest;
14901       break;
14902 
14903     default:
14904       SequencingKind = NoSequencing;
14905       break;
14906     }
14907 
14908     if (SequencingKind == NoSequencing)
14909       return VisitCallExpr(CXXOCE);
14910 
14911     // This is a call, so all subexpressions are sequenced before the result.
14912     SequencedSubexpression Sequenced(*this);
14913 
14914     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14915       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14916              "Should only get there with C++17 and above!");
14917       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14918              "Should only get there with an overloaded binary operator"
14919              " or an overloaded call operator!");
14920 
14921       if (SequencingKind == LHSBeforeRest) {
14922         assert(CXXOCE->getOperator() == OO_Call &&
14923                "We should only have an overloaded call operator here!");
14924 
14925         // This is very similar to VisitCallExpr, except that we only have the
14926         // C++17 case. The postfix-expression is the first argument of the
14927         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14928         // are in the following arguments.
14929         //
14930         // Note that we intentionally do not visit the callee expression since
14931         // it is just a decayed reference to a function.
14932         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14933         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14934         SequenceTree::Seq OldRegion = Region;
14935 
14936         assert(CXXOCE->getNumArgs() >= 1 &&
14937                "An overloaded call operator must have at least one argument"
14938                " for the postfix-expression!");
14939         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14940         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14941                                           CXXOCE->getNumArgs() - 1);
14942 
14943         // Visit the postfix-expression first.
14944         {
14945           Region = PostfixExprRegion;
14946           SequencedSubexpression Sequenced(*this);
14947           Visit(PostfixExpr);
14948         }
14949 
14950         // Then visit the argument expressions.
14951         Region = ArgsRegion;
14952         for (const Expr *Arg : Args)
14953           Visit(Arg);
14954 
14955         Region = OldRegion;
14956         Tree.merge(PostfixExprRegion);
14957         Tree.merge(ArgsRegion);
14958       } else {
14959         assert(CXXOCE->getNumArgs() == 2 &&
14960                "Should only have two arguments here!");
14961         assert((SequencingKind == LHSBeforeRHS ||
14962                 SequencingKind == RHSBeforeLHS) &&
14963                "Unexpected sequencing kind!");
14964 
14965         // We do not visit the callee expression since it is just a decayed
14966         // reference to a function.
14967         const Expr *E1 = CXXOCE->getArg(0);
14968         const Expr *E2 = CXXOCE->getArg(1);
14969         if (SequencingKind == RHSBeforeLHS)
14970           std::swap(E1, E2);
14971 
14972         return VisitSequencedExpressions(E1, E2);
14973       }
14974     });
14975   }
14976 
14977   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14978     // This is a call, so all subexpressions are sequenced before the result.
14979     SequencedSubexpression Sequenced(*this);
14980 
14981     if (!CCE->isListInitialization())
14982       return VisitExpr(CCE);
14983 
14984     // In C++11, list initializations are sequenced.
14985     SmallVector<SequenceTree::Seq, 32> Elts;
14986     SequenceTree::Seq Parent = Region;
14987     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14988                                               E = CCE->arg_end();
14989          I != E; ++I) {
14990       Region = Tree.allocate(Parent);
14991       Elts.push_back(Region);
14992       Visit(*I);
14993     }
14994 
14995     // Forget that the initializers are sequenced.
14996     Region = Parent;
14997     for (unsigned I = 0; I < Elts.size(); ++I)
14998       Tree.merge(Elts[I]);
14999   }
15000 
15001   void VisitInitListExpr(const InitListExpr *ILE) {
15002     if (!SemaRef.getLangOpts().CPlusPlus11)
15003       return VisitExpr(ILE);
15004 
15005     // In C++11, list initializations are sequenced.
15006     SmallVector<SequenceTree::Seq, 32> Elts;
15007     SequenceTree::Seq Parent = Region;
15008     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
15009       const Expr *E = ILE->getInit(I);
15010       if (!E)
15011         continue;
15012       Region = Tree.allocate(Parent);
15013       Elts.push_back(Region);
15014       Visit(E);
15015     }
15016 
15017     // Forget that the initializers are sequenced.
15018     Region = Parent;
15019     for (unsigned I = 0; I < Elts.size(); ++I)
15020       Tree.merge(Elts[I]);
15021   }
15022 };
15023 
15024 } // namespace
15025 
15026 void Sema::CheckUnsequencedOperations(const Expr *E) {
15027   SmallVector<const Expr *, 8> WorkList;
15028   WorkList.push_back(E);
15029   while (!WorkList.empty()) {
15030     const Expr *Item = WorkList.pop_back_val();
15031     SequenceChecker(*this, Item, WorkList);
15032   }
15033 }
15034 
15035 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15036                               bool IsConstexpr) {
15037   llvm::SaveAndRestore<bool> ConstantContext(
15038       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
15039   CheckImplicitConversions(E, CheckLoc);
15040   if (!E->isInstantiationDependent())
15041     CheckUnsequencedOperations(E);
15042   if (!IsConstexpr && !E->isValueDependent())
15043     CheckForIntOverflow(E);
15044   DiagnoseMisalignedMembers();
15045 }
15046 
15047 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15048                                        FieldDecl *BitField,
15049                                        Expr *Init) {
15050   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15051 }
15052 
15053 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15054                                          SourceLocation Loc) {
15055   if (!PType->isVariablyModifiedType())
15056     return;
15057   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15058     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15059     return;
15060   }
15061   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15062     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15063     return;
15064   }
15065   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15066     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15067     return;
15068   }
15069 
15070   const ArrayType *AT = S.Context.getAsArrayType(PType);
15071   if (!AT)
15072     return;
15073 
15074   if (AT->getSizeModifier() != ArrayType::Star) {
15075     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
15076     return;
15077   }
15078 
15079   S.Diag(Loc, diag::err_array_star_in_function_definition);
15080 }
15081 
15082 /// CheckParmsForFunctionDef - Check that the parameters of the given
15083 /// function are appropriate for the definition of a function. This
15084 /// takes care of any checks that cannot be performed on the
15085 /// declaration itself, e.g., that the types of each of the function
15086 /// parameters are complete.
15087 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15088                                     bool CheckParameterNames) {
15089   bool HasInvalidParm = false;
15090   for (ParmVarDecl *Param : Parameters) {
15091     // C99 6.7.5.3p4: the parameters in a parameter type list in a
15092     // function declarator that is part of a function definition of
15093     // that function shall not have incomplete type.
15094     //
15095     // This is also C++ [dcl.fct]p6.
15096     if (!Param->isInvalidDecl() &&
15097         RequireCompleteType(Param->getLocation(), Param->getType(),
15098                             diag::err_typecheck_decl_incomplete_type)) {
15099       Param->setInvalidDecl();
15100       HasInvalidParm = true;
15101     }
15102 
15103     // C99 6.9.1p5: If the declarator includes a parameter type list, the
15104     // declaration of each parameter shall include an identifier.
15105     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15106         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15107       // Diagnose this as an extension in C17 and earlier.
15108       if (!getLangOpts().C2x)
15109         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15110     }
15111 
15112     // C99 6.7.5.3p12:
15113     //   If the function declarator is not part of a definition of that
15114     //   function, parameters may have incomplete type and may use the [*]
15115     //   notation in their sequences of declarator specifiers to specify
15116     //   variable length array types.
15117     QualType PType = Param->getOriginalType();
15118     // FIXME: This diagnostic should point the '[*]' if source-location
15119     // information is added for it.
15120     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15121 
15122     // If the parameter is a c++ class type and it has to be destructed in the
15123     // callee function, declare the destructor so that it can be called by the
15124     // callee function. Do not perform any direct access check on the dtor here.
15125     if (!Param->isInvalidDecl()) {
15126       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15127         if (!ClassDecl->isInvalidDecl() &&
15128             !ClassDecl->hasIrrelevantDestructor() &&
15129             !ClassDecl->isDependentContext() &&
15130             ClassDecl->isParamDestroyedInCallee()) {
15131           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15132           MarkFunctionReferenced(Param->getLocation(), Destructor);
15133           DiagnoseUseOfDecl(Destructor, Param->getLocation());
15134         }
15135       }
15136     }
15137 
15138     // Parameters with the pass_object_size attribute only need to be marked
15139     // constant at function definitions. Because we lack information about
15140     // whether we're on a declaration or definition when we're instantiating the
15141     // attribute, we need to check for constness here.
15142     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15143       if (!Param->getType().isConstQualified())
15144         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15145             << Attr->getSpelling() << 1;
15146 
15147     // Check for parameter names shadowing fields from the class.
15148     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15149       // The owning context for the parameter should be the function, but we
15150       // want to see if this function's declaration context is a record.
15151       DeclContext *DC = Param->getDeclContext();
15152       if (DC && DC->isFunctionOrMethod()) {
15153         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15154           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15155                                      RD, /*DeclIsField*/ false);
15156       }
15157     }
15158   }
15159 
15160   return HasInvalidParm;
15161 }
15162 
15163 Optional<std::pair<CharUnits, CharUnits>>
15164 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15165 
15166 /// Compute the alignment and offset of the base class object given the
15167 /// derived-to-base cast expression and the alignment and offset of the derived
15168 /// class object.
15169 static std::pair<CharUnits, CharUnits>
15170 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15171                                    CharUnits BaseAlignment, CharUnits Offset,
15172                                    ASTContext &Ctx) {
15173   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15174        ++PathI) {
15175     const CXXBaseSpecifier *Base = *PathI;
15176     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15177     if (Base->isVirtual()) {
15178       // The complete object may have a lower alignment than the non-virtual
15179       // alignment of the base, in which case the base may be misaligned. Choose
15180       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15181       // conservative lower bound of the complete object alignment.
15182       CharUnits NonVirtualAlignment =
15183           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15184       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15185       Offset = CharUnits::Zero();
15186     } else {
15187       const ASTRecordLayout &RL =
15188           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15189       Offset += RL.getBaseClassOffset(BaseDecl);
15190     }
15191     DerivedType = Base->getType();
15192   }
15193 
15194   return std::make_pair(BaseAlignment, Offset);
15195 }
15196 
15197 /// Compute the alignment and offset of a binary additive operator.
15198 static Optional<std::pair<CharUnits, CharUnits>>
15199 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15200                                      bool IsSub, ASTContext &Ctx) {
15201   QualType PointeeType = PtrE->getType()->getPointeeType();
15202 
15203   if (!PointeeType->isConstantSizeType())
15204     return llvm::None;
15205 
15206   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15207 
15208   if (!P)
15209     return llvm::None;
15210 
15211   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15212   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15213     CharUnits Offset = EltSize * IdxRes->getExtValue();
15214     if (IsSub)
15215       Offset = -Offset;
15216     return std::make_pair(P->first, P->second + Offset);
15217   }
15218 
15219   // If the integer expression isn't a constant expression, compute the lower
15220   // bound of the alignment using the alignment and offset of the pointer
15221   // expression and the element size.
15222   return std::make_pair(
15223       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15224       CharUnits::Zero());
15225 }
15226 
15227 /// This helper function takes an lvalue expression and returns the alignment of
15228 /// a VarDecl and a constant offset from the VarDecl.
15229 Optional<std::pair<CharUnits, CharUnits>>
15230 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15231   E = E->IgnoreParens();
15232   switch (E->getStmtClass()) {
15233   default:
15234     break;
15235   case Stmt::CStyleCastExprClass:
15236   case Stmt::CXXStaticCastExprClass:
15237   case Stmt::ImplicitCastExprClass: {
15238     auto *CE = cast<CastExpr>(E);
15239     const Expr *From = CE->getSubExpr();
15240     switch (CE->getCastKind()) {
15241     default:
15242       break;
15243     case CK_NoOp:
15244       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15245     case CK_UncheckedDerivedToBase:
15246     case CK_DerivedToBase: {
15247       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15248       if (!P)
15249         break;
15250       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15251                                                 P->second, Ctx);
15252     }
15253     }
15254     break;
15255   }
15256   case Stmt::ArraySubscriptExprClass: {
15257     auto *ASE = cast<ArraySubscriptExpr>(E);
15258     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15259                                                 false, Ctx);
15260   }
15261   case Stmt::DeclRefExprClass: {
15262     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15263       // FIXME: If VD is captured by copy or is an escaping __block variable,
15264       // use the alignment of VD's type.
15265       if (!VD->getType()->isReferenceType())
15266         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15267       if (VD->hasInit())
15268         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15269     }
15270     break;
15271   }
15272   case Stmt::MemberExprClass: {
15273     auto *ME = cast<MemberExpr>(E);
15274     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15275     if (!FD || FD->getType()->isReferenceType() ||
15276         FD->getParent()->isInvalidDecl())
15277       break;
15278     Optional<std::pair<CharUnits, CharUnits>> P;
15279     if (ME->isArrow())
15280       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15281     else
15282       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15283     if (!P)
15284       break;
15285     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15286     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15287     return std::make_pair(P->first,
15288                           P->second + CharUnits::fromQuantity(Offset));
15289   }
15290   case Stmt::UnaryOperatorClass: {
15291     auto *UO = cast<UnaryOperator>(E);
15292     switch (UO->getOpcode()) {
15293     default:
15294       break;
15295     case UO_Deref:
15296       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15297     }
15298     break;
15299   }
15300   case Stmt::BinaryOperatorClass: {
15301     auto *BO = cast<BinaryOperator>(E);
15302     auto Opcode = BO->getOpcode();
15303     switch (Opcode) {
15304     default:
15305       break;
15306     case BO_Comma:
15307       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15308     }
15309     break;
15310   }
15311   }
15312   return llvm::None;
15313 }
15314 
15315 /// This helper function takes a pointer expression and returns the alignment of
15316 /// a VarDecl and a constant offset from the VarDecl.
15317 Optional<std::pair<CharUnits, CharUnits>>
15318 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15319   E = E->IgnoreParens();
15320   switch (E->getStmtClass()) {
15321   default:
15322     break;
15323   case Stmt::CStyleCastExprClass:
15324   case Stmt::CXXStaticCastExprClass:
15325   case Stmt::ImplicitCastExprClass: {
15326     auto *CE = cast<CastExpr>(E);
15327     const Expr *From = CE->getSubExpr();
15328     switch (CE->getCastKind()) {
15329     default:
15330       break;
15331     case CK_NoOp:
15332       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15333     case CK_ArrayToPointerDecay:
15334       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15335     case CK_UncheckedDerivedToBase:
15336     case CK_DerivedToBase: {
15337       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15338       if (!P)
15339         break;
15340       return getDerivedToBaseAlignmentAndOffset(
15341           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15342     }
15343     }
15344     break;
15345   }
15346   case Stmt::CXXThisExprClass: {
15347     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15348     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15349     return std::make_pair(Alignment, CharUnits::Zero());
15350   }
15351   case Stmt::UnaryOperatorClass: {
15352     auto *UO = cast<UnaryOperator>(E);
15353     if (UO->getOpcode() == UO_AddrOf)
15354       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15355     break;
15356   }
15357   case Stmt::BinaryOperatorClass: {
15358     auto *BO = cast<BinaryOperator>(E);
15359     auto Opcode = BO->getOpcode();
15360     switch (Opcode) {
15361     default:
15362       break;
15363     case BO_Add:
15364     case BO_Sub: {
15365       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15366       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15367         std::swap(LHS, RHS);
15368       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15369                                                   Ctx);
15370     }
15371     case BO_Comma:
15372       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15373     }
15374     break;
15375   }
15376   }
15377   return llvm::None;
15378 }
15379 
15380 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15381   // See if we can compute the alignment of a VarDecl and an offset from it.
15382   Optional<std::pair<CharUnits, CharUnits>> P =
15383       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15384 
15385   if (P)
15386     return P->first.alignmentAtOffset(P->second);
15387 
15388   // If that failed, return the type's alignment.
15389   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15390 }
15391 
15392 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15393 /// pointer cast increases the alignment requirements.
15394 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15395   // This is actually a lot of work to potentially be doing on every
15396   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15397   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15398     return;
15399 
15400   // Ignore dependent types.
15401   if (T->isDependentType() || Op->getType()->isDependentType())
15402     return;
15403 
15404   // Require that the destination be a pointer type.
15405   const PointerType *DestPtr = T->getAs<PointerType>();
15406   if (!DestPtr) return;
15407 
15408   // If the destination has alignment 1, we're done.
15409   QualType DestPointee = DestPtr->getPointeeType();
15410   if (DestPointee->isIncompleteType()) return;
15411   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15412   if (DestAlign.isOne()) return;
15413 
15414   // Require that the source be a pointer type.
15415   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15416   if (!SrcPtr) return;
15417   QualType SrcPointee = SrcPtr->getPointeeType();
15418 
15419   // Explicitly allow casts from cv void*.  We already implicitly
15420   // allowed casts to cv void*, since they have alignment 1.
15421   // Also allow casts involving incomplete types, which implicitly
15422   // includes 'void'.
15423   if (SrcPointee->isIncompleteType()) return;
15424 
15425   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15426 
15427   if (SrcAlign >= DestAlign) return;
15428 
15429   Diag(TRange.getBegin(), diag::warn_cast_align)
15430     << Op->getType() << T
15431     << static_cast<unsigned>(SrcAlign.getQuantity())
15432     << static_cast<unsigned>(DestAlign.getQuantity())
15433     << TRange << Op->getSourceRange();
15434 }
15435 
15436 /// Check whether this array fits the idiom of a size-one tail padded
15437 /// array member of a struct.
15438 ///
15439 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15440 /// commonly used to emulate flexible arrays in C89 code.
15441 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15442                                     const NamedDecl *ND) {
15443   if (Size != 1 || !ND) return false;
15444 
15445   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15446   if (!FD) return false;
15447 
15448   // Don't consider sizes resulting from macro expansions or template argument
15449   // substitution to form C89 tail-padded arrays.
15450 
15451   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15452   while (TInfo) {
15453     TypeLoc TL = TInfo->getTypeLoc();
15454     // Look through typedefs.
15455     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15456       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15457       TInfo = TDL->getTypeSourceInfo();
15458       continue;
15459     }
15460     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15461       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15462       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15463         return false;
15464     }
15465     break;
15466   }
15467 
15468   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15469   if (!RD) return false;
15470   if (RD->isUnion()) return false;
15471   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15472     if (!CRD->isStandardLayout()) return false;
15473   }
15474 
15475   // See if this is the last field decl in the record.
15476   const Decl *D = FD;
15477   while ((D = D->getNextDeclInContext()))
15478     if (isa<FieldDecl>(D))
15479       return false;
15480   return true;
15481 }
15482 
15483 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15484                             const ArraySubscriptExpr *ASE,
15485                             bool AllowOnePastEnd, bool IndexNegated) {
15486   // Already diagnosed by the constant evaluator.
15487   if (isConstantEvaluated())
15488     return;
15489 
15490   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15491   if (IndexExpr->isValueDependent())
15492     return;
15493 
15494   const Type *EffectiveType =
15495       BaseExpr->getType()->getPointeeOrArrayElementType();
15496   BaseExpr = BaseExpr->IgnoreParenCasts();
15497   const ConstantArrayType *ArrayTy =
15498       Context.getAsConstantArrayType(BaseExpr->getType());
15499 
15500   const Type *BaseType =
15501       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15502   bool IsUnboundedArray = (BaseType == nullptr);
15503   if (EffectiveType->isDependentType() ||
15504       (!IsUnboundedArray && BaseType->isDependentType()))
15505     return;
15506 
15507   Expr::EvalResult Result;
15508   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15509     return;
15510 
15511   llvm::APSInt index = Result.Val.getInt();
15512   if (IndexNegated) {
15513     index.setIsUnsigned(false);
15514     index = -index;
15515   }
15516 
15517   const NamedDecl *ND = nullptr;
15518   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15519     ND = DRE->getDecl();
15520   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15521     ND = ME->getMemberDecl();
15522 
15523   if (IsUnboundedArray) {
15524     if (EffectiveType->isFunctionType())
15525       return;
15526     if (index.isUnsigned() || !index.isNegative()) {
15527       const auto &ASTC = getASTContext();
15528       unsigned AddrBits =
15529           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15530               EffectiveType->getCanonicalTypeInternal()));
15531       if (index.getBitWidth() < AddrBits)
15532         index = index.zext(AddrBits);
15533       Optional<CharUnits> ElemCharUnits =
15534           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15535       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15536       // pointer) bounds-checking isn't meaningful.
15537       if (!ElemCharUnits)
15538         return;
15539       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15540       // If index has more active bits than address space, we already know
15541       // we have a bounds violation to warn about.  Otherwise, compute
15542       // address of (index + 1)th element, and warn about bounds violation
15543       // only if that address exceeds address space.
15544       if (index.getActiveBits() <= AddrBits) {
15545         bool Overflow;
15546         llvm::APInt Product(index);
15547         Product += 1;
15548         Product = Product.umul_ov(ElemBytes, Overflow);
15549         if (!Overflow && Product.getActiveBits() <= AddrBits)
15550           return;
15551       }
15552 
15553       // Need to compute max possible elements in address space, since that
15554       // is included in diag message.
15555       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15556       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15557       MaxElems += 1;
15558       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15559       MaxElems = MaxElems.udiv(ElemBytes);
15560 
15561       unsigned DiagID =
15562           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15563               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15564 
15565       // Diag message shows element size in bits and in "bytes" (platform-
15566       // dependent CharUnits)
15567       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15568                           PDiag(DiagID)
15569                               << toString(index, 10, true) << AddrBits
15570                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15571                               << toString(ElemBytes, 10, false)
15572                               << toString(MaxElems, 10, false)
15573                               << (unsigned)MaxElems.getLimitedValue(~0U)
15574                               << IndexExpr->getSourceRange());
15575 
15576       if (!ND) {
15577         // Try harder to find a NamedDecl to point at in the note.
15578         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15579           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15580         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15581           ND = DRE->getDecl();
15582         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15583           ND = ME->getMemberDecl();
15584       }
15585 
15586       if (ND)
15587         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15588                             PDiag(diag::note_array_declared_here) << ND);
15589     }
15590     return;
15591   }
15592 
15593   if (index.isUnsigned() || !index.isNegative()) {
15594     // It is possible that the type of the base expression after
15595     // IgnoreParenCasts is incomplete, even though the type of the base
15596     // expression before IgnoreParenCasts is complete (see PR39746 for an
15597     // example). In this case we have no information about whether the array
15598     // access exceeds the array bounds. However we can still diagnose an array
15599     // access which precedes the array bounds.
15600     if (BaseType->isIncompleteType())
15601       return;
15602 
15603     llvm::APInt size = ArrayTy->getSize();
15604     if (!size.isStrictlyPositive())
15605       return;
15606 
15607     if (BaseType != EffectiveType) {
15608       // Make sure we're comparing apples to apples when comparing index to size
15609       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15610       uint64_t array_typesize = Context.getTypeSize(BaseType);
15611       // Handle ptrarith_typesize being zero, such as when casting to void*
15612       if (!ptrarith_typesize) ptrarith_typesize = 1;
15613       if (ptrarith_typesize != array_typesize) {
15614         // There's a cast to a different size type involved
15615         uint64_t ratio = array_typesize / ptrarith_typesize;
15616         // TODO: Be smarter about handling cases where array_typesize is not a
15617         // multiple of ptrarith_typesize
15618         if (ptrarith_typesize * ratio == array_typesize)
15619           size *= llvm::APInt(size.getBitWidth(), ratio);
15620       }
15621     }
15622 
15623     if (size.getBitWidth() > index.getBitWidth())
15624       index = index.zext(size.getBitWidth());
15625     else if (size.getBitWidth() < index.getBitWidth())
15626       size = size.zext(index.getBitWidth());
15627 
15628     // For array subscripting the index must be less than size, but for pointer
15629     // arithmetic also allow the index (offset) to be equal to size since
15630     // computing the next address after the end of the array is legal and
15631     // commonly done e.g. in C++ iterators and range-based for loops.
15632     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15633       return;
15634 
15635     // Also don't warn for arrays of size 1 which are members of some
15636     // structure. These are often used to approximate flexible arrays in C89
15637     // code.
15638     if (IsTailPaddedMemberArray(*this, size, ND))
15639       return;
15640 
15641     // Suppress the warning if the subscript expression (as identified by the
15642     // ']' location) and the index expression are both from macro expansions
15643     // within a system header.
15644     if (ASE) {
15645       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15646           ASE->getRBracketLoc());
15647       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15648         SourceLocation IndexLoc =
15649             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15650         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15651           return;
15652       }
15653     }
15654 
15655     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15656                           : diag::warn_ptr_arith_exceeds_bounds;
15657 
15658     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15659                         PDiag(DiagID) << toString(index, 10, true)
15660                                       << toString(size, 10, true)
15661                                       << (unsigned)size.getLimitedValue(~0U)
15662                                       << IndexExpr->getSourceRange());
15663   } else {
15664     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15665     if (!ASE) {
15666       DiagID = diag::warn_ptr_arith_precedes_bounds;
15667       if (index.isNegative()) index = -index;
15668     }
15669 
15670     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15671                         PDiag(DiagID) << toString(index, 10, true)
15672                                       << IndexExpr->getSourceRange());
15673   }
15674 
15675   if (!ND) {
15676     // Try harder to find a NamedDecl to point at in the note.
15677     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15678       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15679     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15680       ND = DRE->getDecl();
15681     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15682       ND = ME->getMemberDecl();
15683   }
15684 
15685   if (ND)
15686     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15687                         PDiag(diag::note_array_declared_here) << ND);
15688 }
15689 
15690 void Sema::CheckArrayAccess(const Expr *expr) {
15691   int AllowOnePastEnd = 0;
15692   while (expr) {
15693     expr = expr->IgnoreParenImpCasts();
15694     switch (expr->getStmtClass()) {
15695       case Stmt::ArraySubscriptExprClass: {
15696         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15697         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15698                          AllowOnePastEnd > 0);
15699         expr = ASE->getBase();
15700         break;
15701       }
15702       case Stmt::MemberExprClass: {
15703         expr = cast<MemberExpr>(expr)->getBase();
15704         break;
15705       }
15706       case Stmt::OMPArraySectionExprClass: {
15707         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15708         if (ASE->getLowerBound())
15709           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15710                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15711         return;
15712       }
15713       case Stmt::UnaryOperatorClass: {
15714         // Only unwrap the * and & unary operators
15715         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15716         expr = UO->getSubExpr();
15717         switch (UO->getOpcode()) {
15718           case UO_AddrOf:
15719             AllowOnePastEnd++;
15720             break;
15721           case UO_Deref:
15722             AllowOnePastEnd--;
15723             break;
15724           default:
15725             return;
15726         }
15727         break;
15728       }
15729       case Stmt::ConditionalOperatorClass: {
15730         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15731         if (const Expr *lhs = cond->getLHS())
15732           CheckArrayAccess(lhs);
15733         if (const Expr *rhs = cond->getRHS())
15734           CheckArrayAccess(rhs);
15735         return;
15736       }
15737       case Stmt::CXXOperatorCallExprClass: {
15738         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15739         for (const auto *Arg : OCE->arguments())
15740           CheckArrayAccess(Arg);
15741         return;
15742       }
15743       default:
15744         return;
15745     }
15746   }
15747 }
15748 
15749 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15750 
15751 namespace {
15752 
15753 struct RetainCycleOwner {
15754   VarDecl *Variable = nullptr;
15755   SourceRange Range;
15756   SourceLocation Loc;
15757   bool Indirect = false;
15758 
15759   RetainCycleOwner() = default;
15760 
15761   void setLocsFrom(Expr *e) {
15762     Loc = e->getExprLoc();
15763     Range = e->getSourceRange();
15764   }
15765 };
15766 
15767 } // namespace
15768 
15769 /// Consider whether capturing the given variable can possibly lead to
15770 /// a retain cycle.
15771 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15772   // In ARC, it's captured strongly iff the variable has __strong
15773   // lifetime.  In MRR, it's captured strongly if the variable is
15774   // __block and has an appropriate type.
15775   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15776     return false;
15777 
15778   owner.Variable = var;
15779   if (ref)
15780     owner.setLocsFrom(ref);
15781   return true;
15782 }
15783 
15784 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15785   while (true) {
15786     e = e->IgnoreParens();
15787     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15788       switch (cast->getCastKind()) {
15789       case CK_BitCast:
15790       case CK_LValueBitCast:
15791       case CK_LValueToRValue:
15792       case CK_ARCReclaimReturnedObject:
15793         e = cast->getSubExpr();
15794         continue;
15795 
15796       default:
15797         return false;
15798       }
15799     }
15800 
15801     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15802       ObjCIvarDecl *ivar = ref->getDecl();
15803       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15804         return false;
15805 
15806       // Try to find a retain cycle in the base.
15807       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15808         return false;
15809 
15810       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15811       owner.Indirect = true;
15812       return true;
15813     }
15814 
15815     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15816       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15817       if (!var) return false;
15818       return considerVariable(var, ref, owner);
15819     }
15820 
15821     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15822       if (member->isArrow()) return false;
15823 
15824       // Don't count this as an indirect ownership.
15825       e = member->getBase();
15826       continue;
15827     }
15828 
15829     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15830       // Only pay attention to pseudo-objects on property references.
15831       ObjCPropertyRefExpr *pre
15832         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15833                                               ->IgnoreParens());
15834       if (!pre) return false;
15835       if (pre->isImplicitProperty()) return false;
15836       ObjCPropertyDecl *property = pre->getExplicitProperty();
15837       if (!property->isRetaining() &&
15838           !(property->getPropertyIvarDecl() &&
15839             property->getPropertyIvarDecl()->getType()
15840               .getObjCLifetime() == Qualifiers::OCL_Strong))
15841           return false;
15842 
15843       owner.Indirect = true;
15844       if (pre->isSuperReceiver()) {
15845         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15846         if (!owner.Variable)
15847           return false;
15848         owner.Loc = pre->getLocation();
15849         owner.Range = pre->getSourceRange();
15850         return true;
15851       }
15852       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15853                               ->getSourceExpr());
15854       continue;
15855     }
15856 
15857     // Array ivars?
15858 
15859     return false;
15860   }
15861 }
15862 
15863 namespace {
15864 
15865   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15866     ASTContext &Context;
15867     VarDecl *Variable;
15868     Expr *Capturer = nullptr;
15869     bool VarWillBeReased = false;
15870 
15871     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15872         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15873           Context(Context), Variable(variable) {}
15874 
15875     void VisitDeclRefExpr(DeclRefExpr *ref) {
15876       if (ref->getDecl() == Variable && !Capturer)
15877         Capturer = ref;
15878     }
15879 
15880     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15881       if (Capturer) return;
15882       Visit(ref->getBase());
15883       if (Capturer && ref->isFreeIvar())
15884         Capturer = ref;
15885     }
15886 
15887     void VisitBlockExpr(BlockExpr *block) {
15888       // Look inside nested blocks
15889       if (block->getBlockDecl()->capturesVariable(Variable))
15890         Visit(block->getBlockDecl()->getBody());
15891     }
15892 
15893     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15894       if (Capturer) return;
15895       if (OVE->getSourceExpr())
15896         Visit(OVE->getSourceExpr());
15897     }
15898 
15899     void VisitBinaryOperator(BinaryOperator *BinOp) {
15900       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15901         return;
15902       Expr *LHS = BinOp->getLHS();
15903       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15904         if (DRE->getDecl() != Variable)
15905           return;
15906         if (Expr *RHS = BinOp->getRHS()) {
15907           RHS = RHS->IgnoreParenCasts();
15908           Optional<llvm::APSInt> Value;
15909           VarWillBeReased =
15910               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15911                *Value == 0);
15912         }
15913       }
15914     }
15915   };
15916 
15917 } // namespace
15918 
15919 /// Check whether the given argument is a block which captures a
15920 /// variable.
15921 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15922   assert(owner.Variable && owner.Loc.isValid());
15923 
15924   e = e->IgnoreParenCasts();
15925 
15926   // Look through [^{...} copy] and Block_copy(^{...}).
15927   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15928     Selector Cmd = ME->getSelector();
15929     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15930       e = ME->getInstanceReceiver();
15931       if (!e)
15932         return nullptr;
15933       e = e->IgnoreParenCasts();
15934     }
15935   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15936     if (CE->getNumArgs() == 1) {
15937       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15938       if (Fn) {
15939         const IdentifierInfo *FnI = Fn->getIdentifier();
15940         if (FnI && FnI->isStr("_Block_copy")) {
15941           e = CE->getArg(0)->IgnoreParenCasts();
15942         }
15943       }
15944     }
15945   }
15946 
15947   BlockExpr *block = dyn_cast<BlockExpr>(e);
15948   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15949     return nullptr;
15950 
15951   FindCaptureVisitor visitor(S.Context, owner.Variable);
15952   visitor.Visit(block->getBlockDecl()->getBody());
15953   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15954 }
15955 
15956 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15957                                 RetainCycleOwner &owner) {
15958   assert(capturer);
15959   assert(owner.Variable && owner.Loc.isValid());
15960 
15961   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15962     << owner.Variable << capturer->getSourceRange();
15963   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15964     << owner.Indirect << owner.Range;
15965 }
15966 
15967 /// Check for a keyword selector that starts with the word 'add' or
15968 /// 'set'.
15969 static bool isSetterLikeSelector(Selector sel) {
15970   if (sel.isUnarySelector()) return false;
15971 
15972   StringRef str = sel.getNameForSlot(0);
15973   while (!str.empty() && str.front() == '_') str = str.substr(1);
15974   if (str.startswith("set"))
15975     str = str.substr(3);
15976   else if (str.startswith("add")) {
15977     // Specially allow 'addOperationWithBlock:'.
15978     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15979       return false;
15980     str = str.substr(3);
15981   }
15982   else
15983     return false;
15984 
15985   if (str.empty()) return true;
15986   return !isLowercase(str.front());
15987 }
15988 
15989 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15990                                                     ObjCMessageExpr *Message) {
15991   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15992                                                 Message->getReceiverInterface(),
15993                                                 NSAPI::ClassId_NSMutableArray);
15994   if (!IsMutableArray) {
15995     return None;
15996   }
15997 
15998   Selector Sel = Message->getSelector();
15999 
16000   Optional<NSAPI::NSArrayMethodKind> MKOpt =
16001     S.NSAPIObj->getNSArrayMethodKind(Sel);
16002   if (!MKOpt) {
16003     return None;
16004   }
16005 
16006   NSAPI::NSArrayMethodKind MK = *MKOpt;
16007 
16008   switch (MK) {
16009     case NSAPI::NSMutableArr_addObject:
16010     case NSAPI::NSMutableArr_insertObjectAtIndex:
16011     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
16012       return 0;
16013     case NSAPI::NSMutableArr_replaceObjectAtIndex:
16014       return 1;
16015 
16016     default:
16017       return None;
16018   }
16019 
16020   return None;
16021 }
16022 
16023 static
16024 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
16025                                                   ObjCMessageExpr *Message) {
16026   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
16027                                             Message->getReceiverInterface(),
16028                                             NSAPI::ClassId_NSMutableDictionary);
16029   if (!IsMutableDictionary) {
16030     return None;
16031   }
16032 
16033   Selector Sel = Message->getSelector();
16034 
16035   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
16036     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
16037   if (!MKOpt) {
16038     return None;
16039   }
16040 
16041   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
16042 
16043   switch (MK) {
16044     case NSAPI::NSMutableDict_setObjectForKey:
16045     case NSAPI::NSMutableDict_setValueForKey:
16046     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
16047       return 0;
16048 
16049     default:
16050       return None;
16051   }
16052 
16053   return None;
16054 }
16055 
16056 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
16057   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
16058                                                 Message->getReceiverInterface(),
16059                                                 NSAPI::ClassId_NSMutableSet);
16060 
16061   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
16062                                             Message->getReceiverInterface(),
16063                                             NSAPI::ClassId_NSMutableOrderedSet);
16064   if (!IsMutableSet && !IsMutableOrderedSet) {
16065     return None;
16066   }
16067 
16068   Selector Sel = Message->getSelector();
16069 
16070   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
16071   if (!MKOpt) {
16072     return None;
16073   }
16074 
16075   NSAPI::NSSetMethodKind MK = *MKOpt;
16076 
16077   switch (MK) {
16078     case NSAPI::NSMutableSet_addObject:
16079     case NSAPI::NSOrderedSet_setObjectAtIndex:
16080     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
16081     case NSAPI::NSOrderedSet_insertObjectAtIndex:
16082       return 0;
16083     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
16084       return 1;
16085   }
16086 
16087   return None;
16088 }
16089 
16090 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
16091   if (!Message->isInstanceMessage()) {
16092     return;
16093   }
16094 
16095   Optional<int> ArgOpt;
16096 
16097   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
16098       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
16099       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
16100     return;
16101   }
16102 
16103   int ArgIndex = *ArgOpt;
16104 
16105   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
16106   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
16107     Arg = OE->getSourceExpr()->IgnoreImpCasts();
16108   }
16109 
16110   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
16111     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16112       if (ArgRE->isObjCSelfExpr()) {
16113         Diag(Message->getSourceRange().getBegin(),
16114              diag::warn_objc_circular_container)
16115           << ArgRE->getDecl() << StringRef("'super'");
16116       }
16117     }
16118   } else {
16119     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
16120 
16121     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
16122       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
16123     }
16124 
16125     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
16126       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16127         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
16128           ValueDecl *Decl = ReceiverRE->getDecl();
16129           Diag(Message->getSourceRange().getBegin(),
16130                diag::warn_objc_circular_container)
16131             << Decl << Decl;
16132           if (!ArgRE->isObjCSelfExpr()) {
16133             Diag(Decl->getLocation(),
16134                  diag::note_objc_circular_container_declared_here)
16135               << Decl;
16136           }
16137         }
16138       }
16139     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
16140       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
16141         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
16142           ObjCIvarDecl *Decl = IvarRE->getDecl();
16143           Diag(Message->getSourceRange().getBegin(),
16144                diag::warn_objc_circular_container)
16145             << Decl << Decl;
16146           Diag(Decl->getLocation(),
16147                diag::note_objc_circular_container_declared_here)
16148             << Decl;
16149         }
16150       }
16151     }
16152   }
16153 }
16154 
16155 /// Check a message send to see if it's likely to cause a retain cycle.
16156 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
16157   // Only check instance methods whose selector looks like a setter.
16158   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
16159     return;
16160 
16161   // Try to find a variable that the receiver is strongly owned by.
16162   RetainCycleOwner owner;
16163   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
16164     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16165       return;
16166   } else {
16167     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16168     owner.Variable = getCurMethodDecl()->getSelfDecl();
16169     owner.Loc = msg->getSuperLoc();
16170     owner.Range = msg->getSuperLoc();
16171   }
16172 
16173   // Check whether the receiver is captured by any of the arguments.
16174   const ObjCMethodDecl *MD = msg->getMethodDecl();
16175   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16176     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16177       // noescape blocks should not be retained by the method.
16178       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16179         continue;
16180       return diagnoseRetainCycle(*this, capturer, owner);
16181     }
16182   }
16183 }
16184 
16185 /// Check a property assign to see if it's likely to cause a retain cycle.
16186 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16187   RetainCycleOwner owner;
16188   if (!findRetainCycleOwner(*this, receiver, owner))
16189     return;
16190 
16191   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16192     diagnoseRetainCycle(*this, capturer, owner);
16193 }
16194 
16195 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16196   RetainCycleOwner Owner;
16197   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16198     return;
16199 
16200   // Because we don't have an expression for the variable, we have to set the
16201   // location explicitly here.
16202   Owner.Loc = Var->getLocation();
16203   Owner.Range = Var->getSourceRange();
16204 
16205   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16206     diagnoseRetainCycle(*this, Capturer, Owner);
16207 }
16208 
16209 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16210                                      Expr *RHS, bool isProperty) {
16211   // Check if RHS is an Objective-C object literal, which also can get
16212   // immediately zapped in a weak reference.  Note that we explicitly
16213   // allow ObjCStringLiterals, since those are designed to never really die.
16214   RHS = RHS->IgnoreParenImpCasts();
16215 
16216   // This enum needs to match with the 'select' in
16217   // warn_objc_arc_literal_assign (off-by-1).
16218   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16219   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16220     return false;
16221 
16222   S.Diag(Loc, diag::warn_arc_literal_assign)
16223     << (unsigned) Kind
16224     << (isProperty ? 0 : 1)
16225     << RHS->getSourceRange();
16226 
16227   return true;
16228 }
16229 
16230 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16231                                     Qualifiers::ObjCLifetime LT,
16232                                     Expr *RHS, bool isProperty) {
16233   // Strip off any implicit cast added to get to the one ARC-specific.
16234   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16235     if (cast->getCastKind() == CK_ARCConsumeObject) {
16236       S.Diag(Loc, diag::warn_arc_retained_assign)
16237         << (LT == Qualifiers::OCL_ExplicitNone)
16238         << (isProperty ? 0 : 1)
16239         << RHS->getSourceRange();
16240       return true;
16241     }
16242     RHS = cast->getSubExpr();
16243   }
16244 
16245   if (LT == Qualifiers::OCL_Weak &&
16246       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16247     return true;
16248 
16249   return false;
16250 }
16251 
16252 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16253                               QualType LHS, Expr *RHS) {
16254   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16255 
16256   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16257     return false;
16258 
16259   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16260     return true;
16261 
16262   return false;
16263 }
16264 
16265 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16266                               Expr *LHS, Expr *RHS) {
16267   QualType LHSType;
16268   // PropertyRef on LHS type need be directly obtained from
16269   // its declaration as it has a PseudoType.
16270   ObjCPropertyRefExpr *PRE
16271     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16272   if (PRE && !PRE->isImplicitProperty()) {
16273     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16274     if (PD)
16275       LHSType = PD->getType();
16276   }
16277 
16278   if (LHSType.isNull())
16279     LHSType = LHS->getType();
16280 
16281   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16282 
16283   if (LT == Qualifiers::OCL_Weak) {
16284     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16285       getCurFunction()->markSafeWeakUse(LHS);
16286   }
16287 
16288   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16289     return;
16290 
16291   // FIXME. Check for other life times.
16292   if (LT != Qualifiers::OCL_None)
16293     return;
16294 
16295   if (PRE) {
16296     if (PRE->isImplicitProperty())
16297       return;
16298     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16299     if (!PD)
16300       return;
16301 
16302     unsigned Attributes = PD->getPropertyAttributes();
16303     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16304       // when 'assign' attribute was not explicitly specified
16305       // by user, ignore it and rely on property type itself
16306       // for lifetime info.
16307       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16308       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16309           LHSType->isObjCRetainableType())
16310         return;
16311 
16312       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16313         if (cast->getCastKind() == CK_ARCConsumeObject) {
16314           Diag(Loc, diag::warn_arc_retained_property_assign)
16315           << RHS->getSourceRange();
16316           return;
16317         }
16318         RHS = cast->getSubExpr();
16319       }
16320     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16321       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16322         return;
16323     }
16324   }
16325 }
16326 
16327 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16328 
16329 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16330                                         SourceLocation StmtLoc,
16331                                         const NullStmt *Body) {
16332   // Do not warn if the body is a macro that expands to nothing, e.g:
16333   //
16334   // #define CALL(x)
16335   // if (condition)
16336   //   CALL(0);
16337   if (Body->hasLeadingEmptyMacro())
16338     return false;
16339 
16340   // Get line numbers of statement and body.
16341   bool StmtLineInvalid;
16342   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16343                                                       &StmtLineInvalid);
16344   if (StmtLineInvalid)
16345     return false;
16346 
16347   bool BodyLineInvalid;
16348   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16349                                                       &BodyLineInvalid);
16350   if (BodyLineInvalid)
16351     return false;
16352 
16353   // Warn if null statement and body are on the same line.
16354   if (StmtLine != BodyLine)
16355     return false;
16356 
16357   return true;
16358 }
16359 
16360 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16361                                  const Stmt *Body,
16362                                  unsigned DiagID) {
16363   // Since this is a syntactic check, don't emit diagnostic for template
16364   // instantiations, this just adds noise.
16365   if (CurrentInstantiationScope)
16366     return;
16367 
16368   // The body should be a null statement.
16369   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16370   if (!NBody)
16371     return;
16372 
16373   // Do the usual checks.
16374   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16375     return;
16376 
16377   Diag(NBody->getSemiLoc(), DiagID);
16378   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16379 }
16380 
16381 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16382                                  const Stmt *PossibleBody) {
16383   assert(!CurrentInstantiationScope); // Ensured by caller
16384 
16385   SourceLocation StmtLoc;
16386   const Stmt *Body;
16387   unsigned DiagID;
16388   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16389     StmtLoc = FS->getRParenLoc();
16390     Body = FS->getBody();
16391     DiagID = diag::warn_empty_for_body;
16392   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16393     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16394     Body = WS->getBody();
16395     DiagID = diag::warn_empty_while_body;
16396   } else
16397     return; // Neither `for' nor `while'.
16398 
16399   // The body should be a null statement.
16400   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16401   if (!NBody)
16402     return;
16403 
16404   // Skip expensive checks if diagnostic is disabled.
16405   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16406     return;
16407 
16408   // Do the usual checks.
16409   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16410     return;
16411 
16412   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16413   // noise level low, emit diagnostics only if for/while is followed by a
16414   // CompoundStmt, e.g.:
16415   //    for (int i = 0; i < n; i++);
16416   //    {
16417   //      a(i);
16418   //    }
16419   // or if for/while is followed by a statement with more indentation
16420   // than for/while itself:
16421   //    for (int i = 0; i < n; i++);
16422   //      a(i);
16423   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16424   if (!ProbableTypo) {
16425     bool BodyColInvalid;
16426     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16427         PossibleBody->getBeginLoc(), &BodyColInvalid);
16428     if (BodyColInvalid)
16429       return;
16430 
16431     bool StmtColInvalid;
16432     unsigned StmtCol =
16433         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16434     if (StmtColInvalid)
16435       return;
16436 
16437     if (BodyCol > StmtCol)
16438       ProbableTypo = true;
16439   }
16440 
16441   if (ProbableTypo) {
16442     Diag(NBody->getSemiLoc(), DiagID);
16443     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16444   }
16445 }
16446 
16447 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16448 
16449 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16450 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16451                              SourceLocation OpLoc) {
16452   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16453     return;
16454 
16455   if (inTemplateInstantiation())
16456     return;
16457 
16458   // Strip parens and casts away.
16459   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16460   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16461 
16462   // Check for a call expression
16463   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16464   if (!CE || CE->getNumArgs() != 1)
16465     return;
16466 
16467   // Check for a call to std::move
16468   if (!CE->isCallToStdMove())
16469     return;
16470 
16471   // Get argument from std::move
16472   RHSExpr = CE->getArg(0);
16473 
16474   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16475   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16476 
16477   // Two DeclRefExpr's, check that the decls are the same.
16478   if (LHSDeclRef && RHSDeclRef) {
16479     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16480       return;
16481     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16482         RHSDeclRef->getDecl()->getCanonicalDecl())
16483       return;
16484 
16485     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16486                                         << LHSExpr->getSourceRange()
16487                                         << RHSExpr->getSourceRange();
16488     return;
16489   }
16490 
16491   // Member variables require a different approach to check for self moves.
16492   // MemberExpr's are the same if every nested MemberExpr refers to the same
16493   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16494   // the base Expr's are CXXThisExpr's.
16495   const Expr *LHSBase = LHSExpr;
16496   const Expr *RHSBase = RHSExpr;
16497   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16498   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16499   if (!LHSME || !RHSME)
16500     return;
16501 
16502   while (LHSME && RHSME) {
16503     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16504         RHSME->getMemberDecl()->getCanonicalDecl())
16505       return;
16506 
16507     LHSBase = LHSME->getBase();
16508     RHSBase = RHSME->getBase();
16509     LHSME = dyn_cast<MemberExpr>(LHSBase);
16510     RHSME = dyn_cast<MemberExpr>(RHSBase);
16511   }
16512 
16513   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16514   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16515   if (LHSDeclRef && RHSDeclRef) {
16516     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16517       return;
16518     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16519         RHSDeclRef->getDecl()->getCanonicalDecl())
16520       return;
16521 
16522     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16523                                         << LHSExpr->getSourceRange()
16524                                         << RHSExpr->getSourceRange();
16525     return;
16526   }
16527 
16528   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16529     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16530                                         << LHSExpr->getSourceRange()
16531                                         << RHSExpr->getSourceRange();
16532 }
16533 
16534 //===--- Layout compatibility ----------------------------------------------//
16535 
16536 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16537 
16538 /// Check if two enumeration types are layout-compatible.
16539 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16540   // C++11 [dcl.enum] p8:
16541   // Two enumeration types are layout-compatible if they have the same
16542   // underlying type.
16543   return ED1->isComplete() && ED2->isComplete() &&
16544          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16545 }
16546 
16547 /// Check if two fields are layout-compatible.
16548 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16549                                FieldDecl *Field2) {
16550   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16551     return false;
16552 
16553   if (Field1->isBitField() != Field2->isBitField())
16554     return false;
16555 
16556   if (Field1->isBitField()) {
16557     // Make sure that the bit-fields are the same length.
16558     unsigned Bits1 = Field1->getBitWidthValue(C);
16559     unsigned Bits2 = Field2->getBitWidthValue(C);
16560 
16561     if (Bits1 != Bits2)
16562       return false;
16563   }
16564 
16565   return true;
16566 }
16567 
16568 /// Check if two standard-layout structs are layout-compatible.
16569 /// (C++11 [class.mem] p17)
16570 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16571                                      RecordDecl *RD2) {
16572   // If both records are C++ classes, check that base classes match.
16573   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16574     // If one of records is a CXXRecordDecl we are in C++ mode,
16575     // thus the other one is a CXXRecordDecl, too.
16576     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16577     // Check number of base classes.
16578     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16579       return false;
16580 
16581     // Check the base classes.
16582     for (CXXRecordDecl::base_class_const_iterator
16583                Base1 = D1CXX->bases_begin(),
16584            BaseEnd1 = D1CXX->bases_end(),
16585               Base2 = D2CXX->bases_begin();
16586          Base1 != BaseEnd1;
16587          ++Base1, ++Base2) {
16588       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16589         return false;
16590     }
16591   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16592     // If only RD2 is a C++ class, it should have zero base classes.
16593     if (D2CXX->getNumBases() > 0)
16594       return false;
16595   }
16596 
16597   // Check the fields.
16598   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16599                              Field2End = RD2->field_end(),
16600                              Field1 = RD1->field_begin(),
16601                              Field1End = RD1->field_end();
16602   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16603     if (!isLayoutCompatible(C, *Field1, *Field2))
16604       return false;
16605   }
16606   if (Field1 != Field1End || Field2 != Field2End)
16607     return false;
16608 
16609   return true;
16610 }
16611 
16612 /// Check if two standard-layout unions are layout-compatible.
16613 /// (C++11 [class.mem] p18)
16614 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16615                                     RecordDecl *RD2) {
16616   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16617   for (auto *Field2 : RD2->fields())
16618     UnmatchedFields.insert(Field2);
16619 
16620   for (auto *Field1 : RD1->fields()) {
16621     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16622         I = UnmatchedFields.begin(),
16623         E = UnmatchedFields.end();
16624 
16625     for ( ; I != E; ++I) {
16626       if (isLayoutCompatible(C, Field1, *I)) {
16627         bool Result = UnmatchedFields.erase(*I);
16628         (void) Result;
16629         assert(Result);
16630         break;
16631       }
16632     }
16633     if (I == E)
16634       return false;
16635   }
16636 
16637   return UnmatchedFields.empty();
16638 }
16639 
16640 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16641                                RecordDecl *RD2) {
16642   if (RD1->isUnion() != RD2->isUnion())
16643     return false;
16644 
16645   if (RD1->isUnion())
16646     return isLayoutCompatibleUnion(C, RD1, RD2);
16647   else
16648     return isLayoutCompatibleStruct(C, RD1, RD2);
16649 }
16650 
16651 /// Check if two types are layout-compatible in C++11 sense.
16652 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16653   if (T1.isNull() || T2.isNull())
16654     return false;
16655 
16656   // C++11 [basic.types] p11:
16657   // If two types T1 and T2 are the same type, then T1 and T2 are
16658   // layout-compatible types.
16659   if (C.hasSameType(T1, T2))
16660     return true;
16661 
16662   T1 = T1.getCanonicalType().getUnqualifiedType();
16663   T2 = T2.getCanonicalType().getUnqualifiedType();
16664 
16665   const Type::TypeClass TC1 = T1->getTypeClass();
16666   const Type::TypeClass TC2 = T2->getTypeClass();
16667 
16668   if (TC1 != TC2)
16669     return false;
16670 
16671   if (TC1 == Type::Enum) {
16672     return isLayoutCompatible(C,
16673                               cast<EnumType>(T1)->getDecl(),
16674                               cast<EnumType>(T2)->getDecl());
16675   } else if (TC1 == Type::Record) {
16676     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16677       return false;
16678 
16679     return isLayoutCompatible(C,
16680                               cast<RecordType>(T1)->getDecl(),
16681                               cast<RecordType>(T2)->getDecl());
16682   }
16683 
16684   return false;
16685 }
16686 
16687 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16688 
16689 /// Given a type tag expression find the type tag itself.
16690 ///
16691 /// \param TypeExpr Type tag expression, as it appears in user's code.
16692 ///
16693 /// \param VD Declaration of an identifier that appears in a type tag.
16694 ///
16695 /// \param MagicValue Type tag magic value.
16696 ///
16697 /// \param isConstantEvaluated whether the evalaution should be performed in
16698 
16699 /// constant context.
16700 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16701                             const ValueDecl **VD, uint64_t *MagicValue,
16702                             bool isConstantEvaluated) {
16703   while(true) {
16704     if (!TypeExpr)
16705       return false;
16706 
16707     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16708 
16709     switch (TypeExpr->getStmtClass()) {
16710     case Stmt::UnaryOperatorClass: {
16711       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16712       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16713         TypeExpr = UO->getSubExpr();
16714         continue;
16715       }
16716       return false;
16717     }
16718 
16719     case Stmt::DeclRefExprClass: {
16720       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16721       *VD = DRE->getDecl();
16722       return true;
16723     }
16724 
16725     case Stmt::IntegerLiteralClass: {
16726       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16727       llvm::APInt MagicValueAPInt = IL->getValue();
16728       if (MagicValueAPInt.getActiveBits() <= 64) {
16729         *MagicValue = MagicValueAPInt.getZExtValue();
16730         return true;
16731       } else
16732         return false;
16733     }
16734 
16735     case Stmt::BinaryConditionalOperatorClass:
16736     case Stmt::ConditionalOperatorClass: {
16737       const AbstractConditionalOperator *ACO =
16738           cast<AbstractConditionalOperator>(TypeExpr);
16739       bool Result;
16740       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16741                                                      isConstantEvaluated)) {
16742         if (Result)
16743           TypeExpr = ACO->getTrueExpr();
16744         else
16745           TypeExpr = ACO->getFalseExpr();
16746         continue;
16747       }
16748       return false;
16749     }
16750 
16751     case Stmt::BinaryOperatorClass: {
16752       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16753       if (BO->getOpcode() == BO_Comma) {
16754         TypeExpr = BO->getRHS();
16755         continue;
16756       }
16757       return false;
16758     }
16759 
16760     default:
16761       return false;
16762     }
16763   }
16764 }
16765 
16766 /// Retrieve the C type corresponding to type tag TypeExpr.
16767 ///
16768 /// \param TypeExpr Expression that specifies a type tag.
16769 ///
16770 /// \param MagicValues Registered magic values.
16771 ///
16772 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16773 ///        kind.
16774 ///
16775 /// \param TypeInfo Information about the corresponding C type.
16776 ///
16777 /// \param isConstantEvaluated whether the evalaution should be performed in
16778 /// constant context.
16779 ///
16780 /// \returns true if the corresponding C type was found.
16781 static bool GetMatchingCType(
16782     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16783     const ASTContext &Ctx,
16784     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16785         *MagicValues,
16786     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16787     bool isConstantEvaluated) {
16788   FoundWrongKind = false;
16789 
16790   // Variable declaration that has type_tag_for_datatype attribute.
16791   const ValueDecl *VD = nullptr;
16792 
16793   uint64_t MagicValue;
16794 
16795   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16796     return false;
16797 
16798   if (VD) {
16799     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16800       if (I->getArgumentKind() != ArgumentKind) {
16801         FoundWrongKind = true;
16802         return false;
16803       }
16804       TypeInfo.Type = I->getMatchingCType();
16805       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16806       TypeInfo.MustBeNull = I->getMustBeNull();
16807       return true;
16808     }
16809     return false;
16810   }
16811 
16812   if (!MagicValues)
16813     return false;
16814 
16815   llvm::DenseMap<Sema::TypeTagMagicValue,
16816                  Sema::TypeTagData>::const_iterator I =
16817       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16818   if (I == MagicValues->end())
16819     return false;
16820 
16821   TypeInfo = I->second;
16822   return true;
16823 }
16824 
16825 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16826                                       uint64_t MagicValue, QualType Type,
16827                                       bool LayoutCompatible,
16828                                       bool MustBeNull) {
16829   if (!TypeTagForDatatypeMagicValues)
16830     TypeTagForDatatypeMagicValues.reset(
16831         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16832 
16833   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16834   (*TypeTagForDatatypeMagicValues)[Magic] =
16835       TypeTagData(Type, LayoutCompatible, MustBeNull);
16836 }
16837 
16838 static bool IsSameCharType(QualType T1, QualType T2) {
16839   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16840   if (!BT1)
16841     return false;
16842 
16843   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16844   if (!BT2)
16845     return false;
16846 
16847   BuiltinType::Kind T1Kind = BT1->getKind();
16848   BuiltinType::Kind T2Kind = BT2->getKind();
16849 
16850   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16851          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16852          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16853          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16854 }
16855 
16856 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16857                                     const ArrayRef<const Expr *> ExprArgs,
16858                                     SourceLocation CallSiteLoc) {
16859   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16860   bool IsPointerAttr = Attr->getIsPointer();
16861 
16862   // Retrieve the argument representing the 'type_tag'.
16863   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16864   if (TypeTagIdxAST >= ExprArgs.size()) {
16865     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16866         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16867     return;
16868   }
16869   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16870   bool FoundWrongKind;
16871   TypeTagData TypeInfo;
16872   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16873                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16874                         TypeInfo, isConstantEvaluated())) {
16875     if (FoundWrongKind)
16876       Diag(TypeTagExpr->getExprLoc(),
16877            diag::warn_type_tag_for_datatype_wrong_kind)
16878         << TypeTagExpr->getSourceRange();
16879     return;
16880   }
16881 
16882   // Retrieve the argument representing the 'arg_idx'.
16883   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16884   if (ArgumentIdxAST >= ExprArgs.size()) {
16885     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16886         << 1 << Attr->getArgumentIdx().getSourceIndex();
16887     return;
16888   }
16889   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16890   if (IsPointerAttr) {
16891     // Skip implicit cast of pointer to `void *' (as a function argument).
16892     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16893       if (ICE->getType()->isVoidPointerType() &&
16894           ICE->getCastKind() == CK_BitCast)
16895         ArgumentExpr = ICE->getSubExpr();
16896   }
16897   QualType ArgumentType = ArgumentExpr->getType();
16898 
16899   // Passing a `void*' pointer shouldn't trigger a warning.
16900   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16901     return;
16902 
16903   if (TypeInfo.MustBeNull) {
16904     // Type tag with matching void type requires a null pointer.
16905     if (!ArgumentExpr->isNullPointerConstant(Context,
16906                                              Expr::NPC_ValueDependentIsNotNull)) {
16907       Diag(ArgumentExpr->getExprLoc(),
16908            diag::warn_type_safety_null_pointer_required)
16909           << ArgumentKind->getName()
16910           << ArgumentExpr->getSourceRange()
16911           << TypeTagExpr->getSourceRange();
16912     }
16913     return;
16914   }
16915 
16916   QualType RequiredType = TypeInfo.Type;
16917   if (IsPointerAttr)
16918     RequiredType = Context.getPointerType(RequiredType);
16919 
16920   bool mismatch = false;
16921   if (!TypeInfo.LayoutCompatible) {
16922     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16923 
16924     // C++11 [basic.fundamental] p1:
16925     // Plain char, signed char, and unsigned char are three distinct types.
16926     //
16927     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16928     // char' depending on the current char signedness mode.
16929     if (mismatch)
16930       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16931                                            RequiredType->getPointeeType())) ||
16932           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16933         mismatch = false;
16934   } else
16935     if (IsPointerAttr)
16936       mismatch = !isLayoutCompatible(Context,
16937                                      ArgumentType->getPointeeType(),
16938                                      RequiredType->getPointeeType());
16939     else
16940       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16941 
16942   if (mismatch)
16943     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16944         << ArgumentType << ArgumentKind
16945         << TypeInfo.LayoutCompatible << RequiredType
16946         << ArgumentExpr->getSourceRange()
16947         << TypeTagExpr->getSourceRange();
16948 }
16949 
16950 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16951                                          CharUnits Alignment) {
16952   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16953 }
16954 
16955 void Sema::DiagnoseMisalignedMembers() {
16956   for (MisalignedMember &m : MisalignedMembers) {
16957     const NamedDecl *ND = m.RD;
16958     if (ND->getName().empty()) {
16959       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16960         ND = TD;
16961     }
16962     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16963         << m.MD << ND << m.E->getSourceRange();
16964   }
16965   MisalignedMembers.clear();
16966 }
16967 
16968 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16969   E = E->IgnoreParens();
16970   if (!T->isPointerType() && !T->isIntegerType())
16971     return;
16972   if (isa<UnaryOperator>(E) &&
16973       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16974     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16975     if (isa<MemberExpr>(Op)) {
16976       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16977       if (MA != MisalignedMembers.end() &&
16978           (T->isIntegerType() ||
16979            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16980                                    Context.getTypeAlignInChars(
16981                                        T->getPointeeType()) <= MA->Alignment))))
16982         MisalignedMembers.erase(MA);
16983     }
16984   }
16985 }
16986 
16987 void Sema::RefersToMemberWithReducedAlignment(
16988     Expr *E,
16989     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16990         Action) {
16991   const auto *ME = dyn_cast<MemberExpr>(E);
16992   if (!ME)
16993     return;
16994 
16995   // No need to check expressions with an __unaligned-qualified type.
16996   if (E->getType().getQualifiers().hasUnaligned())
16997     return;
16998 
16999   // For a chain of MemberExpr like "a.b.c.d" this list
17000   // will keep FieldDecl's like [d, c, b].
17001   SmallVector<FieldDecl *, 4> ReverseMemberChain;
17002   const MemberExpr *TopME = nullptr;
17003   bool AnyIsPacked = false;
17004   do {
17005     QualType BaseType = ME->getBase()->getType();
17006     if (BaseType->isDependentType())
17007       return;
17008     if (ME->isArrow())
17009       BaseType = BaseType->getPointeeType();
17010     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
17011     if (RD->isInvalidDecl())
17012       return;
17013 
17014     ValueDecl *MD = ME->getMemberDecl();
17015     auto *FD = dyn_cast<FieldDecl>(MD);
17016     // We do not care about non-data members.
17017     if (!FD || FD->isInvalidDecl())
17018       return;
17019 
17020     AnyIsPacked =
17021         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17022     ReverseMemberChain.push_back(FD);
17023 
17024     TopME = ME;
17025     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17026   } while (ME);
17027   assert(TopME && "We did not compute a topmost MemberExpr!");
17028 
17029   // Not the scope of this diagnostic.
17030   if (!AnyIsPacked)
17031     return;
17032 
17033   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17034   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17035   // TODO: The innermost base of the member expression may be too complicated.
17036   // For now, just disregard these cases. This is left for future
17037   // improvement.
17038   if (!DRE && !isa<CXXThisExpr>(TopBase))
17039       return;
17040 
17041   // Alignment expected by the whole expression.
17042   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17043 
17044   // No need to do anything else with this case.
17045   if (ExpectedAlignment.isOne())
17046     return;
17047 
17048   // Synthesize offset of the whole access.
17049   CharUnits Offset;
17050   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17051     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17052 
17053   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17054   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17055       ReverseMemberChain.back()->getParent()->getTypeForDecl());
17056 
17057   // The base expression of the innermost MemberExpr may give
17058   // stronger guarantees than the class containing the member.
17059   if (DRE && !TopME->isArrow()) {
17060     const ValueDecl *VD = DRE->getDecl();
17061     if (!VD->getType()->isReferenceType())
17062       CompleteObjectAlignment =
17063           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17064   }
17065 
17066   // Check if the synthesized offset fulfills the alignment.
17067   if (Offset % ExpectedAlignment != 0 ||
17068       // It may fulfill the offset it but the effective alignment may still be
17069       // lower than the expected expression alignment.
17070       CompleteObjectAlignment < ExpectedAlignment) {
17071     // If this happens, we want to determine a sensible culprit of this.
17072     // Intuitively, watching the chain of member expressions from right to
17073     // left, we start with the required alignment (as required by the field
17074     // type) but some packed attribute in that chain has reduced the alignment.
17075     // It may happen that another packed structure increases it again. But if
17076     // we are here such increase has not been enough. So pointing the first
17077     // FieldDecl that either is packed or else its RecordDecl is,
17078     // seems reasonable.
17079     FieldDecl *FD = nullptr;
17080     CharUnits Alignment;
17081     for (FieldDecl *FDI : ReverseMemberChain) {
17082       if (FDI->hasAttr<PackedAttr>() ||
17083           FDI->getParent()->hasAttr<PackedAttr>()) {
17084         FD = FDI;
17085         Alignment = std::min(
17086             Context.getTypeAlignInChars(FD->getType()),
17087             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
17088         break;
17089       }
17090     }
17091     assert(FD && "We did not find a packed FieldDecl!");
17092     Action(E, FD->getParent(), FD, Alignment);
17093   }
17094 }
17095 
17096 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17097   using namespace std::placeholders;
17098 
17099   RefersToMemberWithReducedAlignment(
17100       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17101                      _2, _3, _4));
17102 }
17103 
17104 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
17105 // not a valid type, emit an error message and return true. Otherwise return
17106 // false.
17107 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
17108                                         QualType Ty) {
17109   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
17110     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
17111         << 1 << /* vector, integer or float ty*/ 0 << Ty;
17112     return true;
17113   }
17114   return false;
17115 }
17116 
17117 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
17118   if (checkArgCount(*this, TheCall, 1))
17119     return true;
17120 
17121   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17122   if (A.isInvalid())
17123     return true;
17124 
17125   TheCall->setArg(0, A.get());
17126   QualType TyA = A.get()->getType();
17127 
17128   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17129     return true;
17130 
17131   TheCall->setType(TyA);
17132   return false;
17133 }
17134 
17135 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
17136   if (checkArgCount(*this, TheCall, 2))
17137     return true;
17138 
17139   ExprResult A = TheCall->getArg(0);
17140   ExprResult B = TheCall->getArg(1);
17141   // Do standard promotions between the two arguments, returning their common
17142   // type.
17143   QualType Res =
17144       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
17145   if (A.isInvalid() || B.isInvalid())
17146     return true;
17147 
17148   QualType TyA = A.get()->getType();
17149   QualType TyB = B.get()->getType();
17150 
17151   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
17152     return Diag(A.get()->getBeginLoc(),
17153                 diag::err_typecheck_call_different_arg_types)
17154            << TyA << TyB;
17155 
17156   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17157     return true;
17158 
17159   TheCall->setArg(0, A.get());
17160   TheCall->setArg(1, B.get());
17161   TheCall->setType(Res);
17162   return false;
17163 }
17164 
17165 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17166   if (checkArgCount(*this, TheCall, 1))
17167     return true;
17168 
17169   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17170   if (A.isInvalid())
17171     return true;
17172 
17173   TheCall->setArg(0, A.get());
17174   return false;
17175 }
17176 
17177 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17178                                             ExprResult CallResult) {
17179   if (checkArgCount(*this, TheCall, 1))
17180     return ExprError();
17181 
17182   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17183   if (MatrixArg.isInvalid())
17184     return MatrixArg;
17185   Expr *Matrix = MatrixArg.get();
17186 
17187   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17188   if (!MType) {
17189     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17190         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17191     return ExprError();
17192   }
17193 
17194   // Create returned matrix type by swapping rows and columns of the argument
17195   // matrix type.
17196   QualType ResultType = Context.getConstantMatrixType(
17197       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17198 
17199   // Change the return type to the type of the returned matrix.
17200   TheCall->setType(ResultType);
17201 
17202   // Update call argument to use the possibly converted matrix argument.
17203   TheCall->setArg(0, Matrix);
17204   return CallResult;
17205 }
17206 
17207 // Get and verify the matrix dimensions.
17208 static llvm::Optional<unsigned>
17209 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17210   SourceLocation ErrorPos;
17211   Optional<llvm::APSInt> Value =
17212       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17213   if (!Value) {
17214     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17215         << Name;
17216     return {};
17217   }
17218   uint64_t Dim = Value->getZExtValue();
17219   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17220     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17221         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17222     return {};
17223   }
17224   return Dim;
17225 }
17226 
17227 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17228                                                   ExprResult CallResult) {
17229   if (!getLangOpts().MatrixTypes) {
17230     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17231     return ExprError();
17232   }
17233 
17234   if (checkArgCount(*this, TheCall, 4))
17235     return ExprError();
17236 
17237   unsigned PtrArgIdx = 0;
17238   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17239   Expr *RowsExpr = TheCall->getArg(1);
17240   Expr *ColumnsExpr = TheCall->getArg(2);
17241   Expr *StrideExpr = TheCall->getArg(3);
17242 
17243   bool ArgError = false;
17244 
17245   // Check pointer argument.
17246   {
17247     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17248     if (PtrConv.isInvalid())
17249       return PtrConv;
17250     PtrExpr = PtrConv.get();
17251     TheCall->setArg(0, PtrExpr);
17252     if (PtrExpr->isTypeDependent()) {
17253       TheCall->setType(Context.DependentTy);
17254       return TheCall;
17255     }
17256   }
17257 
17258   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17259   QualType ElementTy;
17260   if (!PtrTy) {
17261     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17262         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17263     ArgError = true;
17264   } else {
17265     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17266 
17267     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17268       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17269           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17270           << PtrExpr->getType();
17271       ArgError = true;
17272     }
17273   }
17274 
17275   // Apply default Lvalue conversions and convert the expression to size_t.
17276   auto ApplyArgumentConversions = [this](Expr *E) {
17277     ExprResult Conv = DefaultLvalueConversion(E);
17278     if (Conv.isInvalid())
17279       return Conv;
17280 
17281     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17282   };
17283 
17284   // Apply conversion to row and column expressions.
17285   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17286   if (!RowsConv.isInvalid()) {
17287     RowsExpr = RowsConv.get();
17288     TheCall->setArg(1, RowsExpr);
17289   } else
17290     RowsExpr = nullptr;
17291 
17292   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17293   if (!ColumnsConv.isInvalid()) {
17294     ColumnsExpr = ColumnsConv.get();
17295     TheCall->setArg(2, ColumnsExpr);
17296   } else
17297     ColumnsExpr = nullptr;
17298 
17299   // If any any part of the result matrix type is still pending, just use
17300   // Context.DependentTy, until all parts are resolved.
17301   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17302       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17303     TheCall->setType(Context.DependentTy);
17304     return CallResult;
17305   }
17306 
17307   // Check row and column dimensions.
17308   llvm::Optional<unsigned> MaybeRows;
17309   if (RowsExpr)
17310     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17311 
17312   llvm::Optional<unsigned> MaybeColumns;
17313   if (ColumnsExpr)
17314     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17315 
17316   // Check stride argument.
17317   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17318   if (StrideConv.isInvalid())
17319     return ExprError();
17320   StrideExpr = StrideConv.get();
17321   TheCall->setArg(3, StrideExpr);
17322 
17323   if (MaybeRows) {
17324     if (Optional<llvm::APSInt> Value =
17325             StrideExpr->getIntegerConstantExpr(Context)) {
17326       uint64_t Stride = Value->getZExtValue();
17327       if (Stride < *MaybeRows) {
17328         Diag(StrideExpr->getBeginLoc(),
17329              diag::err_builtin_matrix_stride_too_small);
17330         ArgError = true;
17331       }
17332     }
17333   }
17334 
17335   if (ArgError || !MaybeRows || !MaybeColumns)
17336     return ExprError();
17337 
17338   TheCall->setType(
17339       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17340   return CallResult;
17341 }
17342 
17343 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17344                                                    ExprResult CallResult) {
17345   if (checkArgCount(*this, TheCall, 3))
17346     return ExprError();
17347 
17348   unsigned PtrArgIdx = 1;
17349   Expr *MatrixExpr = TheCall->getArg(0);
17350   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17351   Expr *StrideExpr = TheCall->getArg(2);
17352 
17353   bool ArgError = false;
17354 
17355   {
17356     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17357     if (MatrixConv.isInvalid())
17358       return MatrixConv;
17359     MatrixExpr = MatrixConv.get();
17360     TheCall->setArg(0, MatrixExpr);
17361   }
17362   if (MatrixExpr->isTypeDependent()) {
17363     TheCall->setType(Context.DependentTy);
17364     return TheCall;
17365   }
17366 
17367   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17368   if (!MatrixTy) {
17369     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17370         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17371     ArgError = true;
17372   }
17373 
17374   {
17375     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17376     if (PtrConv.isInvalid())
17377       return PtrConv;
17378     PtrExpr = PtrConv.get();
17379     TheCall->setArg(1, PtrExpr);
17380     if (PtrExpr->isTypeDependent()) {
17381       TheCall->setType(Context.DependentTy);
17382       return TheCall;
17383     }
17384   }
17385 
17386   // Check pointer argument.
17387   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17388   if (!PtrTy) {
17389     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17390         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17391     ArgError = true;
17392   } else {
17393     QualType ElementTy = PtrTy->getPointeeType();
17394     if (ElementTy.isConstQualified()) {
17395       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17396       ArgError = true;
17397     }
17398     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17399     if (MatrixTy &&
17400         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17401       Diag(PtrExpr->getBeginLoc(),
17402            diag::err_builtin_matrix_pointer_arg_mismatch)
17403           << ElementTy << MatrixTy->getElementType();
17404       ArgError = true;
17405     }
17406   }
17407 
17408   // Apply default Lvalue conversions and convert the stride expression to
17409   // size_t.
17410   {
17411     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17412     if (StrideConv.isInvalid())
17413       return StrideConv;
17414 
17415     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17416     if (StrideConv.isInvalid())
17417       return StrideConv;
17418     StrideExpr = StrideConv.get();
17419     TheCall->setArg(2, StrideExpr);
17420   }
17421 
17422   // Check stride argument.
17423   if (MatrixTy) {
17424     if (Optional<llvm::APSInt> Value =
17425             StrideExpr->getIntegerConstantExpr(Context)) {
17426       uint64_t Stride = Value->getZExtValue();
17427       if (Stride < MatrixTy->getNumRows()) {
17428         Diag(StrideExpr->getBeginLoc(),
17429              diag::err_builtin_matrix_stride_too_small);
17430         ArgError = true;
17431       }
17432     }
17433   }
17434 
17435   if (ArgError)
17436     return ExprError();
17437 
17438   return CallResult;
17439 }
17440 
17441 /// \brief Enforce the bounds of a TCB
17442 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17443 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17444 /// and enforce_tcb_leaf attributes.
17445 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17446                                const NamedDecl *Callee) {
17447   const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17448 
17449   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17450     return;
17451 
17452   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17453   // all TCBs the callee is a part of.
17454   llvm::StringSet<> CalleeTCBs;
17455   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17456            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17457   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17458            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17459 
17460   // Go through the TCBs the caller is a part of and emit warnings if Caller
17461   // is in a TCB that the Callee is not.
17462   for_each(
17463       Caller->specific_attrs<EnforceTCBAttr>(),
17464       [&](const auto *A) {
17465         StringRef CallerTCB = A->getTCBName();
17466         if (CalleeTCBs.count(CallerTCB) == 0) {
17467           this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17468               << Callee << CallerTCB;
17469         }
17470       });
17471 }
17472