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   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
1046     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1047         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
1048     return true;
1049   }
1050   return false;
1051 }
1052 
1053 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1054   if (checkArgCount(S, TheCall, 2))
1055     return true;
1056 
1057   if (checkOpenCLSubgroupExt(S, TheCall))
1058     return true;
1059 
1060   // First argument is an ndrange_t type.
1061   Expr *NDRangeArg = TheCall->getArg(0);
1062   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1063     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1064         << TheCall->getDirectCallee() << "'ndrange_t'";
1065     return true;
1066   }
1067 
1068   Expr *BlockArg = TheCall->getArg(1);
1069   if (!isBlockPointer(BlockArg)) {
1070     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1071         << TheCall->getDirectCallee() << "block";
1072     return true;
1073   }
1074   return checkOpenCLBlockArgs(S, BlockArg);
1075 }
1076 
1077 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1078 /// get_kernel_work_group_size
1079 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1080 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1081   if (checkArgCount(S, TheCall, 1))
1082     return true;
1083 
1084   Expr *BlockArg = TheCall->getArg(0);
1085   if (!isBlockPointer(BlockArg)) {
1086     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1087         << TheCall->getDirectCallee() << "block";
1088     return true;
1089   }
1090   return checkOpenCLBlockArgs(S, BlockArg);
1091 }
1092 
1093 /// Diagnose integer type and any valid implicit conversion to it.
1094 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1095                                       const QualType &IntType);
1096 
1097 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1098                                             unsigned Start, unsigned End) {
1099   bool IllegalParams = false;
1100   for (unsigned I = Start; I <= End; ++I)
1101     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1102                                               S.Context.getSizeType());
1103   return IllegalParams;
1104 }
1105 
1106 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1107 /// 'local void*' parameter of passed block.
1108 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1109                                            Expr *BlockArg,
1110                                            unsigned NumNonVarArgs) {
1111   const BlockPointerType *BPT =
1112       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1113   unsigned NumBlockParams =
1114       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1115   unsigned TotalNumArgs = TheCall->getNumArgs();
1116 
1117   // For each argument passed to the block, a corresponding uint needs to
1118   // be passed to describe the size of the local memory.
1119   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1120     S.Diag(TheCall->getBeginLoc(),
1121            diag::err_opencl_enqueue_kernel_local_size_args);
1122     return true;
1123   }
1124 
1125   // Check that the sizes of the local memory are specified by integers.
1126   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1127                                          TotalNumArgs - 1);
1128 }
1129 
1130 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1131 /// overload formats specified in Table 6.13.17.1.
1132 /// int enqueue_kernel(queue_t queue,
1133 ///                    kernel_enqueue_flags_t flags,
1134 ///                    const ndrange_t ndrange,
1135 ///                    void (^block)(void))
1136 /// int enqueue_kernel(queue_t queue,
1137 ///                    kernel_enqueue_flags_t flags,
1138 ///                    const ndrange_t ndrange,
1139 ///                    uint num_events_in_wait_list,
1140 ///                    clk_event_t *event_wait_list,
1141 ///                    clk_event_t *event_ret,
1142 ///                    void (^block)(void))
1143 /// int enqueue_kernel(queue_t queue,
1144 ///                    kernel_enqueue_flags_t flags,
1145 ///                    const ndrange_t ndrange,
1146 ///                    void (^block)(local void*, ...),
1147 ///                    uint size0, ...)
1148 /// int enqueue_kernel(queue_t queue,
1149 ///                    kernel_enqueue_flags_t flags,
1150 ///                    const ndrange_t ndrange,
1151 ///                    uint num_events_in_wait_list,
1152 ///                    clk_event_t *event_wait_list,
1153 ///                    clk_event_t *event_ret,
1154 ///                    void (^block)(local void*, ...),
1155 ///                    uint size0, ...)
1156 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1157   unsigned NumArgs = TheCall->getNumArgs();
1158 
1159   if (NumArgs < 4) {
1160     S.Diag(TheCall->getBeginLoc(),
1161            diag::err_typecheck_call_too_few_args_at_least)
1162         << 0 << 4 << NumArgs;
1163     return true;
1164   }
1165 
1166   Expr *Arg0 = TheCall->getArg(0);
1167   Expr *Arg1 = TheCall->getArg(1);
1168   Expr *Arg2 = TheCall->getArg(2);
1169   Expr *Arg3 = TheCall->getArg(3);
1170 
1171   // First argument always needs to be a queue_t type.
1172   if (!Arg0->getType()->isQueueT()) {
1173     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1174            diag::err_opencl_builtin_expected_type)
1175         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1176     return true;
1177   }
1178 
1179   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1180   if (!Arg1->getType()->isIntegerType()) {
1181     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1182            diag::err_opencl_builtin_expected_type)
1183         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1184     return true;
1185   }
1186 
1187   // Third argument is always an ndrange_t type.
1188   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1189     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1190            diag::err_opencl_builtin_expected_type)
1191         << TheCall->getDirectCallee() << "'ndrange_t'";
1192     return true;
1193   }
1194 
1195   // With four arguments, there is only one form that the function could be
1196   // called in: no events and no variable arguments.
1197   if (NumArgs == 4) {
1198     // check that the last argument is the right block type.
1199     if (!isBlockPointer(Arg3)) {
1200       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1201           << TheCall->getDirectCallee() << "block";
1202       return true;
1203     }
1204     // we have a block type, check the prototype
1205     const BlockPointerType *BPT =
1206         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1207     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1208       S.Diag(Arg3->getBeginLoc(),
1209              diag::err_opencl_enqueue_kernel_blocks_no_args);
1210       return true;
1211     }
1212     return false;
1213   }
1214   // we can have block + varargs.
1215   if (isBlockPointer(Arg3))
1216     return (checkOpenCLBlockArgs(S, Arg3) ||
1217             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1218   // last two cases with either exactly 7 args or 7 args and varargs.
1219   if (NumArgs >= 7) {
1220     // check common block argument.
1221     Expr *Arg6 = TheCall->getArg(6);
1222     if (!isBlockPointer(Arg6)) {
1223       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1224           << TheCall->getDirectCallee() << "block";
1225       return true;
1226     }
1227     if (checkOpenCLBlockArgs(S, Arg6))
1228       return true;
1229 
1230     // Forth argument has to be any integer type.
1231     if (!Arg3->getType()->isIntegerType()) {
1232       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1233              diag::err_opencl_builtin_expected_type)
1234           << TheCall->getDirectCallee() << "integer";
1235       return true;
1236     }
1237     // check remaining common arguments.
1238     Expr *Arg4 = TheCall->getArg(4);
1239     Expr *Arg5 = TheCall->getArg(5);
1240 
1241     // Fifth argument is always passed as a pointer to clk_event_t.
1242     if (!Arg4->isNullPointerConstant(S.Context,
1243                                      Expr::NPC_ValueDependentIsNotNull) &&
1244         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1245       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1246              diag::err_opencl_builtin_expected_type)
1247           << TheCall->getDirectCallee()
1248           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1249       return true;
1250     }
1251 
1252     // Sixth argument is always passed as a pointer to clk_event_t.
1253     if (!Arg5->isNullPointerConstant(S.Context,
1254                                      Expr::NPC_ValueDependentIsNotNull) &&
1255         !(Arg5->getType()->isPointerType() &&
1256           Arg5->getType()->getPointeeType()->isClkEventT())) {
1257       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1258              diag::err_opencl_builtin_expected_type)
1259           << TheCall->getDirectCallee()
1260           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1261       return true;
1262     }
1263 
1264     if (NumArgs == 7)
1265       return false;
1266 
1267     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1268   }
1269 
1270   // None of the specific case has been detected, give generic error
1271   S.Diag(TheCall->getBeginLoc(),
1272          diag::err_opencl_enqueue_kernel_incorrect_args);
1273   return true;
1274 }
1275 
1276 /// Returns OpenCL access qual.
1277 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1278     return D->getAttr<OpenCLAccessAttr>();
1279 }
1280 
1281 /// Returns true if pipe element type is different from the pointer.
1282 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1283   const Expr *Arg0 = Call->getArg(0);
1284   // First argument type should always be pipe.
1285   if (!Arg0->getType()->isPipeType()) {
1286     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1287         << Call->getDirectCallee() << Arg0->getSourceRange();
1288     return true;
1289   }
1290   OpenCLAccessAttr *AccessQual =
1291       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1292   // Validates the access qualifier is compatible with the call.
1293   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1294   // read_only and write_only, and assumed to be read_only if no qualifier is
1295   // specified.
1296   switch (Call->getDirectCallee()->getBuiltinID()) {
1297   case Builtin::BIread_pipe:
1298   case Builtin::BIreserve_read_pipe:
1299   case Builtin::BIcommit_read_pipe:
1300   case Builtin::BIwork_group_reserve_read_pipe:
1301   case Builtin::BIsub_group_reserve_read_pipe:
1302   case Builtin::BIwork_group_commit_read_pipe:
1303   case Builtin::BIsub_group_commit_read_pipe:
1304     if (!(!AccessQual || AccessQual->isReadOnly())) {
1305       S.Diag(Arg0->getBeginLoc(),
1306              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1307           << "read_only" << Arg0->getSourceRange();
1308       return true;
1309     }
1310     break;
1311   case Builtin::BIwrite_pipe:
1312   case Builtin::BIreserve_write_pipe:
1313   case Builtin::BIcommit_write_pipe:
1314   case Builtin::BIwork_group_reserve_write_pipe:
1315   case Builtin::BIsub_group_reserve_write_pipe:
1316   case Builtin::BIwork_group_commit_write_pipe:
1317   case Builtin::BIsub_group_commit_write_pipe:
1318     if (!(AccessQual && AccessQual->isWriteOnly())) {
1319       S.Diag(Arg0->getBeginLoc(),
1320              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1321           << "write_only" << Arg0->getSourceRange();
1322       return true;
1323     }
1324     break;
1325   default:
1326     break;
1327   }
1328   return false;
1329 }
1330 
1331 /// Returns true if pipe element type is different from the pointer.
1332 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1333   const Expr *Arg0 = Call->getArg(0);
1334   const Expr *ArgIdx = Call->getArg(Idx);
1335   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1336   const QualType EltTy = PipeTy->getElementType();
1337   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1338   // The Idx argument should be a pointer and the type of the pointer and
1339   // the type of pipe element should also be the same.
1340   if (!ArgTy ||
1341       !S.Context.hasSameType(
1342           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1343     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1344         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1345         << ArgIdx->getType() << ArgIdx->getSourceRange();
1346     return true;
1347   }
1348   return false;
1349 }
1350 
1351 // Performs semantic analysis for the read/write_pipe call.
1352 // \param S Reference to the semantic analyzer.
1353 // \param Call A pointer to the builtin call.
1354 // \return True if a semantic error has been found, false otherwise.
1355 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1356   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1357   // functions have two forms.
1358   switch (Call->getNumArgs()) {
1359   case 2:
1360     if (checkOpenCLPipeArg(S, Call))
1361       return true;
1362     // The call with 2 arguments should be
1363     // read/write_pipe(pipe T, T*).
1364     // Check packet type T.
1365     if (checkOpenCLPipePacketType(S, Call, 1))
1366       return true;
1367     break;
1368 
1369   case 4: {
1370     if (checkOpenCLPipeArg(S, Call))
1371       return true;
1372     // The call with 4 arguments should be
1373     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1374     // Check reserve_id_t.
1375     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1376       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1377           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1378           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1379       return true;
1380     }
1381 
1382     // Check the index.
1383     const Expr *Arg2 = Call->getArg(2);
1384     if (!Arg2->getType()->isIntegerType() &&
1385         !Arg2->getType()->isUnsignedIntegerType()) {
1386       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1387           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1388           << Arg2->getType() << Arg2->getSourceRange();
1389       return true;
1390     }
1391 
1392     // Check packet type T.
1393     if (checkOpenCLPipePacketType(S, Call, 3))
1394       return true;
1395   } break;
1396   default:
1397     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1398         << Call->getDirectCallee() << Call->getSourceRange();
1399     return true;
1400   }
1401 
1402   return false;
1403 }
1404 
1405 // Performs a semantic analysis on the {work_group_/sub_group_
1406 //        /_}reserve_{read/write}_pipe
1407 // \param S Reference to the semantic analyzer.
1408 // \param Call The call to the builtin function to be analyzed.
1409 // \return True if a semantic error was found, false otherwise.
1410 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1411   if (checkArgCount(S, Call, 2))
1412     return true;
1413 
1414   if (checkOpenCLPipeArg(S, Call))
1415     return true;
1416 
1417   // Check the reserve size.
1418   if (!Call->getArg(1)->getType()->isIntegerType() &&
1419       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1420     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1421         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1422         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1423     return true;
1424   }
1425 
1426   // Since return type of reserve_read/write_pipe built-in function is
1427   // reserve_id_t, which is not defined in the builtin def file , we used int
1428   // as return type and need to override the return type of these functions.
1429   Call->setType(S.Context.OCLReserveIDTy);
1430 
1431   return false;
1432 }
1433 
1434 // Performs a semantic analysis on {work_group_/sub_group_
1435 //        /_}commit_{read/write}_pipe
1436 // \param S Reference to the semantic analyzer.
1437 // \param Call The call to the builtin function to be analyzed.
1438 // \return True if a semantic error was found, false otherwise.
1439 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1440   if (checkArgCount(S, Call, 2))
1441     return true;
1442 
1443   if (checkOpenCLPipeArg(S, Call))
1444     return true;
1445 
1446   // Check reserve_id_t.
1447   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1448     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1449         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1450         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1451     return true;
1452   }
1453 
1454   return false;
1455 }
1456 
1457 // Performs a semantic analysis on the call to built-in Pipe
1458 //        Query Functions.
1459 // \param S Reference to the semantic analyzer.
1460 // \param Call The call to the builtin function to be analyzed.
1461 // \return True if a semantic error was found, false otherwise.
1462 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1463   if (checkArgCount(S, Call, 1))
1464     return true;
1465 
1466   if (!Call->getArg(0)->getType()->isPipeType()) {
1467     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1468         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1469     return true;
1470   }
1471 
1472   return false;
1473 }
1474 
1475 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1476 // Performs semantic analysis for the to_global/local/private call.
1477 // \param S Reference to the semantic analyzer.
1478 // \param BuiltinID ID of the builtin function.
1479 // \param Call A pointer to the builtin call.
1480 // \return True if a semantic error has been found, false otherwise.
1481 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1482                                     CallExpr *Call) {
1483   if (checkArgCount(S, Call, 1))
1484     return true;
1485 
1486   auto RT = Call->getArg(0)->getType();
1487   if (!RT->isPointerType() || RT->getPointeeType()
1488       .getAddressSpace() == LangAS::opencl_constant) {
1489     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1490         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1491     return true;
1492   }
1493 
1494   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1495     S.Diag(Call->getArg(0)->getBeginLoc(),
1496            diag::warn_opencl_generic_address_space_arg)
1497         << Call->getDirectCallee()->getNameInfo().getAsString()
1498         << Call->getArg(0)->getSourceRange();
1499   }
1500 
1501   RT = RT->getPointeeType();
1502   auto Qual = RT.getQualifiers();
1503   switch (BuiltinID) {
1504   case Builtin::BIto_global:
1505     Qual.setAddressSpace(LangAS::opencl_global);
1506     break;
1507   case Builtin::BIto_local:
1508     Qual.setAddressSpace(LangAS::opencl_local);
1509     break;
1510   case Builtin::BIto_private:
1511     Qual.setAddressSpace(LangAS::opencl_private);
1512     break;
1513   default:
1514     llvm_unreachable("Invalid builtin function");
1515   }
1516   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1517       RT.getUnqualifiedType(), Qual)));
1518 
1519   return false;
1520 }
1521 
1522 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1523   if (checkArgCount(S, TheCall, 1))
1524     return ExprError();
1525 
1526   // Compute __builtin_launder's parameter type from the argument.
1527   // The parameter type is:
1528   //  * The type of the argument if it's not an array or function type,
1529   //  Otherwise,
1530   //  * The decayed argument type.
1531   QualType ParamTy = [&]() {
1532     QualType ArgTy = TheCall->getArg(0)->getType();
1533     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1534       return S.Context.getPointerType(Ty->getElementType());
1535     if (ArgTy->isFunctionType()) {
1536       return S.Context.getPointerType(ArgTy);
1537     }
1538     return ArgTy;
1539   }();
1540 
1541   TheCall->setType(ParamTy);
1542 
1543   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1544     if (!ParamTy->isPointerType())
1545       return 0;
1546     if (ParamTy->isFunctionPointerType())
1547       return 1;
1548     if (ParamTy->isVoidPointerType())
1549       return 2;
1550     return llvm::Optional<unsigned>{};
1551   }();
1552   if (DiagSelect.hasValue()) {
1553     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1554         << DiagSelect.getValue() << TheCall->getSourceRange();
1555     return ExprError();
1556   }
1557 
1558   // We either have an incomplete class type, or we have a class template
1559   // whose instantiation has not been forced. Example:
1560   //
1561   //   template <class T> struct Foo { T value; };
1562   //   Foo<int> *p = nullptr;
1563   //   auto *d = __builtin_launder(p);
1564   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1565                             diag::err_incomplete_type))
1566     return ExprError();
1567 
1568   assert(ParamTy->getPointeeType()->isObjectType() &&
1569          "Unhandled non-object pointer case");
1570 
1571   InitializedEntity Entity =
1572       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1573   ExprResult Arg =
1574       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1575   if (Arg.isInvalid())
1576     return ExprError();
1577   TheCall->setArg(0, Arg.get());
1578 
1579   return TheCall;
1580 }
1581 
1582 // Emit an error and return true if the current object format type is in the
1583 // list of unsupported types.
1584 static bool CheckBuiltinTargetNotInUnsupported(
1585     Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1586     ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1587   llvm::Triple::ObjectFormatType CurObjFormat =
1588       S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1589   if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1590     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1591         << TheCall->getSourceRange();
1592     return true;
1593   }
1594   return false;
1595 }
1596 
1597 // Emit an error and return true if the current architecture is not in the list
1598 // of supported architectures.
1599 static bool
1600 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1601                               ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1602   llvm::Triple::ArchType CurArch =
1603       S.getASTContext().getTargetInfo().getTriple().getArch();
1604   if (llvm::is_contained(SupportedArchs, CurArch))
1605     return false;
1606   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1607       << TheCall->getSourceRange();
1608   return true;
1609 }
1610 
1611 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1612                                  SourceLocation CallSiteLoc);
1613 
1614 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1615                                       CallExpr *TheCall) {
1616   switch (TI.getTriple().getArch()) {
1617   default:
1618     // Some builtins don't require additional checking, so just consider these
1619     // acceptable.
1620     return false;
1621   case llvm::Triple::arm:
1622   case llvm::Triple::armeb:
1623   case llvm::Triple::thumb:
1624   case llvm::Triple::thumbeb:
1625     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1626   case llvm::Triple::aarch64:
1627   case llvm::Triple::aarch64_32:
1628   case llvm::Triple::aarch64_be:
1629     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1630   case llvm::Triple::bpfeb:
1631   case llvm::Triple::bpfel:
1632     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1633   case llvm::Triple::hexagon:
1634     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1635   case llvm::Triple::mips:
1636   case llvm::Triple::mipsel:
1637   case llvm::Triple::mips64:
1638   case llvm::Triple::mips64el:
1639     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1640   case llvm::Triple::systemz:
1641     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1642   case llvm::Triple::x86:
1643   case llvm::Triple::x86_64:
1644     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1645   case llvm::Triple::ppc:
1646   case llvm::Triple::ppcle:
1647   case llvm::Triple::ppc64:
1648   case llvm::Triple::ppc64le:
1649     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1650   case llvm::Triple::amdgcn:
1651     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1652   case llvm::Triple::riscv32:
1653   case llvm::Triple::riscv64:
1654     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1655   }
1656 }
1657 
1658 ExprResult
1659 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1660                                CallExpr *TheCall) {
1661   ExprResult TheCallResult(TheCall);
1662 
1663   // Find out if any arguments are required to be integer constant expressions.
1664   unsigned ICEArguments = 0;
1665   ASTContext::GetBuiltinTypeError Error;
1666   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1667   if (Error != ASTContext::GE_None)
1668     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1669 
1670   // If any arguments are required to be ICE's, check and diagnose.
1671   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1672     // Skip arguments not required to be ICE's.
1673     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1674 
1675     llvm::APSInt Result;
1676     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1677       return true;
1678     ICEArguments &= ~(1 << ArgNo);
1679   }
1680 
1681   switch (BuiltinID) {
1682   case Builtin::BI__builtin___CFStringMakeConstantString:
1683     // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
1684     // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
1685     if (CheckBuiltinTargetNotInUnsupported(
1686             *this, BuiltinID, TheCall,
1687             {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
1688       return ExprError();
1689     assert(TheCall->getNumArgs() == 1 &&
1690            "Wrong # arguments to builtin CFStringMakeConstantString");
1691     if (CheckObjCString(TheCall->getArg(0)))
1692       return ExprError();
1693     break;
1694   case Builtin::BI__builtin_ms_va_start:
1695   case Builtin::BI__builtin_stdarg_start:
1696   case Builtin::BI__builtin_va_start:
1697     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1698       return ExprError();
1699     break;
1700   case Builtin::BI__va_start: {
1701     switch (Context.getTargetInfo().getTriple().getArch()) {
1702     case llvm::Triple::aarch64:
1703     case llvm::Triple::arm:
1704     case llvm::Triple::thumb:
1705       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1706         return ExprError();
1707       break;
1708     default:
1709       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1710         return ExprError();
1711       break;
1712     }
1713     break;
1714   }
1715 
1716   // The acquire, release, and no fence variants are ARM and AArch64 only.
1717   case Builtin::BI_interlockedbittestandset_acq:
1718   case Builtin::BI_interlockedbittestandset_rel:
1719   case Builtin::BI_interlockedbittestandset_nf:
1720   case Builtin::BI_interlockedbittestandreset_acq:
1721   case Builtin::BI_interlockedbittestandreset_rel:
1722   case Builtin::BI_interlockedbittestandreset_nf:
1723     if (CheckBuiltinTargetInSupported(
1724             *this, BuiltinID, TheCall,
1725             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1726       return ExprError();
1727     break;
1728 
1729   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1730   case Builtin::BI_bittest64:
1731   case Builtin::BI_bittestandcomplement64:
1732   case Builtin::BI_bittestandreset64:
1733   case Builtin::BI_bittestandset64:
1734   case Builtin::BI_interlockedbittestandreset64:
1735   case Builtin::BI_interlockedbittestandset64:
1736     if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
1737                                       {llvm::Triple::x86_64, llvm::Triple::arm,
1738                                        llvm::Triple::thumb,
1739                                        llvm::Triple::aarch64}))
1740       return ExprError();
1741     break;
1742 
1743   case Builtin::BI__builtin_isgreater:
1744   case Builtin::BI__builtin_isgreaterequal:
1745   case Builtin::BI__builtin_isless:
1746   case Builtin::BI__builtin_islessequal:
1747   case Builtin::BI__builtin_islessgreater:
1748   case Builtin::BI__builtin_isunordered:
1749     if (SemaBuiltinUnorderedCompare(TheCall))
1750       return ExprError();
1751     break;
1752   case Builtin::BI__builtin_fpclassify:
1753     if (SemaBuiltinFPClassification(TheCall, 6))
1754       return ExprError();
1755     break;
1756   case Builtin::BI__builtin_isfinite:
1757   case Builtin::BI__builtin_isinf:
1758   case Builtin::BI__builtin_isinf_sign:
1759   case Builtin::BI__builtin_isnan:
1760   case Builtin::BI__builtin_isnormal:
1761   case Builtin::BI__builtin_signbit:
1762   case Builtin::BI__builtin_signbitf:
1763   case Builtin::BI__builtin_signbitl:
1764     if (SemaBuiltinFPClassification(TheCall, 1))
1765       return ExprError();
1766     break;
1767   case Builtin::BI__builtin_shufflevector:
1768     return SemaBuiltinShuffleVector(TheCall);
1769     // TheCall will be freed by the smart pointer here, but that's fine, since
1770     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1771   case Builtin::BI__builtin_prefetch:
1772     if (SemaBuiltinPrefetch(TheCall))
1773       return ExprError();
1774     break;
1775   case Builtin::BI__builtin_alloca_with_align:
1776   case Builtin::BI__builtin_alloca_with_align_uninitialized:
1777     if (SemaBuiltinAllocaWithAlign(TheCall))
1778       return ExprError();
1779     LLVM_FALLTHROUGH;
1780   case Builtin::BI__builtin_alloca:
1781   case Builtin::BI__builtin_alloca_uninitialized:
1782     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1783         << TheCall->getDirectCallee();
1784     break;
1785   case Builtin::BI__arithmetic_fence:
1786     if (SemaBuiltinArithmeticFence(TheCall))
1787       return ExprError();
1788     break;
1789   case Builtin::BI__assume:
1790   case Builtin::BI__builtin_assume:
1791     if (SemaBuiltinAssume(TheCall))
1792       return ExprError();
1793     break;
1794   case Builtin::BI__builtin_assume_aligned:
1795     if (SemaBuiltinAssumeAligned(TheCall))
1796       return ExprError();
1797     break;
1798   case Builtin::BI__builtin_dynamic_object_size:
1799   case Builtin::BI__builtin_object_size:
1800     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1801       return ExprError();
1802     break;
1803   case Builtin::BI__builtin_longjmp:
1804     if (SemaBuiltinLongjmp(TheCall))
1805       return ExprError();
1806     break;
1807   case Builtin::BI__builtin_setjmp:
1808     if (SemaBuiltinSetjmp(TheCall))
1809       return ExprError();
1810     break;
1811   case Builtin::BI__builtin_classify_type:
1812     if (checkArgCount(*this, TheCall, 1)) return true;
1813     TheCall->setType(Context.IntTy);
1814     break;
1815   case Builtin::BI__builtin_complex:
1816     if (SemaBuiltinComplex(TheCall))
1817       return ExprError();
1818     break;
1819   case Builtin::BI__builtin_constant_p: {
1820     if (checkArgCount(*this, TheCall, 1)) return true;
1821     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1822     if (Arg.isInvalid()) return true;
1823     TheCall->setArg(0, Arg.get());
1824     TheCall->setType(Context.IntTy);
1825     break;
1826   }
1827   case Builtin::BI__builtin_launder:
1828     return SemaBuiltinLaunder(*this, TheCall);
1829   case Builtin::BI__sync_fetch_and_add:
1830   case Builtin::BI__sync_fetch_and_add_1:
1831   case Builtin::BI__sync_fetch_and_add_2:
1832   case Builtin::BI__sync_fetch_and_add_4:
1833   case Builtin::BI__sync_fetch_and_add_8:
1834   case Builtin::BI__sync_fetch_and_add_16:
1835   case Builtin::BI__sync_fetch_and_sub:
1836   case Builtin::BI__sync_fetch_and_sub_1:
1837   case Builtin::BI__sync_fetch_and_sub_2:
1838   case Builtin::BI__sync_fetch_and_sub_4:
1839   case Builtin::BI__sync_fetch_and_sub_8:
1840   case Builtin::BI__sync_fetch_and_sub_16:
1841   case Builtin::BI__sync_fetch_and_or:
1842   case Builtin::BI__sync_fetch_and_or_1:
1843   case Builtin::BI__sync_fetch_and_or_2:
1844   case Builtin::BI__sync_fetch_and_or_4:
1845   case Builtin::BI__sync_fetch_and_or_8:
1846   case Builtin::BI__sync_fetch_and_or_16:
1847   case Builtin::BI__sync_fetch_and_and:
1848   case Builtin::BI__sync_fetch_and_and_1:
1849   case Builtin::BI__sync_fetch_and_and_2:
1850   case Builtin::BI__sync_fetch_and_and_4:
1851   case Builtin::BI__sync_fetch_and_and_8:
1852   case Builtin::BI__sync_fetch_and_and_16:
1853   case Builtin::BI__sync_fetch_and_xor:
1854   case Builtin::BI__sync_fetch_and_xor_1:
1855   case Builtin::BI__sync_fetch_and_xor_2:
1856   case Builtin::BI__sync_fetch_and_xor_4:
1857   case Builtin::BI__sync_fetch_and_xor_8:
1858   case Builtin::BI__sync_fetch_and_xor_16:
1859   case Builtin::BI__sync_fetch_and_nand:
1860   case Builtin::BI__sync_fetch_and_nand_1:
1861   case Builtin::BI__sync_fetch_and_nand_2:
1862   case Builtin::BI__sync_fetch_and_nand_4:
1863   case Builtin::BI__sync_fetch_and_nand_8:
1864   case Builtin::BI__sync_fetch_and_nand_16:
1865   case Builtin::BI__sync_add_and_fetch:
1866   case Builtin::BI__sync_add_and_fetch_1:
1867   case Builtin::BI__sync_add_and_fetch_2:
1868   case Builtin::BI__sync_add_and_fetch_4:
1869   case Builtin::BI__sync_add_and_fetch_8:
1870   case Builtin::BI__sync_add_and_fetch_16:
1871   case Builtin::BI__sync_sub_and_fetch:
1872   case Builtin::BI__sync_sub_and_fetch_1:
1873   case Builtin::BI__sync_sub_and_fetch_2:
1874   case Builtin::BI__sync_sub_and_fetch_4:
1875   case Builtin::BI__sync_sub_and_fetch_8:
1876   case Builtin::BI__sync_sub_and_fetch_16:
1877   case Builtin::BI__sync_and_and_fetch:
1878   case Builtin::BI__sync_and_and_fetch_1:
1879   case Builtin::BI__sync_and_and_fetch_2:
1880   case Builtin::BI__sync_and_and_fetch_4:
1881   case Builtin::BI__sync_and_and_fetch_8:
1882   case Builtin::BI__sync_and_and_fetch_16:
1883   case Builtin::BI__sync_or_and_fetch:
1884   case Builtin::BI__sync_or_and_fetch_1:
1885   case Builtin::BI__sync_or_and_fetch_2:
1886   case Builtin::BI__sync_or_and_fetch_4:
1887   case Builtin::BI__sync_or_and_fetch_8:
1888   case Builtin::BI__sync_or_and_fetch_16:
1889   case Builtin::BI__sync_xor_and_fetch:
1890   case Builtin::BI__sync_xor_and_fetch_1:
1891   case Builtin::BI__sync_xor_and_fetch_2:
1892   case Builtin::BI__sync_xor_and_fetch_4:
1893   case Builtin::BI__sync_xor_and_fetch_8:
1894   case Builtin::BI__sync_xor_and_fetch_16:
1895   case Builtin::BI__sync_nand_and_fetch:
1896   case Builtin::BI__sync_nand_and_fetch_1:
1897   case Builtin::BI__sync_nand_and_fetch_2:
1898   case Builtin::BI__sync_nand_and_fetch_4:
1899   case Builtin::BI__sync_nand_and_fetch_8:
1900   case Builtin::BI__sync_nand_and_fetch_16:
1901   case Builtin::BI__sync_val_compare_and_swap:
1902   case Builtin::BI__sync_val_compare_and_swap_1:
1903   case Builtin::BI__sync_val_compare_and_swap_2:
1904   case Builtin::BI__sync_val_compare_and_swap_4:
1905   case Builtin::BI__sync_val_compare_and_swap_8:
1906   case Builtin::BI__sync_val_compare_and_swap_16:
1907   case Builtin::BI__sync_bool_compare_and_swap:
1908   case Builtin::BI__sync_bool_compare_and_swap_1:
1909   case Builtin::BI__sync_bool_compare_and_swap_2:
1910   case Builtin::BI__sync_bool_compare_and_swap_4:
1911   case Builtin::BI__sync_bool_compare_and_swap_8:
1912   case Builtin::BI__sync_bool_compare_and_swap_16:
1913   case Builtin::BI__sync_lock_test_and_set:
1914   case Builtin::BI__sync_lock_test_and_set_1:
1915   case Builtin::BI__sync_lock_test_and_set_2:
1916   case Builtin::BI__sync_lock_test_and_set_4:
1917   case Builtin::BI__sync_lock_test_and_set_8:
1918   case Builtin::BI__sync_lock_test_and_set_16:
1919   case Builtin::BI__sync_lock_release:
1920   case Builtin::BI__sync_lock_release_1:
1921   case Builtin::BI__sync_lock_release_2:
1922   case Builtin::BI__sync_lock_release_4:
1923   case Builtin::BI__sync_lock_release_8:
1924   case Builtin::BI__sync_lock_release_16:
1925   case Builtin::BI__sync_swap:
1926   case Builtin::BI__sync_swap_1:
1927   case Builtin::BI__sync_swap_2:
1928   case Builtin::BI__sync_swap_4:
1929   case Builtin::BI__sync_swap_8:
1930   case Builtin::BI__sync_swap_16:
1931     return SemaBuiltinAtomicOverloaded(TheCallResult);
1932   case Builtin::BI__sync_synchronize:
1933     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1934         << TheCall->getCallee()->getSourceRange();
1935     break;
1936   case Builtin::BI__builtin_nontemporal_load:
1937   case Builtin::BI__builtin_nontemporal_store:
1938     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1939   case Builtin::BI__builtin_memcpy_inline: {
1940     clang::Expr *SizeOp = TheCall->getArg(2);
1941     // We warn about copying to or from `nullptr` pointers when `size` is
1942     // greater than 0. When `size` is value dependent we cannot evaluate its
1943     // value so we bail out.
1944     if (SizeOp->isValueDependent())
1945       break;
1946     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1947       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1948       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1949     }
1950     break;
1951   }
1952 #define BUILTIN(ID, TYPE, ATTRS)
1953 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1954   case Builtin::BI##ID: \
1955     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1956 #include "clang/Basic/Builtins.def"
1957   case Builtin::BI__annotation:
1958     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1959       return ExprError();
1960     break;
1961   case Builtin::BI__builtin_annotation:
1962     if (SemaBuiltinAnnotation(*this, TheCall))
1963       return ExprError();
1964     break;
1965   case Builtin::BI__builtin_addressof:
1966     if (SemaBuiltinAddressof(*this, TheCall))
1967       return ExprError();
1968     break;
1969   case Builtin::BI__builtin_function_start:
1970     if (SemaBuiltinFunctionStart(*this, TheCall))
1971       return ExprError();
1972     break;
1973   case Builtin::BI__builtin_is_aligned:
1974   case Builtin::BI__builtin_align_up:
1975   case Builtin::BI__builtin_align_down:
1976     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1977       return ExprError();
1978     break;
1979   case Builtin::BI__builtin_add_overflow:
1980   case Builtin::BI__builtin_sub_overflow:
1981   case Builtin::BI__builtin_mul_overflow:
1982     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1983       return ExprError();
1984     break;
1985   case Builtin::BI__builtin_operator_new:
1986   case Builtin::BI__builtin_operator_delete: {
1987     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1988     ExprResult Res =
1989         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1990     if (Res.isInvalid())
1991       CorrectDelayedTyposInExpr(TheCallResult.get());
1992     return Res;
1993   }
1994   case Builtin::BI__builtin_dump_struct: {
1995     // We first want to ensure we are called with 2 arguments
1996     if (checkArgCount(*this, TheCall, 2))
1997       return ExprError();
1998     // Ensure that the first argument is of type 'struct XX *'
1999     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
2000     const QualType PtrArgType = PtrArg->getType();
2001     if (!PtrArgType->isPointerType() ||
2002         !PtrArgType->getPointeeType()->isRecordType()) {
2003       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2004           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
2005           << "structure pointer";
2006       return ExprError();
2007     }
2008 
2009     // Ensure that the second argument is of type 'FunctionType'
2010     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
2011     const QualType FnPtrArgType = FnPtrArg->getType();
2012     if (!FnPtrArgType->isPointerType()) {
2013       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2014           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2015           << FnPtrArgType << "'int (*)(const char *, ...)'";
2016       return ExprError();
2017     }
2018 
2019     const auto *FuncType =
2020         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
2021 
2022     if (!FuncType) {
2023       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2024           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2025           << FnPtrArgType << "'int (*)(const char *, ...)'";
2026       return ExprError();
2027     }
2028 
2029     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2030       if (!FT->getNumParams()) {
2031         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2032             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2033             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2034         return ExprError();
2035       }
2036       QualType PT = FT->getParamType(0);
2037       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2038           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2039           !PT->getPointeeType().isConstQualified()) {
2040         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2041             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2042             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2043         return ExprError();
2044       }
2045     }
2046 
2047     TheCall->setType(Context.IntTy);
2048     break;
2049   }
2050   case Builtin::BI__builtin_expect_with_probability: {
2051     // We first want to ensure we are called with 3 arguments
2052     if (checkArgCount(*this, TheCall, 3))
2053       return ExprError();
2054     // then check probability is constant float in range [0.0, 1.0]
2055     const Expr *ProbArg = TheCall->getArg(2);
2056     SmallVector<PartialDiagnosticAt, 8> Notes;
2057     Expr::EvalResult Eval;
2058     Eval.Diag = &Notes;
2059     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2060         !Eval.Val.isFloat()) {
2061       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2062           << ProbArg->getSourceRange();
2063       for (const PartialDiagnosticAt &PDiag : Notes)
2064         Diag(PDiag.first, PDiag.second);
2065       return ExprError();
2066     }
2067     llvm::APFloat Probability = Eval.Val.getFloat();
2068     bool LoseInfo = false;
2069     Probability.convert(llvm::APFloat::IEEEdouble(),
2070                         llvm::RoundingMode::Dynamic, &LoseInfo);
2071     if (!(Probability >= llvm::APFloat(0.0) &&
2072           Probability <= llvm::APFloat(1.0))) {
2073       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2074           << ProbArg->getSourceRange();
2075       return ExprError();
2076     }
2077     break;
2078   }
2079   case Builtin::BI__builtin_preserve_access_index:
2080     if (SemaBuiltinPreserveAI(*this, TheCall))
2081       return ExprError();
2082     break;
2083   case Builtin::BI__builtin_call_with_static_chain:
2084     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2085       return ExprError();
2086     break;
2087   case Builtin::BI__exception_code:
2088   case Builtin::BI_exception_code:
2089     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2090                                  diag::err_seh___except_block))
2091       return ExprError();
2092     break;
2093   case Builtin::BI__exception_info:
2094   case Builtin::BI_exception_info:
2095     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2096                                  diag::err_seh___except_filter))
2097       return ExprError();
2098     break;
2099   case Builtin::BI__GetExceptionInfo:
2100     if (checkArgCount(*this, TheCall, 1))
2101       return ExprError();
2102 
2103     if (CheckCXXThrowOperand(
2104             TheCall->getBeginLoc(),
2105             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2106             TheCall))
2107       return ExprError();
2108 
2109     TheCall->setType(Context.VoidPtrTy);
2110     break;
2111   // OpenCL v2.0, s6.13.16 - Pipe functions
2112   case Builtin::BIread_pipe:
2113   case Builtin::BIwrite_pipe:
2114     // Since those two functions are declared with var args, we need a semantic
2115     // check for the argument.
2116     if (SemaBuiltinRWPipe(*this, TheCall))
2117       return ExprError();
2118     break;
2119   case Builtin::BIreserve_read_pipe:
2120   case Builtin::BIreserve_write_pipe:
2121   case Builtin::BIwork_group_reserve_read_pipe:
2122   case Builtin::BIwork_group_reserve_write_pipe:
2123     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2124       return ExprError();
2125     break;
2126   case Builtin::BIsub_group_reserve_read_pipe:
2127   case Builtin::BIsub_group_reserve_write_pipe:
2128     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2129         SemaBuiltinReserveRWPipe(*this, TheCall))
2130       return ExprError();
2131     break;
2132   case Builtin::BIcommit_read_pipe:
2133   case Builtin::BIcommit_write_pipe:
2134   case Builtin::BIwork_group_commit_read_pipe:
2135   case Builtin::BIwork_group_commit_write_pipe:
2136     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2137       return ExprError();
2138     break;
2139   case Builtin::BIsub_group_commit_read_pipe:
2140   case Builtin::BIsub_group_commit_write_pipe:
2141     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2142         SemaBuiltinCommitRWPipe(*this, TheCall))
2143       return ExprError();
2144     break;
2145   case Builtin::BIget_pipe_num_packets:
2146   case Builtin::BIget_pipe_max_packets:
2147     if (SemaBuiltinPipePackets(*this, TheCall))
2148       return ExprError();
2149     break;
2150   case Builtin::BIto_global:
2151   case Builtin::BIto_local:
2152   case Builtin::BIto_private:
2153     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2154       return ExprError();
2155     break;
2156   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2157   case Builtin::BIenqueue_kernel:
2158     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2159       return ExprError();
2160     break;
2161   case Builtin::BIget_kernel_work_group_size:
2162   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2163     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2164       return ExprError();
2165     break;
2166   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2167   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2168     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2169       return ExprError();
2170     break;
2171   case Builtin::BI__builtin_os_log_format:
2172     Cleanup.setExprNeedsCleanups(true);
2173     LLVM_FALLTHROUGH;
2174   case Builtin::BI__builtin_os_log_format_buffer_size:
2175     if (SemaBuiltinOSLogFormat(TheCall))
2176       return ExprError();
2177     break;
2178   case Builtin::BI__builtin_frame_address:
2179   case Builtin::BI__builtin_return_address: {
2180     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2181       return ExprError();
2182 
2183     // -Wframe-address warning if non-zero passed to builtin
2184     // return/frame address.
2185     Expr::EvalResult Result;
2186     if (!TheCall->getArg(0)->isValueDependent() &&
2187         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2188         Result.Val.getInt() != 0)
2189       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2190           << ((BuiltinID == Builtin::BI__builtin_return_address)
2191                   ? "__builtin_return_address"
2192                   : "__builtin_frame_address")
2193           << TheCall->getSourceRange();
2194     break;
2195   }
2196 
2197   // __builtin_elementwise_abs restricts the element type to signed integers or
2198   // floating point types only.
2199   case Builtin::BI__builtin_elementwise_abs: {
2200     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2201       return ExprError();
2202 
2203     QualType ArgTy = TheCall->getArg(0)->getType();
2204     QualType EltTy = ArgTy;
2205 
2206     if (auto *VecTy = EltTy->getAs<VectorType>())
2207       EltTy = VecTy->getElementType();
2208     if (EltTy->isUnsignedIntegerType()) {
2209       Diag(TheCall->getArg(0)->getBeginLoc(),
2210            diag::err_builtin_invalid_arg_type)
2211           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2212       return ExprError();
2213     }
2214     break;
2215   }
2216 
2217   // These builtins restrict the element type to floating point
2218   // types only.
2219   case Builtin::BI__builtin_elementwise_ceil:
2220   case Builtin::BI__builtin_elementwise_floor:
2221   case Builtin::BI__builtin_elementwise_roundeven:
2222   case Builtin::BI__builtin_elementwise_trunc: {
2223     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2224       return ExprError();
2225 
2226     QualType ArgTy = TheCall->getArg(0)->getType();
2227     QualType EltTy = ArgTy;
2228 
2229     if (auto *VecTy = EltTy->getAs<VectorType>())
2230       EltTy = VecTy->getElementType();
2231     if (!EltTy->isFloatingType()) {
2232       Diag(TheCall->getArg(0)->getBeginLoc(),
2233            diag::err_builtin_invalid_arg_type)
2234           << 1 << /* float ty*/ 5 << ArgTy;
2235 
2236       return ExprError();
2237     }
2238     break;
2239   }
2240 
2241   // These builtins restrict the element type to integer
2242   // types only.
2243   case Builtin::BI__builtin_elementwise_add_sat:
2244   case Builtin::BI__builtin_elementwise_sub_sat: {
2245     if (SemaBuiltinElementwiseMath(TheCall))
2246       return ExprError();
2247 
2248     const Expr *Arg = TheCall->getArg(0);
2249     QualType ArgTy = Arg->getType();
2250     QualType EltTy = ArgTy;
2251 
2252     if (auto *VecTy = EltTy->getAs<VectorType>())
2253       EltTy = VecTy->getElementType();
2254 
2255     if (!EltTy->isIntegerType()) {
2256       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2257           << 1 << /* integer ty */ 6 << ArgTy;
2258       return ExprError();
2259     }
2260     break;
2261   }
2262 
2263   case Builtin::BI__builtin_elementwise_min:
2264   case Builtin::BI__builtin_elementwise_max:
2265     if (SemaBuiltinElementwiseMath(TheCall))
2266       return ExprError();
2267     break;
2268   case Builtin::BI__builtin_reduce_max:
2269   case Builtin::BI__builtin_reduce_min: {
2270     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2271       return ExprError();
2272 
2273     const Expr *Arg = TheCall->getArg(0);
2274     const auto *TyA = Arg->getType()->getAs<VectorType>();
2275     if (!TyA) {
2276       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2277           << 1 << /* vector ty*/ 4 << Arg->getType();
2278       return ExprError();
2279     }
2280 
2281     TheCall->setType(TyA->getElementType());
2282     break;
2283   }
2284 
2285   // These builtins support vectors of integers only.
2286   case Builtin::BI__builtin_reduce_xor:
2287   case Builtin::BI__builtin_reduce_or:
2288   case Builtin::BI__builtin_reduce_and: {
2289     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2290       return ExprError();
2291 
2292     const Expr *Arg = TheCall->getArg(0);
2293     const auto *TyA = Arg->getType()->getAs<VectorType>();
2294     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2295       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2296           << 1  << /* vector of integers */ 6 << Arg->getType();
2297       return ExprError();
2298     }
2299     TheCall->setType(TyA->getElementType());
2300     break;
2301   }
2302 
2303   case Builtin::BI__builtin_matrix_transpose:
2304     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2305 
2306   case Builtin::BI__builtin_matrix_column_major_load:
2307     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2308 
2309   case Builtin::BI__builtin_matrix_column_major_store:
2310     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2311 
2312   case Builtin::BI__builtin_get_device_side_mangled_name: {
2313     auto Check = [](CallExpr *TheCall) {
2314       if (TheCall->getNumArgs() != 1)
2315         return false;
2316       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2317       if (!DRE)
2318         return false;
2319       auto *D = DRE->getDecl();
2320       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2321         return false;
2322       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2323              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2324     };
2325     if (!Check(TheCall)) {
2326       Diag(TheCall->getBeginLoc(),
2327            diag::err_hip_invalid_args_builtin_mangled_name);
2328       return ExprError();
2329     }
2330   }
2331   }
2332 
2333   // Since the target specific builtins for each arch overlap, only check those
2334   // of the arch we are compiling for.
2335   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2336     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2337       assert(Context.getAuxTargetInfo() &&
2338              "Aux Target Builtin, but not an aux target?");
2339 
2340       if (CheckTSBuiltinFunctionCall(
2341               *Context.getAuxTargetInfo(),
2342               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2343         return ExprError();
2344     } else {
2345       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2346                                      TheCall))
2347         return ExprError();
2348     }
2349   }
2350 
2351   return TheCallResult;
2352 }
2353 
2354 // Get the valid immediate range for the specified NEON type code.
2355 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2356   NeonTypeFlags Type(t);
2357   int IsQuad = ForceQuad ? true : Type.isQuad();
2358   switch (Type.getEltType()) {
2359   case NeonTypeFlags::Int8:
2360   case NeonTypeFlags::Poly8:
2361     return shift ? 7 : (8 << IsQuad) - 1;
2362   case NeonTypeFlags::Int16:
2363   case NeonTypeFlags::Poly16:
2364     return shift ? 15 : (4 << IsQuad) - 1;
2365   case NeonTypeFlags::Int32:
2366     return shift ? 31 : (2 << IsQuad) - 1;
2367   case NeonTypeFlags::Int64:
2368   case NeonTypeFlags::Poly64:
2369     return shift ? 63 : (1 << IsQuad) - 1;
2370   case NeonTypeFlags::Poly128:
2371     return shift ? 127 : (1 << IsQuad) - 1;
2372   case NeonTypeFlags::Float16:
2373     assert(!shift && "cannot shift float types!");
2374     return (4 << IsQuad) - 1;
2375   case NeonTypeFlags::Float32:
2376     assert(!shift && "cannot shift float types!");
2377     return (2 << IsQuad) - 1;
2378   case NeonTypeFlags::Float64:
2379     assert(!shift && "cannot shift float types!");
2380     return (1 << IsQuad) - 1;
2381   case NeonTypeFlags::BFloat16:
2382     assert(!shift && "cannot shift float types!");
2383     return (4 << IsQuad) - 1;
2384   }
2385   llvm_unreachable("Invalid NeonTypeFlag!");
2386 }
2387 
2388 /// getNeonEltType - Return the QualType corresponding to the elements of
2389 /// the vector type specified by the NeonTypeFlags.  This is used to check
2390 /// the pointer arguments for Neon load/store intrinsics.
2391 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2392                                bool IsPolyUnsigned, bool IsInt64Long) {
2393   switch (Flags.getEltType()) {
2394   case NeonTypeFlags::Int8:
2395     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2396   case NeonTypeFlags::Int16:
2397     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2398   case NeonTypeFlags::Int32:
2399     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2400   case NeonTypeFlags::Int64:
2401     if (IsInt64Long)
2402       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2403     else
2404       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2405                                 : Context.LongLongTy;
2406   case NeonTypeFlags::Poly8:
2407     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2408   case NeonTypeFlags::Poly16:
2409     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2410   case NeonTypeFlags::Poly64:
2411     if (IsInt64Long)
2412       return Context.UnsignedLongTy;
2413     else
2414       return Context.UnsignedLongLongTy;
2415   case NeonTypeFlags::Poly128:
2416     break;
2417   case NeonTypeFlags::Float16:
2418     return Context.HalfTy;
2419   case NeonTypeFlags::Float32:
2420     return Context.FloatTy;
2421   case NeonTypeFlags::Float64:
2422     return Context.DoubleTy;
2423   case NeonTypeFlags::BFloat16:
2424     return Context.BFloat16Ty;
2425   }
2426   llvm_unreachable("Invalid NeonTypeFlag!");
2427 }
2428 
2429 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2430   // Range check SVE intrinsics that take immediate values.
2431   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2432 
2433   switch (BuiltinID) {
2434   default:
2435     return false;
2436 #define GET_SVE_IMMEDIATE_CHECK
2437 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2438 #undef GET_SVE_IMMEDIATE_CHECK
2439   }
2440 
2441   // Perform all the immediate checks for this builtin call.
2442   bool HasError = false;
2443   for (auto &I : ImmChecks) {
2444     int ArgNum, CheckTy, ElementSizeInBits;
2445     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2446 
2447     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2448 
2449     // Function that checks whether the operand (ArgNum) is an immediate
2450     // that is one of the predefined values.
2451     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2452                                    int ErrDiag) -> bool {
2453       // We can't check the value of a dependent argument.
2454       Expr *Arg = TheCall->getArg(ArgNum);
2455       if (Arg->isTypeDependent() || Arg->isValueDependent())
2456         return false;
2457 
2458       // Check constant-ness first.
2459       llvm::APSInt Imm;
2460       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2461         return true;
2462 
2463       if (!CheckImm(Imm.getSExtValue()))
2464         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2465       return false;
2466     };
2467 
2468     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2469     case SVETypeFlags::ImmCheck0_31:
2470       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2471         HasError = true;
2472       break;
2473     case SVETypeFlags::ImmCheck0_13:
2474       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2475         HasError = true;
2476       break;
2477     case SVETypeFlags::ImmCheck1_16:
2478       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2479         HasError = true;
2480       break;
2481     case SVETypeFlags::ImmCheck0_7:
2482       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2483         HasError = true;
2484       break;
2485     case SVETypeFlags::ImmCheckExtract:
2486       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2487                                       (2048 / ElementSizeInBits) - 1))
2488         HasError = true;
2489       break;
2490     case SVETypeFlags::ImmCheckShiftRight:
2491       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2492         HasError = true;
2493       break;
2494     case SVETypeFlags::ImmCheckShiftRightNarrow:
2495       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2496                                       ElementSizeInBits / 2))
2497         HasError = true;
2498       break;
2499     case SVETypeFlags::ImmCheckShiftLeft:
2500       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2501                                       ElementSizeInBits - 1))
2502         HasError = true;
2503       break;
2504     case SVETypeFlags::ImmCheckLaneIndex:
2505       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2506                                       (128 / (1 * ElementSizeInBits)) - 1))
2507         HasError = true;
2508       break;
2509     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2510       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2511                                       (128 / (2 * ElementSizeInBits)) - 1))
2512         HasError = true;
2513       break;
2514     case SVETypeFlags::ImmCheckLaneIndexDot:
2515       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2516                                       (128 / (4 * ElementSizeInBits)) - 1))
2517         HasError = true;
2518       break;
2519     case SVETypeFlags::ImmCheckComplexRot90_270:
2520       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2521                               diag::err_rotation_argument_to_cadd))
2522         HasError = true;
2523       break;
2524     case SVETypeFlags::ImmCheckComplexRotAll90:
2525       if (CheckImmediateInSet(
2526               [](int64_t V) {
2527                 return V == 0 || V == 90 || V == 180 || V == 270;
2528               },
2529               diag::err_rotation_argument_to_cmla))
2530         HasError = true;
2531       break;
2532     case SVETypeFlags::ImmCheck0_1:
2533       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2534         HasError = true;
2535       break;
2536     case SVETypeFlags::ImmCheck0_2:
2537       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2538         HasError = true;
2539       break;
2540     case SVETypeFlags::ImmCheck0_3:
2541       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2542         HasError = true;
2543       break;
2544     }
2545   }
2546 
2547   return HasError;
2548 }
2549 
2550 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2551                                         unsigned BuiltinID, CallExpr *TheCall) {
2552   llvm::APSInt Result;
2553   uint64_t mask = 0;
2554   unsigned TV = 0;
2555   int PtrArgNum = -1;
2556   bool HasConstPtr = false;
2557   switch (BuiltinID) {
2558 #define GET_NEON_OVERLOAD_CHECK
2559 #include "clang/Basic/arm_neon.inc"
2560 #include "clang/Basic/arm_fp16.inc"
2561 #undef GET_NEON_OVERLOAD_CHECK
2562   }
2563 
2564   // For NEON intrinsics which are overloaded on vector element type, validate
2565   // the immediate which specifies which variant to emit.
2566   unsigned ImmArg = TheCall->getNumArgs()-1;
2567   if (mask) {
2568     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2569       return true;
2570 
2571     TV = Result.getLimitedValue(64);
2572     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2573       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2574              << TheCall->getArg(ImmArg)->getSourceRange();
2575   }
2576 
2577   if (PtrArgNum >= 0) {
2578     // Check that pointer arguments have the specified type.
2579     Expr *Arg = TheCall->getArg(PtrArgNum);
2580     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2581       Arg = ICE->getSubExpr();
2582     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2583     QualType RHSTy = RHS.get()->getType();
2584 
2585     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2586     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2587                           Arch == llvm::Triple::aarch64_32 ||
2588                           Arch == llvm::Triple::aarch64_be;
2589     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2590     QualType EltTy =
2591         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2592     if (HasConstPtr)
2593       EltTy = EltTy.withConst();
2594     QualType LHSTy = Context.getPointerType(EltTy);
2595     AssignConvertType ConvTy;
2596     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2597     if (RHS.isInvalid())
2598       return true;
2599     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2600                                  RHS.get(), AA_Assigning))
2601       return true;
2602   }
2603 
2604   // For NEON intrinsics which take an immediate value as part of the
2605   // instruction, range check them here.
2606   unsigned i = 0, l = 0, u = 0;
2607   switch (BuiltinID) {
2608   default:
2609     return false;
2610   #define GET_NEON_IMMEDIATE_CHECK
2611   #include "clang/Basic/arm_neon.inc"
2612   #include "clang/Basic/arm_fp16.inc"
2613   #undef GET_NEON_IMMEDIATE_CHECK
2614   }
2615 
2616   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2617 }
2618 
2619 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2620   switch (BuiltinID) {
2621   default:
2622     return false;
2623   #include "clang/Basic/arm_mve_builtin_sema.inc"
2624   }
2625 }
2626 
2627 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2628                                        CallExpr *TheCall) {
2629   bool Err = false;
2630   switch (BuiltinID) {
2631   default:
2632     return false;
2633 #include "clang/Basic/arm_cde_builtin_sema.inc"
2634   }
2635 
2636   if (Err)
2637     return true;
2638 
2639   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2640 }
2641 
2642 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2643                                         const Expr *CoprocArg, bool WantCDE) {
2644   if (isConstantEvaluated())
2645     return false;
2646 
2647   // We can't check the value of a dependent argument.
2648   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2649     return false;
2650 
2651   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2652   int64_t CoprocNo = CoprocNoAP.getExtValue();
2653   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2654 
2655   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2656   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2657 
2658   if (IsCDECoproc != WantCDE)
2659     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2660            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2661 
2662   return false;
2663 }
2664 
2665 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2666                                         unsigned MaxWidth) {
2667   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2668           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2669           BuiltinID == ARM::BI__builtin_arm_strex ||
2670           BuiltinID == ARM::BI__builtin_arm_stlex ||
2671           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2672           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2673           BuiltinID == AArch64::BI__builtin_arm_strex ||
2674           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2675          "unexpected ARM builtin");
2676   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2677                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2678                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2679                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2680 
2681   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2682 
2683   // Ensure that we have the proper number of arguments.
2684   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2685     return true;
2686 
2687   // Inspect the pointer argument of the atomic builtin.  This should always be
2688   // a pointer type, whose element is an integral scalar or pointer type.
2689   // Because it is a pointer type, we don't have to worry about any implicit
2690   // casts here.
2691   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2692   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2693   if (PointerArgRes.isInvalid())
2694     return true;
2695   PointerArg = PointerArgRes.get();
2696 
2697   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2698   if (!pointerType) {
2699     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2700         << PointerArg->getType() << PointerArg->getSourceRange();
2701     return true;
2702   }
2703 
2704   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2705   // task is to insert the appropriate casts into the AST. First work out just
2706   // what the appropriate type is.
2707   QualType ValType = pointerType->getPointeeType();
2708   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2709   if (IsLdrex)
2710     AddrType.addConst();
2711 
2712   // Issue a warning if the cast is dodgy.
2713   CastKind CastNeeded = CK_NoOp;
2714   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2715     CastNeeded = CK_BitCast;
2716     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2717         << PointerArg->getType() << Context.getPointerType(AddrType)
2718         << AA_Passing << PointerArg->getSourceRange();
2719   }
2720 
2721   // Finally, do the cast and replace the argument with the corrected version.
2722   AddrType = Context.getPointerType(AddrType);
2723   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2724   if (PointerArgRes.isInvalid())
2725     return true;
2726   PointerArg = PointerArgRes.get();
2727 
2728   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2729 
2730   // In general, we allow ints, floats and pointers to be loaded and stored.
2731   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2732       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2733     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2734         << PointerArg->getType() << PointerArg->getSourceRange();
2735     return true;
2736   }
2737 
2738   // But ARM doesn't have instructions to deal with 128-bit versions.
2739   if (Context.getTypeSize(ValType) > MaxWidth) {
2740     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2741     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2742         << PointerArg->getType() << PointerArg->getSourceRange();
2743     return true;
2744   }
2745 
2746   switch (ValType.getObjCLifetime()) {
2747   case Qualifiers::OCL_None:
2748   case Qualifiers::OCL_ExplicitNone:
2749     // okay
2750     break;
2751 
2752   case Qualifiers::OCL_Weak:
2753   case Qualifiers::OCL_Strong:
2754   case Qualifiers::OCL_Autoreleasing:
2755     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2756         << ValType << PointerArg->getSourceRange();
2757     return true;
2758   }
2759 
2760   if (IsLdrex) {
2761     TheCall->setType(ValType);
2762     return false;
2763   }
2764 
2765   // Initialize the argument to be stored.
2766   ExprResult ValArg = TheCall->getArg(0);
2767   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2768       Context, ValType, /*consume*/ false);
2769   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2770   if (ValArg.isInvalid())
2771     return true;
2772   TheCall->setArg(0, ValArg.get());
2773 
2774   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2775   // but the custom checker bypasses all default analysis.
2776   TheCall->setType(Context.IntTy);
2777   return false;
2778 }
2779 
2780 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2781                                        CallExpr *TheCall) {
2782   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2783       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2784       BuiltinID == ARM::BI__builtin_arm_strex ||
2785       BuiltinID == ARM::BI__builtin_arm_stlex) {
2786     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2787   }
2788 
2789   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2790     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2791       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2792   }
2793 
2794   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2795       BuiltinID == ARM::BI__builtin_arm_wsr64)
2796     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2797 
2798   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2799       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2800       BuiltinID == ARM::BI__builtin_arm_wsr ||
2801       BuiltinID == ARM::BI__builtin_arm_wsrp)
2802     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2803 
2804   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2805     return true;
2806   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2807     return true;
2808   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2809     return true;
2810 
2811   // For intrinsics which take an immediate value as part of the instruction,
2812   // range check them here.
2813   // FIXME: VFP Intrinsics should error if VFP not present.
2814   switch (BuiltinID) {
2815   default: return false;
2816   case ARM::BI__builtin_arm_ssat:
2817     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2818   case ARM::BI__builtin_arm_usat:
2819     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2820   case ARM::BI__builtin_arm_ssat16:
2821     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2822   case ARM::BI__builtin_arm_usat16:
2823     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2824   case ARM::BI__builtin_arm_vcvtr_f:
2825   case ARM::BI__builtin_arm_vcvtr_d:
2826     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2827   case ARM::BI__builtin_arm_dmb:
2828   case ARM::BI__builtin_arm_dsb:
2829   case ARM::BI__builtin_arm_isb:
2830   case ARM::BI__builtin_arm_dbg:
2831     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2832   case ARM::BI__builtin_arm_cdp:
2833   case ARM::BI__builtin_arm_cdp2:
2834   case ARM::BI__builtin_arm_mcr:
2835   case ARM::BI__builtin_arm_mcr2:
2836   case ARM::BI__builtin_arm_mrc:
2837   case ARM::BI__builtin_arm_mrc2:
2838   case ARM::BI__builtin_arm_mcrr:
2839   case ARM::BI__builtin_arm_mcrr2:
2840   case ARM::BI__builtin_arm_mrrc:
2841   case ARM::BI__builtin_arm_mrrc2:
2842   case ARM::BI__builtin_arm_ldc:
2843   case ARM::BI__builtin_arm_ldcl:
2844   case ARM::BI__builtin_arm_ldc2:
2845   case ARM::BI__builtin_arm_ldc2l:
2846   case ARM::BI__builtin_arm_stc:
2847   case ARM::BI__builtin_arm_stcl:
2848   case ARM::BI__builtin_arm_stc2:
2849   case ARM::BI__builtin_arm_stc2l:
2850     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2851            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2852                                         /*WantCDE*/ false);
2853   }
2854 }
2855 
2856 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2857                                            unsigned BuiltinID,
2858                                            CallExpr *TheCall) {
2859   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2860       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2861       BuiltinID == AArch64::BI__builtin_arm_strex ||
2862       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2863     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2864   }
2865 
2866   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2867     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2868       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2869       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2870       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2871   }
2872 
2873   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2874       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2875     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2876 
2877   // Memory Tagging Extensions (MTE) Intrinsics
2878   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2879       BuiltinID == AArch64::BI__builtin_arm_addg ||
2880       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2881       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2882       BuiltinID == AArch64::BI__builtin_arm_stg ||
2883       BuiltinID == AArch64::BI__builtin_arm_subp) {
2884     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2885   }
2886 
2887   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2888       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2889       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2890       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2891     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2892 
2893   // Only check the valid encoding range. Any constant in this range would be
2894   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2895   // an exception for incorrect registers. This matches MSVC behavior.
2896   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2897       BuiltinID == AArch64::BI_WriteStatusReg)
2898     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2899 
2900   if (BuiltinID == AArch64::BI__getReg)
2901     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2902 
2903   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2904     return true;
2905 
2906   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2907     return true;
2908 
2909   // For intrinsics which take an immediate value as part of the instruction,
2910   // range check them here.
2911   unsigned i = 0, l = 0, u = 0;
2912   switch (BuiltinID) {
2913   default: return false;
2914   case AArch64::BI__builtin_arm_dmb:
2915   case AArch64::BI__builtin_arm_dsb:
2916   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2917   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2918   }
2919 
2920   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2921 }
2922 
2923 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2924   if (Arg->getType()->getAsPlaceholderType())
2925     return false;
2926 
2927   // The first argument needs to be a record field access.
2928   // If it is an array element access, we delay decision
2929   // to BPF backend to check whether the access is a
2930   // field access or not.
2931   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2932           isa<MemberExpr>(Arg->IgnoreParens()) ||
2933           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2934 }
2935 
2936 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2937                             QualType VectorTy, QualType EltTy) {
2938   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2939   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2940     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2941         << Call->getSourceRange() << VectorEltTy << EltTy;
2942     return false;
2943   }
2944   return true;
2945 }
2946 
2947 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2948   QualType ArgType = Arg->getType();
2949   if (ArgType->getAsPlaceholderType())
2950     return false;
2951 
2952   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2953   // format:
2954   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2955   //   2. <type> var;
2956   //      __builtin_preserve_type_info(var, flag);
2957   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2958       !isa<UnaryOperator>(Arg->IgnoreParens()))
2959     return false;
2960 
2961   // Typedef type.
2962   if (ArgType->getAs<TypedefType>())
2963     return true;
2964 
2965   // Record type or Enum type.
2966   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2967   if (const auto *RT = Ty->getAs<RecordType>()) {
2968     if (!RT->getDecl()->getDeclName().isEmpty())
2969       return true;
2970   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2971     if (!ET->getDecl()->getDeclName().isEmpty())
2972       return true;
2973   }
2974 
2975   return false;
2976 }
2977 
2978 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2979   QualType ArgType = Arg->getType();
2980   if (ArgType->getAsPlaceholderType())
2981     return false;
2982 
2983   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2984   // format:
2985   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2986   //                                 flag);
2987   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2988   if (!UO)
2989     return false;
2990 
2991   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2992   if (!CE)
2993     return false;
2994   if (CE->getCastKind() != CK_IntegralToPointer &&
2995       CE->getCastKind() != CK_NullToPointer)
2996     return false;
2997 
2998   // The integer must be from an EnumConstantDecl.
2999   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3000   if (!DR)
3001     return false;
3002 
3003   const EnumConstantDecl *Enumerator =
3004       dyn_cast<EnumConstantDecl>(DR->getDecl());
3005   if (!Enumerator)
3006     return false;
3007 
3008   // The type must be EnumType.
3009   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3010   const auto *ET = Ty->getAs<EnumType>();
3011   if (!ET)
3012     return false;
3013 
3014   // The enum value must be supported.
3015   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3016 }
3017 
3018 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3019                                        CallExpr *TheCall) {
3020   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3021           BuiltinID == BPF::BI__builtin_btf_type_id ||
3022           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3023           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3024          "unexpected BPF builtin");
3025 
3026   if (checkArgCount(*this, TheCall, 2))
3027     return true;
3028 
3029   // The second argument needs to be a constant int
3030   Expr *Arg = TheCall->getArg(1);
3031   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3032   diag::kind kind;
3033   if (!Value) {
3034     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3035       kind = diag::err_preserve_field_info_not_const;
3036     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3037       kind = diag::err_btf_type_id_not_const;
3038     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3039       kind = diag::err_preserve_type_info_not_const;
3040     else
3041       kind = diag::err_preserve_enum_value_not_const;
3042     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3043     return true;
3044   }
3045 
3046   // The first argument
3047   Arg = TheCall->getArg(0);
3048   bool InvalidArg = false;
3049   bool ReturnUnsignedInt = true;
3050   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3051     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3052       InvalidArg = true;
3053       kind = diag::err_preserve_field_info_not_field;
3054     }
3055   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3056     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3057       InvalidArg = true;
3058       kind = diag::err_preserve_type_info_invalid;
3059     }
3060   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3061     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3062       InvalidArg = true;
3063       kind = diag::err_preserve_enum_value_invalid;
3064     }
3065     ReturnUnsignedInt = false;
3066   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3067     ReturnUnsignedInt = false;
3068   }
3069 
3070   if (InvalidArg) {
3071     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3072     return true;
3073   }
3074 
3075   if (ReturnUnsignedInt)
3076     TheCall->setType(Context.UnsignedIntTy);
3077   else
3078     TheCall->setType(Context.UnsignedLongTy);
3079   return false;
3080 }
3081 
3082 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3083   struct ArgInfo {
3084     uint8_t OpNum;
3085     bool IsSigned;
3086     uint8_t BitWidth;
3087     uint8_t Align;
3088   };
3089   struct BuiltinInfo {
3090     unsigned BuiltinID;
3091     ArgInfo Infos[2];
3092   };
3093 
3094   static BuiltinInfo Infos[] = {
3095     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3096     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3097     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3098     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3099     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3100     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3101     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3102     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3103     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3104     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3105     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3106 
3107     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3108     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3109     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3110     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3111     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3112     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3113     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3114     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3115     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3116     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3117     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3118 
3119     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3120     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3121     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3122     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3123     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3124     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3125     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3126     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3127     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3128     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3129     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3130     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3131     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3132     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3133     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3134     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3135     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3136     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3137     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3138     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3139     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3140     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3141     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3142     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3143     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3144     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3145     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3146     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3147     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3148     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3149     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3150     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3151     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3152     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3153     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3154     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3155     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3156     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3157     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3158     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3159     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3160     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3161     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3162     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3163     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3164     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3165     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3166     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3167     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3168     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3169     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3170     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3171                                                       {{ 1, false, 6,  0 }} },
3172     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3173     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3174     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3175     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3176     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3177     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3178     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3179                                                       {{ 1, false, 5,  0 }} },
3180     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3181     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3182     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3183     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3184     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3185     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3186                                                        { 2, false, 5,  0 }} },
3187     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3188                                                        { 2, false, 6,  0 }} },
3189     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3190                                                        { 3, false, 5,  0 }} },
3191     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3192                                                        { 3, false, 6,  0 }} },
3193     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3194     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3195     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3196     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3197     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3198     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3199     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3200     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3201     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3202     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3203     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3204     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3205     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3206     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3207     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3208     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3209                                                       {{ 2, false, 4,  0 },
3210                                                        { 3, false, 5,  0 }} },
3211     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3212                                                       {{ 2, false, 4,  0 },
3213                                                        { 3, false, 5,  0 }} },
3214     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3215                                                       {{ 2, false, 4,  0 },
3216                                                        { 3, false, 5,  0 }} },
3217     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3218                                                       {{ 2, false, 4,  0 },
3219                                                        { 3, false, 5,  0 }} },
3220     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3221     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3222     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3223     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3224     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3225     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3226     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3227     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3228     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3229     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3230     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3231                                                        { 2, false, 5,  0 }} },
3232     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3233                                                        { 2, false, 6,  0 }} },
3234     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3235     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3236     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3237     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3238     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3239     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3240     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3241     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3242     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3243                                                       {{ 1, false, 4,  0 }} },
3244     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3245     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3246                                                       {{ 1, false, 4,  0 }} },
3247     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3248     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3249     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3250     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3251     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3252     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3253     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3254     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3255     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3256     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3257     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3258     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3259     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3260     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3261     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3262     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3263     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3264     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3265     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3266     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3267                                                       {{ 3, false, 1,  0 }} },
3268     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3269     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3270     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3271     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3272                                                       {{ 3, false, 1,  0 }} },
3273     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3274     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3275     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3276     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3277                                                       {{ 3, false, 1,  0 }} },
3278   };
3279 
3280   // Use a dynamically initialized static to sort the table exactly once on
3281   // first run.
3282   static const bool SortOnce =
3283       (llvm::sort(Infos,
3284                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3285                    return LHS.BuiltinID < RHS.BuiltinID;
3286                  }),
3287        true);
3288   (void)SortOnce;
3289 
3290   const BuiltinInfo *F = llvm::partition_point(
3291       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3292   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3293     return false;
3294 
3295   bool Error = false;
3296 
3297   for (const ArgInfo &A : F->Infos) {
3298     // Ignore empty ArgInfo elements.
3299     if (A.BitWidth == 0)
3300       continue;
3301 
3302     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3303     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3304     if (!A.Align) {
3305       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3306     } else {
3307       unsigned M = 1 << A.Align;
3308       Min *= M;
3309       Max *= M;
3310       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3311       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3312     }
3313   }
3314   return Error;
3315 }
3316 
3317 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3318                                            CallExpr *TheCall) {
3319   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3320 }
3321 
3322 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3323                                         unsigned BuiltinID, CallExpr *TheCall) {
3324   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3325          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3326 }
3327 
3328 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3329                                CallExpr *TheCall) {
3330 
3331   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3332       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3333     if (!TI.hasFeature("dsp"))
3334       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3335   }
3336 
3337   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3338       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3339     if (!TI.hasFeature("dspr2"))
3340       return Diag(TheCall->getBeginLoc(),
3341                   diag::err_mips_builtin_requires_dspr2);
3342   }
3343 
3344   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3345       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3346     if (!TI.hasFeature("msa"))
3347       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3348   }
3349 
3350   return false;
3351 }
3352 
3353 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3354 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3355 // ordering for DSP is unspecified. MSA is ordered by the data format used
3356 // by the underlying instruction i.e., df/m, df/n and then by size.
3357 //
3358 // FIXME: The size tests here should instead be tablegen'd along with the
3359 //        definitions from include/clang/Basic/BuiltinsMips.def.
3360 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3361 //        be too.
3362 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3363   unsigned i = 0, l = 0, u = 0, m = 0;
3364   switch (BuiltinID) {
3365   default: return false;
3366   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3367   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3368   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3369   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3370   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3371   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3372   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3373   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3374   // df/m field.
3375   // These intrinsics take an unsigned 3 bit immediate.
3376   case Mips::BI__builtin_msa_bclri_b:
3377   case Mips::BI__builtin_msa_bnegi_b:
3378   case Mips::BI__builtin_msa_bseti_b:
3379   case Mips::BI__builtin_msa_sat_s_b:
3380   case Mips::BI__builtin_msa_sat_u_b:
3381   case Mips::BI__builtin_msa_slli_b:
3382   case Mips::BI__builtin_msa_srai_b:
3383   case Mips::BI__builtin_msa_srari_b:
3384   case Mips::BI__builtin_msa_srli_b:
3385   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3386   case Mips::BI__builtin_msa_binsli_b:
3387   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3388   // These intrinsics take an unsigned 4 bit immediate.
3389   case Mips::BI__builtin_msa_bclri_h:
3390   case Mips::BI__builtin_msa_bnegi_h:
3391   case Mips::BI__builtin_msa_bseti_h:
3392   case Mips::BI__builtin_msa_sat_s_h:
3393   case Mips::BI__builtin_msa_sat_u_h:
3394   case Mips::BI__builtin_msa_slli_h:
3395   case Mips::BI__builtin_msa_srai_h:
3396   case Mips::BI__builtin_msa_srari_h:
3397   case Mips::BI__builtin_msa_srli_h:
3398   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3399   case Mips::BI__builtin_msa_binsli_h:
3400   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3401   // These intrinsics take an unsigned 5 bit immediate.
3402   // The first block of intrinsics actually have an unsigned 5 bit field,
3403   // not a df/n field.
3404   case Mips::BI__builtin_msa_cfcmsa:
3405   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3406   case Mips::BI__builtin_msa_clei_u_b:
3407   case Mips::BI__builtin_msa_clei_u_h:
3408   case Mips::BI__builtin_msa_clei_u_w:
3409   case Mips::BI__builtin_msa_clei_u_d:
3410   case Mips::BI__builtin_msa_clti_u_b:
3411   case Mips::BI__builtin_msa_clti_u_h:
3412   case Mips::BI__builtin_msa_clti_u_w:
3413   case Mips::BI__builtin_msa_clti_u_d:
3414   case Mips::BI__builtin_msa_maxi_u_b:
3415   case Mips::BI__builtin_msa_maxi_u_h:
3416   case Mips::BI__builtin_msa_maxi_u_w:
3417   case Mips::BI__builtin_msa_maxi_u_d:
3418   case Mips::BI__builtin_msa_mini_u_b:
3419   case Mips::BI__builtin_msa_mini_u_h:
3420   case Mips::BI__builtin_msa_mini_u_w:
3421   case Mips::BI__builtin_msa_mini_u_d:
3422   case Mips::BI__builtin_msa_addvi_b:
3423   case Mips::BI__builtin_msa_addvi_h:
3424   case Mips::BI__builtin_msa_addvi_w:
3425   case Mips::BI__builtin_msa_addvi_d:
3426   case Mips::BI__builtin_msa_bclri_w:
3427   case Mips::BI__builtin_msa_bnegi_w:
3428   case Mips::BI__builtin_msa_bseti_w:
3429   case Mips::BI__builtin_msa_sat_s_w:
3430   case Mips::BI__builtin_msa_sat_u_w:
3431   case Mips::BI__builtin_msa_slli_w:
3432   case Mips::BI__builtin_msa_srai_w:
3433   case Mips::BI__builtin_msa_srari_w:
3434   case Mips::BI__builtin_msa_srli_w:
3435   case Mips::BI__builtin_msa_srlri_w:
3436   case Mips::BI__builtin_msa_subvi_b:
3437   case Mips::BI__builtin_msa_subvi_h:
3438   case Mips::BI__builtin_msa_subvi_w:
3439   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3440   case Mips::BI__builtin_msa_binsli_w:
3441   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3442   // These intrinsics take an unsigned 6 bit immediate.
3443   case Mips::BI__builtin_msa_bclri_d:
3444   case Mips::BI__builtin_msa_bnegi_d:
3445   case Mips::BI__builtin_msa_bseti_d:
3446   case Mips::BI__builtin_msa_sat_s_d:
3447   case Mips::BI__builtin_msa_sat_u_d:
3448   case Mips::BI__builtin_msa_slli_d:
3449   case Mips::BI__builtin_msa_srai_d:
3450   case Mips::BI__builtin_msa_srari_d:
3451   case Mips::BI__builtin_msa_srli_d:
3452   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3453   case Mips::BI__builtin_msa_binsli_d:
3454   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3455   // These intrinsics take a signed 5 bit immediate.
3456   case Mips::BI__builtin_msa_ceqi_b:
3457   case Mips::BI__builtin_msa_ceqi_h:
3458   case Mips::BI__builtin_msa_ceqi_w:
3459   case Mips::BI__builtin_msa_ceqi_d:
3460   case Mips::BI__builtin_msa_clti_s_b:
3461   case Mips::BI__builtin_msa_clti_s_h:
3462   case Mips::BI__builtin_msa_clti_s_w:
3463   case Mips::BI__builtin_msa_clti_s_d:
3464   case Mips::BI__builtin_msa_clei_s_b:
3465   case Mips::BI__builtin_msa_clei_s_h:
3466   case Mips::BI__builtin_msa_clei_s_w:
3467   case Mips::BI__builtin_msa_clei_s_d:
3468   case Mips::BI__builtin_msa_maxi_s_b:
3469   case Mips::BI__builtin_msa_maxi_s_h:
3470   case Mips::BI__builtin_msa_maxi_s_w:
3471   case Mips::BI__builtin_msa_maxi_s_d:
3472   case Mips::BI__builtin_msa_mini_s_b:
3473   case Mips::BI__builtin_msa_mini_s_h:
3474   case Mips::BI__builtin_msa_mini_s_w:
3475   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3476   // These intrinsics take an unsigned 8 bit immediate.
3477   case Mips::BI__builtin_msa_andi_b:
3478   case Mips::BI__builtin_msa_nori_b:
3479   case Mips::BI__builtin_msa_ori_b:
3480   case Mips::BI__builtin_msa_shf_b:
3481   case Mips::BI__builtin_msa_shf_h:
3482   case Mips::BI__builtin_msa_shf_w:
3483   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3484   case Mips::BI__builtin_msa_bseli_b:
3485   case Mips::BI__builtin_msa_bmnzi_b:
3486   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3487   // df/n format
3488   // These intrinsics take an unsigned 4 bit immediate.
3489   case Mips::BI__builtin_msa_copy_s_b:
3490   case Mips::BI__builtin_msa_copy_u_b:
3491   case Mips::BI__builtin_msa_insve_b:
3492   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3493   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3494   // These intrinsics take an unsigned 3 bit immediate.
3495   case Mips::BI__builtin_msa_copy_s_h:
3496   case Mips::BI__builtin_msa_copy_u_h:
3497   case Mips::BI__builtin_msa_insve_h:
3498   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3499   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3500   // These intrinsics take an unsigned 2 bit immediate.
3501   case Mips::BI__builtin_msa_copy_s_w:
3502   case Mips::BI__builtin_msa_copy_u_w:
3503   case Mips::BI__builtin_msa_insve_w:
3504   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3505   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3506   // These intrinsics take an unsigned 1 bit immediate.
3507   case Mips::BI__builtin_msa_copy_s_d:
3508   case Mips::BI__builtin_msa_copy_u_d:
3509   case Mips::BI__builtin_msa_insve_d:
3510   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3511   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3512   // Memory offsets and immediate loads.
3513   // These intrinsics take a signed 10 bit immediate.
3514   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3515   case Mips::BI__builtin_msa_ldi_h:
3516   case Mips::BI__builtin_msa_ldi_w:
3517   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3518   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3519   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3520   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3521   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3522   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3523   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3524   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3525   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3526   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3527   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3528   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3529   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3530   }
3531 
3532   if (!m)
3533     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3534 
3535   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3536          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3537 }
3538 
3539 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3540 /// advancing the pointer over the consumed characters. The decoded type is
3541 /// returned. If the decoded type represents a constant integer with a
3542 /// constraint on its value then Mask is set to that value. The type descriptors
3543 /// used in Str are specific to PPC MMA builtins and are documented in the file
3544 /// defining the PPC builtins.
3545 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3546                                         unsigned &Mask) {
3547   bool RequireICE = false;
3548   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3549   switch (*Str++) {
3550   case 'V':
3551     return Context.getVectorType(Context.UnsignedCharTy, 16,
3552                                  VectorType::VectorKind::AltiVecVector);
3553   case 'i': {
3554     char *End;
3555     unsigned size = strtoul(Str, &End, 10);
3556     assert(End != Str && "Missing constant parameter constraint");
3557     Str = End;
3558     Mask = size;
3559     return Context.IntTy;
3560   }
3561   case 'W': {
3562     char *End;
3563     unsigned size = strtoul(Str, &End, 10);
3564     assert(End != Str && "Missing PowerPC MMA type size");
3565     Str = End;
3566     QualType Type;
3567     switch (size) {
3568   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3569     case size: Type = Context.Id##Ty; break;
3570   #include "clang/Basic/PPCTypes.def"
3571     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3572     }
3573     bool CheckVectorArgs = false;
3574     while (!CheckVectorArgs) {
3575       switch (*Str++) {
3576       case '*':
3577         Type = Context.getPointerType(Type);
3578         break;
3579       case 'C':
3580         Type = Type.withConst();
3581         break;
3582       default:
3583         CheckVectorArgs = true;
3584         --Str;
3585         break;
3586       }
3587     }
3588     return Type;
3589   }
3590   default:
3591     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3592   }
3593 }
3594 
3595 static bool isPPC_64Builtin(unsigned BuiltinID) {
3596   // These builtins only work on PPC 64bit targets.
3597   switch (BuiltinID) {
3598   case PPC::BI__builtin_divde:
3599   case PPC::BI__builtin_divdeu:
3600   case PPC::BI__builtin_bpermd:
3601   case PPC::BI__builtin_ppc_ldarx:
3602   case PPC::BI__builtin_ppc_stdcx:
3603   case PPC::BI__builtin_ppc_tdw:
3604   case PPC::BI__builtin_ppc_trapd:
3605   case PPC::BI__builtin_ppc_cmpeqb:
3606   case PPC::BI__builtin_ppc_setb:
3607   case PPC::BI__builtin_ppc_mulhd:
3608   case PPC::BI__builtin_ppc_mulhdu:
3609   case PPC::BI__builtin_ppc_maddhd:
3610   case PPC::BI__builtin_ppc_maddhdu:
3611   case PPC::BI__builtin_ppc_maddld:
3612   case PPC::BI__builtin_ppc_load8r:
3613   case PPC::BI__builtin_ppc_store8r:
3614   case PPC::BI__builtin_ppc_insert_exp:
3615   case PPC::BI__builtin_ppc_extract_sig:
3616   case PPC::BI__builtin_ppc_addex:
3617   case PPC::BI__builtin_darn:
3618   case PPC::BI__builtin_darn_raw:
3619   case PPC::BI__builtin_ppc_compare_and_swaplp:
3620   case PPC::BI__builtin_ppc_fetch_and_addlp:
3621   case PPC::BI__builtin_ppc_fetch_and_andlp:
3622   case PPC::BI__builtin_ppc_fetch_and_orlp:
3623   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3624     return true;
3625   }
3626   return false;
3627 }
3628 
3629 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3630                              StringRef FeatureToCheck, unsigned DiagID,
3631                              StringRef DiagArg = "") {
3632   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3633     return false;
3634 
3635   if (DiagArg.empty())
3636     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3637   else
3638     S.Diag(TheCall->getBeginLoc(), DiagID)
3639         << DiagArg << TheCall->getSourceRange();
3640 
3641   return true;
3642 }
3643 
3644 /// Returns true if the argument consists of one contiguous run of 1s with any
3645 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3646 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3647 /// since all 1s are not contiguous.
3648 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3649   llvm::APSInt Result;
3650   // We can't check the value of a dependent argument.
3651   Expr *Arg = TheCall->getArg(ArgNum);
3652   if (Arg->isTypeDependent() || Arg->isValueDependent())
3653     return false;
3654 
3655   // Check constant-ness first.
3656   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3657     return true;
3658 
3659   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3660   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3661     return false;
3662 
3663   return Diag(TheCall->getBeginLoc(),
3664               diag::err_argument_not_contiguous_bit_field)
3665          << ArgNum << Arg->getSourceRange();
3666 }
3667 
3668 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3669                                        CallExpr *TheCall) {
3670   unsigned i = 0, l = 0, u = 0;
3671   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3672   llvm::APSInt Result;
3673 
3674   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3675     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3676            << TheCall->getSourceRange();
3677 
3678   switch (BuiltinID) {
3679   default: return false;
3680   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3681   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3682     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3683            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3684   case PPC::BI__builtin_altivec_dss:
3685     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3686   case PPC::BI__builtin_tbegin:
3687   case PPC::BI__builtin_tend:
3688     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3689            SemaFeatureCheck(*this, TheCall, "htm",
3690                             diag::err_ppc_builtin_requires_htm);
3691   case PPC::BI__builtin_tsr:
3692     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3693            SemaFeatureCheck(*this, TheCall, "htm",
3694                             diag::err_ppc_builtin_requires_htm);
3695   case PPC::BI__builtin_tabortwc:
3696   case PPC::BI__builtin_tabortdc:
3697     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3698            SemaFeatureCheck(*this, TheCall, "htm",
3699                             diag::err_ppc_builtin_requires_htm);
3700   case PPC::BI__builtin_tabortwci:
3701   case PPC::BI__builtin_tabortdci:
3702     return SemaFeatureCheck(*this, TheCall, "htm",
3703                             diag::err_ppc_builtin_requires_htm) ||
3704            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3705             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3706   case PPC::BI__builtin_tabort:
3707   case PPC::BI__builtin_tcheck:
3708   case PPC::BI__builtin_treclaim:
3709   case PPC::BI__builtin_trechkpt:
3710   case PPC::BI__builtin_tendall:
3711   case PPC::BI__builtin_tresume:
3712   case PPC::BI__builtin_tsuspend:
3713   case PPC::BI__builtin_get_texasr:
3714   case PPC::BI__builtin_get_texasru:
3715   case PPC::BI__builtin_get_tfhar:
3716   case PPC::BI__builtin_get_tfiar:
3717   case PPC::BI__builtin_set_texasr:
3718   case PPC::BI__builtin_set_texasru:
3719   case PPC::BI__builtin_set_tfhar:
3720   case PPC::BI__builtin_set_tfiar:
3721   case PPC::BI__builtin_ttest:
3722     return SemaFeatureCheck(*this, TheCall, "htm",
3723                             diag::err_ppc_builtin_requires_htm);
3724   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3725   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3726   // extended double representation.
3727   case PPC::BI__builtin_unpack_longdouble:
3728     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3729       return true;
3730     LLVM_FALLTHROUGH;
3731   case PPC::BI__builtin_pack_longdouble:
3732     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3733       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3734              << "ibmlongdouble";
3735     return false;
3736   case PPC::BI__builtin_altivec_dst:
3737   case PPC::BI__builtin_altivec_dstt:
3738   case PPC::BI__builtin_altivec_dstst:
3739   case PPC::BI__builtin_altivec_dststt:
3740     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3741   case PPC::BI__builtin_vsx_xxpermdi:
3742   case PPC::BI__builtin_vsx_xxsldwi:
3743     return SemaBuiltinVSX(TheCall);
3744   case PPC::BI__builtin_divwe:
3745   case PPC::BI__builtin_divweu:
3746   case PPC::BI__builtin_divde:
3747   case PPC::BI__builtin_divdeu:
3748     return SemaFeatureCheck(*this, TheCall, "extdiv",
3749                             diag::err_ppc_builtin_only_on_arch, "7");
3750   case PPC::BI__builtin_bpermd:
3751     return SemaFeatureCheck(*this, TheCall, "bpermd",
3752                             diag::err_ppc_builtin_only_on_arch, "7");
3753   case PPC::BI__builtin_unpack_vector_int128:
3754     return SemaFeatureCheck(*this, TheCall, "vsx",
3755                             diag::err_ppc_builtin_only_on_arch, "7") ||
3756            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3757   case PPC::BI__builtin_pack_vector_int128:
3758     return SemaFeatureCheck(*this, TheCall, "vsx",
3759                             diag::err_ppc_builtin_only_on_arch, "7");
3760   case PPC::BI__builtin_altivec_vgnb:
3761      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3762   case PPC::BI__builtin_altivec_vec_replace_elt:
3763   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3764     QualType VecTy = TheCall->getArg(0)->getType();
3765     QualType EltTy = TheCall->getArg(1)->getType();
3766     unsigned Width = Context.getIntWidth(EltTy);
3767     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3768            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3769   }
3770   case PPC::BI__builtin_vsx_xxeval:
3771      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3772   case PPC::BI__builtin_altivec_vsldbi:
3773      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3774   case PPC::BI__builtin_altivec_vsrdbi:
3775      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3776   case PPC::BI__builtin_vsx_xxpermx:
3777      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3778   case PPC::BI__builtin_ppc_tw:
3779   case PPC::BI__builtin_ppc_tdw:
3780     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3781   case PPC::BI__builtin_ppc_cmpeqb:
3782   case PPC::BI__builtin_ppc_setb:
3783   case PPC::BI__builtin_ppc_maddhd:
3784   case PPC::BI__builtin_ppc_maddhdu:
3785   case PPC::BI__builtin_ppc_maddld:
3786     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3787                             diag::err_ppc_builtin_only_on_arch, "9");
3788   case PPC::BI__builtin_ppc_cmprb:
3789     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3790                             diag::err_ppc_builtin_only_on_arch, "9") ||
3791            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3792   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3793   // be a constant that represents a contiguous bit field.
3794   case PPC::BI__builtin_ppc_rlwnm:
3795     return SemaValueIsRunOfOnes(TheCall, 2);
3796   case PPC::BI__builtin_ppc_rlwimi:
3797   case PPC::BI__builtin_ppc_rldimi:
3798     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3799            SemaValueIsRunOfOnes(TheCall, 3);
3800   case PPC::BI__builtin_ppc_extract_exp:
3801   case PPC::BI__builtin_ppc_extract_sig:
3802   case PPC::BI__builtin_ppc_insert_exp:
3803     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3804                             diag::err_ppc_builtin_only_on_arch, "9");
3805   case PPC::BI__builtin_ppc_addex: {
3806     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3807                          diag::err_ppc_builtin_only_on_arch, "9") ||
3808         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3809       return true;
3810     // Output warning for reserved values 1 to 3.
3811     int ArgValue =
3812         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3813     if (ArgValue != 0)
3814       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3815           << ArgValue;
3816     return false;
3817   }
3818   case PPC::BI__builtin_ppc_mtfsb0:
3819   case PPC::BI__builtin_ppc_mtfsb1:
3820     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3821   case PPC::BI__builtin_ppc_mtfsf:
3822     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3823   case PPC::BI__builtin_ppc_mtfsfi:
3824     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3825            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3826   case PPC::BI__builtin_ppc_alignx:
3827     return SemaBuiltinConstantArgPower2(TheCall, 0);
3828   case PPC::BI__builtin_ppc_rdlam:
3829     return SemaValueIsRunOfOnes(TheCall, 2);
3830   case PPC::BI__builtin_ppc_icbt:
3831   case PPC::BI__builtin_ppc_sthcx:
3832   case PPC::BI__builtin_ppc_stbcx:
3833   case PPC::BI__builtin_ppc_lharx:
3834   case PPC::BI__builtin_ppc_lbarx:
3835     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3836                             diag::err_ppc_builtin_only_on_arch, "8");
3837   case PPC::BI__builtin_vsx_ldrmb:
3838   case PPC::BI__builtin_vsx_strmb:
3839     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3840                             diag::err_ppc_builtin_only_on_arch, "8") ||
3841            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3842   case PPC::BI__builtin_altivec_vcntmbb:
3843   case PPC::BI__builtin_altivec_vcntmbh:
3844   case PPC::BI__builtin_altivec_vcntmbw:
3845   case PPC::BI__builtin_altivec_vcntmbd:
3846     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3847   case PPC::BI__builtin_darn:
3848   case PPC::BI__builtin_darn_raw:
3849   case PPC::BI__builtin_darn_32:
3850     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3851                             diag::err_ppc_builtin_only_on_arch, "9");
3852   case PPC::BI__builtin_vsx_xxgenpcvbm:
3853   case PPC::BI__builtin_vsx_xxgenpcvhm:
3854   case PPC::BI__builtin_vsx_xxgenpcvwm:
3855   case PPC::BI__builtin_vsx_xxgenpcvdm:
3856     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3857   case PPC::BI__builtin_ppc_compare_exp_uo:
3858   case PPC::BI__builtin_ppc_compare_exp_lt:
3859   case PPC::BI__builtin_ppc_compare_exp_gt:
3860   case PPC::BI__builtin_ppc_compare_exp_eq:
3861     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3862                             diag::err_ppc_builtin_only_on_arch, "9") ||
3863            SemaFeatureCheck(*this, TheCall, "vsx",
3864                             diag::err_ppc_builtin_requires_vsx);
3865   case PPC::BI__builtin_ppc_test_data_class: {
3866     // Check if the first argument of the __builtin_ppc_test_data_class call is
3867     // valid. The argument must be either a 'float' or a 'double'.
3868     QualType ArgType = TheCall->getArg(0)->getType();
3869     if (ArgType != QualType(Context.FloatTy) &&
3870         ArgType != QualType(Context.DoubleTy))
3871       return Diag(TheCall->getBeginLoc(),
3872                   diag::err_ppc_invalid_test_data_class_type);
3873     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3874                             diag::err_ppc_builtin_only_on_arch, "9") ||
3875            SemaFeatureCheck(*this, TheCall, "vsx",
3876                             diag::err_ppc_builtin_requires_vsx) ||
3877            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3878   }
3879   case PPC::BI__builtin_ppc_load8r:
3880   case PPC::BI__builtin_ppc_store8r:
3881     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3882                             diag::err_ppc_builtin_only_on_arch, "7");
3883 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3884   case PPC::BI__builtin_##Name:                                                \
3885     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3886 #include "clang/Basic/BuiltinsPPC.def"
3887   }
3888   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3889 }
3890 
3891 // Check if the given type is a non-pointer PPC MMA type. This function is used
3892 // in Sema to prevent invalid uses of restricted PPC MMA types.
3893 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3894   if (Type->isPointerType() || Type->isArrayType())
3895     return false;
3896 
3897   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3898 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3899   if (false
3900 #include "clang/Basic/PPCTypes.def"
3901      ) {
3902     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3903     return true;
3904   }
3905   return false;
3906 }
3907 
3908 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3909                                           CallExpr *TheCall) {
3910   // position of memory order and scope arguments in the builtin
3911   unsigned OrderIndex, ScopeIndex;
3912   switch (BuiltinID) {
3913   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3914   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3915   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3916   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3917     OrderIndex = 2;
3918     ScopeIndex = 3;
3919     break;
3920   case AMDGPU::BI__builtin_amdgcn_fence:
3921     OrderIndex = 0;
3922     ScopeIndex = 1;
3923     break;
3924   default:
3925     return false;
3926   }
3927 
3928   ExprResult Arg = TheCall->getArg(OrderIndex);
3929   auto ArgExpr = Arg.get();
3930   Expr::EvalResult ArgResult;
3931 
3932   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3933     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3934            << ArgExpr->getType();
3935   auto Ord = ArgResult.Val.getInt().getZExtValue();
3936 
3937   // Check validity of memory ordering as per C11 / C++11's memody model.
3938   // Only fence needs check. Atomic dec/inc allow all memory orders.
3939   if (!llvm::isValidAtomicOrderingCABI(Ord))
3940     return Diag(ArgExpr->getBeginLoc(),
3941                 diag::warn_atomic_op_has_invalid_memory_order)
3942            << ArgExpr->getSourceRange();
3943   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3944   case llvm::AtomicOrderingCABI::relaxed:
3945   case llvm::AtomicOrderingCABI::consume:
3946     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3947       return Diag(ArgExpr->getBeginLoc(),
3948                   diag::warn_atomic_op_has_invalid_memory_order)
3949              << ArgExpr->getSourceRange();
3950     break;
3951   case llvm::AtomicOrderingCABI::acquire:
3952   case llvm::AtomicOrderingCABI::release:
3953   case llvm::AtomicOrderingCABI::acq_rel:
3954   case llvm::AtomicOrderingCABI::seq_cst:
3955     break;
3956   }
3957 
3958   Arg = TheCall->getArg(ScopeIndex);
3959   ArgExpr = Arg.get();
3960   Expr::EvalResult ArgResult1;
3961   // Check that sync scope is a constant literal
3962   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3963     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3964            << ArgExpr->getType();
3965 
3966   return false;
3967 }
3968 
3969 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3970   llvm::APSInt Result;
3971 
3972   // We can't check the value of a dependent argument.
3973   Expr *Arg = TheCall->getArg(ArgNum);
3974   if (Arg->isTypeDependent() || Arg->isValueDependent())
3975     return false;
3976 
3977   // Check constant-ness first.
3978   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3979     return true;
3980 
3981   int64_t Val = Result.getSExtValue();
3982   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3983     return false;
3984 
3985   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3986          << Arg->getSourceRange();
3987 }
3988 
3989 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3990                                          unsigned BuiltinID,
3991                                          CallExpr *TheCall) {
3992   // CodeGenFunction can also detect this, but this gives a better error
3993   // message.
3994   bool FeatureMissing = false;
3995   SmallVector<StringRef> ReqFeatures;
3996   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3997   Features.split(ReqFeatures, ',');
3998 
3999   // Check if each required feature is included
4000   for (StringRef F : ReqFeatures) {
4001     SmallVector<StringRef> ReqOpFeatures;
4002     F.split(ReqOpFeatures, '|');
4003     bool HasFeature = false;
4004     for (StringRef OF : ReqOpFeatures) {
4005       if (TI.hasFeature(OF)) {
4006         HasFeature = true;
4007         continue;
4008       }
4009     }
4010 
4011     if (!HasFeature) {
4012       std::string FeatureStrs;
4013       for (StringRef OF : ReqOpFeatures) {
4014         // If the feature is 64bit, alter the string so it will print better in
4015         // the diagnostic.
4016         if (OF == "64bit")
4017           OF = "RV64";
4018 
4019         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4020         OF.consume_front("experimental-");
4021         std::string FeatureStr = OF.str();
4022         FeatureStr[0] = std::toupper(FeatureStr[0]);
4023         // Combine strings.
4024         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4025         FeatureStrs += "'";
4026         FeatureStrs += FeatureStr;
4027         FeatureStrs += "'";
4028       }
4029       // Error message
4030       FeatureMissing = true;
4031       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4032           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4033     }
4034   }
4035 
4036   if (FeatureMissing)
4037     return true;
4038 
4039   switch (BuiltinID) {
4040   case RISCVVector::BI__builtin_rvv_vsetvli:
4041     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4042            CheckRISCVLMUL(TheCall, 2);
4043   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4044     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4045            CheckRISCVLMUL(TheCall, 1);
4046   }
4047 
4048   return false;
4049 }
4050 
4051 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4052                                            CallExpr *TheCall) {
4053   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4054     Expr *Arg = TheCall->getArg(0);
4055     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4056       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4057         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4058                << Arg->getSourceRange();
4059   }
4060 
4061   // For intrinsics which take an immediate value as part of the instruction,
4062   // range check them here.
4063   unsigned i = 0, l = 0, u = 0;
4064   switch (BuiltinID) {
4065   default: return false;
4066   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4067   case SystemZ::BI__builtin_s390_verimb:
4068   case SystemZ::BI__builtin_s390_verimh:
4069   case SystemZ::BI__builtin_s390_verimf:
4070   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4071   case SystemZ::BI__builtin_s390_vfaeb:
4072   case SystemZ::BI__builtin_s390_vfaeh:
4073   case SystemZ::BI__builtin_s390_vfaef:
4074   case SystemZ::BI__builtin_s390_vfaebs:
4075   case SystemZ::BI__builtin_s390_vfaehs:
4076   case SystemZ::BI__builtin_s390_vfaefs:
4077   case SystemZ::BI__builtin_s390_vfaezb:
4078   case SystemZ::BI__builtin_s390_vfaezh:
4079   case SystemZ::BI__builtin_s390_vfaezf:
4080   case SystemZ::BI__builtin_s390_vfaezbs:
4081   case SystemZ::BI__builtin_s390_vfaezhs:
4082   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4083   case SystemZ::BI__builtin_s390_vfisb:
4084   case SystemZ::BI__builtin_s390_vfidb:
4085     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4086            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4087   case SystemZ::BI__builtin_s390_vftcisb:
4088   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4089   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4090   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4091   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4092   case SystemZ::BI__builtin_s390_vstrcb:
4093   case SystemZ::BI__builtin_s390_vstrch:
4094   case SystemZ::BI__builtin_s390_vstrcf:
4095   case SystemZ::BI__builtin_s390_vstrczb:
4096   case SystemZ::BI__builtin_s390_vstrczh:
4097   case SystemZ::BI__builtin_s390_vstrczf:
4098   case SystemZ::BI__builtin_s390_vstrcbs:
4099   case SystemZ::BI__builtin_s390_vstrchs:
4100   case SystemZ::BI__builtin_s390_vstrcfs:
4101   case SystemZ::BI__builtin_s390_vstrczbs:
4102   case SystemZ::BI__builtin_s390_vstrczhs:
4103   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4104   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4105   case SystemZ::BI__builtin_s390_vfminsb:
4106   case SystemZ::BI__builtin_s390_vfmaxsb:
4107   case SystemZ::BI__builtin_s390_vfmindb:
4108   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4109   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4110   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4111   case SystemZ::BI__builtin_s390_vclfnhs:
4112   case SystemZ::BI__builtin_s390_vclfnls:
4113   case SystemZ::BI__builtin_s390_vcfn:
4114   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4115   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4116   }
4117   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4118 }
4119 
4120 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4121 /// This checks that the target supports __builtin_cpu_supports and
4122 /// that the string argument is constant and valid.
4123 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4124                                    CallExpr *TheCall) {
4125   Expr *Arg = TheCall->getArg(0);
4126 
4127   // Check if the argument is a string literal.
4128   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4129     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4130            << Arg->getSourceRange();
4131 
4132   // Check the contents of the string.
4133   StringRef Feature =
4134       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4135   if (!TI.validateCpuSupports(Feature))
4136     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4137            << Arg->getSourceRange();
4138   return false;
4139 }
4140 
4141 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4142 /// This checks that the target supports __builtin_cpu_is and
4143 /// that the string argument is constant and valid.
4144 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4145   Expr *Arg = TheCall->getArg(0);
4146 
4147   // Check if the argument is a string literal.
4148   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4149     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4150            << Arg->getSourceRange();
4151 
4152   // Check the contents of the string.
4153   StringRef Feature =
4154       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4155   if (!TI.validateCpuIs(Feature))
4156     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4157            << Arg->getSourceRange();
4158   return false;
4159 }
4160 
4161 // Check if the rounding mode is legal.
4162 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4163   // Indicates if this instruction has rounding control or just SAE.
4164   bool HasRC = false;
4165 
4166   unsigned ArgNum = 0;
4167   switch (BuiltinID) {
4168   default:
4169     return false;
4170   case X86::BI__builtin_ia32_vcvttsd2si32:
4171   case X86::BI__builtin_ia32_vcvttsd2si64:
4172   case X86::BI__builtin_ia32_vcvttsd2usi32:
4173   case X86::BI__builtin_ia32_vcvttsd2usi64:
4174   case X86::BI__builtin_ia32_vcvttss2si32:
4175   case X86::BI__builtin_ia32_vcvttss2si64:
4176   case X86::BI__builtin_ia32_vcvttss2usi32:
4177   case X86::BI__builtin_ia32_vcvttss2usi64:
4178   case X86::BI__builtin_ia32_vcvttsh2si32:
4179   case X86::BI__builtin_ia32_vcvttsh2si64:
4180   case X86::BI__builtin_ia32_vcvttsh2usi32:
4181   case X86::BI__builtin_ia32_vcvttsh2usi64:
4182     ArgNum = 1;
4183     break;
4184   case X86::BI__builtin_ia32_maxpd512:
4185   case X86::BI__builtin_ia32_maxps512:
4186   case X86::BI__builtin_ia32_minpd512:
4187   case X86::BI__builtin_ia32_minps512:
4188   case X86::BI__builtin_ia32_maxph512:
4189   case X86::BI__builtin_ia32_minph512:
4190     ArgNum = 2;
4191     break;
4192   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4193   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4194   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4195   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4196   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4197   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4198   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4199   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4200   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4201   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4202   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4203   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4204   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4205   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4206   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4207   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4208   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4209   case X86::BI__builtin_ia32_exp2pd_mask:
4210   case X86::BI__builtin_ia32_exp2ps_mask:
4211   case X86::BI__builtin_ia32_getexppd512_mask:
4212   case X86::BI__builtin_ia32_getexpps512_mask:
4213   case X86::BI__builtin_ia32_getexpph512_mask:
4214   case X86::BI__builtin_ia32_rcp28pd_mask:
4215   case X86::BI__builtin_ia32_rcp28ps_mask:
4216   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4217   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4218   case X86::BI__builtin_ia32_vcomisd:
4219   case X86::BI__builtin_ia32_vcomiss:
4220   case X86::BI__builtin_ia32_vcomish:
4221   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4222     ArgNum = 3;
4223     break;
4224   case X86::BI__builtin_ia32_cmppd512_mask:
4225   case X86::BI__builtin_ia32_cmpps512_mask:
4226   case X86::BI__builtin_ia32_cmpsd_mask:
4227   case X86::BI__builtin_ia32_cmpss_mask:
4228   case X86::BI__builtin_ia32_cmpsh_mask:
4229   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4230   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4231   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4232   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4233   case X86::BI__builtin_ia32_getexpss128_round_mask:
4234   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4235   case X86::BI__builtin_ia32_getmantpd512_mask:
4236   case X86::BI__builtin_ia32_getmantps512_mask:
4237   case X86::BI__builtin_ia32_getmantph512_mask:
4238   case X86::BI__builtin_ia32_maxsd_round_mask:
4239   case X86::BI__builtin_ia32_maxss_round_mask:
4240   case X86::BI__builtin_ia32_maxsh_round_mask:
4241   case X86::BI__builtin_ia32_minsd_round_mask:
4242   case X86::BI__builtin_ia32_minss_round_mask:
4243   case X86::BI__builtin_ia32_minsh_round_mask:
4244   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4245   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4246   case X86::BI__builtin_ia32_reducepd512_mask:
4247   case X86::BI__builtin_ia32_reduceps512_mask:
4248   case X86::BI__builtin_ia32_reduceph512_mask:
4249   case X86::BI__builtin_ia32_rndscalepd_mask:
4250   case X86::BI__builtin_ia32_rndscaleps_mask:
4251   case X86::BI__builtin_ia32_rndscaleph_mask:
4252   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4253   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4254     ArgNum = 4;
4255     break;
4256   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4257   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4258   case X86::BI__builtin_ia32_fixupimmps512_mask:
4259   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4260   case X86::BI__builtin_ia32_fixupimmsd_mask:
4261   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4262   case X86::BI__builtin_ia32_fixupimmss_mask:
4263   case X86::BI__builtin_ia32_fixupimmss_maskz:
4264   case X86::BI__builtin_ia32_getmantsd_round_mask:
4265   case X86::BI__builtin_ia32_getmantss_round_mask:
4266   case X86::BI__builtin_ia32_getmantsh_round_mask:
4267   case X86::BI__builtin_ia32_rangepd512_mask:
4268   case X86::BI__builtin_ia32_rangeps512_mask:
4269   case X86::BI__builtin_ia32_rangesd128_round_mask:
4270   case X86::BI__builtin_ia32_rangess128_round_mask:
4271   case X86::BI__builtin_ia32_reducesd_mask:
4272   case X86::BI__builtin_ia32_reducess_mask:
4273   case X86::BI__builtin_ia32_reducesh_mask:
4274   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4275   case X86::BI__builtin_ia32_rndscaless_round_mask:
4276   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4277     ArgNum = 5;
4278     break;
4279   case X86::BI__builtin_ia32_vcvtsd2si64:
4280   case X86::BI__builtin_ia32_vcvtsd2si32:
4281   case X86::BI__builtin_ia32_vcvtsd2usi32:
4282   case X86::BI__builtin_ia32_vcvtsd2usi64:
4283   case X86::BI__builtin_ia32_vcvtss2si32:
4284   case X86::BI__builtin_ia32_vcvtss2si64:
4285   case X86::BI__builtin_ia32_vcvtss2usi32:
4286   case X86::BI__builtin_ia32_vcvtss2usi64:
4287   case X86::BI__builtin_ia32_vcvtsh2si32:
4288   case X86::BI__builtin_ia32_vcvtsh2si64:
4289   case X86::BI__builtin_ia32_vcvtsh2usi32:
4290   case X86::BI__builtin_ia32_vcvtsh2usi64:
4291   case X86::BI__builtin_ia32_sqrtpd512:
4292   case X86::BI__builtin_ia32_sqrtps512:
4293   case X86::BI__builtin_ia32_sqrtph512:
4294     ArgNum = 1;
4295     HasRC = true;
4296     break;
4297   case X86::BI__builtin_ia32_addph512:
4298   case X86::BI__builtin_ia32_divph512:
4299   case X86::BI__builtin_ia32_mulph512:
4300   case X86::BI__builtin_ia32_subph512:
4301   case X86::BI__builtin_ia32_addpd512:
4302   case X86::BI__builtin_ia32_addps512:
4303   case X86::BI__builtin_ia32_divpd512:
4304   case X86::BI__builtin_ia32_divps512:
4305   case X86::BI__builtin_ia32_mulpd512:
4306   case X86::BI__builtin_ia32_mulps512:
4307   case X86::BI__builtin_ia32_subpd512:
4308   case X86::BI__builtin_ia32_subps512:
4309   case X86::BI__builtin_ia32_cvtsi2sd64:
4310   case X86::BI__builtin_ia32_cvtsi2ss32:
4311   case X86::BI__builtin_ia32_cvtsi2ss64:
4312   case X86::BI__builtin_ia32_cvtusi2sd64:
4313   case X86::BI__builtin_ia32_cvtusi2ss32:
4314   case X86::BI__builtin_ia32_cvtusi2ss64:
4315   case X86::BI__builtin_ia32_vcvtusi2sh:
4316   case X86::BI__builtin_ia32_vcvtusi642sh:
4317   case X86::BI__builtin_ia32_vcvtsi2sh:
4318   case X86::BI__builtin_ia32_vcvtsi642sh:
4319     ArgNum = 2;
4320     HasRC = true;
4321     break;
4322   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4323   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4324   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4325   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4326   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4327   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4328   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4329   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4330   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4331   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4332   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4333   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4334   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4335   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4336   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4337   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4338   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4339   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4340   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4341   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4342   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4343   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4344   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4345   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4346   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4347   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4348   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4349   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4350   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4351     ArgNum = 3;
4352     HasRC = true;
4353     break;
4354   case X86::BI__builtin_ia32_addsh_round_mask:
4355   case X86::BI__builtin_ia32_addss_round_mask:
4356   case X86::BI__builtin_ia32_addsd_round_mask:
4357   case X86::BI__builtin_ia32_divsh_round_mask:
4358   case X86::BI__builtin_ia32_divss_round_mask:
4359   case X86::BI__builtin_ia32_divsd_round_mask:
4360   case X86::BI__builtin_ia32_mulsh_round_mask:
4361   case X86::BI__builtin_ia32_mulss_round_mask:
4362   case X86::BI__builtin_ia32_mulsd_round_mask:
4363   case X86::BI__builtin_ia32_subsh_round_mask:
4364   case X86::BI__builtin_ia32_subss_round_mask:
4365   case X86::BI__builtin_ia32_subsd_round_mask:
4366   case X86::BI__builtin_ia32_scalefph512_mask:
4367   case X86::BI__builtin_ia32_scalefpd512_mask:
4368   case X86::BI__builtin_ia32_scalefps512_mask:
4369   case X86::BI__builtin_ia32_scalefsd_round_mask:
4370   case X86::BI__builtin_ia32_scalefss_round_mask:
4371   case X86::BI__builtin_ia32_scalefsh_round_mask:
4372   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4373   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4374   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4375   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4376   case X86::BI__builtin_ia32_sqrtss_round_mask:
4377   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4378   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4379   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4380   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4381   case X86::BI__builtin_ia32_vfmaddss3_mask:
4382   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4383   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4384   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4385   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4386   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4387   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4388   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4389   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4390   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4391   case X86::BI__builtin_ia32_vfmaddps512_mask:
4392   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4393   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4394   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4395   case X86::BI__builtin_ia32_vfmaddph512_mask:
4396   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4397   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4398   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4399   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4400   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4401   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4402   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4403   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4404   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4405   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4406   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4407   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4408   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4409   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4410   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4411   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4412   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4413   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4414   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4415   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4416   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4417   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4418   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4419   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4420   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4421   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4422   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4423   case X86::BI__builtin_ia32_vfmulcsh_mask:
4424   case X86::BI__builtin_ia32_vfmulcph512_mask:
4425   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4426   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4427     ArgNum = 4;
4428     HasRC = true;
4429     break;
4430   }
4431 
4432   llvm::APSInt Result;
4433 
4434   // We can't check the value of a dependent argument.
4435   Expr *Arg = TheCall->getArg(ArgNum);
4436   if (Arg->isTypeDependent() || Arg->isValueDependent())
4437     return false;
4438 
4439   // Check constant-ness first.
4440   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4441     return true;
4442 
4443   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4444   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4445   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4446   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4447   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4448       Result == 8/*ROUND_NO_EXC*/ ||
4449       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4450       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4451     return false;
4452 
4453   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4454          << Arg->getSourceRange();
4455 }
4456 
4457 // Check if the gather/scatter scale is legal.
4458 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4459                                              CallExpr *TheCall) {
4460   unsigned ArgNum = 0;
4461   switch (BuiltinID) {
4462   default:
4463     return false;
4464   case X86::BI__builtin_ia32_gatherpfdpd:
4465   case X86::BI__builtin_ia32_gatherpfdps:
4466   case X86::BI__builtin_ia32_gatherpfqpd:
4467   case X86::BI__builtin_ia32_gatherpfqps:
4468   case X86::BI__builtin_ia32_scatterpfdpd:
4469   case X86::BI__builtin_ia32_scatterpfdps:
4470   case X86::BI__builtin_ia32_scatterpfqpd:
4471   case X86::BI__builtin_ia32_scatterpfqps:
4472     ArgNum = 3;
4473     break;
4474   case X86::BI__builtin_ia32_gatherd_pd:
4475   case X86::BI__builtin_ia32_gatherd_pd256:
4476   case X86::BI__builtin_ia32_gatherq_pd:
4477   case X86::BI__builtin_ia32_gatherq_pd256:
4478   case X86::BI__builtin_ia32_gatherd_ps:
4479   case X86::BI__builtin_ia32_gatherd_ps256:
4480   case X86::BI__builtin_ia32_gatherq_ps:
4481   case X86::BI__builtin_ia32_gatherq_ps256:
4482   case X86::BI__builtin_ia32_gatherd_q:
4483   case X86::BI__builtin_ia32_gatherd_q256:
4484   case X86::BI__builtin_ia32_gatherq_q:
4485   case X86::BI__builtin_ia32_gatherq_q256:
4486   case X86::BI__builtin_ia32_gatherd_d:
4487   case X86::BI__builtin_ia32_gatherd_d256:
4488   case X86::BI__builtin_ia32_gatherq_d:
4489   case X86::BI__builtin_ia32_gatherq_d256:
4490   case X86::BI__builtin_ia32_gather3div2df:
4491   case X86::BI__builtin_ia32_gather3div2di:
4492   case X86::BI__builtin_ia32_gather3div4df:
4493   case X86::BI__builtin_ia32_gather3div4di:
4494   case X86::BI__builtin_ia32_gather3div4sf:
4495   case X86::BI__builtin_ia32_gather3div4si:
4496   case X86::BI__builtin_ia32_gather3div8sf:
4497   case X86::BI__builtin_ia32_gather3div8si:
4498   case X86::BI__builtin_ia32_gather3siv2df:
4499   case X86::BI__builtin_ia32_gather3siv2di:
4500   case X86::BI__builtin_ia32_gather3siv4df:
4501   case X86::BI__builtin_ia32_gather3siv4di:
4502   case X86::BI__builtin_ia32_gather3siv4sf:
4503   case X86::BI__builtin_ia32_gather3siv4si:
4504   case X86::BI__builtin_ia32_gather3siv8sf:
4505   case X86::BI__builtin_ia32_gather3siv8si:
4506   case X86::BI__builtin_ia32_gathersiv8df:
4507   case X86::BI__builtin_ia32_gathersiv16sf:
4508   case X86::BI__builtin_ia32_gatherdiv8df:
4509   case X86::BI__builtin_ia32_gatherdiv16sf:
4510   case X86::BI__builtin_ia32_gathersiv8di:
4511   case X86::BI__builtin_ia32_gathersiv16si:
4512   case X86::BI__builtin_ia32_gatherdiv8di:
4513   case X86::BI__builtin_ia32_gatherdiv16si:
4514   case X86::BI__builtin_ia32_scatterdiv2df:
4515   case X86::BI__builtin_ia32_scatterdiv2di:
4516   case X86::BI__builtin_ia32_scatterdiv4df:
4517   case X86::BI__builtin_ia32_scatterdiv4di:
4518   case X86::BI__builtin_ia32_scatterdiv4sf:
4519   case X86::BI__builtin_ia32_scatterdiv4si:
4520   case X86::BI__builtin_ia32_scatterdiv8sf:
4521   case X86::BI__builtin_ia32_scatterdiv8si:
4522   case X86::BI__builtin_ia32_scattersiv2df:
4523   case X86::BI__builtin_ia32_scattersiv2di:
4524   case X86::BI__builtin_ia32_scattersiv4df:
4525   case X86::BI__builtin_ia32_scattersiv4di:
4526   case X86::BI__builtin_ia32_scattersiv4sf:
4527   case X86::BI__builtin_ia32_scattersiv4si:
4528   case X86::BI__builtin_ia32_scattersiv8sf:
4529   case X86::BI__builtin_ia32_scattersiv8si:
4530   case X86::BI__builtin_ia32_scattersiv8df:
4531   case X86::BI__builtin_ia32_scattersiv16sf:
4532   case X86::BI__builtin_ia32_scatterdiv8df:
4533   case X86::BI__builtin_ia32_scatterdiv16sf:
4534   case X86::BI__builtin_ia32_scattersiv8di:
4535   case X86::BI__builtin_ia32_scattersiv16si:
4536   case X86::BI__builtin_ia32_scatterdiv8di:
4537   case X86::BI__builtin_ia32_scatterdiv16si:
4538     ArgNum = 4;
4539     break;
4540   }
4541 
4542   llvm::APSInt Result;
4543 
4544   // We can't check the value of a dependent argument.
4545   Expr *Arg = TheCall->getArg(ArgNum);
4546   if (Arg->isTypeDependent() || Arg->isValueDependent())
4547     return false;
4548 
4549   // Check constant-ness first.
4550   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4551     return true;
4552 
4553   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4554     return false;
4555 
4556   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4557          << Arg->getSourceRange();
4558 }
4559 
4560 enum { TileRegLow = 0, TileRegHigh = 7 };
4561 
4562 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4563                                              ArrayRef<int> ArgNums) {
4564   for (int ArgNum : ArgNums) {
4565     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4566       return true;
4567   }
4568   return false;
4569 }
4570 
4571 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4572                                         ArrayRef<int> ArgNums) {
4573   // Because the max number of tile register is TileRegHigh + 1, so here we use
4574   // each bit to represent the usage of them in bitset.
4575   std::bitset<TileRegHigh + 1> ArgValues;
4576   for (int ArgNum : ArgNums) {
4577     Expr *Arg = TheCall->getArg(ArgNum);
4578     if (Arg->isTypeDependent() || Arg->isValueDependent())
4579       continue;
4580 
4581     llvm::APSInt Result;
4582     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4583       return true;
4584     int ArgExtValue = Result.getExtValue();
4585     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4586            "Incorrect tile register num.");
4587     if (ArgValues.test(ArgExtValue))
4588       return Diag(TheCall->getBeginLoc(),
4589                   diag::err_x86_builtin_tile_arg_duplicate)
4590              << TheCall->getArg(ArgNum)->getSourceRange();
4591     ArgValues.set(ArgExtValue);
4592   }
4593   return false;
4594 }
4595 
4596 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4597                                                 ArrayRef<int> ArgNums) {
4598   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4599          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4600 }
4601 
4602 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4603   switch (BuiltinID) {
4604   default:
4605     return false;
4606   case X86::BI__builtin_ia32_tileloadd64:
4607   case X86::BI__builtin_ia32_tileloaddt164:
4608   case X86::BI__builtin_ia32_tilestored64:
4609   case X86::BI__builtin_ia32_tilezero:
4610     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4611   case X86::BI__builtin_ia32_tdpbssd:
4612   case X86::BI__builtin_ia32_tdpbsud:
4613   case X86::BI__builtin_ia32_tdpbusd:
4614   case X86::BI__builtin_ia32_tdpbuud:
4615   case X86::BI__builtin_ia32_tdpbf16ps:
4616     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4617   }
4618 }
4619 static bool isX86_32Builtin(unsigned BuiltinID) {
4620   // These builtins only work on x86-32 targets.
4621   switch (BuiltinID) {
4622   case X86::BI__builtin_ia32_readeflags_u32:
4623   case X86::BI__builtin_ia32_writeeflags_u32:
4624     return true;
4625   }
4626 
4627   return false;
4628 }
4629 
4630 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4631                                        CallExpr *TheCall) {
4632   if (BuiltinID == X86::BI__builtin_cpu_supports)
4633     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4634 
4635   if (BuiltinID == X86::BI__builtin_cpu_is)
4636     return SemaBuiltinCpuIs(*this, TI, TheCall);
4637 
4638   // Check for 32-bit only builtins on a 64-bit target.
4639   const llvm::Triple &TT = TI.getTriple();
4640   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4641     return Diag(TheCall->getCallee()->getBeginLoc(),
4642                 diag::err_32_bit_builtin_64_bit_tgt);
4643 
4644   // If the intrinsic has rounding or SAE make sure its valid.
4645   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4646     return true;
4647 
4648   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4649   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4650     return true;
4651 
4652   // If the intrinsic has a tile arguments, make sure they are valid.
4653   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4654     return true;
4655 
4656   // For intrinsics which take an immediate value as part of the instruction,
4657   // range check them here.
4658   int i = 0, l = 0, u = 0;
4659   switch (BuiltinID) {
4660   default:
4661     return false;
4662   case X86::BI__builtin_ia32_vec_ext_v2si:
4663   case X86::BI__builtin_ia32_vec_ext_v2di:
4664   case X86::BI__builtin_ia32_vextractf128_pd256:
4665   case X86::BI__builtin_ia32_vextractf128_ps256:
4666   case X86::BI__builtin_ia32_vextractf128_si256:
4667   case X86::BI__builtin_ia32_extract128i256:
4668   case X86::BI__builtin_ia32_extractf64x4_mask:
4669   case X86::BI__builtin_ia32_extracti64x4_mask:
4670   case X86::BI__builtin_ia32_extractf32x8_mask:
4671   case X86::BI__builtin_ia32_extracti32x8_mask:
4672   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4673   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4674   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4675   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4676     i = 1; l = 0; u = 1;
4677     break;
4678   case X86::BI__builtin_ia32_vec_set_v2di:
4679   case X86::BI__builtin_ia32_vinsertf128_pd256:
4680   case X86::BI__builtin_ia32_vinsertf128_ps256:
4681   case X86::BI__builtin_ia32_vinsertf128_si256:
4682   case X86::BI__builtin_ia32_insert128i256:
4683   case X86::BI__builtin_ia32_insertf32x8:
4684   case X86::BI__builtin_ia32_inserti32x8:
4685   case X86::BI__builtin_ia32_insertf64x4:
4686   case X86::BI__builtin_ia32_inserti64x4:
4687   case X86::BI__builtin_ia32_insertf64x2_256:
4688   case X86::BI__builtin_ia32_inserti64x2_256:
4689   case X86::BI__builtin_ia32_insertf32x4_256:
4690   case X86::BI__builtin_ia32_inserti32x4_256:
4691     i = 2; l = 0; u = 1;
4692     break;
4693   case X86::BI__builtin_ia32_vpermilpd:
4694   case X86::BI__builtin_ia32_vec_ext_v4hi:
4695   case X86::BI__builtin_ia32_vec_ext_v4si:
4696   case X86::BI__builtin_ia32_vec_ext_v4sf:
4697   case X86::BI__builtin_ia32_vec_ext_v4di:
4698   case X86::BI__builtin_ia32_extractf32x4_mask:
4699   case X86::BI__builtin_ia32_extracti32x4_mask:
4700   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4701   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4702     i = 1; l = 0; u = 3;
4703     break;
4704   case X86::BI_mm_prefetch:
4705   case X86::BI__builtin_ia32_vec_ext_v8hi:
4706   case X86::BI__builtin_ia32_vec_ext_v8si:
4707     i = 1; l = 0; u = 7;
4708     break;
4709   case X86::BI__builtin_ia32_sha1rnds4:
4710   case X86::BI__builtin_ia32_blendpd:
4711   case X86::BI__builtin_ia32_shufpd:
4712   case X86::BI__builtin_ia32_vec_set_v4hi:
4713   case X86::BI__builtin_ia32_vec_set_v4si:
4714   case X86::BI__builtin_ia32_vec_set_v4di:
4715   case X86::BI__builtin_ia32_shuf_f32x4_256:
4716   case X86::BI__builtin_ia32_shuf_f64x2_256:
4717   case X86::BI__builtin_ia32_shuf_i32x4_256:
4718   case X86::BI__builtin_ia32_shuf_i64x2_256:
4719   case X86::BI__builtin_ia32_insertf64x2_512:
4720   case X86::BI__builtin_ia32_inserti64x2_512:
4721   case X86::BI__builtin_ia32_insertf32x4:
4722   case X86::BI__builtin_ia32_inserti32x4:
4723     i = 2; l = 0; u = 3;
4724     break;
4725   case X86::BI__builtin_ia32_vpermil2pd:
4726   case X86::BI__builtin_ia32_vpermil2pd256:
4727   case X86::BI__builtin_ia32_vpermil2ps:
4728   case X86::BI__builtin_ia32_vpermil2ps256:
4729     i = 3; l = 0; u = 3;
4730     break;
4731   case X86::BI__builtin_ia32_cmpb128_mask:
4732   case X86::BI__builtin_ia32_cmpw128_mask:
4733   case X86::BI__builtin_ia32_cmpd128_mask:
4734   case X86::BI__builtin_ia32_cmpq128_mask:
4735   case X86::BI__builtin_ia32_cmpb256_mask:
4736   case X86::BI__builtin_ia32_cmpw256_mask:
4737   case X86::BI__builtin_ia32_cmpd256_mask:
4738   case X86::BI__builtin_ia32_cmpq256_mask:
4739   case X86::BI__builtin_ia32_cmpb512_mask:
4740   case X86::BI__builtin_ia32_cmpw512_mask:
4741   case X86::BI__builtin_ia32_cmpd512_mask:
4742   case X86::BI__builtin_ia32_cmpq512_mask:
4743   case X86::BI__builtin_ia32_ucmpb128_mask:
4744   case X86::BI__builtin_ia32_ucmpw128_mask:
4745   case X86::BI__builtin_ia32_ucmpd128_mask:
4746   case X86::BI__builtin_ia32_ucmpq128_mask:
4747   case X86::BI__builtin_ia32_ucmpb256_mask:
4748   case X86::BI__builtin_ia32_ucmpw256_mask:
4749   case X86::BI__builtin_ia32_ucmpd256_mask:
4750   case X86::BI__builtin_ia32_ucmpq256_mask:
4751   case X86::BI__builtin_ia32_ucmpb512_mask:
4752   case X86::BI__builtin_ia32_ucmpw512_mask:
4753   case X86::BI__builtin_ia32_ucmpd512_mask:
4754   case X86::BI__builtin_ia32_ucmpq512_mask:
4755   case X86::BI__builtin_ia32_vpcomub:
4756   case X86::BI__builtin_ia32_vpcomuw:
4757   case X86::BI__builtin_ia32_vpcomud:
4758   case X86::BI__builtin_ia32_vpcomuq:
4759   case X86::BI__builtin_ia32_vpcomb:
4760   case X86::BI__builtin_ia32_vpcomw:
4761   case X86::BI__builtin_ia32_vpcomd:
4762   case X86::BI__builtin_ia32_vpcomq:
4763   case X86::BI__builtin_ia32_vec_set_v8hi:
4764   case X86::BI__builtin_ia32_vec_set_v8si:
4765     i = 2; l = 0; u = 7;
4766     break;
4767   case X86::BI__builtin_ia32_vpermilpd256:
4768   case X86::BI__builtin_ia32_roundps:
4769   case X86::BI__builtin_ia32_roundpd:
4770   case X86::BI__builtin_ia32_roundps256:
4771   case X86::BI__builtin_ia32_roundpd256:
4772   case X86::BI__builtin_ia32_getmantpd128_mask:
4773   case X86::BI__builtin_ia32_getmantpd256_mask:
4774   case X86::BI__builtin_ia32_getmantps128_mask:
4775   case X86::BI__builtin_ia32_getmantps256_mask:
4776   case X86::BI__builtin_ia32_getmantpd512_mask:
4777   case X86::BI__builtin_ia32_getmantps512_mask:
4778   case X86::BI__builtin_ia32_getmantph128_mask:
4779   case X86::BI__builtin_ia32_getmantph256_mask:
4780   case X86::BI__builtin_ia32_getmantph512_mask:
4781   case X86::BI__builtin_ia32_vec_ext_v16qi:
4782   case X86::BI__builtin_ia32_vec_ext_v16hi:
4783     i = 1; l = 0; u = 15;
4784     break;
4785   case X86::BI__builtin_ia32_pblendd128:
4786   case X86::BI__builtin_ia32_blendps:
4787   case X86::BI__builtin_ia32_blendpd256:
4788   case X86::BI__builtin_ia32_shufpd256:
4789   case X86::BI__builtin_ia32_roundss:
4790   case X86::BI__builtin_ia32_roundsd:
4791   case X86::BI__builtin_ia32_rangepd128_mask:
4792   case X86::BI__builtin_ia32_rangepd256_mask:
4793   case X86::BI__builtin_ia32_rangepd512_mask:
4794   case X86::BI__builtin_ia32_rangeps128_mask:
4795   case X86::BI__builtin_ia32_rangeps256_mask:
4796   case X86::BI__builtin_ia32_rangeps512_mask:
4797   case X86::BI__builtin_ia32_getmantsd_round_mask:
4798   case X86::BI__builtin_ia32_getmantss_round_mask:
4799   case X86::BI__builtin_ia32_getmantsh_round_mask:
4800   case X86::BI__builtin_ia32_vec_set_v16qi:
4801   case X86::BI__builtin_ia32_vec_set_v16hi:
4802     i = 2; l = 0; u = 15;
4803     break;
4804   case X86::BI__builtin_ia32_vec_ext_v32qi:
4805     i = 1; l = 0; u = 31;
4806     break;
4807   case X86::BI__builtin_ia32_cmpps:
4808   case X86::BI__builtin_ia32_cmpss:
4809   case X86::BI__builtin_ia32_cmppd:
4810   case X86::BI__builtin_ia32_cmpsd:
4811   case X86::BI__builtin_ia32_cmpps256:
4812   case X86::BI__builtin_ia32_cmppd256:
4813   case X86::BI__builtin_ia32_cmpps128_mask:
4814   case X86::BI__builtin_ia32_cmppd128_mask:
4815   case X86::BI__builtin_ia32_cmpps256_mask:
4816   case X86::BI__builtin_ia32_cmppd256_mask:
4817   case X86::BI__builtin_ia32_cmpps512_mask:
4818   case X86::BI__builtin_ia32_cmppd512_mask:
4819   case X86::BI__builtin_ia32_cmpsd_mask:
4820   case X86::BI__builtin_ia32_cmpss_mask:
4821   case X86::BI__builtin_ia32_vec_set_v32qi:
4822     i = 2; l = 0; u = 31;
4823     break;
4824   case X86::BI__builtin_ia32_permdf256:
4825   case X86::BI__builtin_ia32_permdi256:
4826   case X86::BI__builtin_ia32_permdf512:
4827   case X86::BI__builtin_ia32_permdi512:
4828   case X86::BI__builtin_ia32_vpermilps:
4829   case X86::BI__builtin_ia32_vpermilps256:
4830   case X86::BI__builtin_ia32_vpermilpd512:
4831   case X86::BI__builtin_ia32_vpermilps512:
4832   case X86::BI__builtin_ia32_pshufd:
4833   case X86::BI__builtin_ia32_pshufd256:
4834   case X86::BI__builtin_ia32_pshufd512:
4835   case X86::BI__builtin_ia32_pshufhw:
4836   case X86::BI__builtin_ia32_pshufhw256:
4837   case X86::BI__builtin_ia32_pshufhw512:
4838   case X86::BI__builtin_ia32_pshuflw:
4839   case X86::BI__builtin_ia32_pshuflw256:
4840   case X86::BI__builtin_ia32_pshuflw512:
4841   case X86::BI__builtin_ia32_vcvtps2ph:
4842   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4843   case X86::BI__builtin_ia32_vcvtps2ph256:
4844   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4845   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4846   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4847   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4848   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4849   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4850   case X86::BI__builtin_ia32_rndscaleps_mask:
4851   case X86::BI__builtin_ia32_rndscalepd_mask:
4852   case X86::BI__builtin_ia32_rndscaleph_mask:
4853   case X86::BI__builtin_ia32_reducepd128_mask:
4854   case X86::BI__builtin_ia32_reducepd256_mask:
4855   case X86::BI__builtin_ia32_reducepd512_mask:
4856   case X86::BI__builtin_ia32_reduceps128_mask:
4857   case X86::BI__builtin_ia32_reduceps256_mask:
4858   case X86::BI__builtin_ia32_reduceps512_mask:
4859   case X86::BI__builtin_ia32_reduceph128_mask:
4860   case X86::BI__builtin_ia32_reduceph256_mask:
4861   case X86::BI__builtin_ia32_reduceph512_mask:
4862   case X86::BI__builtin_ia32_prold512:
4863   case X86::BI__builtin_ia32_prolq512:
4864   case X86::BI__builtin_ia32_prold128:
4865   case X86::BI__builtin_ia32_prold256:
4866   case X86::BI__builtin_ia32_prolq128:
4867   case X86::BI__builtin_ia32_prolq256:
4868   case X86::BI__builtin_ia32_prord512:
4869   case X86::BI__builtin_ia32_prorq512:
4870   case X86::BI__builtin_ia32_prord128:
4871   case X86::BI__builtin_ia32_prord256:
4872   case X86::BI__builtin_ia32_prorq128:
4873   case X86::BI__builtin_ia32_prorq256:
4874   case X86::BI__builtin_ia32_fpclasspd128_mask:
4875   case X86::BI__builtin_ia32_fpclasspd256_mask:
4876   case X86::BI__builtin_ia32_fpclassps128_mask:
4877   case X86::BI__builtin_ia32_fpclassps256_mask:
4878   case X86::BI__builtin_ia32_fpclassps512_mask:
4879   case X86::BI__builtin_ia32_fpclasspd512_mask:
4880   case X86::BI__builtin_ia32_fpclassph128_mask:
4881   case X86::BI__builtin_ia32_fpclassph256_mask:
4882   case X86::BI__builtin_ia32_fpclassph512_mask:
4883   case X86::BI__builtin_ia32_fpclasssd_mask:
4884   case X86::BI__builtin_ia32_fpclassss_mask:
4885   case X86::BI__builtin_ia32_fpclasssh_mask:
4886   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4887   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4888   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4889   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4890   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4891   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4892   case X86::BI__builtin_ia32_kshiftliqi:
4893   case X86::BI__builtin_ia32_kshiftlihi:
4894   case X86::BI__builtin_ia32_kshiftlisi:
4895   case X86::BI__builtin_ia32_kshiftlidi:
4896   case X86::BI__builtin_ia32_kshiftriqi:
4897   case X86::BI__builtin_ia32_kshiftrihi:
4898   case X86::BI__builtin_ia32_kshiftrisi:
4899   case X86::BI__builtin_ia32_kshiftridi:
4900     i = 1; l = 0; u = 255;
4901     break;
4902   case X86::BI__builtin_ia32_vperm2f128_pd256:
4903   case X86::BI__builtin_ia32_vperm2f128_ps256:
4904   case X86::BI__builtin_ia32_vperm2f128_si256:
4905   case X86::BI__builtin_ia32_permti256:
4906   case X86::BI__builtin_ia32_pblendw128:
4907   case X86::BI__builtin_ia32_pblendw256:
4908   case X86::BI__builtin_ia32_blendps256:
4909   case X86::BI__builtin_ia32_pblendd256:
4910   case X86::BI__builtin_ia32_palignr128:
4911   case X86::BI__builtin_ia32_palignr256:
4912   case X86::BI__builtin_ia32_palignr512:
4913   case X86::BI__builtin_ia32_alignq512:
4914   case X86::BI__builtin_ia32_alignd512:
4915   case X86::BI__builtin_ia32_alignd128:
4916   case X86::BI__builtin_ia32_alignd256:
4917   case X86::BI__builtin_ia32_alignq128:
4918   case X86::BI__builtin_ia32_alignq256:
4919   case X86::BI__builtin_ia32_vcomisd:
4920   case X86::BI__builtin_ia32_vcomiss:
4921   case X86::BI__builtin_ia32_shuf_f32x4:
4922   case X86::BI__builtin_ia32_shuf_f64x2:
4923   case X86::BI__builtin_ia32_shuf_i32x4:
4924   case X86::BI__builtin_ia32_shuf_i64x2:
4925   case X86::BI__builtin_ia32_shufpd512:
4926   case X86::BI__builtin_ia32_shufps:
4927   case X86::BI__builtin_ia32_shufps256:
4928   case X86::BI__builtin_ia32_shufps512:
4929   case X86::BI__builtin_ia32_dbpsadbw128:
4930   case X86::BI__builtin_ia32_dbpsadbw256:
4931   case X86::BI__builtin_ia32_dbpsadbw512:
4932   case X86::BI__builtin_ia32_vpshldd128:
4933   case X86::BI__builtin_ia32_vpshldd256:
4934   case X86::BI__builtin_ia32_vpshldd512:
4935   case X86::BI__builtin_ia32_vpshldq128:
4936   case X86::BI__builtin_ia32_vpshldq256:
4937   case X86::BI__builtin_ia32_vpshldq512:
4938   case X86::BI__builtin_ia32_vpshldw128:
4939   case X86::BI__builtin_ia32_vpshldw256:
4940   case X86::BI__builtin_ia32_vpshldw512:
4941   case X86::BI__builtin_ia32_vpshrdd128:
4942   case X86::BI__builtin_ia32_vpshrdd256:
4943   case X86::BI__builtin_ia32_vpshrdd512:
4944   case X86::BI__builtin_ia32_vpshrdq128:
4945   case X86::BI__builtin_ia32_vpshrdq256:
4946   case X86::BI__builtin_ia32_vpshrdq512:
4947   case X86::BI__builtin_ia32_vpshrdw128:
4948   case X86::BI__builtin_ia32_vpshrdw256:
4949   case X86::BI__builtin_ia32_vpshrdw512:
4950     i = 2; l = 0; u = 255;
4951     break;
4952   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4953   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4954   case X86::BI__builtin_ia32_fixupimmps512_mask:
4955   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4956   case X86::BI__builtin_ia32_fixupimmsd_mask:
4957   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4958   case X86::BI__builtin_ia32_fixupimmss_mask:
4959   case X86::BI__builtin_ia32_fixupimmss_maskz:
4960   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4961   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4962   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4963   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4964   case X86::BI__builtin_ia32_fixupimmps128_mask:
4965   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4966   case X86::BI__builtin_ia32_fixupimmps256_mask:
4967   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4968   case X86::BI__builtin_ia32_pternlogd512_mask:
4969   case X86::BI__builtin_ia32_pternlogd512_maskz:
4970   case X86::BI__builtin_ia32_pternlogq512_mask:
4971   case X86::BI__builtin_ia32_pternlogq512_maskz:
4972   case X86::BI__builtin_ia32_pternlogd128_mask:
4973   case X86::BI__builtin_ia32_pternlogd128_maskz:
4974   case X86::BI__builtin_ia32_pternlogd256_mask:
4975   case X86::BI__builtin_ia32_pternlogd256_maskz:
4976   case X86::BI__builtin_ia32_pternlogq128_mask:
4977   case X86::BI__builtin_ia32_pternlogq128_maskz:
4978   case X86::BI__builtin_ia32_pternlogq256_mask:
4979   case X86::BI__builtin_ia32_pternlogq256_maskz:
4980     i = 3; l = 0; u = 255;
4981     break;
4982   case X86::BI__builtin_ia32_gatherpfdpd:
4983   case X86::BI__builtin_ia32_gatherpfdps:
4984   case X86::BI__builtin_ia32_gatherpfqpd:
4985   case X86::BI__builtin_ia32_gatherpfqps:
4986   case X86::BI__builtin_ia32_scatterpfdpd:
4987   case X86::BI__builtin_ia32_scatterpfdps:
4988   case X86::BI__builtin_ia32_scatterpfqpd:
4989   case X86::BI__builtin_ia32_scatterpfqps:
4990     i = 4; l = 2; u = 3;
4991     break;
4992   case X86::BI__builtin_ia32_reducesd_mask:
4993   case X86::BI__builtin_ia32_reducess_mask:
4994   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4995   case X86::BI__builtin_ia32_rndscaless_round_mask:
4996   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4997   case X86::BI__builtin_ia32_reducesh_mask:
4998     i = 4; l = 0; u = 255;
4999     break;
5000   }
5001 
5002   // Note that we don't force a hard error on the range check here, allowing
5003   // template-generated or macro-generated dead code to potentially have out-of-
5004   // range values. These need to code generate, but don't need to necessarily
5005   // make any sense. We use a warning that defaults to an error.
5006   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5007 }
5008 
5009 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5010 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5011 /// Returns true when the format fits the function and the FormatStringInfo has
5012 /// been populated.
5013 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5014                                FormatStringInfo *FSI) {
5015   FSI->HasVAListArg = Format->getFirstArg() == 0;
5016   FSI->FormatIdx = Format->getFormatIdx() - 1;
5017   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5018 
5019   // The way the format attribute works in GCC, the implicit this argument
5020   // of member functions is counted. However, it doesn't appear in our own
5021   // lists, so decrement format_idx in that case.
5022   if (IsCXXMember) {
5023     if(FSI->FormatIdx == 0)
5024       return false;
5025     --FSI->FormatIdx;
5026     if (FSI->FirstDataArg != 0)
5027       --FSI->FirstDataArg;
5028   }
5029   return true;
5030 }
5031 
5032 /// Checks if a the given expression evaluates to null.
5033 ///
5034 /// Returns true if the value evaluates to null.
5035 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5036   // If the expression has non-null type, it doesn't evaluate to null.
5037   if (auto nullability
5038         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5039     if (*nullability == NullabilityKind::NonNull)
5040       return false;
5041   }
5042 
5043   // As a special case, transparent unions initialized with zero are
5044   // considered null for the purposes of the nonnull attribute.
5045   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5046     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5047       if (const CompoundLiteralExpr *CLE =
5048           dyn_cast<CompoundLiteralExpr>(Expr))
5049         if (const InitListExpr *ILE =
5050             dyn_cast<InitListExpr>(CLE->getInitializer()))
5051           Expr = ILE->getInit(0);
5052   }
5053 
5054   bool Result;
5055   return (!Expr->isValueDependent() &&
5056           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5057           !Result);
5058 }
5059 
5060 static void CheckNonNullArgument(Sema &S,
5061                                  const Expr *ArgExpr,
5062                                  SourceLocation CallSiteLoc) {
5063   if (CheckNonNullExpr(S, ArgExpr))
5064     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5065                           S.PDiag(diag::warn_null_arg)
5066                               << ArgExpr->getSourceRange());
5067 }
5068 
5069 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5070   FormatStringInfo FSI;
5071   if ((GetFormatStringType(Format) == FST_NSString) &&
5072       getFormatStringInfo(Format, false, &FSI)) {
5073     Idx = FSI.FormatIdx;
5074     return true;
5075   }
5076   return false;
5077 }
5078 
5079 /// Diagnose use of %s directive in an NSString which is being passed
5080 /// as formatting string to formatting method.
5081 static void
5082 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5083                                         const NamedDecl *FDecl,
5084                                         Expr **Args,
5085                                         unsigned NumArgs) {
5086   unsigned Idx = 0;
5087   bool Format = false;
5088   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5089   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5090     Idx = 2;
5091     Format = true;
5092   }
5093   else
5094     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5095       if (S.GetFormatNSStringIdx(I, Idx)) {
5096         Format = true;
5097         break;
5098       }
5099     }
5100   if (!Format || NumArgs <= Idx)
5101     return;
5102   const Expr *FormatExpr = Args[Idx];
5103   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5104     FormatExpr = CSCE->getSubExpr();
5105   const StringLiteral *FormatString;
5106   if (const ObjCStringLiteral *OSL =
5107       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5108     FormatString = OSL->getString();
5109   else
5110     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5111   if (!FormatString)
5112     return;
5113   if (S.FormatStringHasSArg(FormatString)) {
5114     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5115       << "%s" << 1 << 1;
5116     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5117       << FDecl->getDeclName();
5118   }
5119 }
5120 
5121 /// Determine whether the given type has a non-null nullability annotation.
5122 static bool isNonNullType(ASTContext &ctx, QualType type) {
5123   if (auto nullability = type->getNullability(ctx))
5124     return *nullability == NullabilityKind::NonNull;
5125 
5126   return false;
5127 }
5128 
5129 static void CheckNonNullArguments(Sema &S,
5130                                   const NamedDecl *FDecl,
5131                                   const FunctionProtoType *Proto,
5132                                   ArrayRef<const Expr *> Args,
5133                                   SourceLocation CallSiteLoc) {
5134   assert((FDecl || Proto) && "Need a function declaration or prototype");
5135 
5136   // Already checked by by constant evaluator.
5137   if (S.isConstantEvaluated())
5138     return;
5139   // Check the attributes attached to the method/function itself.
5140   llvm::SmallBitVector NonNullArgs;
5141   if (FDecl) {
5142     // Handle the nonnull attribute on the function/method declaration itself.
5143     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5144       if (!NonNull->args_size()) {
5145         // Easy case: all pointer arguments are nonnull.
5146         for (const auto *Arg : Args)
5147           if (S.isValidPointerAttrType(Arg->getType()))
5148             CheckNonNullArgument(S, Arg, CallSiteLoc);
5149         return;
5150       }
5151 
5152       for (const ParamIdx &Idx : NonNull->args()) {
5153         unsigned IdxAST = Idx.getASTIndex();
5154         if (IdxAST >= Args.size())
5155           continue;
5156         if (NonNullArgs.empty())
5157           NonNullArgs.resize(Args.size());
5158         NonNullArgs.set(IdxAST);
5159       }
5160     }
5161   }
5162 
5163   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5164     // Handle the nonnull attribute on the parameters of the
5165     // function/method.
5166     ArrayRef<ParmVarDecl*> parms;
5167     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5168       parms = FD->parameters();
5169     else
5170       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5171 
5172     unsigned ParamIndex = 0;
5173     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5174          I != E; ++I, ++ParamIndex) {
5175       const ParmVarDecl *PVD = *I;
5176       if (PVD->hasAttr<NonNullAttr>() ||
5177           isNonNullType(S.Context, PVD->getType())) {
5178         if (NonNullArgs.empty())
5179           NonNullArgs.resize(Args.size());
5180 
5181         NonNullArgs.set(ParamIndex);
5182       }
5183     }
5184   } else {
5185     // If we have a non-function, non-method declaration but no
5186     // function prototype, try to dig out the function prototype.
5187     if (!Proto) {
5188       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5189         QualType type = VD->getType().getNonReferenceType();
5190         if (auto pointerType = type->getAs<PointerType>())
5191           type = pointerType->getPointeeType();
5192         else if (auto blockType = type->getAs<BlockPointerType>())
5193           type = blockType->getPointeeType();
5194         // FIXME: data member pointers?
5195 
5196         // Dig out the function prototype, if there is one.
5197         Proto = type->getAs<FunctionProtoType>();
5198       }
5199     }
5200 
5201     // Fill in non-null argument information from the nullability
5202     // information on the parameter types (if we have them).
5203     if (Proto) {
5204       unsigned Index = 0;
5205       for (auto paramType : Proto->getParamTypes()) {
5206         if (isNonNullType(S.Context, paramType)) {
5207           if (NonNullArgs.empty())
5208             NonNullArgs.resize(Args.size());
5209 
5210           NonNullArgs.set(Index);
5211         }
5212 
5213         ++Index;
5214       }
5215     }
5216   }
5217 
5218   // Check for non-null arguments.
5219   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5220        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5221     if (NonNullArgs[ArgIndex])
5222       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5223   }
5224 }
5225 
5226 /// Warn if a pointer or reference argument passed to a function points to an
5227 /// object that is less aligned than the parameter. This can happen when
5228 /// creating a typedef with a lower alignment than the original type and then
5229 /// calling functions defined in terms of the original type.
5230 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5231                              StringRef ParamName, QualType ArgTy,
5232                              QualType ParamTy) {
5233 
5234   // If a function accepts a pointer or reference type
5235   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5236     return;
5237 
5238   // If the parameter is a pointer type, get the pointee type for the
5239   // argument too. If the parameter is a reference type, don't try to get
5240   // the pointee type for the argument.
5241   if (ParamTy->isPointerType())
5242     ArgTy = ArgTy->getPointeeType();
5243 
5244   // Remove reference or pointer
5245   ParamTy = ParamTy->getPointeeType();
5246 
5247   // Find expected alignment, and the actual alignment of the passed object.
5248   // getTypeAlignInChars requires complete types
5249   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5250       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5251       ArgTy->isUndeducedType())
5252     return;
5253 
5254   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5255   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5256 
5257   // If the argument is less aligned than the parameter, there is a
5258   // potential alignment issue.
5259   if (ArgAlign < ParamAlign)
5260     Diag(Loc, diag::warn_param_mismatched_alignment)
5261         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5262         << ParamName << (FDecl != nullptr) << FDecl;
5263 }
5264 
5265 /// Handles the checks for format strings, non-POD arguments to vararg
5266 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5267 /// attributes.
5268 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5269                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5270                      bool IsMemberFunction, SourceLocation Loc,
5271                      SourceRange Range, VariadicCallType CallType) {
5272   // FIXME: We should check as much as we can in the template definition.
5273   if (CurContext->isDependentContext())
5274     return;
5275 
5276   // Printf and scanf checking.
5277   llvm::SmallBitVector CheckedVarArgs;
5278   if (FDecl) {
5279     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5280       // Only create vector if there are format attributes.
5281       CheckedVarArgs.resize(Args.size());
5282 
5283       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5284                            CheckedVarArgs);
5285     }
5286   }
5287 
5288   // Refuse POD arguments that weren't caught by the format string
5289   // checks above.
5290   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5291   if (CallType != VariadicDoesNotApply &&
5292       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5293     unsigned NumParams = Proto ? Proto->getNumParams()
5294                        : FDecl && isa<FunctionDecl>(FDecl)
5295                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5296                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5297                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5298                        : 0;
5299 
5300     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5301       // Args[ArgIdx] can be null in malformed code.
5302       if (const Expr *Arg = Args[ArgIdx]) {
5303         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5304           checkVariadicArgument(Arg, CallType);
5305       }
5306     }
5307   }
5308 
5309   if (FDecl || Proto) {
5310     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5311 
5312     // Type safety checking.
5313     if (FDecl) {
5314       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5315         CheckArgumentWithTypeTag(I, Args, Loc);
5316     }
5317   }
5318 
5319   // Check that passed arguments match the alignment of original arguments.
5320   // Try to get the missing prototype from the declaration.
5321   if (!Proto && FDecl) {
5322     const auto *FT = FDecl->getFunctionType();
5323     if (isa_and_nonnull<FunctionProtoType>(FT))
5324       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5325   }
5326   if (Proto) {
5327     // For variadic functions, we may have more args than parameters.
5328     // For some K&R functions, we may have less args than parameters.
5329     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5330     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5331       // Args[ArgIdx] can be null in malformed code.
5332       if (const Expr *Arg = Args[ArgIdx]) {
5333         if (Arg->containsErrors())
5334           continue;
5335 
5336         QualType ParamTy = Proto->getParamType(ArgIdx);
5337         QualType ArgTy = Arg->getType();
5338         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5339                           ArgTy, ParamTy);
5340       }
5341     }
5342   }
5343 
5344   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5345     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5346     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5347     if (!Arg->isValueDependent()) {
5348       Expr::EvalResult Align;
5349       if (Arg->EvaluateAsInt(Align, Context)) {
5350         const llvm::APSInt &I = Align.Val.getInt();
5351         if (!I.isPowerOf2())
5352           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5353               << Arg->getSourceRange();
5354 
5355         if (I > Sema::MaximumAlignment)
5356           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5357               << Arg->getSourceRange() << Sema::MaximumAlignment;
5358       }
5359     }
5360   }
5361 
5362   if (FD)
5363     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5364 }
5365 
5366 /// CheckConstructorCall - Check a constructor call for correctness and safety
5367 /// properties not enforced by the C type system.
5368 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5369                                 ArrayRef<const Expr *> Args,
5370                                 const FunctionProtoType *Proto,
5371                                 SourceLocation Loc) {
5372   VariadicCallType CallType =
5373       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5374 
5375   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5376   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5377                     Context.getPointerType(Ctor->getThisObjectType()));
5378 
5379   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5380             Loc, SourceRange(), CallType);
5381 }
5382 
5383 /// CheckFunctionCall - Check a direct function call for various correctness
5384 /// and safety properties not strictly enforced by the C type system.
5385 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5386                              const FunctionProtoType *Proto) {
5387   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5388                               isa<CXXMethodDecl>(FDecl);
5389   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5390                           IsMemberOperatorCall;
5391   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5392                                                   TheCall->getCallee());
5393   Expr** Args = TheCall->getArgs();
5394   unsigned NumArgs = TheCall->getNumArgs();
5395 
5396   Expr *ImplicitThis = nullptr;
5397   if (IsMemberOperatorCall) {
5398     // If this is a call to a member operator, hide the first argument
5399     // from checkCall.
5400     // FIXME: Our choice of AST representation here is less than ideal.
5401     ImplicitThis = Args[0];
5402     ++Args;
5403     --NumArgs;
5404   } else if (IsMemberFunction)
5405     ImplicitThis =
5406         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5407 
5408   if (ImplicitThis) {
5409     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5410     // used.
5411     QualType ThisType = ImplicitThis->getType();
5412     if (!ThisType->isPointerType()) {
5413       assert(!ThisType->isReferenceType());
5414       ThisType = Context.getPointerType(ThisType);
5415     }
5416 
5417     QualType ThisTypeFromDecl =
5418         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5419 
5420     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5421                       ThisTypeFromDecl);
5422   }
5423 
5424   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5425             IsMemberFunction, TheCall->getRParenLoc(),
5426             TheCall->getCallee()->getSourceRange(), CallType);
5427 
5428   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5429   // None of the checks below are needed for functions that don't have
5430   // simple names (e.g., C++ conversion functions).
5431   if (!FnInfo)
5432     return false;
5433 
5434   CheckTCBEnforcement(TheCall, FDecl);
5435 
5436   CheckAbsoluteValueFunction(TheCall, FDecl);
5437   CheckMaxUnsignedZero(TheCall, FDecl);
5438 
5439   if (getLangOpts().ObjC)
5440     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5441 
5442   unsigned CMId = FDecl->getMemoryFunctionKind();
5443 
5444   // Handle memory setting and copying functions.
5445   switch (CMId) {
5446   case 0:
5447     return false;
5448   case Builtin::BIstrlcpy: // fallthrough
5449   case Builtin::BIstrlcat:
5450     CheckStrlcpycatArguments(TheCall, FnInfo);
5451     break;
5452   case Builtin::BIstrncat:
5453     CheckStrncatArguments(TheCall, FnInfo);
5454     break;
5455   case Builtin::BIfree:
5456     CheckFreeArguments(TheCall);
5457     break;
5458   default:
5459     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5460   }
5461 
5462   return false;
5463 }
5464 
5465 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5466                                ArrayRef<const Expr *> Args) {
5467   VariadicCallType CallType =
5468       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5469 
5470   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5471             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5472             CallType);
5473 
5474   return false;
5475 }
5476 
5477 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5478                             const FunctionProtoType *Proto) {
5479   QualType Ty;
5480   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5481     Ty = V->getType().getNonReferenceType();
5482   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5483     Ty = F->getType().getNonReferenceType();
5484   else
5485     return false;
5486 
5487   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5488       !Ty->isFunctionProtoType())
5489     return false;
5490 
5491   VariadicCallType CallType;
5492   if (!Proto || !Proto->isVariadic()) {
5493     CallType = VariadicDoesNotApply;
5494   } else if (Ty->isBlockPointerType()) {
5495     CallType = VariadicBlock;
5496   } else { // Ty->isFunctionPointerType()
5497     CallType = VariadicFunction;
5498   }
5499 
5500   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5501             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5502             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5503             TheCall->getCallee()->getSourceRange(), CallType);
5504 
5505   return false;
5506 }
5507 
5508 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5509 /// such as function pointers returned from functions.
5510 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5511   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5512                                                   TheCall->getCallee());
5513   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5514             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5515             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5516             TheCall->getCallee()->getSourceRange(), CallType);
5517 
5518   return false;
5519 }
5520 
5521 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5522   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5523     return false;
5524 
5525   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5526   switch (Op) {
5527   case AtomicExpr::AO__c11_atomic_init:
5528   case AtomicExpr::AO__opencl_atomic_init:
5529     llvm_unreachable("There is no ordering argument for an init");
5530 
5531   case AtomicExpr::AO__c11_atomic_load:
5532   case AtomicExpr::AO__opencl_atomic_load:
5533   case AtomicExpr::AO__hip_atomic_load:
5534   case AtomicExpr::AO__atomic_load_n:
5535   case AtomicExpr::AO__atomic_load:
5536     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5537            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5538 
5539   case AtomicExpr::AO__c11_atomic_store:
5540   case AtomicExpr::AO__opencl_atomic_store:
5541   case AtomicExpr::AO__hip_atomic_store:
5542   case AtomicExpr::AO__atomic_store:
5543   case AtomicExpr::AO__atomic_store_n:
5544     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5545            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5546            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5547 
5548   default:
5549     return true;
5550   }
5551 }
5552 
5553 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5554                                          AtomicExpr::AtomicOp Op) {
5555   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5556   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5557   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5558   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5559                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5560                          Op);
5561 }
5562 
5563 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5564                                  SourceLocation RParenLoc, MultiExprArg Args,
5565                                  AtomicExpr::AtomicOp Op,
5566                                  AtomicArgumentOrder ArgOrder) {
5567   // All the non-OpenCL operations take one of the following forms.
5568   // The OpenCL operations take the __c11 forms with one extra argument for
5569   // synchronization scope.
5570   enum {
5571     // C    __c11_atomic_init(A *, C)
5572     Init,
5573 
5574     // C    __c11_atomic_load(A *, int)
5575     Load,
5576 
5577     // void __atomic_load(A *, CP, int)
5578     LoadCopy,
5579 
5580     // void __atomic_store(A *, CP, int)
5581     Copy,
5582 
5583     // C    __c11_atomic_add(A *, M, int)
5584     Arithmetic,
5585 
5586     // C    __atomic_exchange_n(A *, CP, int)
5587     Xchg,
5588 
5589     // void __atomic_exchange(A *, C *, CP, int)
5590     GNUXchg,
5591 
5592     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5593     C11CmpXchg,
5594 
5595     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5596     GNUCmpXchg
5597   } Form = Init;
5598 
5599   const unsigned NumForm = GNUCmpXchg + 1;
5600   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5601   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5602   // where:
5603   //   C is an appropriate type,
5604   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5605   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5606   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5607   //   the int parameters are for orderings.
5608 
5609   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5610       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5611       "need to update code for modified forms");
5612   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5613                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5614                         AtomicExpr::AO__atomic_load,
5615                 "need to update code for modified C11 atomics");
5616   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5617                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5618   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5619                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5620   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5621                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5622                IsOpenCL;
5623   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5624              Op == AtomicExpr::AO__atomic_store_n ||
5625              Op == AtomicExpr::AO__atomic_exchange_n ||
5626              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5627   bool IsAddSub = false;
5628 
5629   switch (Op) {
5630   case AtomicExpr::AO__c11_atomic_init:
5631   case AtomicExpr::AO__opencl_atomic_init:
5632     Form = Init;
5633     break;
5634 
5635   case AtomicExpr::AO__c11_atomic_load:
5636   case AtomicExpr::AO__opencl_atomic_load:
5637   case AtomicExpr::AO__hip_atomic_load:
5638   case AtomicExpr::AO__atomic_load_n:
5639     Form = Load;
5640     break;
5641 
5642   case AtomicExpr::AO__atomic_load:
5643     Form = LoadCopy;
5644     break;
5645 
5646   case AtomicExpr::AO__c11_atomic_store:
5647   case AtomicExpr::AO__opencl_atomic_store:
5648   case AtomicExpr::AO__hip_atomic_store:
5649   case AtomicExpr::AO__atomic_store:
5650   case AtomicExpr::AO__atomic_store_n:
5651     Form = Copy;
5652     break;
5653   case AtomicExpr::AO__hip_atomic_fetch_add:
5654   case AtomicExpr::AO__hip_atomic_fetch_min:
5655   case AtomicExpr::AO__hip_atomic_fetch_max:
5656   case AtomicExpr::AO__c11_atomic_fetch_add:
5657   case AtomicExpr::AO__c11_atomic_fetch_sub:
5658   case AtomicExpr::AO__opencl_atomic_fetch_add:
5659   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5660   case AtomicExpr::AO__atomic_fetch_add:
5661   case AtomicExpr::AO__atomic_fetch_sub:
5662   case AtomicExpr::AO__atomic_add_fetch:
5663   case AtomicExpr::AO__atomic_sub_fetch:
5664     IsAddSub = true;
5665     Form = Arithmetic;
5666     break;
5667   case AtomicExpr::AO__c11_atomic_fetch_and:
5668   case AtomicExpr::AO__c11_atomic_fetch_or:
5669   case AtomicExpr::AO__c11_atomic_fetch_xor:
5670   case AtomicExpr::AO__hip_atomic_fetch_and:
5671   case AtomicExpr::AO__hip_atomic_fetch_or:
5672   case AtomicExpr::AO__hip_atomic_fetch_xor:
5673   case AtomicExpr::AO__c11_atomic_fetch_nand:
5674   case AtomicExpr::AO__opencl_atomic_fetch_and:
5675   case AtomicExpr::AO__opencl_atomic_fetch_or:
5676   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5677   case AtomicExpr::AO__atomic_fetch_and:
5678   case AtomicExpr::AO__atomic_fetch_or:
5679   case AtomicExpr::AO__atomic_fetch_xor:
5680   case AtomicExpr::AO__atomic_fetch_nand:
5681   case AtomicExpr::AO__atomic_and_fetch:
5682   case AtomicExpr::AO__atomic_or_fetch:
5683   case AtomicExpr::AO__atomic_xor_fetch:
5684   case AtomicExpr::AO__atomic_nand_fetch:
5685     Form = Arithmetic;
5686     break;
5687   case AtomicExpr::AO__c11_atomic_fetch_min:
5688   case AtomicExpr::AO__c11_atomic_fetch_max:
5689   case AtomicExpr::AO__opencl_atomic_fetch_min:
5690   case AtomicExpr::AO__opencl_atomic_fetch_max:
5691   case AtomicExpr::AO__atomic_min_fetch:
5692   case AtomicExpr::AO__atomic_max_fetch:
5693   case AtomicExpr::AO__atomic_fetch_min:
5694   case AtomicExpr::AO__atomic_fetch_max:
5695     Form = Arithmetic;
5696     break;
5697 
5698   case AtomicExpr::AO__c11_atomic_exchange:
5699   case AtomicExpr::AO__hip_atomic_exchange:
5700   case AtomicExpr::AO__opencl_atomic_exchange:
5701   case AtomicExpr::AO__atomic_exchange_n:
5702     Form = Xchg;
5703     break;
5704 
5705   case AtomicExpr::AO__atomic_exchange:
5706     Form = GNUXchg;
5707     break;
5708 
5709   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5710   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5711   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5712   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5713   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5714   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5715     Form = C11CmpXchg;
5716     break;
5717 
5718   case AtomicExpr::AO__atomic_compare_exchange:
5719   case AtomicExpr::AO__atomic_compare_exchange_n:
5720     Form = GNUCmpXchg;
5721     break;
5722   }
5723 
5724   unsigned AdjustedNumArgs = NumArgs[Form];
5725   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5726     ++AdjustedNumArgs;
5727   // Check we have the right number of arguments.
5728   if (Args.size() < AdjustedNumArgs) {
5729     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5730         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5731         << ExprRange;
5732     return ExprError();
5733   } else if (Args.size() > AdjustedNumArgs) {
5734     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5735          diag::err_typecheck_call_too_many_args)
5736         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5737         << ExprRange;
5738     return ExprError();
5739   }
5740 
5741   // Inspect the first argument of the atomic operation.
5742   Expr *Ptr = Args[0];
5743   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5744   if (ConvertedPtr.isInvalid())
5745     return ExprError();
5746 
5747   Ptr = ConvertedPtr.get();
5748   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5749   if (!pointerType) {
5750     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5751         << Ptr->getType() << Ptr->getSourceRange();
5752     return ExprError();
5753   }
5754 
5755   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5756   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5757   QualType ValType = AtomTy; // 'C'
5758   if (IsC11) {
5759     if (!AtomTy->isAtomicType()) {
5760       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5761           << Ptr->getType() << Ptr->getSourceRange();
5762       return ExprError();
5763     }
5764     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5765         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5766       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5767           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5768           << Ptr->getSourceRange();
5769       return ExprError();
5770     }
5771     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5772   } else if (Form != Load && Form != LoadCopy) {
5773     if (ValType.isConstQualified()) {
5774       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5775           << Ptr->getType() << Ptr->getSourceRange();
5776       return ExprError();
5777     }
5778   }
5779 
5780   // For an arithmetic operation, the implied arithmetic must be well-formed.
5781   if (Form == Arithmetic) {
5782     // GCC does not enforce these rules for GNU atomics, but we do to help catch
5783     // trivial type errors.
5784     auto IsAllowedValueType = [&](QualType ValType) {
5785       if (ValType->isIntegerType())
5786         return true;
5787       if (ValType->isPointerType())
5788         return true;
5789       if (!ValType->isFloatingType())
5790         return false;
5791       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5792       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5793           &Context.getTargetInfo().getLongDoubleFormat() ==
5794               &llvm::APFloat::x87DoubleExtended())
5795         return false;
5796       return true;
5797     };
5798     if (IsAddSub && !IsAllowedValueType(ValType)) {
5799       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5800           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5801       return ExprError();
5802     }
5803     if (!IsAddSub && !ValType->isIntegerType()) {
5804       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5805           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5806       return ExprError();
5807     }
5808     if (IsC11 && ValType->isPointerType() &&
5809         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5810                             diag::err_incomplete_type)) {
5811       return ExprError();
5812     }
5813   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5814     // For __atomic_*_n operations, the value type must be a scalar integral or
5815     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5816     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5817         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5818     return ExprError();
5819   }
5820 
5821   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5822       !AtomTy->isScalarType()) {
5823     // For GNU atomics, require a trivially-copyable type. This is not part of
5824     // the GNU atomics specification but we enforce it for consistency with
5825     // other atomics which generally all require a trivially-copyable type. This
5826     // is because atomics just copy bits.
5827     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5828         << Ptr->getType() << Ptr->getSourceRange();
5829     return ExprError();
5830   }
5831 
5832   switch (ValType.getObjCLifetime()) {
5833   case Qualifiers::OCL_None:
5834   case Qualifiers::OCL_ExplicitNone:
5835     // okay
5836     break;
5837 
5838   case Qualifiers::OCL_Weak:
5839   case Qualifiers::OCL_Strong:
5840   case Qualifiers::OCL_Autoreleasing:
5841     // FIXME: Can this happen? By this point, ValType should be known
5842     // to be trivially copyable.
5843     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5844         << ValType << Ptr->getSourceRange();
5845     return ExprError();
5846   }
5847 
5848   // All atomic operations have an overload which takes a pointer to a volatile
5849   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5850   // into the result or the other operands. Similarly atomic_load takes a
5851   // pointer to a const 'A'.
5852   ValType.removeLocalVolatile();
5853   ValType.removeLocalConst();
5854   QualType ResultType = ValType;
5855   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5856       Form == Init)
5857     ResultType = Context.VoidTy;
5858   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5859     ResultType = Context.BoolTy;
5860 
5861   // The type of a parameter passed 'by value'. In the GNU atomics, such
5862   // arguments are actually passed as pointers.
5863   QualType ByValType = ValType; // 'CP'
5864   bool IsPassedByAddress = false;
5865   if (!IsC11 && !IsHIP && !IsN) {
5866     ByValType = Ptr->getType();
5867     IsPassedByAddress = true;
5868   }
5869 
5870   SmallVector<Expr *, 5> APIOrderedArgs;
5871   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5872     APIOrderedArgs.push_back(Args[0]);
5873     switch (Form) {
5874     case Init:
5875     case Load:
5876       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5877       break;
5878     case LoadCopy:
5879     case Copy:
5880     case Arithmetic:
5881     case Xchg:
5882       APIOrderedArgs.push_back(Args[2]); // Val1
5883       APIOrderedArgs.push_back(Args[1]); // Order
5884       break;
5885     case GNUXchg:
5886       APIOrderedArgs.push_back(Args[2]); // Val1
5887       APIOrderedArgs.push_back(Args[3]); // Val2
5888       APIOrderedArgs.push_back(Args[1]); // Order
5889       break;
5890     case C11CmpXchg:
5891       APIOrderedArgs.push_back(Args[2]); // Val1
5892       APIOrderedArgs.push_back(Args[4]); // Val2
5893       APIOrderedArgs.push_back(Args[1]); // Order
5894       APIOrderedArgs.push_back(Args[3]); // OrderFail
5895       break;
5896     case GNUCmpXchg:
5897       APIOrderedArgs.push_back(Args[2]); // Val1
5898       APIOrderedArgs.push_back(Args[4]); // Val2
5899       APIOrderedArgs.push_back(Args[5]); // Weak
5900       APIOrderedArgs.push_back(Args[1]); // Order
5901       APIOrderedArgs.push_back(Args[3]); // OrderFail
5902       break;
5903     }
5904   } else
5905     APIOrderedArgs.append(Args.begin(), Args.end());
5906 
5907   // The first argument's non-CV pointer type is used to deduce the type of
5908   // subsequent arguments, except for:
5909   //  - weak flag (always converted to bool)
5910   //  - memory order (always converted to int)
5911   //  - scope  (always converted to int)
5912   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5913     QualType Ty;
5914     if (i < NumVals[Form] + 1) {
5915       switch (i) {
5916       case 0:
5917         // The first argument is always a pointer. It has a fixed type.
5918         // It is always dereferenced, a nullptr is undefined.
5919         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5920         // Nothing else to do: we already know all we want about this pointer.
5921         continue;
5922       case 1:
5923         // The second argument is the non-atomic operand. For arithmetic, this
5924         // is always passed by value, and for a compare_exchange it is always
5925         // passed by address. For the rest, GNU uses by-address and C11 uses
5926         // by-value.
5927         assert(Form != Load);
5928         if (Form == Arithmetic && ValType->isPointerType())
5929           Ty = Context.getPointerDiffType();
5930         else if (Form == Init || Form == Arithmetic)
5931           Ty = ValType;
5932         else if (Form == Copy || Form == Xchg) {
5933           if (IsPassedByAddress) {
5934             // The value pointer is always dereferenced, a nullptr is undefined.
5935             CheckNonNullArgument(*this, APIOrderedArgs[i],
5936                                  ExprRange.getBegin());
5937           }
5938           Ty = ByValType;
5939         } else {
5940           Expr *ValArg = APIOrderedArgs[i];
5941           // The value pointer is always dereferenced, a nullptr is undefined.
5942           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5943           LangAS AS = LangAS::Default;
5944           // Keep address space of non-atomic pointer type.
5945           if (const PointerType *PtrTy =
5946                   ValArg->getType()->getAs<PointerType>()) {
5947             AS = PtrTy->getPointeeType().getAddressSpace();
5948           }
5949           Ty = Context.getPointerType(
5950               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5951         }
5952         break;
5953       case 2:
5954         // The third argument to compare_exchange / GNU exchange is the desired
5955         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5956         if (IsPassedByAddress)
5957           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5958         Ty = ByValType;
5959         break;
5960       case 3:
5961         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5962         Ty = Context.BoolTy;
5963         break;
5964       }
5965     } else {
5966       // The order(s) and scope are always converted to int.
5967       Ty = Context.IntTy;
5968     }
5969 
5970     InitializedEntity Entity =
5971         InitializedEntity::InitializeParameter(Context, Ty, false);
5972     ExprResult Arg = APIOrderedArgs[i];
5973     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5974     if (Arg.isInvalid())
5975       return true;
5976     APIOrderedArgs[i] = Arg.get();
5977   }
5978 
5979   // Permute the arguments into a 'consistent' order.
5980   SmallVector<Expr*, 5> SubExprs;
5981   SubExprs.push_back(Ptr);
5982   switch (Form) {
5983   case Init:
5984     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5985     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5986     break;
5987   case Load:
5988     SubExprs.push_back(APIOrderedArgs[1]); // Order
5989     break;
5990   case LoadCopy:
5991   case Copy:
5992   case Arithmetic:
5993   case Xchg:
5994     SubExprs.push_back(APIOrderedArgs[2]); // Order
5995     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5996     break;
5997   case GNUXchg:
5998     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5999     SubExprs.push_back(APIOrderedArgs[3]); // Order
6000     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6001     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6002     break;
6003   case C11CmpXchg:
6004     SubExprs.push_back(APIOrderedArgs[3]); // Order
6005     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6006     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6007     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6008     break;
6009   case GNUCmpXchg:
6010     SubExprs.push_back(APIOrderedArgs[4]); // Order
6011     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6012     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6013     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6014     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6015     break;
6016   }
6017 
6018   if (SubExprs.size() >= 2 && Form != Init) {
6019     if (Optional<llvm::APSInt> Result =
6020             SubExprs[1]->getIntegerConstantExpr(Context))
6021       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6022         Diag(SubExprs[1]->getBeginLoc(),
6023              diag::warn_atomic_op_has_invalid_memory_order)
6024             << SubExprs[1]->getSourceRange();
6025   }
6026 
6027   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6028     auto *Scope = Args[Args.size() - 1];
6029     if (Optional<llvm::APSInt> Result =
6030             Scope->getIntegerConstantExpr(Context)) {
6031       if (!ScopeModel->isValid(Result->getZExtValue()))
6032         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6033             << Scope->getSourceRange();
6034     }
6035     SubExprs.push_back(Scope);
6036   }
6037 
6038   AtomicExpr *AE = new (Context)
6039       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6040 
6041   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6042        Op == AtomicExpr::AO__c11_atomic_store ||
6043        Op == AtomicExpr::AO__opencl_atomic_load ||
6044        Op == AtomicExpr::AO__hip_atomic_load ||
6045        Op == AtomicExpr::AO__opencl_atomic_store ||
6046        Op == AtomicExpr::AO__hip_atomic_store) &&
6047       Context.AtomicUsesUnsupportedLibcall(AE))
6048     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6049         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6050              Op == AtomicExpr::AO__opencl_atomic_load ||
6051              Op == AtomicExpr::AO__hip_atomic_load)
6052                 ? 0
6053                 : 1);
6054 
6055   if (ValType->isBitIntType()) {
6056     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6057     return ExprError();
6058   }
6059 
6060   return AE;
6061 }
6062 
6063 /// checkBuiltinArgument - Given a call to a builtin function, perform
6064 /// normal type-checking on the given argument, updating the call in
6065 /// place.  This is useful when a builtin function requires custom
6066 /// type-checking for some of its arguments but not necessarily all of
6067 /// them.
6068 ///
6069 /// Returns true on error.
6070 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6071   FunctionDecl *Fn = E->getDirectCallee();
6072   assert(Fn && "builtin call without direct callee!");
6073 
6074   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6075   InitializedEntity Entity =
6076     InitializedEntity::InitializeParameter(S.Context, Param);
6077 
6078   ExprResult Arg = E->getArg(0);
6079   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6080   if (Arg.isInvalid())
6081     return true;
6082 
6083   E->setArg(ArgIndex, Arg.get());
6084   return false;
6085 }
6086 
6087 /// We have a call to a function like __sync_fetch_and_add, which is an
6088 /// overloaded function based on the pointer type of its first argument.
6089 /// The main BuildCallExpr routines have already promoted the types of
6090 /// arguments because all of these calls are prototyped as void(...).
6091 ///
6092 /// This function goes through and does final semantic checking for these
6093 /// builtins, as well as generating any warnings.
6094 ExprResult
6095 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6096   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6097   Expr *Callee = TheCall->getCallee();
6098   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6099   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6100 
6101   // Ensure that we have at least one argument to do type inference from.
6102   if (TheCall->getNumArgs() < 1) {
6103     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6104         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6105     return ExprError();
6106   }
6107 
6108   // Inspect the first argument of the atomic builtin.  This should always be
6109   // a pointer type, whose element is an integral scalar or pointer type.
6110   // Because it is a pointer type, we don't have to worry about any implicit
6111   // casts here.
6112   // FIXME: We don't allow floating point scalars as input.
6113   Expr *FirstArg = TheCall->getArg(0);
6114   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6115   if (FirstArgResult.isInvalid())
6116     return ExprError();
6117   FirstArg = FirstArgResult.get();
6118   TheCall->setArg(0, FirstArg);
6119 
6120   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6121   if (!pointerType) {
6122     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6123         << FirstArg->getType() << FirstArg->getSourceRange();
6124     return ExprError();
6125   }
6126 
6127   QualType ValType = pointerType->getPointeeType();
6128   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6129       !ValType->isBlockPointerType()) {
6130     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6131         << FirstArg->getType() << FirstArg->getSourceRange();
6132     return ExprError();
6133   }
6134 
6135   if (ValType.isConstQualified()) {
6136     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6137         << FirstArg->getType() << FirstArg->getSourceRange();
6138     return ExprError();
6139   }
6140 
6141   switch (ValType.getObjCLifetime()) {
6142   case Qualifiers::OCL_None:
6143   case Qualifiers::OCL_ExplicitNone:
6144     // okay
6145     break;
6146 
6147   case Qualifiers::OCL_Weak:
6148   case Qualifiers::OCL_Strong:
6149   case Qualifiers::OCL_Autoreleasing:
6150     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6151         << ValType << FirstArg->getSourceRange();
6152     return ExprError();
6153   }
6154 
6155   // Strip any qualifiers off ValType.
6156   ValType = ValType.getUnqualifiedType();
6157 
6158   // The majority of builtins return a value, but a few have special return
6159   // types, so allow them to override appropriately below.
6160   QualType ResultType = ValType;
6161 
6162   // We need to figure out which concrete builtin this maps onto.  For example,
6163   // __sync_fetch_and_add with a 2 byte object turns into
6164   // __sync_fetch_and_add_2.
6165 #define BUILTIN_ROW(x) \
6166   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6167     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6168 
6169   static const unsigned BuiltinIndices[][5] = {
6170     BUILTIN_ROW(__sync_fetch_and_add),
6171     BUILTIN_ROW(__sync_fetch_and_sub),
6172     BUILTIN_ROW(__sync_fetch_and_or),
6173     BUILTIN_ROW(__sync_fetch_and_and),
6174     BUILTIN_ROW(__sync_fetch_and_xor),
6175     BUILTIN_ROW(__sync_fetch_and_nand),
6176 
6177     BUILTIN_ROW(__sync_add_and_fetch),
6178     BUILTIN_ROW(__sync_sub_and_fetch),
6179     BUILTIN_ROW(__sync_and_and_fetch),
6180     BUILTIN_ROW(__sync_or_and_fetch),
6181     BUILTIN_ROW(__sync_xor_and_fetch),
6182     BUILTIN_ROW(__sync_nand_and_fetch),
6183 
6184     BUILTIN_ROW(__sync_val_compare_and_swap),
6185     BUILTIN_ROW(__sync_bool_compare_and_swap),
6186     BUILTIN_ROW(__sync_lock_test_and_set),
6187     BUILTIN_ROW(__sync_lock_release),
6188     BUILTIN_ROW(__sync_swap)
6189   };
6190 #undef BUILTIN_ROW
6191 
6192   // Determine the index of the size.
6193   unsigned SizeIndex;
6194   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6195   case 1: SizeIndex = 0; break;
6196   case 2: SizeIndex = 1; break;
6197   case 4: SizeIndex = 2; break;
6198   case 8: SizeIndex = 3; break;
6199   case 16: SizeIndex = 4; break;
6200   default:
6201     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6202         << FirstArg->getType() << FirstArg->getSourceRange();
6203     return ExprError();
6204   }
6205 
6206   // Each of these builtins has one pointer argument, followed by some number of
6207   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6208   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6209   // as the number of fixed args.
6210   unsigned BuiltinID = FDecl->getBuiltinID();
6211   unsigned BuiltinIndex, NumFixed = 1;
6212   bool WarnAboutSemanticsChange = false;
6213   switch (BuiltinID) {
6214   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6215   case Builtin::BI__sync_fetch_and_add:
6216   case Builtin::BI__sync_fetch_and_add_1:
6217   case Builtin::BI__sync_fetch_and_add_2:
6218   case Builtin::BI__sync_fetch_and_add_4:
6219   case Builtin::BI__sync_fetch_and_add_8:
6220   case Builtin::BI__sync_fetch_and_add_16:
6221     BuiltinIndex = 0;
6222     break;
6223 
6224   case Builtin::BI__sync_fetch_and_sub:
6225   case Builtin::BI__sync_fetch_and_sub_1:
6226   case Builtin::BI__sync_fetch_and_sub_2:
6227   case Builtin::BI__sync_fetch_and_sub_4:
6228   case Builtin::BI__sync_fetch_and_sub_8:
6229   case Builtin::BI__sync_fetch_and_sub_16:
6230     BuiltinIndex = 1;
6231     break;
6232 
6233   case Builtin::BI__sync_fetch_and_or:
6234   case Builtin::BI__sync_fetch_and_or_1:
6235   case Builtin::BI__sync_fetch_and_or_2:
6236   case Builtin::BI__sync_fetch_and_or_4:
6237   case Builtin::BI__sync_fetch_and_or_8:
6238   case Builtin::BI__sync_fetch_and_or_16:
6239     BuiltinIndex = 2;
6240     break;
6241 
6242   case Builtin::BI__sync_fetch_and_and:
6243   case Builtin::BI__sync_fetch_and_and_1:
6244   case Builtin::BI__sync_fetch_and_and_2:
6245   case Builtin::BI__sync_fetch_and_and_4:
6246   case Builtin::BI__sync_fetch_and_and_8:
6247   case Builtin::BI__sync_fetch_and_and_16:
6248     BuiltinIndex = 3;
6249     break;
6250 
6251   case Builtin::BI__sync_fetch_and_xor:
6252   case Builtin::BI__sync_fetch_and_xor_1:
6253   case Builtin::BI__sync_fetch_and_xor_2:
6254   case Builtin::BI__sync_fetch_and_xor_4:
6255   case Builtin::BI__sync_fetch_and_xor_8:
6256   case Builtin::BI__sync_fetch_and_xor_16:
6257     BuiltinIndex = 4;
6258     break;
6259 
6260   case Builtin::BI__sync_fetch_and_nand:
6261   case Builtin::BI__sync_fetch_and_nand_1:
6262   case Builtin::BI__sync_fetch_and_nand_2:
6263   case Builtin::BI__sync_fetch_and_nand_4:
6264   case Builtin::BI__sync_fetch_and_nand_8:
6265   case Builtin::BI__sync_fetch_and_nand_16:
6266     BuiltinIndex = 5;
6267     WarnAboutSemanticsChange = true;
6268     break;
6269 
6270   case Builtin::BI__sync_add_and_fetch:
6271   case Builtin::BI__sync_add_and_fetch_1:
6272   case Builtin::BI__sync_add_and_fetch_2:
6273   case Builtin::BI__sync_add_and_fetch_4:
6274   case Builtin::BI__sync_add_and_fetch_8:
6275   case Builtin::BI__sync_add_and_fetch_16:
6276     BuiltinIndex = 6;
6277     break;
6278 
6279   case Builtin::BI__sync_sub_and_fetch:
6280   case Builtin::BI__sync_sub_and_fetch_1:
6281   case Builtin::BI__sync_sub_and_fetch_2:
6282   case Builtin::BI__sync_sub_and_fetch_4:
6283   case Builtin::BI__sync_sub_and_fetch_8:
6284   case Builtin::BI__sync_sub_and_fetch_16:
6285     BuiltinIndex = 7;
6286     break;
6287 
6288   case Builtin::BI__sync_and_and_fetch:
6289   case Builtin::BI__sync_and_and_fetch_1:
6290   case Builtin::BI__sync_and_and_fetch_2:
6291   case Builtin::BI__sync_and_and_fetch_4:
6292   case Builtin::BI__sync_and_and_fetch_8:
6293   case Builtin::BI__sync_and_and_fetch_16:
6294     BuiltinIndex = 8;
6295     break;
6296 
6297   case Builtin::BI__sync_or_and_fetch:
6298   case Builtin::BI__sync_or_and_fetch_1:
6299   case Builtin::BI__sync_or_and_fetch_2:
6300   case Builtin::BI__sync_or_and_fetch_4:
6301   case Builtin::BI__sync_or_and_fetch_8:
6302   case Builtin::BI__sync_or_and_fetch_16:
6303     BuiltinIndex = 9;
6304     break;
6305 
6306   case Builtin::BI__sync_xor_and_fetch:
6307   case Builtin::BI__sync_xor_and_fetch_1:
6308   case Builtin::BI__sync_xor_and_fetch_2:
6309   case Builtin::BI__sync_xor_and_fetch_4:
6310   case Builtin::BI__sync_xor_and_fetch_8:
6311   case Builtin::BI__sync_xor_and_fetch_16:
6312     BuiltinIndex = 10;
6313     break;
6314 
6315   case Builtin::BI__sync_nand_and_fetch:
6316   case Builtin::BI__sync_nand_and_fetch_1:
6317   case Builtin::BI__sync_nand_and_fetch_2:
6318   case Builtin::BI__sync_nand_and_fetch_4:
6319   case Builtin::BI__sync_nand_and_fetch_8:
6320   case Builtin::BI__sync_nand_and_fetch_16:
6321     BuiltinIndex = 11;
6322     WarnAboutSemanticsChange = true;
6323     break;
6324 
6325   case Builtin::BI__sync_val_compare_and_swap:
6326   case Builtin::BI__sync_val_compare_and_swap_1:
6327   case Builtin::BI__sync_val_compare_and_swap_2:
6328   case Builtin::BI__sync_val_compare_and_swap_4:
6329   case Builtin::BI__sync_val_compare_and_swap_8:
6330   case Builtin::BI__sync_val_compare_and_swap_16:
6331     BuiltinIndex = 12;
6332     NumFixed = 2;
6333     break;
6334 
6335   case Builtin::BI__sync_bool_compare_and_swap:
6336   case Builtin::BI__sync_bool_compare_and_swap_1:
6337   case Builtin::BI__sync_bool_compare_and_swap_2:
6338   case Builtin::BI__sync_bool_compare_and_swap_4:
6339   case Builtin::BI__sync_bool_compare_and_swap_8:
6340   case Builtin::BI__sync_bool_compare_and_swap_16:
6341     BuiltinIndex = 13;
6342     NumFixed = 2;
6343     ResultType = Context.BoolTy;
6344     break;
6345 
6346   case Builtin::BI__sync_lock_test_and_set:
6347   case Builtin::BI__sync_lock_test_and_set_1:
6348   case Builtin::BI__sync_lock_test_and_set_2:
6349   case Builtin::BI__sync_lock_test_and_set_4:
6350   case Builtin::BI__sync_lock_test_and_set_8:
6351   case Builtin::BI__sync_lock_test_and_set_16:
6352     BuiltinIndex = 14;
6353     break;
6354 
6355   case Builtin::BI__sync_lock_release:
6356   case Builtin::BI__sync_lock_release_1:
6357   case Builtin::BI__sync_lock_release_2:
6358   case Builtin::BI__sync_lock_release_4:
6359   case Builtin::BI__sync_lock_release_8:
6360   case Builtin::BI__sync_lock_release_16:
6361     BuiltinIndex = 15;
6362     NumFixed = 0;
6363     ResultType = Context.VoidTy;
6364     break;
6365 
6366   case Builtin::BI__sync_swap:
6367   case Builtin::BI__sync_swap_1:
6368   case Builtin::BI__sync_swap_2:
6369   case Builtin::BI__sync_swap_4:
6370   case Builtin::BI__sync_swap_8:
6371   case Builtin::BI__sync_swap_16:
6372     BuiltinIndex = 16;
6373     break;
6374   }
6375 
6376   // Now that we know how many fixed arguments we expect, first check that we
6377   // have at least that many.
6378   if (TheCall->getNumArgs() < 1+NumFixed) {
6379     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6380         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6381         << Callee->getSourceRange();
6382     return ExprError();
6383   }
6384 
6385   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6386       << Callee->getSourceRange();
6387 
6388   if (WarnAboutSemanticsChange) {
6389     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6390         << Callee->getSourceRange();
6391   }
6392 
6393   // Get the decl for the concrete builtin from this, we can tell what the
6394   // concrete integer type we should convert to is.
6395   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6396   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6397   FunctionDecl *NewBuiltinDecl;
6398   if (NewBuiltinID == BuiltinID)
6399     NewBuiltinDecl = FDecl;
6400   else {
6401     // Perform builtin lookup to avoid redeclaring it.
6402     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6403     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6404     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6405     assert(Res.getFoundDecl());
6406     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6407     if (!NewBuiltinDecl)
6408       return ExprError();
6409   }
6410 
6411   // The first argument --- the pointer --- has a fixed type; we
6412   // deduce the types of the rest of the arguments accordingly.  Walk
6413   // the remaining arguments, converting them to the deduced value type.
6414   for (unsigned i = 0; i != NumFixed; ++i) {
6415     ExprResult Arg = TheCall->getArg(i+1);
6416 
6417     // GCC does an implicit conversion to the pointer or integer ValType.  This
6418     // can fail in some cases (1i -> int**), check for this error case now.
6419     // Initialize the argument.
6420     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6421                                                    ValType, /*consume*/ false);
6422     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6423     if (Arg.isInvalid())
6424       return ExprError();
6425 
6426     // Okay, we have something that *can* be converted to the right type.  Check
6427     // to see if there is a potentially weird extension going on here.  This can
6428     // happen when you do an atomic operation on something like an char* and
6429     // pass in 42.  The 42 gets converted to char.  This is even more strange
6430     // for things like 45.123 -> char, etc.
6431     // FIXME: Do this check.
6432     TheCall->setArg(i+1, Arg.get());
6433   }
6434 
6435   // Create a new DeclRefExpr to refer to the new decl.
6436   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6437       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6438       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6439       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6440 
6441   // Set the callee in the CallExpr.
6442   // FIXME: This loses syntactic information.
6443   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6444   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6445                                               CK_BuiltinFnToFnPtr);
6446   TheCall->setCallee(PromotedCall.get());
6447 
6448   // Change the result type of the call to match the original value type. This
6449   // is arbitrary, but the codegen for these builtins ins design to handle it
6450   // gracefully.
6451   TheCall->setType(ResultType);
6452 
6453   // Prohibit problematic uses of bit-precise integer types with atomic
6454   // builtins. The arguments would have already been converted to the first
6455   // argument's type, so only need to check the first argument.
6456   const auto *BitIntValType = ValType->getAs<BitIntType>();
6457   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6458     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6459     return ExprError();
6460   }
6461 
6462   return TheCallResult;
6463 }
6464 
6465 /// SemaBuiltinNontemporalOverloaded - We have a call to
6466 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6467 /// overloaded function based on the pointer type of its last argument.
6468 ///
6469 /// This function goes through and does final semantic checking for these
6470 /// builtins.
6471 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6472   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6473   DeclRefExpr *DRE =
6474       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6475   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6476   unsigned BuiltinID = FDecl->getBuiltinID();
6477   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6478           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6479          "Unexpected nontemporal load/store builtin!");
6480   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6481   unsigned numArgs = isStore ? 2 : 1;
6482 
6483   // Ensure that we have the proper number of arguments.
6484   if (checkArgCount(*this, TheCall, numArgs))
6485     return ExprError();
6486 
6487   // Inspect the last argument of the nontemporal builtin.  This should always
6488   // be a pointer type, from which we imply the type of the memory access.
6489   // Because it is a pointer type, we don't have to worry about any implicit
6490   // casts here.
6491   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6492   ExprResult PointerArgResult =
6493       DefaultFunctionArrayLvalueConversion(PointerArg);
6494 
6495   if (PointerArgResult.isInvalid())
6496     return ExprError();
6497   PointerArg = PointerArgResult.get();
6498   TheCall->setArg(numArgs - 1, PointerArg);
6499 
6500   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6501   if (!pointerType) {
6502     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6503         << PointerArg->getType() << PointerArg->getSourceRange();
6504     return ExprError();
6505   }
6506 
6507   QualType ValType = pointerType->getPointeeType();
6508 
6509   // Strip any qualifiers off ValType.
6510   ValType = ValType.getUnqualifiedType();
6511   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6512       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6513       !ValType->isVectorType()) {
6514     Diag(DRE->getBeginLoc(),
6515          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6516         << PointerArg->getType() << PointerArg->getSourceRange();
6517     return ExprError();
6518   }
6519 
6520   if (!isStore) {
6521     TheCall->setType(ValType);
6522     return TheCallResult;
6523   }
6524 
6525   ExprResult ValArg = TheCall->getArg(0);
6526   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6527       Context, ValType, /*consume*/ false);
6528   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6529   if (ValArg.isInvalid())
6530     return ExprError();
6531 
6532   TheCall->setArg(0, ValArg.get());
6533   TheCall->setType(Context.VoidTy);
6534   return TheCallResult;
6535 }
6536 
6537 /// CheckObjCString - Checks that the argument to the builtin
6538 /// CFString constructor is correct
6539 /// Note: It might also make sense to do the UTF-16 conversion here (would
6540 /// simplify the backend).
6541 bool Sema::CheckObjCString(Expr *Arg) {
6542   Arg = Arg->IgnoreParenCasts();
6543   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6544 
6545   if (!Literal || !Literal->isAscii()) {
6546     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6547         << Arg->getSourceRange();
6548     return true;
6549   }
6550 
6551   if (Literal->containsNonAsciiOrNull()) {
6552     StringRef String = Literal->getString();
6553     unsigned NumBytes = String.size();
6554     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6555     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6556     llvm::UTF16 *ToPtr = &ToBuf[0];
6557 
6558     llvm::ConversionResult Result =
6559         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6560                                  ToPtr + NumBytes, llvm::strictConversion);
6561     // Check for conversion failure.
6562     if (Result != llvm::conversionOK)
6563       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6564           << Arg->getSourceRange();
6565   }
6566   return false;
6567 }
6568 
6569 /// CheckObjCString - Checks that the format string argument to the os_log()
6570 /// and os_trace() functions is correct, and converts it to const char *.
6571 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6572   Arg = Arg->IgnoreParenCasts();
6573   auto *Literal = dyn_cast<StringLiteral>(Arg);
6574   if (!Literal) {
6575     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6576       Literal = ObjcLiteral->getString();
6577     }
6578   }
6579 
6580   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6581     return ExprError(
6582         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6583         << Arg->getSourceRange());
6584   }
6585 
6586   ExprResult Result(Literal);
6587   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6588   InitializedEntity Entity =
6589       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6590   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6591   return Result;
6592 }
6593 
6594 /// Check that the user is calling the appropriate va_start builtin for the
6595 /// target and calling convention.
6596 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6597   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6598   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6599   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6600                     TT.getArch() == llvm::Triple::aarch64_32);
6601   bool IsWindows = TT.isOSWindows();
6602   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6603   if (IsX64 || IsAArch64) {
6604     CallingConv CC = CC_C;
6605     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6606       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6607     if (IsMSVAStart) {
6608       // Don't allow this in System V ABI functions.
6609       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6610         return S.Diag(Fn->getBeginLoc(),
6611                       diag::err_ms_va_start_used_in_sysv_function);
6612     } else {
6613       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6614       // On x64 Windows, don't allow this in System V ABI functions.
6615       // (Yes, that means there's no corresponding way to support variadic
6616       // System V ABI functions on Windows.)
6617       if ((IsWindows && CC == CC_X86_64SysV) ||
6618           (!IsWindows && CC == CC_Win64))
6619         return S.Diag(Fn->getBeginLoc(),
6620                       diag::err_va_start_used_in_wrong_abi_function)
6621                << !IsWindows;
6622     }
6623     return false;
6624   }
6625 
6626   if (IsMSVAStart)
6627     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6628   return false;
6629 }
6630 
6631 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6632                                              ParmVarDecl **LastParam = nullptr) {
6633   // Determine whether the current function, block, or obj-c method is variadic
6634   // and get its parameter list.
6635   bool IsVariadic = false;
6636   ArrayRef<ParmVarDecl *> Params;
6637   DeclContext *Caller = S.CurContext;
6638   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6639     IsVariadic = Block->isVariadic();
6640     Params = Block->parameters();
6641   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6642     IsVariadic = FD->isVariadic();
6643     Params = FD->parameters();
6644   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6645     IsVariadic = MD->isVariadic();
6646     // FIXME: This isn't correct for methods (results in bogus warning).
6647     Params = MD->parameters();
6648   } else if (isa<CapturedDecl>(Caller)) {
6649     // We don't support va_start in a CapturedDecl.
6650     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6651     return true;
6652   } else {
6653     // This must be some other declcontext that parses exprs.
6654     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6655     return true;
6656   }
6657 
6658   if (!IsVariadic) {
6659     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6660     return true;
6661   }
6662 
6663   if (LastParam)
6664     *LastParam = Params.empty() ? nullptr : Params.back();
6665 
6666   return false;
6667 }
6668 
6669 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6670 /// for validity.  Emit an error and return true on failure; return false
6671 /// on success.
6672 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6673   Expr *Fn = TheCall->getCallee();
6674 
6675   if (checkVAStartABI(*this, BuiltinID, Fn))
6676     return true;
6677 
6678   if (checkArgCount(*this, TheCall, 2))
6679     return true;
6680 
6681   // Type-check the first argument normally.
6682   if (checkBuiltinArgument(*this, TheCall, 0))
6683     return true;
6684 
6685   // Check that the current function is variadic, and get its last parameter.
6686   ParmVarDecl *LastParam;
6687   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6688     return true;
6689 
6690   // Verify that the second argument to the builtin is the last argument of the
6691   // current function or method.
6692   bool SecondArgIsLastNamedArgument = false;
6693   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6694 
6695   // These are valid if SecondArgIsLastNamedArgument is false after the next
6696   // block.
6697   QualType Type;
6698   SourceLocation ParamLoc;
6699   bool IsCRegister = false;
6700 
6701   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6702     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6703       SecondArgIsLastNamedArgument = PV == LastParam;
6704 
6705       Type = PV->getType();
6706       ParamLoc = PV->getLocation();
6707       IsCRegister =
6708           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6709     }
6710   }
6711 
6712   if (!SecondArgIsLastNamedArgument)
6713     Diag(TheCall->getArg(1)->getBeginLoc(),
6714          diag::warn_second_arg_of_va_start_not_last_named_param);
6715   else if (IsCRegister || Type->isReferenceType() ||
6716            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6717              // Promotable integers are UB, but enumerations need a bit of
6718              // extra checking to see what their promotable type actually is.
6719              if (!Type->isPromotableIntegerType())
6720                return false;
6721              if (!Type->isEnumeralType())
6722                return true;
6723              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6724              return !(ED &&
6725                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6726            }()) {
6727     unsigned Reason = 0;
6728     if (Type->isReferenceType())  Reason = 1;
6729     else if (IsCRegister)         Reason = 2;
6730     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6731     Diag(ParamLoc, diag::note_parameter_type) << Type;
6732   }
6733 
6734   TheCall->setType(Context.VoidTy);
6735   return false;
6736 }
6737 
6738 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6739   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6740     const LangOptions &LO = getLangOpts();
6741 
6742     if (LO.CPlusPlus)
6743       return Arg->getType()
6744                  .getCanonicalType()
6745                  .getTypePtr()
6746                  ->getPointeeType()
6747                  .withoutLocalFastQualifiers() == Context.CharTy;
6748 
6749     // In C, allow aliasing through `char *`, this is required for AArch64 at
6750     // least.
6751     return true;
6752   };
6753 
6754   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6755   //                 const char *named_addr);
6756 
6757   Expr *Func = Call->getCallee();
6758 
6759   if (Call->getNumArgs() < 3)
6760     return Diag(Call->getEndLoc(),
6761                 diag::err_typecheck_call_too_few_args_at_least)
6762            << 0 /*function call*/ << 3 << Call->getNumArgs();
6763 
6764   // Type-check the first argument normally.
6765   if (checkBuiltinArgument(*this, Call, 0))
6766     return true;
6767 
6768   // Check that the current function is variadic.
6769   if (checkVAStartIsInVariadicFunction(*this, Func))
6770     return true;
6771 
6772   // __va_start on Windows does not validate the parameter qualifiers
6773 
6774   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6775   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6776 
6777   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6778   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6779 
6780   const QualType &ConstCharPtrTy =
6781       Context.getPointerType(Context.CharTy.withConst());
6782   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6783     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6784         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6785         << 0                                      /* qualifier difference */
6786         << 3                                      /* parameter mismatch */
6787         << 2 << Arg1->getType() << ConstCharPtrTy;
6788 
6789   const QualType SizeTy = Context.getSizeType();
6790   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6791     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6792         << Arg2->getType() << SizeTy << 1 /* different class */
6793         << 0                              /* qualifier difference */
6794         << 3                              /* parameter mismatch */
6795         << 3 << Arg2->getType() << SizeTy;
6796 
6797   return false;
6798 }
6799 
6800 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6801 /// friends.  This is declared to take (...), so we have to check everything.
6802 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6803   if (checkArgCount(*this, TheCall, 2))
6804     return true;
6805 
6806   ExprResult OrigArg0 = TheCall->getArg(0);
6807   ExprResult OrigArg1 = TheCall->getArg(1);
6808 
6809   // Do standard promotions between the two arguments, returning their common
6810   // type.
6811   QualType Res = UsualArithmeticConversions(
6812       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6813   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6814     return true;
6815 
6816   // Make sure any conversions are pushed back into the call; this is
6817   // type safe since unordered compare builtins are declared as "_Bool
6818   // foo(...)".
6819   TheCall->setArg(0, OrigArg0.get());
6820   TheCall->setArg(1, OrigArg1.get());
6821 
6822   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6823     return false;
6824 
6825   // If the common type isn't a real floating type, then the arguments were
6826   // invalid for this operation.
6827   if (Res.isNull() || !Res->isRealFloatingType())
6828     return Diag(OrigArg0.get()->getBeginLoc(),
6829                 diag::err_typecheck_call_invalid_ordered_compare)
6830            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6831            << SourceRange(OrigArg0.get()->getBeginLoc(),
6832                           OrigArg1.get()->getEndLoc());
6833 
6834   return false;
6835 }
6836 
6837 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6838 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6839 /// to check everything. We expect the last argument to be a floating point
6840 /// value.
6841 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6842   if (checkArgCount(*this, TheCall, NumArgs))
6843     return true;
6844 
6845   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6846   // on all preceding parameters just being int.  Try all of those.
6847   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6848     Expr *Arg = TheCall->getArg(i);
6849 
6850     if (Arg->isTypeDependent())
6851       return false;
6852 
6853     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6854 
6855     if (Res.isInvalid())
6856       return true;
6857     TheCall->setArg(i, Res.get());
6858   }
6859 
6860   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6861 
6862   if (OrigArg->isTypeDependent())
6863     return false;
6864 
6865   // Usual Unary Conversions will convert half to float, which we want for
6866   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6867   // type how it is, but do normal L->Rvalue conversions.
6868   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6869     OrigArg = UsualUnaryConversions(OrigArg).get();
6870   else
6871     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6872   TheCall->setArg(NumArgs - 1, OrigArg);
6873 
6874   // This operation requires a non-_Complex floating-point number.
6875   if (!OrigArg->getType()->isRealFloatingType())
6876     return Diag(OrigArg->getBeginLoc(),
6877                 diag::err_typecheck_call_invalid_unary_fp)
6878            << OrigArg->getType() << OrigArg->getSourceRange();
6879 
6880   return false;
6881 }
6882 
6883 /// Perform semantic analysis for a call to __builtin_complex.
6884 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6885   if (checkArgCount(*this, TheCall, 2))
6886     return true;
6887 
6888   bool Dependent = false;
6889   for (unsigned I = 0; I != 2; ++I) {
6890     Expr *Arg = TheCall->getArg(I);
6891     QualType T = Arg->getType();
6892     if (T->isDependentType()) {
6893       Dependent = true;
6894       continue;
6895     }
6896 
6897     // Despite supporting _Complex int, GCC requires a real floating point type
6898     // for the operands of __builtin_complex.
6899     if (!T->isRealFloatingType()) {
6900       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6901              << Arg->getType() << Arg->getSourceRange();
6902     }
6903 
6904     ExprResult Converted = DefaultLvalueConversion(Arg);
6905     if (Converted.isInvalid())
6906       return true;
6907     TheCall->setArg(I, Converted.get());
6908   }
6909 
6910   if (Dependent) {
6911     TheCall->setType(Context.DependentTy);
6912     return false;
6913   }
6914 
6915   Expr *Real = TheCall->getArg(0);
6916   Expr *Imag = TheCall->getArg(1);
6917   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6918     return Diag(Real->getBeginLoc(),
6919                 diag::err_typecheck_call_different_arg_types)
6920            << Real->getType() << Imag->getType()
6921            << Real->getSourceRange() << Imag->getSourceRange();
6922   }
6923 
6924   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6925   // don't allow this builtin to form those types either.
6926   // FIXME: Should we allow these types?
6927   if (Real->getType()->isFloat16Type())
6928     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6929            << "_Float16";
6930   if (Real->getType()->isHalfType())
6931     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6932            << "half";
6933 
6934   TheCall->setType(Context.getComplexType(Real->getType()));
6935   return false;
6936 }
6937 
6938 // Customized Sema Checking for VSX builtins that have the following signature:
6939 // vector [...] builtinName(vector [...], vector [...], const int);
6940 // Which takes the same type of vectors (any legal vector type) for the first
6941 // two arguments and takes compile time constant for the third argument.
6942 // Example builtins are :
6943 // vector double vec_xxpermdi(vector double, vector double, int);
6944 // vector short vec_xxsldwi(vector short, vector short, int);
6945 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6946   unsigned ExpectedNumArgs = 3;
6947   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6948     return true;
6949 
6950   // Check the third argument is a compile time constant
6951   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6952     return Diag(TheCall->getBeginLoc(),
6953                 diag::err_vsx_builtin_nonconstant_argument)
6954            << 3 /* argument index */ << TheCall->getDirectCallee()
6955            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6956                           TheCall->getArg(2)->getEndLoc());
6957 
6958   QualType Arg1Ty = TheCall->getArg(0)->getType();
6959   QualType Arg2Ty = TheCall->getArg(1)->getType();
6960 
6961   // Check the type of argument 1 and argument 2 are vectors.
6962   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6963   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6964       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6965     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6966            << TheCall->getDirectCallee()
6967            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6968                           TheCall->getArg(1)->getEndLoc());
6969   }
6970 
6971   // Check the first two arguments are the same type.
6972   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6973     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6974            << TheCall->getDirectCallee()
6975            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6976                           TheCall->getArg(1)->getEndLoc());
6977   }
6978 
6979   // When default clang type checking is turned off and the customized type
6980   // checking is used, the returning type of the function must be explicitly
6981   // set. Otherwise it is _Bool by default.
6982   TheCall->setType(Arg1Ty);
6983 
6984   return false;
6985 }
6986 
6987 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6988 // This is declared to take (...), so we have to check everything.
6989 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6990   if (TheCall->getNumArgs() < 2)
6991     return ExprError(Diag(TheCall->getEndLoc(),
6992                           diag::err_typecheck_call_too_few_args_at_least)
6993                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6994                      << TheCall->getSourceRange());
6995 
6996   // Determine which of the following types of shufflevector we're checking:
6997   // 1) unary, vector mask: (lhs, mask)
6998   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6999   QualType resType = TheCall->getArg(0)->getType();
7000   unsigned numElements = 0;
7001 
7002   if (!TheCall->getArg(0)->isTypeDependent() &&
7003       !TheCall->getArg(1)->isTypeDependent()) {
7004     QualType LHSType = TheCall->getArg(0)->getType();
7005     QualType RHSType = TheCall->getArg(1)->getType();
7006 
7007     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7008       return ExprError(
7009           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7010           << TheCall->getDirectCallee()
7011           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7012                          TheCall->getArg(1)->getEndLoc()));
7013 
7014     numElements = LHSType->castAs<VectorType>()->getNumElements();
7015     unsigned numResElements = TheCall->getNumArgs() - 2;
7016 
7017     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7018     // with mask.  If so, verify that RHS is an integer vector type with the
7019     // same number of elts as lhs.
7020     if (TheCall->getNumArgs() == 2) {
7021       if (!RHSType->hasIntegerRepresentation() ||
7022           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7023         return ExprError(Diag(TheCall->getBeginLoc(),
7024                               diag::err_vec_builtin_incompatible_vector)
7025                          << TheCall->getDirectCallee()
7026                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7027                                         TheCall->getArg(1)->getEndLoc()));
7028     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7029       return ExprError(Diag(TheCall->getBeginLoc(),
7030                             diag::err_vec_builtin_incompatible_vector)
7031                        << TheCall->getDirectCallee()
7032                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7033                                       TheCall->getArg(1)->getEndLoc()));
7034     } else if (numElements != numResElements) {
7035       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7036       resType = Context.getVectorType(eltType, numResElements,
7037                                       VectorType::GenericVector);
7038     }
7039   }
7040 
7041   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7042     if (TheCall->getArg(i)->isTypeDependent() ||
7043         TheCall->getArg(i)->isValueDependent())
7044       continue;
7045 
7046     Optional<llvm::APSInt> Result;
7047     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7048       return ExprError(Diag(TheCall->getBeginLoc(),
7049                             diag::err_shufflevector_nonconstant_argument)
7050                        << TheCall->getArg(i)->getSourceRange());
7051 
7052     // Allow -1 which will be translated to undef in the IR.
7053     if (Result->isSigned() && Result->isAllOnes())
7054       continue;
7055 
7056     if (Result->getActiveBits() > 64 ||
7057         Result->getZExtValue() >= numElements * 2)
7058       return ExprError(Diag(TheCall->getBeginLoc(),
7059                             diag::err_shufflevector_argument_too_large)
7060                        << TheCall->getArg(i)->getSourceRange());
7061   }
7062 
7063   SmallVector<Expr*, 32> exprs;
7064 
7065   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7066     exprs.push_back(TheCall->getArg(i));
7067     TheCall->setArg(i, nullptr);
7068   }
7069 
7070   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7071                                          TheCall->getCallee()->getBeginLoc(),
7072                                          TheCall->getRParenLoc());
7073 }
7074 
7075 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7076 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7077                                        SourceLocation BuiltinLoc,
7078                                        SourceLocation RParenLoc) {
7079   ExprValueKind VK = VK_PRValue;
7080   ExprObjectKind OK = OK_Ordinary;
7081   QualType DstTy = TInfo->getType();
7082   QualType SrcTy = E->getType();
7083 
7084   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7085     return ExprError(Diag(BuiltinLoc,
7086                           diag::err_convertvector_non_vector)
7087                      << E->getSourceRange());
7088   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7089     return ExprError(Diag(BuiltinLoc,
7090                           diag::err_convertvector_non_vector_type));
7091 
7092   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7093     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7094     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7095     if (SrcElts != DstElts)
7096       return ExprError(Diag(BuiltinLoc,
7097                             diag::err_convertvector_incompatible_vector)
7098                        << E->getSourceRange());
7099   }
7100 
7101   return new (Context)
7102       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7103 }
7104 
7105 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7106 // This is declared to take (const void*, ...) and can take two
7107 // optional constant int args.
7108 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7109   unsigned NumArgs = TheCall->getNumArgs();
7110 
7111   if (NumArgs > 3)
7112     return Diag(TheCall->getEndLoc(),
7113                 diag::err_typecheck_call_too_many_args_at_most)
7114            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7115 
7116   // Argument 0 is checked for us and the remaining arguments must be
7117   // constant integers.
7118   for (unsigned i = 1; i != NumArgs; ++i)
7119     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7120       return true;
7121 
7122   return false;
7123 }
7124 
7125 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7126 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7127   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7128     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7129            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7130   if (checkArgCount(*this, TheCall, 1))
7131     return true;
7132   Expr *Arg = TheCall->getArg(0);
7133   if (Arg->isInstantiationDependent())
7134     return false;
7135 
7136   QualType ArgTy = Arg->getType();
7137   if (!ArgTy->hasFloatingRepresentation())
7138     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7139            << ArgTy;
7140   if (Arg->isLValue()) {
7141     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7142     TheCall->setArg(0, FirstArg.get());
7143   }
7144   TheCall->setType(TheCall->getArg(0)->getType());
7145   return false;
7146 }
7147 
7148 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7149 // __assume does not evaluate its arguments, and should warn if its argument
7150 // has side effects.
7151 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7152   Expr *Arg = TheCall->getArg(0);
7153   if (Arg->isInstantiationDependent()) return false;
7154 
7155   if (Arg->HasSideEffects(Context))
7156     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7157         << Arg->getSourceRange()
7158         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7159 
7160   return false;
7161 }
7162 
7163 /// Handle __builtin_alloca_with_align. This is declared
7164 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7165 /// than 8.
7166 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7167   // The alignment must be a constant integer.
7168   Expr *Arg = TheCall->getArg(1);
7169 
7170   // We can't check the value of a dependent argument.
7171   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7172     if (const auto *UE =
7173             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7174       if (UE->getKind() == UETT_AlignOf ||
7175           UE->getKind() == UETT_PreferredAlignOf)
7176         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7177             << Arg->getSourceRange();
7178 
7179     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7180 
7181     if (!Result.isPowerOf2())
7182       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7183              << Arg->getSourceRange();
7184 
7185     if (Result < Context.getCharWidth())
7186       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7187              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7188 
7189     if (Result > std::numeric_limits<int32_t>::max())
7190       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7191              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7192   }
7193 
7194   return false;
7195 }
7196 
7197 /// Handle __builtin_assume_aligned. This is declared
7198 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7199 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7200   unsigned NumArgs = TheCall->getNumArgs();
7201 
7202   if (NumArgs > 3)
7203     return Diag(TheCall->getEndLoc(),
7204                 diag::err_typecheck_call_too_many_args_at_most)
7205            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7206 
7207   // The alignment must be a constant integer.
7208   Expr *Arg = TheCall->getArg(1);
7209 
7210   // We can't check the value of a dependent argument.
7211   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7212     llvm::APSInt Result;
7213     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7214       return true;
7215 
7216     if (!Result.isPowerOf2())
7217       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7218              << Arg->getSourceRange();
7219 
7220     if (Result > Sema::MaximumAlignment)
7221       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7222           << Arg->getSourceRange() << Sema::MaximumAlignment;
7223   }
7224 
7225   if (NumArgs > 2) {
7226     ExprResult Arg(TheCall->getArg(2));
7227     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7228       Context.getSizeType(), false);
7229     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7230     if (Arg.isInvalid()) return true;
7231     TheCall->setArg(2, Arg.get());
7232   }
7233 
7234   return false;
7235 }
7236 
7237 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7238   unsigned BuiltinID =
7239       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7240   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7241 
7242   unsigned NumArgs = TheCall->getNumArgs();
7243   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7244   if (NumArgs < NumRequiredArgs) {
7245     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7246            << 0 /* function call */ << NumRequiredArgs << NumArgs
7247            << TheCall->getSourceRange();
7248   }
7249   if (NumArgs >= NumRequiredArgs + 0x100) {
7250     return Diag(TheCall->getEndLoc(),
7251                 diag::err_typecheck_call_too_many_args_at_most)
7252            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7253            << TheCall->getSourceRange();
7254   }
7255   unsigned i = 0;
7256 
7257   // For formatting call, check buffer arg.
7258   if (!IsSizeCall) {
7259     ExprResult Arg(TheCall->getArg(i));
7260     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7261         Context, Context.VoidPtrTy, false);
7262     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7263     if (Arg.isInvalid())
7264       return true;
7265     TheCall->setArg(i, Arg.get());
7266     i++;
7267   }
7268 
7269   // Check string literal arg.
7270   unsigned FormatIdx = i;
7271   {
7272     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7273     if (Arg.isInvalid())
7274       return true;
7275     TheCall->setArg(i, Arg.get());
7276     i++;
7277   }
7278 
7279   // Make sure variadic args are scalar.
7280   unsigned FirstDataArg = i;
7281   while (i < NumArgs) {
7282     ExprResult Arg = DefaultVariadicArgumentPromotion(
7283         TheCall->getArg(i), VariadicFunction, nullptr);
7284     if (Arg.isInvalid())
7285       return true;
7286     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7287     if (ArgSize.getQuantity() >= 0x100) {
7288       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7289              << i << (int)ArgSize.getQuantity() << 0xff
7290              << TheCall->getSourceRange();
7291     }
7292     TheCall->setArg(i, Arg.get());
7293     i++;
7294   }
7295 
7296   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7297   // call to avoid duplicate diagnostics.
7298   if (!IsSizeCall) {
7299     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7300     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7301     bool Success = CheckFormatArguments(
7302         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7303         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7304         CheckedVarArgs);
7305     if (!Success)
7306       return true;
7307   }
7308 
7309   if (IsSizeCall) {
7310     TheCall->setType(Context.getSizeType());
7311   } else {
7312     TheCall->setType(Context.VoidPtrTy);
7313   }
7314   return false;
7315 }
7316 
7317 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7318 /// TheCall is a constant expression.
7319 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7320                                   llvm::APSInt &Result) {
7321   Expr *Arg = TheCall->getArg(ArgNum);
7322   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7323   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7324 
7325   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7326 
7327   Optional<llvm::APSInt> R;
7328   if (!(R = Arg->getIntegerConstantExpr(Context)))
7329     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7330            << FDecl->getDeclName() << Arg->getSourceRange();
7331   Result = *R;
7332   return false;
7333 }
7334 
7335 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7336 /// TheCall is a constant expression in the range [Low, High].
7337 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7338                                        int Low, int High, bool RangeIsError) {
7339   if (isConstantEvaluated())
7340     return false;
7341   llvm::APSInt Result;
7342 
7343   // We can't check the value of a dependent argument.
7344   Expr *Arg = TheCall->getArg(ArgNum);
7345   if (Arg->isTypeDependent() || Arg->isValueDependent())
7346     return false;
7347 
7348   // Check constant-ness first.
7349   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7350     return true;
7351 
7352   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7353     if (RangeIsError)
7354       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7355              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7356     else
7357       // Defer the warning until we know if the code will be emitted so that
7358       // dead code can ignore this.
7359       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7360                           PDiag(diag::warn_argument_invalid_range)
7361                               << toString(Result, 10) << Low << High
7362                               << Arg->getSourceRange());
7363   }
7364 
7365   return false;
7366 }
7367 
7368 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7369 /// TheCall is a constant expression is a multiple of Num..
7370 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7371                                           unsigned Num) {
7372   llvm::APSInt Result;
7373 
7374   // We can't check the value of a dependent argument.
7375   Expr *Arg = TheCall->getArg(ArgNum);
7376   if (Arg->isTypeDependent() || Arg->isValueDependent())
7377     return false;
7378 
7379   // Check constant-ness first.
7380   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7381     return true;
7382 
7383   if (Result.getSExtValue() % Num != 0)
7384     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7385            << Num << Arg->getSourceRange();
7386 
7387   return false;
7388 }
7389 
7390 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7391 /// constant expression representing a power of 2.
7392 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7393   llvm::APSInt Result;
7394 
7395   // We can't check the value of a dependent argument.
7396   Expr *Arg = TheCall->getArg(ArgNum);
7397   if (Arg->isTypeDependent() || Arg->isValueDependent())
7398     return false;
7399 
7400   // Check constant-ness first.
7401   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7402     return true;
7403 
7404   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7405   // and only if x is a power of 2.
7406   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7407     return false;
7408 
7409   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7410          << Arg->getSourceRange();
7411 }
7412 
7413 static bool IsShiftedByte(llvm::APSInt Value) {
7414   if (Value.isNegative())
7415     return false;
7416 
7417   // Check if it's a shifted byte, by shifting it down
7418   while (true) {
7419     // If the value fits in the bottom byte, the check passes.
7420     if (Value < 0x100)
7421       return true;
7422 
7423     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7424     // fails.
7425     if ((Value & 0xFF) != 0)
7426       return false;
7427 
7428     // If the bottom 8 bits are all 0, but something above that is nonzero,
7429     // then shifting the value right by 8 bits won't affect whether it's a
7430     // shifted byte or not. So do that, and go round again.
7431     Value >>= 8;
7432   }
7433 }
7434 
7435 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7436 /// a constant expression representing an arbitrary byte value shifted left by
7437 /// a multiple of 8 bits.
7438 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7439                                              unsigned ArgBits) {
7440   llvm::APSInt Result;
7441 
7442   // We can't check the value of a dependent argument.
7443   Expr *Arg = TheCall->getArg(ArgNum);
7444   if (Arg->isTypeDependent() || Arg->isValueDependent())
7445     return false;
7446 
7447   // Check constant-ness first.
7448   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7449     return true;
7450 
7451   // Truncate to the given size.
7452   Result = Result.getLoBits(ArgBits);
7453   Result.setIsUnsigned(true);
7454 
7455   if (IsShiftedByte(Result))
7456     return false;
7457 
7458   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7459          << Arg->getSourceRange();
7460 }
7461 
7462 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7463 /// TheCall is a constant expression representing either a shifted byte value,
7464 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7465 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7466 /// Arm MVE intrinsics.
7467 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7468                                                    int ArgNum,
7469                                                    unsigned ArgBits) {
7470   llvm::APSInt Result;
7471 
7472   // We can't check the value of a dependent argument.
7473   Expr *Arg = TheCall->getArg(ArgNum);
7474   if (Arg->isTypeDependent() || Arg->isValueDependent())
7475     return false;
7476 
7477   // Check constant-ness first.
7478   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7479     return true;
7480 
7481   // Truncate to the given size.
7482   Result = Result.getLoBits(ArgBits);
7483   Result.setIsUnsigned(true);
7484 
7485   // Check to see if it's in either of the required forms.
7486   if (IsShiftedByte(Result) ||
7487       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7488     return false;
7489 
7490   return Diag(TheCall->getBeginLoc(),
7491               diag::err_argument_not_shifted_byte_or_xxff)
7492          << Arg->getSourceRange();
7493 }
7494 
7495 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7496 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7497   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7498     if (checkArgCount(*this, TheCall, 2))
7499       return true;
7500     Expr *Arg0 = TheCall->getArg(0);
7501     Expr *Arg1 = TheCall->getArg(1);
7502 
7503     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7504     if (FirstArg.isInvalid())
7505       return true;
7506     QualType FirstArgType = FirstArg.get()->getType();
7507     if (!FirstArgType->isAnyPointerType())
7508       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7509                << "first" << FirstArgType << Arg0->getSourceRange();
7510     TheCall->setArg(0, FirstArg.get());
7511 
7512     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7513     if (SecArg.isInvalid())
7514       return true;
7515     QualType SecArgType = SecArg.get()->getType();
7516     if (!SecArgType->isIntegerType())
7517       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7518                << "second" << SecArgType << Arg1->getSourceRange();
7519 
7520     // Derive the return type from the pointer argument.
7521     TheCall->setType(FirstArgType);
7522     return false;
7523   }
7524 
7525   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7526     if (checkArgCount(*this, TheCall, 2))
7527       return true;
7528 
7529     Expr *Arg0 = TheCall->getArg(0);
7530     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7531     if (FirstArg.isInvalid())
7532       return true;
7533     QualType FirstArgType = FirstArg.get()->getType();
7534     if (!FirstArgType->isAnyPointerType())
7535       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7536                << "first" << FirstArgType << Arg0->getSourceRange();
7537     TheCall->setArg(0, FirstArg.get());
7538 
7539     // Derive the return type from the pointer argument.
7540     TheCall->setType(FirstArgType);
7541 
7542     // Second arg must be an constant in range [0,15]
7543     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7544   }
7545 
7546   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7547     if (checkArgCount(*this, TheCall, 2))
7548       return true;
7549     Expr *Arg0 = TheCall->getArg(0);
7550     Expr *Arg1 = TheCall->getArg(1);
7551 
7552     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7553     if (FirstArg.isInvalid())
7554       return true;
7555     QualType FirstArgType = FirstArg.get()->getType();
7556     if (!FirstArgType->isAnyPointerType())
7557       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7558                << "first" << FirstArgType << Arg0->getSourceRange();
7559 
7560     QualType SecArgType = Arg1->getType();
7561     if (!SecArgType->isIntegerType())
7562       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7563                << "second" << SecArgType << Arg1->getSourceRange();
7564     TheCall->setType(Context.IntTy);
7565     return false;
7566   }
7567 
7568   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7569       BuiltinID == AArch64::BI__builtin_arm_stg) {
7570     if (checkArgCount(*this, TheCall, 1))
7571       return true;
7572     Expr *Arg0 = TheCall->getArg(0);
7573     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7574     if (FirstArg.isInvalid())
7575       return true;
7576 
7577     QualType FirstArgType = FirstArg.get()->getType();
7578     if (!FirstArgType->isAnyPointerType())
7579       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7580                << "first" << FirstArgType << Arg0->getSourceRange();
7581     TheCall->setArg(0, FirstArg.get());
7582 
7583     // Derive the return type from the pointer argument.
7584     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7585       TheCall->setType(FirstArgType);
7586     return false;
7587   }
7588 
7589   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7590     Expr *ArgA = TheCall->getArg(0);
7591     Expr *ArgB = TheCall->getArg(1);
7592 
7593     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7594     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7595 
7596     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7597       return true;
7598 
7599     QualType ArgTypeA = ArgExprA.get()->getType();
7600     QualType ArgTypeB = ArgExprB.get()->getType();
7601 
7602     auto isNull = [&] (Expr *E) -> bool {
7603       return E->isNullPointerConstant(
7604                         Context, Expr::NPC_ValueDependentIsNotNull); };
7605 
7606     // argument should be either a pointer or null
7607     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7608       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7609         << "first" << ArgTypeA << ArgA->getSourceRange();
7610 
7611     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7612       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7613         << "second" << ArgTypeB << ArgB->getSourceRange();
7614 
7615     // Ensure Pointee types are compatible
7616     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7617         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7618       QualType pointeeA = ArgTypeA->getPointeeType();
7619       QualType pointeeB = ArgTypeB->getPointeeType();
7620       if (!Context.typesAreCompatible(
7621              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7622              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7623         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7624           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7625           << ArgB->getSourceRange();
7626       }
7627     }
7628 
7629     // at least one argument should be pointer type
7630     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7631       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7632         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7633 
7634     if (isNull(ArgA)) // adopt type of the other pointer
7635       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7636 
7637     if (isNull(ArgB))
7638       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7639 
7640     TheCall->setArg(0, ArgExprA.get());
7641     TheCall->setArg(1, ArgExprB.get());
7642     TheCall->setType(Context.LongLongTy);
7643     return false;
7644   }
7645   assert(false && "Unhandled ARM MTE intrinsic");
7646   return true;
7647 }
7648 
7649 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7650 /// TheCall is an ARM/AArch64 special register string literal.
7651 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7652                                     int ArgNum, unsigned ExpectedFieldNum,
7653                                     bool AllowName) {
7654   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7655                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7656                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7657                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7658                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7659                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7660   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7661                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7662                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7663                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7664                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7665                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7666   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7667 
7668   // We can't check the value of a dependent argument.
7669   Expr *Arg = TheCall->getArg(ArgNum);
7670   if (Arg->isTypeDependent() || Arg->isValueDependent())
7671     return false;
7672 
7673   // Check if the argument is a string literal.
7674   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7675     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7676            << Arg->getSourceRange();
7677 
7678   // Check the type of special register given.
7679   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7680   SmallVector<StringRef, 6> Fields;
7681   Reg.split(Fields, ":");
7682 
7683   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7684     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7685            << Arg->getSourceRange();
7686 
7687   // If the string is the name of a register then we cannot check that it is
7688   // valid here but if the string is of one the forms described in ACLE then we
7689   // can check that the supplied fields are integers and within the valid
7690   // ranges.
7691   if (Fields.size() > 1) {
7692     bool FiveFields = Fields.size() == 5;
7693 
7694     bool ValidString = true;
7695     if (IsARMBuiltin) {
7696       ValidString &= Fields[0].startswith_insensitive("cp") ||
7697                      Fields[0].startswith_insensitive("p");
7698       if (ValidString)
7699         Fields[0] = Fields[0].drop_front(
7700             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7701 
7702       ValidString &= Fields[2].startswith_insensitive("c");
7703       if (ValidString)
7704         Fields[2] = Fields[2].drop_front(1);
7705 
7706       if (FiveFields) {
7707         ValidString &= Fields[3].startswith_insensitive("c");
7708         if (ValidString)
7709           Fields[3] = Fields[3].drop_front(1);
7710       }
7711     }
7712 
7713     SmallVector<int, 5> Ranges;
7714     if (FiveFields)
7715       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7716     else
7717       Ranges.append({15, 7, 15});
7718 
7719     for (unsigned i=0; i<Fields.size(); ++i) {
7720       int IntField;
7721       ValidString &= !Fields[i].getAsInteger(10, IntField);
7722       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7723     }
7724 
7725     if (!ValidString)
7726       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7727              << Arg->getSourceRange();
7728   } else if (IsAArch64Builtin && Fields.size() == 1) {
7729     // If the register name is one of those that appear in the condition below
7730     // and the special register builtin being used is one of the write builtins,
7731     // then we require that the argument provided for writing to the register
7732     // is an integer constant expression. This is because it will be lowered to
7733     // an MSR (immediate) instruction, so we need to know the immediate at
7734     // compile time.
7735     if (TheCall->getNumArgs() != 2)
7736       return false;
7737 
7738     std::string RegLower = Reg.lower();
7739     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7740         RegLower != "pan" && RegLower != "uao")
7741       return false;
7742 
7743     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7744   }
7745 
7746   return false;
7747 }
7748 
7749 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7750 /// Emit an error and return true on failure; return false on success.
7751 /// TypeStr is a string containing the type descriptor of the value returned by
7752 /// the builtin and the descriptors of the expected type of the arguments.
7753 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7754                                  const char *TypeStr) {
7755 
7756   assert((TypeStr[0] != '\0') &&
7757          "Invalid types in PPC MMA builtin declaration");
7758 
7759   switch (BuiltinID) {
7760   default:
7761     // This function is called in CheckPPCBuiltinFunctionCall where the
7762     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7763     // we are isolating the pair vector memop builtins that can be used with mma
7764     // off so the default case is every builtin that requires mma and paired
7765     // vector memops.
7766     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7767                          diag::err_ppc_builtin_only_on_arch, "10") ||
7768         SemaFeatureCheck(*this, TheCall, "mma",
7769                          diag::err_ppc_builtin_only_on_arch, "10"))
7770       return true;
7771     break;
7772   case PPC::BI__builtin_vsx_lxvp:
7773   case PPC::BI__builtin_vsx_stxvp:
7774   case PPC::BI__builtin_vsx_assemble_pair:
7775   case PPC::BI__builtin_vsx_disassemble_pair:
7776     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7777                          diag::err_ppc_builtin_only_on_arch, "10"))
7778       return true;
7779     break;
7780   }
7781 
7782   unsigned Mask = 0;
7783   unsigned ArgNum = 0;
7784 
7785   // The first type in TypeStr is the type of the value returned by the
7786   // builtin. So we first read that type and change the type of TheCall.
7787   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7788   TheCall->setType(type);
7789 
7790   while (*TypeStr != '\0') {
7791     Mask = 0;
7792     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7793     if (ArgNum >= TheCall->getNumArgs()) {
7794       ArgNum++;
7795       break;
7796     }
7797 
7798     Expr *Arg = TheCall->getArg(ArgNum);
7799     QualType PassedType = Arg->getType();
7800     QualType StrippedRVType = PassedType.getCanonicalType();
7801 
7802     // Strip Restrict/Volatile qualifiers.
7803     if (StrippedRVType.isRestrictQualified() ||
7804         StrippedRVType.isVolatileQualified())
7805       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7806 
7807     // The only case where the argument type and expected type are allowed to
7808     // mismatch is if the argument type is a non-void pointer (or array) and
7809     // expected type is a void pointer.
7810     if (StrippedRVType != ExpectedType)
7811       if (!(ExpectedType->isVoidPointerType() &&
7812             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7813         return Diag(Arg->getBeginLoc(),
7814                     diag::err_typecheck_convert_incompatible)
7815                << PassedType << ExpectedType << 1 << 0 << 0;
7816 
7817     // If the value of the Mask is not 0, we have a constraint in the size of
7818     // the integer argument so here we ensure the argument is a constant that
7819     // is in the valid range.
7820     if (Mask != 0 &&
7821         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7822       return true;
7823 
7824     ArgNum++;
7825   }
7826 
7827   // In case we exited early from the previous loop, there are other types to
7828   // read from TypeStr. So we need to read them all to ensure we have the right
7829   // number of arguments in TheCall and if it is not the case, to display a
7830   // better error message.
7831   while (*TypeStr != '\0') {
7832     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7833     ArgNum++;
7834   }
7835   if (checkArgCount(*this, TheCall, ArgNum))
7836     return true;
7837 
7838   return false;
7839 }
7840 
7841 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7842 /// This checks that the target supports __builtin_longjmp and
7843 /// that val is a constant 1.
7844 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7845   if (!Context.getTargetInfo().hasSjLjLowering())
7846     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7847            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7848 
7849   Expr *Arg = TheCall->getArg(1);
7850   llvm::APSInt Result;
7851 
7852   // TODO: This is less than ideal. Overload this to take a value.
7853   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7854     return true;
7855 
7856   if (Result != 1)
7857     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7858            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7859 
7860   return false;
7861 }
7862 
7863 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7864 /// This checks that the target supports __builtin_setjmp.
7865 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7866   if (!Context.getTargetInfo().hasSjLjLowering())
7867     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7868            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7869   return false;
7870 }
7871 
7872 namespace {
7873 
7874 class UncoveredArgHandler {
7875   enum { Unknown = -1, AllCovered = -2 };
7876 
7877   signed FirstUncoveredArg = Unknown;
7878   SmallVector<const Expr *, 4> DiagnosticExprs;
7879 
7880 public:
7881   UncoveredArgHandler() = default;
7882 
7883   bool hasUncoveredArg() const {
7884     return (FirstUncoveredArg >= 0);
7885   }
7886 
7887   unsigned getUncoveredArg() const {
7888     assert(hasUncoveredArg() && "no uncovered argument");
7889     return FirstUncoveredArg;
7890   }
7891 
7892   void setAllCovered() {
7893     // A string has been found with all arguments covered, so clear out
7894     // the diagnostics.
7895     DiagnosticExprs.clear();
7896     FirstUncoveredArg = AllCovered;
7897   }
7898 
7899   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7900     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7901 
7902     // Don't update if a previous string covers all arguments.
7903     if (FirstUncoveredArg == AllCovered)
7904       return;
7905 
7906     // UncoveredArgHandler tracks the highest uncovered argument index
7907     // and with it all the strings that match this index.
7908     if (NewFirstUncoveredArg == FirstUncoveredArg)
7909       DiagnosticExprs.push_back(StrExpr);
7910     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7911       DiagnosticExprs.clear();
7912       DiagnosticExprs.push_back(StrExpr);
7913       FirstUncoveredArg = NewFirstUncoveredArg;
7914     }
7915   }
7916 
7917   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7918 };
7919 
7920 enum StringLiteralCheckType {
7921   SLCT_NotALiteral,
7922   SLCT_UncheckedLiteral,
7923   SLCT_CheckedLiteral
7924 };
7925 
7926 } // namespace
7927 
7928 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7929                                      BinaryOperatorKind BinOpKind,
7930                                      bool AddendIsRight) {
7931   unsigned BitWidth = Offset.getBitWidth();
7932   unsigned AddendBitWidth = Addend.getBitWidth();
7933   // There might be negative interim results.
7934   if (Addend.isUnsigned()) {
7935     Addend = Addend.zext(++AddendBitWidth);
7936     Addend.setIsSigned(true);
7937   }
7938   // Adjust the bit width of the APSInts.
7939   if (AddendBitWidth > BitWidth) {
7940     Offset = Offset.sext(AddendBitWidth);
7941     BitWidth = AddendBitWidth;
7942   } else if (BitWidth > AddendBitWidth) {
7943     Addend = Addend.sext(BitWidth);
7944   }
7945 
7946   bool Ov = false;
7947   llvm::APSInt ResOffset = Offset;
7948   if (BinOpKind == BO_Add)
7949     ResOffset = Offset.sadd_ov(Addend, Ov);
7950   else {
7951     assert(AddendIsRight && BinOpKind == BO_Sub &&
7952            "operator must be add or sub with addend on the right");
7953     ResOffset = Offset.ssub_ov(Addend, Ov);
7954   }
7955 
7956   // We add an offset to a pointer here so we should support an offset as big as
7957   // possible.
7958   if (Ov) {
7959     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7960            "index (intermediate) result too big");
7961     Offset = Offset.sext(2 * BitWidth);
7962     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7963     return;
7964   }
7965 
7966   Offset = ResOffset;
7967 }
7968 
7969 namespace {
7970 
7971 // This is a wrapper class around StringLiteral to support offsetted string
7972 // literals as format strings. It takes the offset into account when returning
7973 // the string and its length or the source locations to display notes correctly.
7974 class FormatStringLiteral {
7975   const StringLiteral *FExpr;
7976   int64_t Offset;
7977 
7978  public:
7979   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7980       : FExpr(fexpr), Offset(Offset) {}
7981 
7982   StringRef getString() const {
7983     return FExpr->getString().drop_front(Offset);
7984   }
7985 
7986   unsigned getByteLength() const {
7987     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7988   }
7989 
7990   unsigned getLength() const { return FExpr->getLength() - Offset; }
7991   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7992 
7993   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7994 
7995   QualType getType() const { return FExpr->getType(); }
7996 
7997   bool isAscii() const { return FExpr->isAscii(); }
7998   bool isWide() const { return FExpr->isWide(); }
7999   bool isUTF8() const { return FExpr->isUTF8(); }
8000   bool isUTF16() const { return FExpr->isUTF16(); }
8001   bool isUTF32() const { return FExpr->isUTF32(); }
8002   bool isPascal() const { return FExpr->isPascal(); }
8003 
8004   SourceLocation getLocationOfByte(
8005       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8006       const TargetInfo &Target, unsigned *StartToken = nullptr,
8007       unsigned *StartTokenByteOffset = nullptr) const {
8008     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8009                                     StartToken, StartTokenByteOffset);
8010   }
8011 
8012   SourceLocation getBeginLoc() const LLVM_READONLY {
8013     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8014   }
8015 
8016   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8017 };
8018 
8019 }  // namespace
8020 
8021 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8022                               const Expr *OrigFormatExpr,
8023                               ArrayRef<const Expr *> Args,
8024                               bool HasVAListArg, unsigned format_idx,
8025                               unsigned firstDataArg,
8026                               Sema::FormatStringType Type,
8027                               bool inFunctionCall,
8028                               Sema::VariadicCallType CallType,
8029                               llvm::SmallBitVector &CheckedVarArgs,
8030                               UncoveredArgHandler &UncoveredArg,
8031                               bool IgnoreStringsWithoutSpecifiers);
8032 
8033 // Determine if an expression is a string literal or constant string.
8034 // If this function returns false on the arguments to a function expecting a
8035 // format string, we will usually need to emit a warning.
8036 // True string literals are then checked by CheckFormatString.
8037 static StringLiteralCheckType
8038 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8039                       bool HasVAListArg, unsigned format_idx,
8040                       unsigned firstDataArg, Sema::FormatStringType Type,
8041                       Sema::VariadicCallType CallType, bool InFunctionCall,
8042                       llvm::SmallBitVector &CheckedVarArgs,
8043                       UncoveredArgHandler &UncoveredArg,
8044                       llvm::APSInt Offset,
8045                       bool IgnoreStringsWithoutSpecifiers = false) {
8046   if (S.isConstantEvaluated())
8047     return SLCT_NotALiteral;
8048  tryAgain:
8049   assert(Offset.isSigned() && "invalid offset");
8050 
8051   if (E->isTypeDependent() || E->isValueDependent())
8052     return SLCT_NotALiteral;
8053 
8054   E = E->IgnoreParenCasts();
8055 
8056   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8057     // Technically -Wformat-nonliteral does not warn about this case.
8058     // The behavior of printf and friends in this case is implementation
8059     // dependent.  Ideally if the format string cannot be null then
8060     // it should have a 'nonnull' attribute in the function prototype.
8061     return SLCT_UncheckedLiteral;
8062 
8063   switch (E->getStmtClass()) {
8064   case Stmt::BinaryConditionalOperatorClass:
8065   case Stmt::ConditionalOperatorClass: {
8066     // The expression is a literal if both sub-expressions were, and it was
8067     // completely checked only if both sub-expressions were checked.
8068     const AbstractConditionalOperator *C =
8069         cast<AbstractConditionalOperator>(E);
8070 
8071     // Determine whether it is necessary to check both sub-expressions, for
8072     // example, because the condition expression is a constant that can be
8073     // evaluated at compile time.
8074     bool CheckLeft = true, CheckRight = true;
8075 
8076     bool Cond;
8077     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8078                                                  S.isConstantEvaluated())) {
8079       if (Cond)
8080         CheckRight = false;
8081       else
8082         CheckLeft = false;
8083     }
8084 
8085     // We need to maintain the offsets for the right and the left hand side
8086     // separately to check if every possible indexed expression is a valid
8087     // string literal. They might have different offsets for different string
8088     // literals in the end.
8089     StringLiteralCheckType Left;
8090     if (!CheckLeft)
8091       Left = SLCT_UncheckedLiteral;
8092     else {
8093       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8094                                    HasVAListArg, format_idx, firstDataArg,
8095                                    Type, CallType, InFunctionCall,
8096                                    CheckedVarArgs, UncoveredArg, Offset,
8097                                    IgnoreStringsWithoutSpecifiers);
8098       if (Left == SLCT_NotALiteral || !CheckRight) {
8099         return Left;
8100       }
8101     }
8102 
8103     StringLiteralCheckType Right = checkFormatStringExpr(
8104         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8105         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8106         IgnoreStringsWithoutSpecifiers);
8107 
8108     return (CheckLeft && Left < Right) ? Left : Right;
8109   }
8110 
8111   case Stmt::ImplicitCastExprClass:
8112     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8113     goto tryAgain;
8114 
8115   case Stmt::OpaqueValueExprClass:
8116     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8117       E = src;
8118       goto tryAgain;
8119     }
8120     return SLCT_NotALiteral;
8121 
8122   case Stmt::PredefinedExprClass:
8123     // While __func__, etc., are technically not string literals, they
8124     // cannot contain format specifiers and thus are not a security
8125     // liability.
8126     return SLCT_UncheckedLiteral;
8127 
8128   case Stmt::DeclRefExprClass: {
8129     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8130 
8131     // As an exception, do not flag errors for variables binding to
8132     // const string literals.
8133     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8134       bool isConstant = false;
8135       QualType T = DR->getType();
8136 
8137       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8138         isConstant = AT->getElementType().isConstant(S.Context);
8139       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8140         isConstant = T.isConstant(S.Context) &&
8141                      PT->getPointeeType().isConstant(S.Context);
8142       } else if (T->isObjCObjectPointerType()) {
8143         // In ObjC, there is usually no "const ObjectPointer" type,
8144         // so don't check if the pointee type is constant.
8145         isConstant = T.isConstant(S.Context);
8146       }
8147 
8148       if (isConstant) {
8149         if (const Expr *Init = VD->getAnyInitializer()) {
8150           // Look through initializers like const char c[] = { "foo" }
8151           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8152             if (InitList->isStringLiteralInit())
8153               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8154           }
8155           return checkFormatStringExpr(S, Init, Args,
8156                                        HasVAListArg, format_idx,
8157                                        firstDataArg, Type, CallType,
8158                                        /*InFunctionCall*/ false, CheckedVarArgs,
8159                                        UncoveredArg, Offset);
8160         }
8161       }
8162 
8163       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8164       // special check to see if the format string is a function parameter
8165       // of the function calling the printf function.  If the function
8166       // has an attribute indicating it is a printf-like function, then we
8167       // should suppress warnings concerning non-literals being used in a call
8168       // to a vprintf function.  For example:
8169       //
8170       // void
8171       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8172       //      va_list ap;
8173       //      va_start(ap, fmt);
8174       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8175       //      ...
8176       // }
8177       if (HasVAListArg) {
8178         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8179           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8180             int PVIndex = PV->getFunctionScopeIndex() + 1;
8181             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8182               // adjust for implicit parameter
8183               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8184                 if (MD->isInstance())
8185                   ++PVIndex;
8186               // We also check if the formats are compatible.
8187               // We can't pass a 'scanf' string to a 'printf' function.
8188               if (PVIndex == PVFormat->getFormatIdx() &&
8189                   Type == S.GetFormatStringType(PVFormat))
8190                 return SLCT_UncheckedLiteral;
8191             }
8192           }
8193         }
8194       }
8195     }
8196 
8197     return SLCT_NotALiteral;
8198   }
8199 
8200   case Stmt::CallExprClass:
8201   case Stmt::CXXMemberCallExprClass: {
8202     const CallExpr *CE = cast<CallExpr>(E);
8203     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8204       bool IsFirst = true;
8205       StringLiteralCheckType CommonResult;
8206       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8207         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8208         StringLiteralCheckType Result = checkFormatStringExpr(
8209             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8210             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8211             IgnoreStringsWithoutSpecifiers);
8212         if (IsFirst) {
8213           CommonResult = Result;
8214           IsFirst = false;
8215         }
8216       }
8217       if (!IsFirst)
8218         return CommonResult;
8219 
8220       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8221         unsigned BuiltinID = FD->getBuiltinID();
8222         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8223             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8224           const Expr *Arg = CE->getArg(0);
8225           return checkFormatStringExpr(S, Arg, Args,
8226                                        HasVAListArg, format_idx,
8227                                        firstDataArg, Type, CallType,
8228                                        InFunctionCall, CheckedVarArgs,
8229                                        UncoveredArg, Offset,
8230                                        IgnoreStringsWithoutSpecifiers);
8231         }
8232       }
8233     }
8234 
8235     return SLCT_NotALiteral;
8236   }
8237   case Stmt::ObjCMessageExprClass: {
8238     const auto *ME = cast<ObjCMessageExpr>(E);
8239     if (const auto *MD = ME->getMethodDecl()) {
8240       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8241         // As a special case heuristic, if we're using the method -[NSBundle
8242         // localizedStringForKey:value:table:], ignore any key strings that lack
8243         // format specifiers. The idea is that if the key doesn't have any
8244         // format specifiers then its probably just a key to map to the
8245         // localized strings. If it does have format specifiers though, then its
8246         // likely that the text of the key is the format string in the
8247         // programmer's language, and should be checked.
8248         const ObjCInterfaceDecl *IFace;
8249         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8250             IFace->getIdentifier()->isStr("NSBundle") &&
8251             MD->getSelector().isKeywordSelector(
8252                 {"localizedStringForKey", "value", "table"})) {
8253           IgnoreStringsWithoutSpecifiers = true;
8254         }
8255 
8256         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8257         return checkFormatStringExpr(
8258             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8259             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8260             IgnoreStringsWithoutSpecifiers);
8261       }
8262     }
8263 
8264     return SLCT_NotALiteral;
8265   }
8266   case Stmt::ObjCStringLiteralClass:
8267   case Stmt::StringLiteralClass: {
8268     const StringLiteral *StrE = nullptr;
8269 
8270     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8271       StrE = ObjCFExpr->getString();
8272     else
8273       StrE = cast<StringLiteral>(E);
8274 
8275     if (StrE) {
8276       if (Offset.isNegative() || Offset > StrE->getLength()) {
8277         // TODO: It would be better to have an explicit warning for out of
8278         // bounds literals.
8279         return SLCT_NotALiteral;
8280       }
8281       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8282       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8283                         firstDataArg, Type, InFunctionCall, CallType,
8284                         CheckedVarArgs, UncoveredArg,
8285                         IgnoreStringsWithoutSpecifiers);
8286       return SLCT_CheckedLiteral;
8287     }
8288 
8289     return SLCT_NotALiteral;
8290   }
8291   case Stmt::BinaryOperatorClass: {
8292     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8293 
8294     // A string literal + an int offset is still a string literal.
8295     if (BinOp->isAdditiveOp()) {
8296       Expr::EvalResult LResult, RResult;
8297 
8298       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8299           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8300       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8301           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8302 
8303       if (LIsInt != RIsInt) {
8304         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8305 
8306         if (LIsInt) {
8307           if (BinOpKind == BO_Add) {
8308             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8309             E = BinOp->getRHS();
8310             goto tryAgain;
8311           }
8312         } else {
8313           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8314           E = BinOp->getLHS();
8315           goto tryAgain;
8316         }
8317       }
8318     }
8319 
8320     return SLCT_NotALiteral;
8321   }
8322   case Stmt::UnaryOperatorClass: {
8323     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8324     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8325     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8326       Expr::EvalResult IndexResult;
8327       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8328                                        Expr::SE_NoSideEffects,
8329                                        S.isConstantEvaluated())) {
8330         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8331                    /*RHS is int*/ true);
8332         E = ASE->getBase();
8333         goto tryAgain;
8334       }
8335     }
8336 
8337     return SLCT_NotALiteral;
8338   }
8339 
8340   default:
8341     return SLCT_NotALiteral;
8342   }
8343 }
8344 
8345 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8346   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8347       .Case("scanf", FST_Scanf)
8348       .Cases("printf", "printf0", FST_Printf)
8349       .Cases("NSString", "CFString", FST_NSString)
8350       .Case("strftime", FST_Strftime)
8351       .Case("strfmon", FST_Strfmon)
8352       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8353       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8354       .Case("os_trace", FST_OSLog)
8355       .Case("os_log", FST_OSLog)
8356       .Default(FST_Unknown);
8357 }
8358 
8359 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8360 /// functions) for correct use of format strings.
8361 /// Returns true if a format string has been fully checked.
8362 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8363                                 ArrayRef<const Expr *> Args,
8364                                 bool IsCXXMember,
8365                                 VariadicCallType CallType,
8366                                 SourceLocation Loc, SourceRange Range,
8367                                 llvm::SmallBitVector &CheckedVarArgs) {
8368   FormatStringInfo FSI;
8369   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8370     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8371                                 FSI.FirstDataArg, GetFormatStringType(Format),
8372                                 CallType, Loc, Range, CheckedVarArgs);
8373   return false;
8374 }
8375 
8376 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8377                                 bool HasVAListArg, unsigned format_idx,
8378                                 unsigned firstDataArg, FormatStringType Type,
8379                                 VariadicCallType CallType,
8380                                 SourceLocation Loc, SourceRange Range,
8381                                 llvm::SmallBitVector &CheckedVarArgs) {
8382   // CHECK: printf/scanf-like function is called with no format string.
8383   if (format_idx >= Args.size()) {
8384     Diag(Loc, diag::warn_missing_format_string) << Range;
8385     return false;
8386   }
8387 
8388   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8389 
8390   // CHECK: format string is not a string literal.
8391   //
8392   // Dynamically generated format strings are difficult to
8393   // automatically vet at compile time.  Requiring that format strings
8394   // are string literals: (1) permits the checking of format strings by
8395   // the compiler and thereby (2) can practically remove the source of
8396   // many format string exploits.
8397 
8398   // Format string can be either ObjC string (e.g. @"%d") or
8399   // C string (e.g. "%d")
8400   // ObjC string uses the same format specifiers as C string, so we can use
8401   // the same format string checking logic for both ObjC and C strings.
8402   UncoveredArgHandler UncoveredArg;
8403   StringLiteralCheckType CT =
8404       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8405                             format_idx, firstDataArg, Type, CallType,
8406                             /*IsFunctionCall*/ true, CheckedVarArgs,
8407                             UncoveredArg,
8408                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8409 
8410   // Generate a diagnostic where an uncovered argument is detected.
8411   if (UncoveredArg.hasUncoveredArg()) {
8412     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8413     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8414     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8415   }
8416 
8417   if (CT != SLCT_NotALiteral)
8418     // Literal format string found, check done!
8419     return CT == SLCT_CheckedLiteral;
8420 
8421   // Strftime is particular as it always uses a single 'time' argument,
8422   // so it is safe to pass a non-literal string.
8423   if (Type == FST_Strftime)
8424     return false;
8425 
8426   // Do not emit diag when the string param is a macro expansion and the
8427   // format is either NSString or CFString. This is a hack to prevent
8428   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8429   // which are usually used in place of NS and CF string literals.
8430   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8431   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8432     return false;
8433 
8434   // If there are no arguments specified, warn with -Wformat-security, otherwise
8435   // warn only with -Wformat-nonliteral.
8436   if (Args.size() == firstDataArg) {
8437     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8438       << OrigFormatExpr->getSourceRange();
8439     switch (Type) {
8440     default:
8441       break;
8442     case FST_Kprintf:
8443     case FST_FreeBSDKPrintf:
8444     case FST_Printf:
8445       Diag(FormatLoc, diag::note_format_security_fixit)
8446         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8447       break;
8448     case FST_NSString:
8449       Diag(FormatLoc, diag::note_format_security_fixit)
8450         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8451       break;
8452     }
8453   } else {
8454     Diag(FormatLoc, diag::warn_format_nonliteral)
8455       << OrigFormatExpr->getSourceRange();
8456   }
8457   return false;
8458 }
8459 
8460 namespace {
8461 
8462 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8463 protected:
8464   Sema &S;
8465   const FormatStringLiteral *FExpr;
8466   const Expr *OrigFormatExpr;
8467   const Sema::FormatStringType FSType;
8468   const unsigned FirstDataArg;
8469   const unsigned NumDataArgs;
8470   const char *Beg; // Start of format string.
8471   const bool HasVAListArg;
8472   ArrayRef<const Expr *> Args;
8473   unsigned FormatIdx;
8474   llvm::SmallBitVector CoveredArgs;
8475   bool usesPositionalArgs = false;
8476   bool atFirstArg = true;
8477   bool inFunctionCall;
8478   Sema::VariadicCallType CallType;
8479   llvm::SmallBitVector &CheckedVarArgs;
8480   UncoveredArgHandler &UncoveredArg;
8481 
8482 public:
8483   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8484                      const Expr *origFormatExpr,
8485                      const Sema::FormatStringType type, unsigned firstDataArg,
8486                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8487                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8488                      bool inFunctionCall, Sema::VariadicCallType callType,
8489                      llvm::SmallBitVector &CheckedVarArgs,
8490                      UncoveredArgHandler &UncoveredArg)
8491       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8492         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8493         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8494         inFunctionCall(inFunctionCall), CallType(callType),
8495         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8496     CoveredArgs.resize(numDataArgs);
8497     CoveredArgs.reset();
8498   }
8499 
8500   void DoneProcessing();
8501 
8502   void HandleIncompleteSpecifier(const char *startSpecifier,
8503                                  unsigned specifierLen) override;
8504 
8505   void HandleInvalidLengthModifier(
8506                            const analyze_format_string::FormatSpecifier &FS,
8507                            const analyze_format_string::ConversionSpecifier &CS,
8508                            const char *startSpecifier, unsigned specifierLen,
8509                            unsigned DiagID);
8510 
8511   void HandleNonStandardLengthModifier(
8512                     const analyze_format_string::FormatSpecifier &FS,
8513                     const char *startSpecifier, unsigned specifierLen);
8514 
8515   void HandleNonStandardConversionSpecifier(
8516                     const analyze_format_string::ConversionSpecifier &CS,
8517                     const char *startSpecifier, unsigned specifierLen);
8518 
8519   void HandlePosition(const char *startPos, unsigned posLen) override;
8520 
8521   void HandleInvalidPosition(const char *startSpecifier,
8522                              unsigned specifierLen,
8523                              analyze_format_string::PositionContext p) override;
8524 
8525   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8526 
8527   void HandleNullChar(const char *nullCharacter) override;
8528 
8529   template <typename Range>
8530   static void
8531   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8532                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8533                        bool IsStringLocation, Range StringRange,
8534                        ArrayRef<FixItHint> Fixit = None);
8535 
8536 protected:
8537   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8538                                         const char *startSpec,
8539                                         unsigned specifierLen,
8540                                         const char *csStart, unsigned csLen);
8541 
8542   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8543                                          const char *startSpec,
8544                                          unsigned specifierLen);
8545 
8546   SourceRange getFormatStringRange();
8547   CharSourceRange getSpecifierRange(const char *startSpecifier,
8548                                     unsigned specifierLen);
8549   SourceLocation getLocationOfByte(const char *x);
8550 
8551   const Expr *getDataArg(unsigned i) const;
8552 
8553   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8554                     const analyze_format_string::ConversionSpecifier &CS,
8555                     const char *startSpecifier, unsigned specifierLen,
8556                     unsigned argIndex);
8557 
8558   template <typename Range>
8559   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8560                             bool IsStringLocation, Range StringRange,
8561                             ArrayRef<FixItHint> Fixit = None);
8562 };
8563 
8564 } // namespace
8565 
8566 SourceRange CheckFormatHandler::getFormatStringRange() {
8567   return OrigFormatExpr->getSourceRange();
8568 }
8569 
8570 CharSourceRange CheckFormatHandler::
8571 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8572   SourceLocation Start = getLocationOfByte(startSpecifier);
8573   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8574 
8575   // Advance the end SourceLocation by one due to half-open ranges.
8576   End = End.getLocWithOffset(1);
8577 
8578   return CharSourceRange::getCharRange(Start, End);
8579 }
8580 
8581 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8582   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8583                                   S.getLangOpts(), S.Context.getTargetInfo());
8584 }
8585 
8586 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8587                                                    unsigned specifierLen){
8588   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8589                        getLocationOfByte(startSpecifier),
8590                        /*IsStringLocation*/true,
8591                        getSpecifierRange(startSpecifier, specifierLen));
8592 }
8593 
8594 void CheckFormatHandler::HandleInvalidLengthModifier(
8595     const analyze_format_string::FormatSpecifier &FS,
8596     const analyze_format_string::ConversionSpecifier &CS,
8597     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8598   using namespace analyze_format_string;
8599 
8600   const LengthModifier &LM = FS.getLengthModifier();
8601   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8602 
8603   // See if we know how to fix this length modifier.
8604   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8605   if (FixedLM) {
8606     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8607                          getLocationOfByte(LM.getStart()),
8608                          /*IsStringLocation*/true,
8609                          getSpecifierRange(startSpecifier, specifierLen));
8610 
8611     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8612       << FixedLM->toString()
8613       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8614 
8615   } else {
8616     FixItHint Hint;
8617     if (DiagID == diag::warn_format_nonsensical_length)
8618       Hint = FixItHint::CreateRemoval(LMRange);
8619 
8620     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8621                          getLocationOfByte(LM.getStart()),
8622                          /*IsStringLocation*/true,
8623                          getSpecifierRange(startSpecifier, specifierLen),
8624                          Hint);
8625   }
8626 }
8627 
8628 void CheckFormatHandler::HandleNonStandardLengthModifier(
8629     const analyze_format_string::FormatSpecifier &FS,
8630     const char *startSpecifier, unsigned specifierLen) {
8631   using namespace analyze_format_string;
8632 
8633   const LengthModifier &LM = FS.getLengthModifier();
8634   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8635 
8636   // See if we know how to fix this length modifier.
8637   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8638   if (FixedLM) {
8639     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8640                            << LM.toString() << 0,
8641                          getLocationOfByte(LM.getStart()),
8642                          /*IsStringLocation*/true,
8643                          getSpecifierRange(startSpecifier, specifierLen));
8644 
8645     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8646       << FixedLM->toString()
8647       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8648 
8649   } else {
8650     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8651                            << LM.toString() << 0,
8652                          getLocationOfByte(LM.getStart()),
8653                          /*IsStringLocation*/true,
8654                          getSpecifierRange(startSpecifier, specifierLen));
8655   }
8656 }
8657 
8658 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8659     const analyze_format_string::ConversionSpecifier &CS,
8660     const char *startSpecifier, unsigned specifierLen) {
8661   using namespace analyze_format_string;
8662 
8663   // See if we know how to fix this conversion specifier.
8664   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8665   if (FixedCS) {
8666     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8667                           << CS.toString() << /*conversion specifier*/1,
8668                          getLocationOfByte(CS.getStart()),
8669                          /*IsStringLocation*/true,
8670                          getSpecifierRange(startSpecifier, specifierLen));
8671 
8672     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8673     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8674       << FixedCS->toString()
8675       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8676   } else {
8677     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8678                           << CS.toString() << /*conversion specifier*/1,
8679                          getLocationOfByte(CS.getStart()),
8680                          /*IsStringLocation*/true,
8681                          getSpecifierRange(startSpecifier, specifierLen));
8682   }
8683 }
8684 
8685 void CheckFormatHandler::HandlePosition(const char *startPos,
8686                                         unsigned posLen) {
8687   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8688                                getLocationOfByte(startPos),
8689                                /*IsStringLocation*/true,
8690                                getSpecifierRange(startPos, posLen));
8691 }
8692 
8693 void
8694 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8695                                      analyze_format_string::PositionContext p) {
8696   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8697                          << (unsigned) p,
8698                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8699                        getSpecifierRange(startPos, posLen));
8700 }
8701 
8702 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8703                                             unsigned posLen) {
8704   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8705                                getLocationOfByte(startPos),
8706                                /*IsStringLocation*/true,
8707                                getSpecifierRange(startPos, posLen));
8708 }
8709 
8710 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8711   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8712     // The presence of a null character is likely an error.
8713     EmitFormatDiagnostic(
8714       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8715       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8716       getFormatStringRange());
8717   }
8718 }
8719 
8720 // Note that this may return NULL if there was an error parsing or building
8721 // one of the argument expressions.
8722 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8723   return Args[FirstDataArg + i];
8724 }
8725 
8726 void CheckFormatHandler::DoneProcessing() {
8727   // Does the number of data arguments exceed the number of
8728   // format conversions in the format string?
8729   if (!HasVAListArg) {
8730       // Find any arguments that weren't covered.
8731     CoveredArgs.flip();
8732     signed notCoveredArg = CoveredArgs.find_first();
8733     if (notCoveredArg >= 0) {
8734       assert((unsigned)notCoveredArg < NumDataArgs);
8735       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8736     } else {
8737       UncoveredArg.setAllCovered();
8738     }
8739   }
8740 }
8741 
8742 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8743                                    const Expr *ArgExpr) {
8744   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8745          "Invalid state");
8746 
8747   if (!ArgExpr)
8748     return;
8749 
8750   SourceLocation Loc = ArgExpr->getBeginLoc();
8751 
8752   if (S.getSourceManager().isInSystemMacro(Loc))
8753     return;
8754 
8755   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8756   for (auto E : DiagnosticExprs)
8757     PDiag << E->getSourceRange();
8758 
8759   CheckFormatHandler::EmitFormatDiagnostic(
8760                                   S, IsFunctionCall, DiagnosticExprs[0],
8761                                   PDiag, Loc, /*IsStringLocation*/false,
8762                                   DiagnosticExprs[0]->getSourceRange());
8763 }
8764 
8765 bool
8766 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8767                                                      SourceLocation Loc,
8768                                                      const char *startSpec,
8769                                                      unsigned specifierLen,
8770                                                      const char *csStart,
8771                                                      unsigned csLen) {
8772   bool keepGoing = true;
8773   if (argIndex < NumDataArgs) {
8774     // Consider the argument coverered, even though the specifier doesn't
8775     // make sense.
8776     CoveredArgs.set(argIndex);
8777   }
8778   else {
8779     // If argIndex exceeds the number of data arguments we
8780     // don't issue a warning because that is just a cascade of warnings (and
8781     // they may have intended '%%' anyway). We don't want to continue processing
8782     // the format string after this point, however, as we will like just get
8783     // gibberish when trying to match arguments.
8784     keepGoing = false;
8785   }
8786 
8787   StringRef Specifier(csStart, csLen);
8788 
8789   // If the specifier in non-printable, it could be the first byte of a UTF-8
8790   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8791   // hex value.
8792   std::string CodePointStr;
8793   if (!llvm::sys::locale::isPrint(*csStart)) {
8794     llvm::UTF32 CodePoint;
8795     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8796     const llvm::UTF8 *E =
8797         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8798     llvm::ConversionResult Result =
8799         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8800 
8801     if (Result != llvm::conversionOK) {
8802       unsigned char FirstChar = *csStart;
8803       CodePoint = (llvm::UTF32)FirstChar;
8804     }
8805 
8806     llvm::raw_string_ostream OS(CodePointStr);
8807     if (CodePoint < 256)
8808       OS << "\\x" << llvm::format("%02x", CodePoint);
8809     else if (CodePoint <= 0xFFFF)
8810       OS << "\\u" << llvm::format("%04x", CodePoint);
8811     else
8812       OS << "\\U" << llvm::format("%08x", CodePoint);
8813     OS.flush();
8814     Specifier = CodePointStr;
8815   }
8816 
8817   EmitFormatDiagnostic(
8818       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8819       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8820 
8821   return keepGoing;
8822 }
8823 
8824 void
8825 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8826                                                       const char *startSpec,
8827                                                       unsigned specifierLen) {
8828   EmitFormatDiagnostic(
8829     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8830     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8831 }
8832 
8833 bool
8834 CheckFormatHandler::CheckNumArgs(
8835   const analyze_format_string::FormatSpecifier &FS,
8836   const analyze_format_string::ConversionSpecifier &CS,
8837   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8838 
8839   if (argIndex >= NumDataArgs) {
8840     PartialDiagnostic PDiag = FS.usesPositionalArg()
8841       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8842            << (argIndex+1) << NumDataArgs)
8843       : S.PDiag(diag::warn_printf_insufficient_data_args);
8844     EmitFormatDiagnostic(
8845       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8846       getSpecifierRange(startSpecifier, specifierLen));
8847 
8848     // Since more arguments than conversion tokens are given, by extension
8849     // all arguments are covered, so mark this as so.
8850     UncoveredArg.setAllCovered();
8851     return false;
8852   }
8853   return true;
8854 }
8855 
8856 template<typename Range>
8857 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8858                                               SourceLocation Loc,
8859                                               bool IsStringLocation,
8860                                               Range StringRange,
8861                                               ArrayRef<FixItHint> FixIt) {
8862   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8863                        Loc, IsStringLocation, StringRange, FixIt);
8864 }
8865 
8866 /// If the format string is not within the function call, emit a note
8867 /// so that the function call and string are in diagnostic messages.
8868 ///
8869 /// \param InFunctionCall if true, the format string is within the function
8870 /// call and only one diagnostic message will be produced.  Otherwise, an
8871 /// extra note will be emitted pointing to location of the format string.
8872 ///
8873 /// \param ArgumentExpr the expression that is passed as the format string
8874 /// argument in the function call.  Used for getting locations when two
8875 /// diagnostics are emitted.
8876 ///
8877 /// \param PDiag the callee should already have provided any strings for the
8878 /// diagnostic message.  This function only adds locations and fixits
8879 /// to diagnostics.
8880 ///
8881 /// \param Loc primary location for diagnostic.  If two diagnostics are
8882 /// required, one will be at Loc and a new SourceLocation will be created for
8883 /// the other one.
8884 ///
8885 /// \param IsStringLocation if true, Loc points to the format string should be
8886 /// used for the note.  Otherwise, Loc points to the argument list and will
8887 /// be used with PDiag.
8888 ///
8889 /// \param StringRange some or all of the string to highlight.  This is
8890 /// templated so it can accept either a CharSourceRange or a SourceRange.
8891 ///
8892 /// \param FixIt optional fix it hint for the format string.
8893 template <typename Range>
8894 void CheckFormatHandler::EmitFormatDiagnostic(
8895     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8896     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8897     Range StringRange, ArrayRef<FixItHint> FixIt) {
8898   if (InFunctionCall) {
8899     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8900     D << StringRange;
8901     D << FixIt;
8902   } else {
8903     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8904       << ArgumentExpr->getSourceRange();
8905 
8906     const Sema::SemaDiagnosticBuilder &Note =
8907       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8908              diag::note_format_string_defined);
8909 
8910     Note << StringRange;
8911     Note << FixIt;
8912   }
8913 }
8914 
8915 //===--- CHECK: Printf format string checking ------------------------------===//
8916 
8917 namespace {
8918 
8919 class CheckPrintfHandler : public CheckFormatHandler {
8920 public:
8921   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8922                      const Expr *origFormatExpr,
8923                      const Sema::FormatStringType type, unsigned firstDataArg,
8924                      unsigned numDataArgs, bool isObjC, const char *beg,
8925                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8926                      unsigned formatIdx, bool inFunctionCall,
8927                      Sema::VariadicCallType CallType,
8928                      llvm::SmallBitVector &CheckedVarArgs,
8929                      UncoveredArgHandler &UncoveredArg)
8930       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8931                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8932                            inFunctionCall, CallType, CheckedVarArgs,
8933                            UncoveredArg) {}
8934 
8935   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8936 
8937   /// Returns true if '%@' specifiers are allowed in the format string.
8938   bool allowsObjCArg() const {
8939     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8940            FSType == Sema::FST_OSTrace;
8941   }
8942 
8943   bool HandleInvalidPrintfConversionSpecifier(
8944                                       const analyze_printf::PrintfSpecifier &FS,
8945                                       const char *startSpecifier,
8946                                       unsigned specifierLen) override;
8947 
8948   void handleInvalidMaskType(StringRef MaskType) override;
8949 
8950   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8951                              const char *startSpecifier, unsigned specifierLen,
8952                              const TargetInfo &Target) override;
8953   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8954                        const char *StartSpecifier,
8955                        unsigned SpecifierLen,
8956                        const Expr *E);
8957 
8958   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8959                     const char *startSpecifier, unsigned specifierLen);
8960   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8961                            const analyze_printf::OptionalAmount &Amt,
8962                            unsigned type,
8963                            const char *startSpecifier, unsigned specifierLen);
8964   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8965                   const analyze_printf::OptionalFlag &flag,
8966                   const char *startSpecifier, unsigned specifierLen);
8967   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8968                          const analyze_printf::OptionalFlag &ignoredFlag,
8969                          const analyze_printf::OptionalFlag &flag,
8970                          const char *startSpecifier, unsigned specifierLen);
8971   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8972                            const Expr *E);
8973 
8974   void HandleEmptyObjCModifierFlag(const char *startFlag,
8975                                    unsigned flagLen) override;
8976 
8977   void HandleInvalidObjCModifierFlag(const char *startFlag,
8978                                             unsigned flagLen) override;
8979 
8980   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8981                                            const char *flagsEnd,
8982                                            const char *conversionPosition)
8983                                              override;
8984 };
8985 
8986 } // namespace
8987 
8988 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8989                                       const analyze_printf::PrintfSpecifier &FS,
8990                                       const char *startSpecifier,
8991                                       unsigned specifierLen) {
8992   const analyze_printf::PrintfConversionSpecifier &CS =
8993     FS.getConversionSpecifier();
8994 
8995   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8996                                           getLocationOfByte(CS.getStart()),
8997                                           startSpecifier, specifierLen,
8998                                           CS.getStart(), CS.getLength());
8999 }
9000 
9001 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9002   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9003 }
9004 
9005 bool CheckPrintfHandler::HandleAmount(
9006                                const analyze_format_string::OptionalAmount &Amt,
9007                                unsigned k, const char *startSpecifier,
9008                                unsigned specifierLen) {
9009   if (Amt.hasDataArgument()) {
9010     if (!HasVAListArg) {
9011       unsigned argIndex = Amt.getArgIndex();
9012       if (argIndex >= NumDataArgs) {
9013         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9014                                << k,
9015                              getLocationOfByte(Amt.getStart()),
9016                              /*IsStringLocation*/true,
9017                              getSpecifierRange(startSpecifier, specifierLen));
9018         // Don't do any more checking.  We will just emit
9019         // spurious errors.
9020         return false;
9021       }
9022 
9023       // Type check the data argument.  It should be an 'int'.
9024       // Although not in conformance with C99, we also allow the argument to be
9025       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9026       // doesn't emit a warning for that case.
9027       CoveredArgs.set(argIndex);
9028       const Expr *Arg = getDataArg(argIndex);
9029       if (!Arg)
9030         return false;
9031 
9032       QualType T = Arg->getType();
9033 
9034       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9035       assert(AT.isValid());
9036 
9037       if (!AT.matchesType(S.Context, T)) {
9038         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9039                                << k << AT.getRepresentativeTypeName(S.Context)
9040                                << T << Arg->getSourceRange(),
9041                              getLocationOfByte(Amt.getStart()),
9042                              /*IsStringLocation*/true,
9043                              getSpecifierRange(startSpecifier, specifierLen));
9044         // Don't do any more checking.  We will just emit
9045         // spurious errors.
9046         return false;
9047       }
9048     }
9049   }
9050   return true;
9051 }
9052 
9053 void CheckPrintfHandler::HandleInvalidAmount(
9054                                       const analyze_printf::PrintfSpecifier &FS,
9055                                       const analyze_printf::OptionalAmount &Amt,
9056                                       unsigned type,
9057                                       const char *startSpecifier,
9058                                       unsigned specifierLen) {
9059   const analyze_printf::PrintfConversionSpecifier &CS =
9060     FS.getConversionSpecifier();
9061 
9062   FixItHint fixit =
9063     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9064       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9065                                  Amt.getConstantLength()))
9066       : FixItHint();
9067 
9068   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9069                          << type << CS.toString(),
9070                        getLocationOfByte(Amt.getStart()),
9071                        /*IsStringLocation*/true,
9072                        getSpecifierRange(startSpecifier, specifierLen),
9073                        fixit);
9074 }
9075 
9076 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9077                                     const analyze_printf::OptionalFlag &flag,
9078                                     const char *startSpecifier,
9079                                     unsigned specifierLen) {
9080   // Warn about pointless flag with a fixit removal.
9081   const analyze_printf::PrintfConversionSpecifier &CS =
9082     FS.getConversionSpecifier();
9083   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9084                          << flag.toString() << CS.toString(),
9085                        getLocationOfByte(flag.getPosition()),
9086                        /*IsStringLocation*/true,
9087                        getSpecifierRange(startSpecifier, specifierLen),
9088                        FixItHint::CreateRemoval(
9089                          getSpecifierRange(flag.getPosition(), 1)));
9090 }
9091 
9092 void CheckPrintfHandler::HandleIgnoredFlag(
9093                                 const analyze_printf::PrintfSpecifier &FS,
9094                                 const analyze_printf::OptionalFlag &ignoredFlag,
9095                                 const analyze_printf::OptionalFlag &flag,
9096                                 const char *startSpecifier,
9097                                 unsigned specifierLen) {
9098   // Warn about ignored flag with a fixit removal.
9099   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9100                          << ignoredFlag.toString() << flag.toString(),
9101                        getLocationOfByte(ignoredFlag.getPosition()),
9102                        /*IsStringLocation*/true,
9103                        getSpecifierRange(startSpecifier, specifierLen),
9104                        FixItHint::CreateRemoval(
9105                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9106 }
9107 
9108 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9109                                                      unsigned flagLen) {
9110   // Warn about an empty flag.
9111   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9112                        getLocationOfByte(startFlag),
9113                        /*IsStringLocation*/true,
9114                        getSpecifierRange(startFlag, flagLen));
9115 }
9116 
9117 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9118                                                        unsigned flagLen) {
9119   // Warn about an invalid flag.
9120   auto Range = getSpecifierRange(startFlag, flagLen);
9121   StringRef flag(startFlag, flagLen);
9122   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9123                       getLocationOfByte(startFlag),
9124                       /*IsStringLocation*/true,
9125                       Range, FixItHint::CreateRemoval(Range));
9126 }
9127 
9128 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9129     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9130     // Warn about using '[...]' without a '@' conversion.
9131     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9132     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9133     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9134                          getLocationOfByte(conversionPosition),
9135                          /*IsStringLocation*/true,
9136                          Range, FixItHint::CreateRemoval(Range));
9137 }
9138 
9139 // Determines if the specified is a C++ class or struct containing
9140 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9141 // "c_str()").
9142 template<typename MemberKind>
9143 static llvm::SmallPtrSet<MemberKind*, 1>
9144 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9145   const RecordType *RT = Ty->getAs<RecordType>();
9146   llvm::SmallPtrSet<MemberKind*, 1> Results;
9147 
9148   if (!RT)
9149     return Results;
9150   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9151   if (!RD || !RD->getDefinition())
9152     return Results;
9153 
9154   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9155                  Sema::LookupMemberName);
9156   R.suppressDiagnostics();
9157 
9158   // We just need to include all members of the right kind turned up by the
9159   // filter, at this point.
9160   if (S.LookupQualifiedName(R, RT->getDecl()))
9161     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9162       NamedDecl *decl = (*I)->getUnderlyingDecl();
9163       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9164         Results.insert(FK);
9165     }
9166   return Results;
9167 }
9168 
9169 /// Check if we could call '.c_str()' on an object.
9170 ///
9171 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9172 /// allow the call, or if it would be ambiguous).
9173 bool Sema::hasCStrMethod(const Expr *E) {
9174   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9175 
9176   MethodSet Results =
9177       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9178   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9179        MI != ME; ++MI)
9180     if ((*MI)->getMinRequiredArguments() == 0)
9181       return true;
9182   return false;
9183 }
9184 
9185 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9186 // better diagnostic if so. AT is assumed to be valid.
9187 // Returns true when a c_str() conversion method is found.
9188 bool CheckPrintfHandler::checkForCStrMembers(
9189     const analyze_printf::ArgType &AT, const Expr *E) {
9190   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9191 
9192   MethodSet Results =
9193       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9194 
9195   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9196        MI != ME; ++MI) {
9197     const CXXMethodDecl *Method = *MI;
9198     if (Method->getMinRequiredArguments() == 0 &&
9199         AT.matchesType(S.Context, Method->getReturnType())) {
9200       // FIXME: Suggest parens if the expression needs them.
9201       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9202       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9203           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9204       return true;
9205     }
9206   }
9207 
9208   return false;
9209 }
9210 
9211 bool CheckPrintfHandler::HandlePrintfSpecifier(
9212     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9213     unsigned specifierLen, const TargetInfo &Target) {
9214   using namespace analyze_format_string;
9215   using namespace analyze_printf;
9216 
9217   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9218 
9219   if (FS.consumesDataArgument()) {
9220     if (atFirstArg) {
9221         atFirstArg = false;
9222         usesPositionalArgs = FS.usesPositionalArg();
9223     }
9224     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9225       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9226                                         startSpecifier, specifierLen);
9227       return false;
9228     }
9229   }
9230 
9231   // First check if the field width, precision, and conversion specifier
9232   // have matching data arguments.
9233   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9234                     startSpecifier, specifierLen)) {
9235     return false;
9236   }
9237 
9238   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9239                     startSpecifier, specifierLen)) {
9240     return false;
9241   }
9242 
9243   if (!CS.consumesDataArgument()) {
9244     // FIXME: Technically specifying a precision or field width here
9245     // makes no sense.  Worth issuing a warning at some point.
9246     return true;
9247   }
9248 
9249   // Consume the argument.
9250   unsigned argIndex = FS.getArgIndex();
9251   if (argIndex < NumDataArgs) {
9252     // The check to see if the argIndex is valid will come later.
9253     // We set the bit here because we may exit early from this
9254     // function if we encounter some other error.
9255     CoveredArgs.set(argIndex);
9256   }
9257 
9258   // FreeBSD kernel extensions.
9259   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9260       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9261     // We need at least two arguments.
9262     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9263       return false;
9264 
9265     // Claim the second argument.
9266     CoveredArgs.set(argIndex + 1);
9267 
9268     // Type check the first argument (int for %b, pointer for %D)
9269     const Expr *Ex = getDataArg(argIndex);
9270     const analyze_printf::ArgType &AT =
9271       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9272         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9273     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9274       EmitFormatDiagnostic(
9275           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9276               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9277               << false << Ex->getSourceRange(),
9278           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9279           getSpecifierRange(startSpecifier, specifierLen));
9280 
9281     // Type check the second argument (char * for both %b and %D)
9282     Ex = getDataArg(argIndex + 1);
9283     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9284     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9285       EmitFormatDiagnostic(
9286           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9287               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9288               << false << Ex->getSourceRange(),
9289           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9290           getSpecifierRange(startSpecifier, specifierLen));
9291 
9292      return true;
9293   }
9294 
9295   // Check for using an Objective-C specific conversion specifier
9296   // in a non-ObjC literal.
9297   if (!allowsObjCArg() && CS.isObjCArg()) {
9298     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9299                                                   specifierLen);
9300   }
9301 
9302   // %P can only be used with os_log.
9303   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9304     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9305                                                   specifierLen);
9306   }
9307 
9308   // %n is not allowed with os_log.
9309   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9310     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9311                          getLocationOfByte(CS.getStart()),
9312                          /*IsStringLocation*/ false,
9313                          getSpecifierRange(startSpecifier, specifierLen));
9314 
9315     return true;
9316   }
9317 
9318   // Only scalars are allowed for os_trace.
9319   if (FSType == Sema::FST_OSTrace &&
9320       (CS.getKind() == ConversionSpecifier::PArg ||
9321        CS.getKind() == ConversionSpecifier::sArg ||
9322        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9323     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9324                                                   specifierLen);
9325   }
9326 
9327   // Check for use of public/private annotation outside of os_log().
9328   if (FSType != Sema::FST_OSLog) {
9329     if (FS.isPublic().isSet()) {
9330       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9331                                << "public",
9332                            getLocationOfByte(FS.isPublic().getPosition()),
9333                            /*IsStringLocation*/ false,
9334                            getSpecifierRange(startSpecifier, specifierLen));
9335     }
9336     if (FS.isPrivate().isSet()) {
9337       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9338                                << "private",
9339                            getLocationOfByte(FS.isPrivate().getPosition()),
9340                            /*IsStringLocation*/ false,
9341                            getSpecifierRange(startSpecifier, specifierLen));
9342     }
9343   }
9344 
9345   const llvm::Triple &Triple = Target.getTriple();
9346   if (CS.getKind() == ConversionSpecifier::nArg &&
9347       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9348     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9349                          getLocationOfByte(CS.getStart()),
9350                          /*IsStringLocation*/ false,
9351                          getSpecifierRange(startSpecifier, specifierLen));
9352   }
9353 
9354   // Check for invalid use of field width
9355   if (!FS.hasValidFieldWidth()) {
9356     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9357         startSpecifier, specifierLen);
9358   }
9359 
9360   // Check for invalid use of precision
9361   if (!FS.hasValidPrecision()) {
9362     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9363         startSpecifier, specifierLen);
9364   }
9365 
9366   // Precision is mandatory for %P specifier.
9367   if (CS.getKind() == ConversionSpecifier::PArg &&
9368       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9369     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9370                          getLocationOfByte(startSpecifier),
9371                          /*IsStringLocation*/ false,
9372                          getSpecifierRange(startSpecifier, specifierLen));
9373   }
9374 
9375   // Check each flag does not conflict with any other component.
9376   if (!FS.hasValidThousandsGroupingPrefix())
9377     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9378   if (!FS.hasValidLeadingZeros())
9379     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9380   if (!FS.hasValidPlusPrefix())
9381     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9382   if (!FS.hasValidSpacePrefix())
9383     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9384   if (!FS.hasValidAlternativeForm())
9385     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9386   if (!FS.hasValidLeftJustified())
9387     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9388 
9389   // Check that flags are not ignored by another flag
9390   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9391     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9392         startSpecifier, specifierLen);
9393   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9394     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9395             startSpecifier, specifierLen);
9396 
9397   // Check the length modifier is valid with the given conversion specifier.
9398   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9399                                  S.getLangOpts()))
9400     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9401                                 diag::warn_format_nonsensical_length);
9402   else if (!FS.hasStandardLengthModifier())
9403     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9404   else if (!FS.hasStandardLengthConversionCombination())
9405     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9406                                 diag::warn_format_non_standard_conversion_spec);
9407 
9408   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9409     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9410 
9411   // The remaining checks depend on the data arguments.
9412   if (HasVAListArg)
9413     return true;
9414 
9415   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9416     return false;
9417 
9418   const Expr *Arg = getDataArg(argIndex);
9419   if (!Arg)
9420     return true;
9421 
9422   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9423 }
9424 
9425 static bool requiresParensToAddCast(const Expr *E) {
9426   // FIXME: We should have a general way to reason about operator
9427   // precedence and whether parens are actually needed here.
9428   // Take care of a few common cases where they aren't.
9429   const Expr *Inside = E->IgnoreImpCasts();
9430   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9431     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9432 
9433   switch (Inside->getStmtClass()) {
9434   case Stmt::ArraySubscriptExprClass:
9435   case Stmt::CallExprClass:
9436   case Stmt::CharacterLiteralClass:
9437   case Stmt::CXXBoolLiteralExprClass:
9438   case Stmt::DeclRefExprClass:
9439   case Stmt::FloatingLiteralClass:
9440   case Stmt::IntegerLiteralClass:
9441   case Stmt::MemberExprClass:
9442   case Stmt::ObjCArrayLiteralClass:
9443   case Stmt::ObjCBoolLiteralExprClass:
9444   case Stmt::ObjCBoxedExprClass:
9445   case Stmt::ObjCDictionaryLiteralClass:
9446   case Stmt::ObjCEncodeExprClass:
9447   case Stmt::ObjCIvarRefExprClass:
9448   case Stmt::ObjCMessageExprClass:
9449   case Stmt::ObjCPropertyRefExprClass:
9450   case Stmt::ObjCStringLiteralClass:
9451   case Stmt::ObjCSubscriptRefExprClass:
9452   case Stmt::ParenExprClass:
9453   case Stmt::StringLiteralClass:
9454   case Stmt::UnaryOperatorClass:
9455     return false;
9456   default:
9457     return true;
9458   }
9459 }
9460 
9461 static std::pair<QualType, StringRef>
9462 shouldNotPrintDirectly(const ASTContext &Context,
9463                        QualType IntendedTy,
9464                        const Expr *E) {
9465   // Use a 'while' to peel off layers of typedefs.
9466   QualType TyTy = IntendedTy;
9467   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9468     StringRef Name = UserTy->getDecl()->getName();
9469     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9470       .Case("CFIndex", Context.getNSIntegerType())
9471       .Case("NSInteger", Context.getNSIntegerType())
9472       .Case("NSUInteger", Context.getNSUIntegerType())
9473       .Case("SInt32", Context.IntTy)
9474       .Case("UInt32", Context.UnsignedIntTy)
9475       .Default(QualType());
9476 
9477     if (!CastTy.isNull())
9478       return std::make_pair(CastTy, Name);
9479 
9480     TyTy = UserTy->desugar();
9481   }
9482 
9483   // Strip parens if necessary.
9484   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9485     return shouldNotPrintDirectly(Context,
9486                                   PE->getSubExpr()->getType(),
9487                                   PE->getSubExpr());
9488 
9489   // If this is a conditional expression, then its result type is constructed
9490   // via usual arithmetic conversions and thus there might be no necessary
9491   // typedef sugar there.  Recurse to operands to check for NSInteger &
9492   // Co. usage condition.
9493   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9494     QualType TrueTy, FalseTy;
9495     StringRef TrueName, FalseName;
9496 
9497     std::tie(TrueTy, TrueName) =
9498       shouldNotPrintDirectly(Context,
9499                              CO->getTrueExpr()->getType(),
9500                              CO->getTrueExpr());
9501     std::tie(FalseTy, FalseName) =
9502       shouldNotPrintDirectly(Context,
9503                              CO->getFalseExpr()->getType(),
9504                              CO->getFalseExpr());
9505 
9506     if (TrueTy == FalseTy)
9507       return std::make_pair(TrueTy, TrueName);
9508     else if (TrueTy.isNull())
9509       return std::make_pair(FalseTy, FalseName);
9510     else if (FalseTy.isNull())
9511       return std::make_pair(TrueTy, TrueName);
9512   }
9513 
9514   return std::make_pair(QualType(), StringRef());
9515 }
9516 
9517 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9518 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9519 /// type do not count.
9520 static bool
9521 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9522   QualType From = ICE->getSubExpr()->getType();
9523   QualType To = ICE->getType();
9524   // It's an integer promotion if the destination type is the promoted
9525   // source type.
9526   if (ICE->getCastKind() == CK_IntegralCast &&
9527       From->isPromotableIntegerType() &&
9528       S.Context.getPromotedIntegerType(From) == To)
9529     return true;
9530   // Look through vector types, since we do default argument promotion for
9531   // those in OpenCL.
9532   if (const auto *VecTy = From->getAs<ExtVectorType>())
9533     From = VecTy->getElementType();
9534   if (const auto *VecTy = To->getAs<ExtVectorType>())
9535     To = VecTy->getElementType();
9536   // It's a floating promotion if the source type is a lower rank.
9537   return ICE->getCastKind() == CK_FloatingCast &&
9538          S.Context.getFloatingTypeOrder(From, To) < 0;
9539 }
9540 
9541 bool
9542 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9543                                     const char *StartSpecifier,
9544                                     unsigned SpecifierLen,
9545                                     const Expr *E) {
9546   using namespace analyze_format_string;
9547   using namespace analyze_printf;
9548 
9549   // Now type check the data expression that matches the
9550   // format specifier.
9551   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9552   if (!AT.isValid())
9553     return true;
9554 
9555   QualType ExprTy = E->getType();
9556   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9557     ExprTy = TET->getUnderlyingExpr()->getType();
9558   }
9559 
9560   // Diagnose attempts to print a boolean value as a character. Unlike other
9561   // -Wformat diagnostics, this is fine from a type perspective, but it still
9562   // doesn't make sense.
9563   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9564       E->isKnownToHaveBooleanValue()) {
9565     const CharSourceRange &CSR =
9566         getSpecifierRange(StartSpecifier, SpecifierLen);
9567     SmallString<4> FSString;
9568     llvm::raw_svector_ostream os(FSString);
9569     FS.toString(os);
9570     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9571                              << FSString,
9572                          E->getExprLoc(), false, CSR);
9573     return true;
9574   }
9575 
9576   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9577   if (Match == analyze_printf::ArgType::Match)
9578     return true;
9579 
9580   // Look through argument promotions for our error message's reported type.
9581   // This includes the integral and floating promotions, but excludes array
9582   // and function pointer decay (seeing that an argument intended to be a
9583   // string has type 'char [6]' is probably more confusing than 'char *') and
9584   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9585   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9586     if (isArithmeticArgumentPromotion(S, ICE)) {
9587       E = ICE->getSubExpr();
9588       ExprTy = E->getType();
9589 
9590       // Check if we didn't match because of an implicit cast from a 'char'
9591       // or 'short' to an 'int'.  This is done because printf is a varargs
9592       // function.
9593       if (ICE->getType() == S.Context.IntTy ||
9594           ICE->getType() == S.Context.UnsignedIntTy) {
9595         // All further checking is done on the subexpression
9596         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9597             AT.matchesType(S.Context, ExprTy);
9598         if (ImplicitMatch == analyze_printf::ArgType::Match)
9599           return true;
9600         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9601             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9602           Match = ImplicitMatch;
9603       }
9604     }
9605   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9606     // Special case for 'a', which has type 'int' in C.
9607     // Note, however, that we do /not/ want to treat multibyte constants like
9608     // 'MooV' as characters! This form is deprecated but still exists. In
9609     // addition, don't treat expressions as of type 'char' if one byte length
9610     // modifier is provided.
9611     if (ExprTy == S.Context.IntTy &&
9612         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9613       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9614         ExprTy = S.Context.CharTy;
9615   }
9616 
9617   // Look through enums to their underlying type.
9618   bool IsEnum = false;
9619   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9620     ExprTy = EnumTy->getDecl()->getIntegerType();
9621     IsEnum = true;
9622   }
9623 
9624   // %C in an Objective-C context prints a unichar, not a wchar_t.
9625   // If the argument is an integer of some kind, believe the %C and suggest
9626   // a cast instead of changing the conversion specifier.
9627   QualType IntendedTy = ExprTy;
9628   if (isObjCContext() &&
9629       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9630     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9631         !ExprTy->isCharType()) {
9632       // 'unichar' is defined as a typedef of unsigned short, but we should
9633       // prefer using the typedef if it is visible.
9634       IntendedTy = S.Context.UnsignedShortTy;
9635 
9636       // While we are here, check if the value is an IntegerLiteral that happens
9637       // to be within the valid range.
9638       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9639         const llvm::APInt &V = IL->getValue();
9640         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9641           return true;
9642       }
9643 
9644       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9645                           Sema::LookupOrdinaryName);
9646       if (S.LookupName(Result, S.getCurScope())) {
9647         NamedDecl *ND = Result.getFoundDecl();
9648         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9649           if (TD->getUnderlyingType() == IntendedTy)
9650             IntendedTy = S.Context.getTypedefType(TD);
9651       }
9652     }
9653   }
9654 
9655   // Special-case some of Darwin's platform-independence types by suggesting
9656   // casts to primitive types that are known to be large enough.
9657   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9658   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9659     QualType CastTy;
9660     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9661     if (!CastTy.isNull()) {
9662       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9663       // (long in ASTContext). Only complain to pedants.
9664       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9665           (AT.isSizeT() || AT.isPtrdiffT()) &&
9666           AT.matchesType(S.Context, CastTy))
9667         Match = ArgType::NoMatchPedantic;
9668       IntendedTy = CastTy;
9669       ShouldNotPrintDirectly = true;
9670     }
9671   }
9672 
9673   // We may be able to offer a FixItHint if it is a supported type.
9674   PrintfSpecifier fixedFS = FS;
9675   bool Success =
9676       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9677 
9678   if (Success) {
9679     // Get the fix string from the fixed format specifier
9680     SmallString<16> buf;
9681     llvm::raw_svector_ostream os(buf);
9682     fixedFS.toString(os);
9683 
9684     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9685 
9686     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9687       unsigned Diag;
9688       switch (Match) {
9689       case ArgType::Match: llvm_unreachable("expected non-matching");
9690       case ArgType::NoMatchPedantic:
9691         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9692         break;
9693       case ArgType::NoMatchTypeConfusion:
9694         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9695         break;
9696       case ArgType::NoMatch:
9697         Diag = diag::warn_format_conversion_argument_type_mismatch;
9698         break;
9699       }
9700 
9701       // In this case, the specifier is wrong and should be changed to match
9702       // the argument.
9703       EmitFormatDiagnostic(S.PDiag(Diag)
9704                                << AT.getRepresentativeTypeName(S.Context)
9705                                << IntendedTy << IsEnum << E->getSourceRange(),
9706                            E->getBeginLoc(),
9707                            /*IsStringLocation*/ false, SpecRange,
9708                            FixItHint::CreateReplacement(SpecRange, os.str()));
9709     } else {
9710       // The canonical type for formatting this value is different from the
9711       // actual type of the expression. (This occurs, for example, with Darwin's
9712       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9713       // should be printed as 'long' for 64-bit compatibility.)
9714       // Rather than emitting a normal format/argument mismatch, we want to
9715       // add a cast to the recommended type (and correct the format string
9716       // if necessary).
9717       SmallString<16> CastBuf;
9718       llvm::raw_svector_ostream CastFix(CastBuf);
9719       CastFix << "(";
9720       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9721       CastFix << ")";
9722 
9723       SmallVector<FixItHint,4> Hints;
9724       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9725         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9726 
9727       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9728         // If there's already a cast present, just replace it.
9729         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9730         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9731 
9732       } else if (!requiresParensToAddCast(E)) {
9733         // If the expression has high enough precedence,
9734         // just write the C-style cast.
9735         Hints.push_back(
9736             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9737       } else {
9738         // Otherwise, add parens around the expression as well as the cast.
9739         CastFix << "(";
9740         Hints.push_back(
9741             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9742 
9743         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9744         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9745       }
9746 
9747       if (ShouldNotPrintDirectly) {
9748         // The expression has a type that should not be printed directly.
9749         // We extract the name from the typedef because we don't want to show
9750         // the underlying type in the diagnostic.
9751         StringRef Name;
9752         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9753           Name = TypedefTy->getDecl()->getName();
9754         else
9755           Name = CastTyName;
9756         unsigned Diag = Match == ArgType::NoMatchPedantic
9757                             ? diag::warn_format_argument_needs_cast_pedantic
9758                             : diag::warn_format_argument_needs_cast;
9759         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9760                                            << E->getSourceRange(),
9761                              E->getBeginLoc(), /*IsStringLocation=*/false,
9762                              SpecRange, Hints);
9763       } else {
9764         // In this case, the expression could be printed using a different
9765         // specifier, but we've decided that the specifier is probably correct
9766         // and we should cast instead. Just use the normal warning message.
9767         EmitFormatDiagnostic(
9768             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9769                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9770                 << E->getSourceRange(),
9771             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9772       }
9773     }
9774   } else {
9775     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9776                                                    SpecifierLen);
9777     // Since the warning for passing non-POD types to variadic functions
9778     // was deferred until now, we emit a warning for non-POD
9779     // arguments here.
9780     switch (S.isValidVarArgType(ExprTy)) {
9781     case Sema::VAK_Valid:
9782     case Sema::VAK_ValidInCXX11: {
9783       unsigned Diag;
9784       switch (Match) {
9785       case ArgType::Match: llvm_unreachable("expected non-matching");
9786       case ArgType::NoMatchPedantic:
9787         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9788         break;
9789       case ArgType::NoMatchTypeConfusion:
9790         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9791         break;
9792       case ArgType::NoMatch:
9793         Diag = diag::warn_format_conversion_argument_type_mismatch;
9794         break;
9795       }
9796 
9797       EmitFormatDiagnostic(
9798           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9799                         << IsEnum << CSR << E->getSourceRange(),
9800           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9801       break;
9802     }
9803     case Sema::VAK_Undefined:
9804     case Sema::VAK_MSVCUndefined:
9805       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9806                                << S.getLangOpts().CPlusPlus11 << ExprTy
9807                                << CallType
9808                                << AT.getRepresentativeTypeName(S.Context) << CSR
9809                                << E->getSourceRange(),
9810                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9811       checkForCStrMembers(AT, E);
9812       break;
9813 
9814     case Sema::VAK_Invalid:
9815       if (ExprTy->isObjCObjectType())
9816         EmitFormatDiagnostic(
9817             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9818                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9819                 << AT.getRepresentativeTypeName(S.Context) << CSR
9820                 << E->getSourceRange(),
9821             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9822       else
9823         // FIXME: If this is an initializer list, suggest removing the braces
9824         // or inserting a cast to the target type.
9825         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9826             << isa<InitListExpr>(E) << ExprTy << CallType
9827             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9828       break;
9829     }
9830 
9831     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9832            "format string specifier index out of range");
9833     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9834   }
9835 
9836   return true;
9837 }
9838 
9839 //===--- CHECK: Scanf format string checking ------------------------------===//
9840 
9841 namespace {
9842 
9843 class CheckScanfHandler : public CheckFormatHandler {
9844 public:
9845   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9846                     const Expr *origFormatExpr, Sema::FormatStringType type,
9847                     unsigned firstDataArg, unsigned numDataArgs,
9848                     const char *beg, bool hasVAListArg,
9849                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9850                     bool inFunctionCall, Sema::VariadicCallType CallType,
9851                     llvm::SmallBitVector &CheckedVarArgs,
9852                     UncoveredArgHandler &UncoveredArg)
9853       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9854                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9855                            inFunctionCall, CallType, CheckedVarArgs,
9856                            UncoveredArg) {}
9857 
9858   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9859                             const char *startSpecifier,
9860                             unsigned specifierLen) override;
9861 
9862   bool HandleInvalidScanfConversionSpecifier(
9863           const analyze_scanf::ScanfSpecifier &FS,
9864           const char *startSpecifier,
9865           unsigned specifierLen) override;
9866 
9867   void HandleIncompleteScanList(const char *start, const char *end) override;
9868 };
9869 
9870 } // namespace
9871 
9872 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9873                                                  const char *end) {
9874   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9875                        getLocationOfByte(end), /*IsStringLocation*/true,
9876                        getSpecifierRange(start, end - start));
9877 }
9878 
9879 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9880                                         const analyze_scanf::ScanfSpecifier &FS,
9881                                         const char *startSpecifier,
9882                                         unsigned specifierLen) {
9883   const analyze_scanf::ScanfConversionSpecifier &CS =
9884     FS.getConversionSpecifier();
9885 
9886   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9887                                           getLocationOfByte(CS.getStart()),
9888                                           startSpecifier, specifierLen,
9889                                           CS.getStart(), CS.getLength());
9890 }
9891 
9892 bool CheckScanfHandler::HandleScanfSpecifier(
9893                                        const analyze_scanf::ScanfSpecifier &FS,
9894                                        const char *startSpecifier,
9895                                        unsigned specifierLen) {
9896   using namespace analyze_scanf;
9897   using namespace analyze_format_string;
9898 
9899   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9900 
9901   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9902   // be used to decide if we are using positional arguments consistently.
9903   if (FS.consumesDataArgument()) {
9904     if (atFirstArg) {
9905       atFirstArg = false;
9906       usesPositionalArgs = FS.usesPositionalArg();
9907     }
9908     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9909       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9910                                         startSpecifier, specifierLen);
9911       return false;
9912     }
9913   }
9914 
9915   // Check if the field with is non-zero.
9916   const OptionalAmount &Amt = FS.getFieldWidth();
9917   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9918     if (Amt.getConstantAmount() == 0) {
9919       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9920                                                    Amt.getConstantLength());
9921       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9922                            getLocationOfByte(Amt.getStart()),
9923                            /*IsStringLocation*/true, R,
9924                            FixItHint::CreateRemoval(R));
9925     }
9926   }
9927 
9928   if (!FS.consumesDataArgument()) {
9929     // FIXME: Technically specifying a precision or field width here
9930     // makes no sense.  Worth issuing a warning at some point.
9931     return true;
9932   }
9933 
9934   // Consume the argument.
9935   unsigned argIndex = FS.getArgIndex();
9936   if (argIndex < NumDataArgs) {
9937       // The check to see if the argIndex is valid will come later.
9938       // We set the bit here because we may exit early from this
9939       // function if we encounter some other error.
9940     CoveredArgs.set(argIndex);
9941   }
9942 
9943   // Check the length modifier is valid with the given conversion specifier.
9944   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9945                                  S.getLangOpts()))
9946     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9947                                 diag::warn_format_nonsensical_length);
9948   else if (!FS.hasStandardLengthModifier())
9949     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9950   else if (!FS.hasStandardLengthConversionCombination())
9951     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9952                                 diag::warn_format_non_standard_conversion_spec);
9953 
9954   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9955     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9956 
9957   // The remaining checks depend on the data arguments.
9958   if (HasVAListArg)
9959     return true;
9960 
9961   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9962     return false;
9963 
9964   // Check that the argument type matches the format specifier.
9965   const Expr *Ex = getDataArg(argIndex);
9966   if (!Ex)
9967     return true;
9968 
9969   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9970 
9971   if (!AT.isValid()) {
9972     return true;
9973   }
9974 
9975   analyze_format_string::ArgType::MatchKind Match =
9976       AT.matchesType(S.Context, Ex->getType());
9977   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9978   if (Match == analyze_format_string::ArgType::Match)
9979     return true;
9980 
9981   ScanfSpecifier fixedFS = FS;
9982   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9983                                  S.getLangOpts(), S.Context);
9984 
9985   unsigned Diag =
9986       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9987                : diag::warn_format_conversion_argument_type_mismatch;
9988 
9989   if (Success) {
9990     // Get the fix string from the fixed format specifier.
9991     SmallString<128> buf;
9992     llvm::raw_svector_ostream os(buf);
9993     fixedFS.toString(os);
9994 
9995     EmitFormatDiagnostic(
9996         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9997                       << Ex->getType() << false << Ex->getSourceRange(),
9998         Ex->getBeginLoc(),
9999         /*IsStringLocation*/ false,
10000         getSpecifierRange(startSpecifier, specifierLen),
10001         FixItHint::CreateReplacement(
10002             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10003   } else {
10004     EmitFormatDiagnostic(S.PDiag(Diag)
10005                              << AT.getRepresentativeTypeName(S.Context)
10006                              << Ex->getType() << false << Ex->getSourceRange(),
10007                          Ex->getBeginLoc(),
10008                          /*IsStringLocation*/ false,
10009                          getSpecifierRange(startSpecifier, specifierLen));
10010   }
10011 
10012   return true;
10013 }
10014 
10015 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10016                               const Expr *OrigFormatExpr,
10017                               ArrayRef<const Expr *> Args,
10018                               bool HasVAListArg, unsigned format_idx,
10019                               unsigned firstDataArg,
10020                               Sema::FormatStringType Type,
10021                               bool inFunctionCall,
10022                               Sema::VariadicCallType CallType,
10023                               llvm::SmallBitVector &CheckedVarArgs,
10024                               UncoveredArgHandler &UncoveredArg,
10025                               bool IgnoreStringsWithoutSpecifiers) {
10026   // CHECK: is the format string a wide literal?
10027   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10028     CheckFormatHandler::EmitFormatDiagnostic(
10029         S, inFunctionCall, Args[format_idx],
10030         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10031         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10032     return;
10033   }
10034 
10035   // Str - The format string.  NOTE: this is NOT null-terminated!
10036   StringRef StrRef = FExpr->getString();
10037   const char *Str = StrRef.data();
10038   // Account for cases where the string literal is truncated in a declaration.
10039   const ConstantArrayType *T =
10040     S.Context.getAsConstantArrayType(FExpr->getType());
10041   assert(T && "String literal not of constant array type!");
10042   size_t TypeSize = T->getSize().getZExtValue();
10043   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10044   const unsigned numDataArgs = Args.size() - firstDataArg;
10045 
10046   if (IgnoreStringsWithoutSpecifiers &&
10047       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10048           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10049     return;
10050 
10051   // Emit a warning if the string literal is truncated and does not contain an
10052   // embedded null character.
10053   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10054     CheckFormatHandler::EmitFormatDiagnostic(
10055         S, inFunctionCall, Args[format_idx],
10056         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10057         FExpr->getBeginLoc(),
10058         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10059     return;
10060   }
10061 
10062   // CHECK: empty format string?
10063   if (StrLen == 0 && numDataArgs > 0) {
10064     CheckFormatHandler::EmitFormatDiagnostic(
10065         S, inFunctionCall, Args[format_idx],
10066         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10067         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10068     return;
10069   }
10070 
10071   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10072       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10073       Type == Sema::FST_OSTrace) {
10074     CheckPrintfHandler H(
10075         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10076         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10077         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10078         CheckedVarArgs, UncoveredArg);
10079 
10080     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10081                                                   S.getLangOpts(),
10082                                                   S.Context.getTargetInfo(),
10083                                             Type == Sema::FST_FreeBSDKPrintf))
10084       H.DoneProcessing();
10085   } else if (Type == Sema::FST_Scanf) {
10086     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10087                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10088                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10089 
10090     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10091                                                  S.getLangOpts(),
10092                                                  S.Context.getTargetInfo()))
10093       H.DoneProcessing();
10094   } // TODO: handle other formats
10095 }
10096 
10097 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10098   // Str - The format string.  NOTE: this is NOT null-terminated!
10099   StringRef StrRef = FExpr->getString();
10100   const char *Str = StrRef.data();
10101   // Account for cases where the string literal is truncated in a declaration.
10102   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10103   assert(T && "String literal not of constant array type!");
10104   size_t TypeSize = T->getSize().getZExtValue();
10105   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10106   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10107                                                          getLangOpts(),
10108                                                          Context.getTargetInfo());
10109 }
10110 
10111 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10112 
10113 // Returns the related absolute value function that is larger, of 0 if one
10114 // does not exist.
10115 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10116   switch (AbsFunction) {
10117   default:
10118     return 0;
10119 
10120   case Builtin::BI__builtin_abs:
10121     return Builtin::BI__builtin_labs;
10122   case Builtin::BI__builtin_labs:
10123     return Builtin::BI__builtin_llabs;
10124   case Builtin::BI__builtin_llabs:
10125     return 0;
10126 
10127   case Builtin::BI__builtin_fabsf:
10128     return Builtin::BI__builtin_fabs;
10129   case Builtin::BI__builtin_fabs:
10130     return Builtin::BI__builtin_fabsl;
10131   case Builtin::BI__builtin_fabsl:
10132     return 0;
10133 
10134   case Builtin::BI__builtin_cabsf:
10135     return Builtin::BI__builtin_cabs;
10136   case Builtin::BI__builtin_cabs:
10137     return Builtin::BI__builtin_cabsl;
10138   case Builtin::BI__builtin_cabsl:
10139     return 0;
10140 
10141   case Builtin::BIabs:
10142     return Builtin::BIlabs;
10143   case Builtin::BIlabs:
10144     return Builtin::BIllabs;
10145   case Builtin::BIllabs:
10146     return 0;
10147 
10148   case Builtin::BIfabsf:
10149     return Builtin::BIfabs;
10150   case Builtin::BIfabs:
10151     return Builtin::BIfabsl;
10152   case Builtin::BIfabsl:
10153     return 0;
10154 
10155   case Builtin::BIcabsf:
10156    return Builtin::BIcabs;
10157   case Builtin::BIcabs:
10158     return Builtin::BIcabsl;
10159   case Builtin::BIcabsl:
10160     return 0;
10161   }
10162 }
10163 
10164 // Returns the argument type of the absolute value function.
10165 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10166                                              unsigned AbsType) {
10167   if (AbsType == 0)
10168     return QualType();
10169 
10170   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10171   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10172   if (Error != ASTContext::GE_None)
10173     return QualType();
10174 
10175   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10176   if (!FT)
10177     return QualType();
10178 
10179   if (FT->getNumParams() != 1)
10180     return QualType();
10181 
10182   return FT->getParamType(0);
10183 }
10184 
10185 // Returns the best absolute value function, or zero, based on type and
10186 // current absolute value function.
10187 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10188                                    unsigned AbsFunctionKind) {
10189   unsigned BestKind = 0;
10190   uint64_t ArgSize = Context.getTypeSize(ArgType);
10191   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10192        Kind = getLargerAbsoluteValueFunction(Kind)) {
10193     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10194     if (Context.getTypeSize(ParamType) >= ArgSize) {
10195       if (BestKind == 0)
10196         BestKind = Kind;
10197       else if (Context.hasSameType(ParamType, ArgType)) {
10198         BestKind = Kind;
10199         break;
10200       }
10201     }
10202   }
10203   return BestKind;
10204 }
10205 
10206 enum AbsoluteValueKind {
10207   AVK_Integer,
10208   AVK_Floating,
10209   AVK_Complex
10210 };
10211 
10212 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10213   if (T->isIntegralOrEnumerationType())
10214     return AVK_Integer;
10215   if (T->isRealFloatingType())
10216     return AVK_Floating;
10217   if (T->isAnyComplexType())
10218     return AVK_Complex;
10219 
10220   llvm_unreachable("Type not integer, floating, or complex");
10221 }
10222 
10223 // Changes the absolute value function to a different type.  Preserves whether
10224 // the function is a builtin.
10225 static unsigned changeAbsFunction(unsigned AbsKind,
10226                                   AbsoluteValueKind ValueKind) {
10227   switch (ValueKind) {
10228   case AVK_Integer:
10229     switch (AbsKind) {
10230     default:
10231       return 0;
10232     case Builtin::BI__builtin_fabsf:
10233     case Builtin::BI__builtin_fabs:
10234     case Builtin::BI__builtin_fabsl:
10235     case Builtin::BI__builtin_cabsf:
10236     case Builtin::BI__builtin_cabs:
10237     case Builtin::BI__builtin_cabsl:
10238       return Builtin::BI__builtin_abs;
10239     case Builtin::BIfabsf:
10240     case Builtin::BIfabs:
10241     case Builtin::BIfabsl:
10242     case Builtin::BIcabsf:
10243     case Builtin::BIcabs:
10244     case Builtin::BIcabsl:
10245       return Builtin::BIabs;
10246     }
10247   case AVK_Floating:
10248     switch (AbsKind) {
10249     default:
10250       return 0;
10251     case Builtin::BI__builtin_abs:
10252     case Builtin::BI__builtin_labs:
10253     case Builtin::BI__builtin_llabs:
10254     case Builtin::BI__builtin_cabsf:
10255     case Builtin::BI__builtin_cabs:
10256     case Builtin::BI__builtin_cabsl:
10257       return Builtin::BI__builtin_fabsf;
10258     case Builtin::BIabs:
10259     case Builtin::BIlabs:
10260     case Builtin::BIllabs:
10261     case Builtin::BIcabsf:
10262     case Builtin::BIcabs:
10263     case Builtin::BIcabsl:
10264       return Builtin::BIfabsf;
10265     }
10266   case AVK_Complex:
10267     switch (AbsKind) {
10268     default:
10269       return 0;
10270     case Builtin::BI__builtin_abs:
10271     case Builtin::BI__builtin_labs:
10272     case Builtin::BI__builtin_llabs:
10273     case Builtin::BI__builtin_fabsf:
10274     case Builtin::BI__builtin_fabs:
10275     case Builtin::BI__builtin_fabsl:
10276       return Builtin::BI__builtin_cabsf;
10277     case Builtin::BIabs:
10278     case Builtin::BIlabs:
10279     case Builtin::BIllabs:
10280     case Builtin::BIfabsf:
10281     case Builtin::BIfabs:
10282     case Builtin::BIfabsl:
10283       return Builtin::BIcabsf;
10284     }
10285   }
10286   llvm_unreachable("Unable to convert function");
10287 }
10288 
10289 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10290   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10291   if (!FnInfo)
10292     return 0;
10293 
10294   switch (FDecl->getBuiltinID()) {
10295   default:
10296     return 0;
10297   case Builtin::BI__builtin_abs:
10298   case Builtin::BI__builtin_fabs:
10299   case Builtin::BI__builtin_fabsf:
10300   case Builtin::BI__builtin_fabsl:
10301   case Builtin::BI__builtin_labs:
10302   case Builtin::BI__builtin_llabs:
10303   case Builtin::BI__builtin_cabs:
10304   case Builtin::BI__builtin_cabsf:
10305   case Builtin::BI__builtin_cabsl:
10306   case Builtin::BIabs:
10307   case Builtin::BIlabs:
10308   case Builtin::BIllabs:
10309   case Builtin::BIfabs:
10310   case Builtin::BIfabsf:
10311   case Builtin::BIfabsl:
10312   case Builtin::BIcabs:
10313   case Builtin::BIcabsf:
10314   case Builtin::BIcabsl:
10315     return FDecl->getBuiltinID();
10316   }
10317   llvm_unreachable("Unknown Builtin type");
10318 }
10319 
10320 // If the replacement is valid, emit a note with replacement function.
10321 // Additionally, suggest including the proper header if not already included.
10322 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10323                             unsigned AbsKind, QualType ArgType) {
10324   bool EmitHeaderHint = true;
10325   const char *HeaderName = nullptr;
10326   const char *FunctionName = nullptr;
10327   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10328     FunctionName = "std::abs";
10329     if (ArgType->isIntegralOrEnumerationType()) {
10330       HeaderName = "cstdlib";
10331     } else if (ArgType->isRealFloatingType()) {
10332       HeaderName = "cmath";
10333     } else {
10334       llvm_unreachable("Invalid Type");
10335     }
10336 
10337     // Lookup all std::abs
10338     if (NamespaceDecl *Std = S.getStdNamespace()) {
10339       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10340       R.suppressDiagnostics();
10341       S.LookupQualifiedName(R, Std);
10342 
10343       for (const auto *I : R) {
10344         const FunctionDecl *FDecl = nullptr;
10345         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10346           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10347         } else {
10348           FDecl = dyn_cast<FunctionDecl>(I);
10349         }
10350         if (!FDecl)
10351           continue;
10352 
10353         // Found std::abs(), check that they are the right ones.
10354         if (FDecl->getNumParams() != 1)
10355           continue;
10356 
10357         // Check that the parameter type can handle the argument.
10358         QualType ParamType = FDecl->getParamDecl(0)->getType();
10359         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10360             S.Context.getTypeSize(ArgType) <=
10361                 S.Context.getTypeSize(ParamType)) {
10362           // Found a function, don't need the header hint.
10363           EmitHeaderHint = false;
10364           break;
10365         }
10366       }
10367     }
10368   } else {
10369     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10370     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10371 
10372     if (HeaderName) {
10373       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10374       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10375       R.suppressDiagnostics();
10376       S.LookupName(R, S.getCurScope());
10377 
10378       if (R.isSingleResult()) {
10379         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10380         if (FD && FD->getBuiltinID() == AbsKind) {
10381           EmitHeaderHint = false;
10382         } else {
10383           return;
10384         }
10385       } else if (!R.empty()) {
10386         return;
10387       }
10388     }
10389   }
10390 
10391   S.Diag(Loc, diag::note_replace_abs_function)
10392       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10393 
10394   if (!HeaderName)
10395     return;
10396 
10397   if (!EmitHeaderHint)
10398     return;
10399 
10400   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10401                                                     << FunctionName;
10402 }
10403 
10404 template <std::size_t StrLen>
10405 static bool IsStdFunction(const FunctionDecl *FDecl,
10406                           const char (&Str)[StrLen]) {
10407   if (!FDecl)
10408     return false;
10409   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10410     return false;
10411   if (!FDecl->isInStdNamespace())
10412     return false;
10413 
10414   return true;
10415 }
10416 
10417 // Warn when using the wrong abs() function.
10418 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10419                                       const FunctionDecl *FDecl) {
10420   if (Call->getNumArgs() != 1)
10421     return;
10422 
10423   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10424   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10425   if (AbsKind == 0 && !IsStdAbs)
10426     return;
10427 
10428   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10429   QualType ParamType = Call->getArg(0)->getType();
10430 
10431   // Unsigned types cannot be negative.  Suggest removing the absolute value
10432   // function call.
10433   if (ArgType->isUnsignedIntegerType()) {
10434     const char *FunctionName =
10435         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10436     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10437     Diag(Call->getExprLoc(), diag::note_remove_abs)
10438         << FunctionName
10439         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10440     return;
10441   }
10442 
10443   // Taking the absolute value of a pointer is very suspicious, they probably
10444   // wanted to index into an array, dereference a pointer, call a function, etc.
10445   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10446     unsigned DiagType = 0;
10447     if (ArgType->isFunctionType())
10448       DiagType = 1;
10449     else if (ArgType->isArrayType())
10450       DiagType = 2;
10451 
10452     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10453     return;
10454   }
10455 
10456   // std::abs has overloads which prevent most of the absolute value problems
10457   // from occurring.
10458   if (IsStdAbs)
10459     return;
10460 
10461   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10462   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10463 
10464   // The argument and parameter are the same kind.  Check if they are the right
10465   // size.
10466   if (ArgValueKind == ParamValueKind) {
10467     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10468       return;
10469 
10470     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10471     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10472         << FDecl << ArgType << ParamType;
10473 
10474     if (NewAbsKind == 0)
10475       return;
10476 
10477     emitReplacement(*this, Call->getExprLoc(),
10478                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10479     return;
10480   }
10481 
10482   // ArgValueKind != ParamValueKind
10483   // The wrong type of absolute value function was used.  Attempt to find the
10484   // proper one.
10485   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10486   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10487   if (NewAbsKind == 0)
10488     return;
10489 
10490   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10491       << FDecl << ParamValueKind << ArgValueKind;
10492 
10493   emitReplacement(*this, Call->getExprLoc(),
10494                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10495 }
10496 
10497 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10498 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10499                                 const FunctionDecl *FDecl) {
10500   if (!Call || !FDecl) return;
10501 
10502   // Ignore template specializations and macros.
10503   if (inTemplateInstantiation()) return;
10504   if (Call->getExprLoc().isMacroID()) return;
10505 
10506   // Only care about the one template argument, two function parameter std::max
10507   if (Call->getNumArgs() != 2) return;
10508   if (!IsStdFunction(FDecl, "max")) return;
10509   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10510   if (!ArgList) return;
10511   if (ArgList->size() != 1) return;
10512 
10513   // Check that template type argument is unsigned integer.
10514   const auto& TA = ArgList->get(0);
10515   if (TA.getKind() != TemplateArgument::Type) return;
10516   QualType ArgType = TA.getAsType();
10517   if (!ArgType->isUnsignedIntegerType()) return;
10518 
10519   // See if either argument is a literal zero.
10520   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10521     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10522     if (!MTE) return false;
10523     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10524     if (!Num) return false;
10525     if (Num->getValue() != 0) return false;
10526     return true;
10527   };
10528 
10529   const Expr *FirstArg = Call->getArg(0);
10530   const Expr *SecondArg = Call->getArg(1);
10531   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10532   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10533 
10534   // Only warn when exactly one argument is zero.
10535   if (IsFirstArgZero == IsSecondArgZero) return;
10536 
10537   SourceRange FirstRange = FirstArg->getSourceRange();
10538   SourceRange SecondRange = SecondArg->getSourceRange();
10539 
10540   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10541 
10542   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10543       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10544 
10545   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10546   SourceRange RemovalRange;
10547   if (IsFirstArgZero) {
10548     RemovalRange = SourceRange(FirstRange.getBegin(),
10549                                SecondRange.getBegin().getLocWithOffset(-1));
10550   } else {
10551     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10552                                SecondRange.getEnd());
10553   }
10554 
10555   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10556         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10557         << FixItHint::CreateRemoval(RemovalRange);
10558 }
10559 
10560 //===--- CHECK: Standard memory functions ---------------------------------===//
10561 
10562 /// Takes the expression passed to the size_t parameter of functions
10563 /// such as memcmp, strncat, etc and warns if it's a comparison.
10564 ///
10565 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10566 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10567                                            IdentifierInfo *FnName,
10568                                            SourceLocation FnLoc,
10569                                            SourceLocation RParenLoc) {
10570   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10571   if (!Size)
10572     return false;
10573 
10574   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10575   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10576     return false;
10577 
10578   SourceRange SizeRange = Size->getSourceRange();
10579   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10580       << SizeRange << FnName;
10581   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10582       << FnName
10583       << FixItHint::CreateInsertion(
10584              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10585       << FixItHint::CreateRemoval(RParenLoc);
10586   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10587       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10588       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10589                                     ")");
10590 
10591   return true;
10592 }
10593 
10594 /// Determine whether the given type is or contains a dynamic class type
10595 /// (e.g., whether it has a vtable).
10596 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10597                                                      bool &IsContained) {
10598   // Look through array types while ignoring qualifiers.
10599   const Type *Ty = T->getBaseElementTypeUnsafe();
10600   IsContained = false;
10601 
10602   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10603   RD = RD ? RD->getDefinition() : nullptr;
10604   if (!RD || RD->isInvalidDecl())
10605     return nullptr;
10606 
10607   if (RD->isDynamicClass())
10608     return RD;
10609 
10610   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10611   // It's impossible for a class to transitively contain itself by value, so
10612   // infinite recursion is impossible.
10613   for (auto *FD : RD->fields()) {
10614     bool SubContained;
10615     if (const CXXRecordDecl *ContainedRD =
10616             getContainedDynamicClass(FD->getType(), SubContained)) {
10617       IsContained = true;
10618       return ContainedRD;
10619     }
10620   }
10621 
10622   return nullptr;
10623 }
10624 
10625 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10626   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10627     if (Unary->getKind() == UETT_SizeOf)
10628       return Unary;
10629   return nullptr;
10630 }
10631 
10632 /// If E is a sizeof expression, returns its argument expression,
10633 /// otherwise returns NULL.
10634 static const Expr *getSizeOfExprArg(const Expr *E) {
10635   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10636     if (!SizeOf->isArgumentType())
10637       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10638   return nullptr;
10639 }
10640 
10641 /// If E is a sizeof expression, returns its argument type.
10642 static QualType getSizeOfArgType(const Expr *E) {
10643   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10644     return SizeOf->getTypeOfArgument();
10645   return QualType();
10646 }
10647 
10648 namespace {
10649 
10650 struct SearchNonTrivialToInitializeField
10651     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10652   using Super =
10653       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10654 
10655   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10656 
10657   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10658                      SourceLocation SL) {
10659     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10660       asDerived().visitArray(PDIK, AT, SL);
10661       return;
10662     }
10663 
10664     Super::visitWithKind(PDIK, FT, SL);
10665   }
10666 
10667   void visitARCStrong(QualType FT, SourceLocation SL) {
10668     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10669   }
10670   void visitARCWeak(QualType FT, SourceLocation SL) {
10671     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10672   }
10673   void visitStruct(QualType FT, SourceLocation SL) {
10674     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10675       visit(FD->getType(), FD->getLocation());
10676   }
10677   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10678                   const ArrayType *AT, SourceLocation SL) {
10679     visit(getContext().getBaseElementType(AT), SL);
10680   }
10681   void visitTrivial(QualType FT, SourceLocation SL) {}
10682 
10683   static void diag(QualType RT, const Expr *E, Sema &S) {
10684     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10685   }
10686 
10687   ASTContext &getContext() { return S.getASTContext(); }
10688 
10689   const Expr *E;
10690   Sema &S;
10691 };
10692 
10693 struct SearchNonTrivialToCopyField
10694     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10695   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10696 
10697   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10698 
10699   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10700                      SourceLocation SL) {
10701     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10702       asDerived().visitArray(PCK, AT, SL);
10703       return;
10704     }
10705 
10706     Super::visitWithKind(PCK, FT, SL);
10707   }
10708 
10709   void visitARCStrong(QualType FT, SourceLocation SL) {
10710     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10711   }
10712   void visitARCWeak(QualType FT, SourceLocation SL) {
10713     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10714   }
10715   void visitStruct(QualType FT, SourceLocation SL) {
10716     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10717       visit(FD->getType(), FD->getLocation());
10718   }
10719   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10720                   SourceLocation SL) {
10721     visit(getContext().getBaseElementType(AT), SL);
10722   }
10723   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10724                 SourceLocation SL) {}
10725   void visitTrivial(QualType FT, SourceLocation SL) {}
10726   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10727 
10728   static void diag(QualType RT, const Expr *E, Sema &S) {
10729     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10730   }
10731 
10732   ASTContext &getContext() { return S.getASTContext(); }
10733 
10734   const Expr *E;
10735   Sema &S;
10736 };
10737 
10738 }
10739 
10740 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10741 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10742   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10743 
10744   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10745     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10746       return false;
10747 
10748     return doesExprLikelyComputeSize(BO->getLHS()) ||
10749            doesExprLikelyComputeSize(BO->getRHS());
10750   }
10751 
10752   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10753 }
10754 
10755 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10756 ///
10757 /// \code
10758 ///   #define MACRO 0
10759 ///   foo(MACRO);
10760 ///   foo(0);
10761 /// \endcode
10762 ///
10763 /// This should return true for the first call to foo, but not for the second
10764 /// (regardless of whether foo is a macro or function).
10765 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10766                                         SourceLocation CallLoc,
10767                                         SourceLocation ArgLoc) {
10768   if (!CallLoc.isMacroID())
10769     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10770 
10771   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10772          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10773 }
10774 
10775 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10776 /// last two arguments transposed.
10777 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10778   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10779     return;
10780 
10781   const Expr *SizeArg =
10782     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10783 
10784   auto isLiteralZero = [](const Expr *E) {
10785     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10786   };
10787 
10788   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10789   SourceLocation CallLoc = Call->getRParenLoc();
10790   SourceManager &SM = S.getSourceManager();
10791   if (isLiteralZero(SizeArg) &&
10792       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10793 
10794     SourceLocation DiagLoc = SizeArg->getExprLoc();
10795 
10796     // Some platforms #define bzero to __builtin_memset. See if this is the
10797     // case, and if so, emit a better diagnostic.
10798     if (BId == Builtin::BIbzero ||
10799         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10800                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10801       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10802       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10803     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10804       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10805       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10806     }
10807     return;
10808   }
10809 
10810   // If the second argument to a memset is a sizeof expression and the third
10811   // isn't, this is also likely an error. This should catch
10812   // 'memset(buf, sizeof(buf), 0xff)'.
10813   if (BId == Builtin::BImemset &&
10814       doesExprLikelyComputeSize(Call->getArg(1)) &&
10815       !doesExprLikelyComputeSize(Call->getArg(2))) {
10816     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10817     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10818     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10819     return;
10820   }
10821 }
10822 
10823 /// Check for dangerous or invalid arguments to memset().
10824 ///
10825 /// This issues warnings on known problematic, dangerous or unspecified
10826 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10827 /// function calls.
10828 ///
10829 /// \param Call The call expression to diagnose.
10830 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10831                                    unsigned BId,
10832                                    IdentifierInfo *FnName) {
10833   assert(BId != 0);
10834 
10835   // It is possible to have a non-standard definition of memset.  Validate
10836   // we have enough arguments, and if not, abort further checking.
10837   unsigned ExpectedNumArgs =
10838       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10839   if (Call->getNumArgs() < ExpectedNumArgs)
10840     return;
10841 
10842   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10843                       BId == Builtin::BIstrndup ? 1 : 2);
10844   unsigned LenArg =
10845       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10846   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10847 
10848   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10849                                      Call->getBeginLoc(), Call->getRParenLoc()))
10850     return;
10851 
10852   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10853   CheckMemaccessSize(*this, BId, Call);
10854 
10855   // We have special checking when the length is a sizeof expression.
10856   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10857   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10858   llvm::FoldingSetNodeID SizeOfArgID;
10859 
10860   // Although widely used, 'bzero' is not a standard function. Be more strict
10861   // with the argument types before allowing diagnostics and only allow the
10862   // form bzero(ptr, sizeof(...)).
10863   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10864   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10865     return;
10866 
10867   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10868     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10869     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10870 
10871     QualType DestTy = Dest->getType();
10872     QualType PointeeTy;
10873     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10874       PointeeTy = DestPtrTy->getPointeeType();
10875 
10876       // Never warn about void type pointers. This can be used to suppress
10877       // false positives.
10878       if (PointeeTy->isVoidType())
10879         continue;
10880 
10881       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10882       // actually comparing the expressions for equality. Because computing the
10883       // expression IDs can be expensive, we only do this if the diagnostic is
10884       // enabled.
10885       if (SizeOfArg &&
10886           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10887                            SizeOfArg->getExprLoc())) {
10888         // We only compute IDs for expressions if the warning is enabled, and
10889         // cache the sizeof arg's ID.
10890         if (SizeOfArgID == llvm::FoldingSetNodeID())
10891           SizeOfArg->Profile(SizeOfArgID, Context, true);
10892         llvm::FoldingSetNodeID DestID;
10893         Dest->Profile(DestID, Context, true);
10894         if (DestID == SizeOfArgID) {
10895           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10896           //       over sizeof(src) as well.
10897           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10898           StringRef ReadableName = FnName->getName();
10899 
10900           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10901             if (UnaryOp->getOpcode() == UO_AddrOf)
10902               ActionIdx = 1; // If its an address-of operator, just remove it.
10903           if (!PointeeTy->isIncompleteType() &&
10904               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10905             ActionIdx = 2; // If the pointee's size is sizeof(char),
10906                            // suggest an explicit length.
10907 
10908           // If the function is defined as a builtin macro, do not show macro
10909           // expansion.
10910           SourceLocation SL = SizeOfArg->getExprLoc();
10911           SourceRange DSR = Dest->getSourceRange();
10912           SourceRange SSR = SizeOfArg->getSourceRange();
10913           SourceManager &SM = getSourceManager();
10914 
10915           if (SM.isMacroArgExpansion(SL)) {
10916             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10917             SL = SM.getSpellingLoc(SL);
10918             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10919                              SM.getSpellingLoc(DSR.getEnd()));
10920             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10921                              SM.getSpellingLoc(SSR.getEnd()));
10922           }
10923 
10924           DiagRuntimeBehavior(SL, SizeOfArg,
10925                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10926                                 << ReadableName
10927                                 << PointeeTy
10928                                 << DestTy
10929                                 << DSR
10930                                 << SSR);
10931           DiagRuntimeBehavior(SL, SizeOfArg,
10932                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10933                                 << ActionIdx
10934                                 << SSR);
10935 
10936           break;
10937         }
10938       }
10939 
10940       // Also check for cases where the sizeof argument is the exact same
10941       // type as the memory argument, and where it points to a user-defined
10942       // record type.
10943       if (SizeOfArgTy != QualType()) {
10944         if (PointeeTy->isRecordType() &&
10945             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10946           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10947                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10948                                 << FnName << SizeOfArgTy << ArgIdx
10949                                 << PointeeTy << Dest->getSourceRange()
10950                                 << LenExpr->getSourceRange());
10951           break;
10952         }
10953       }
10954     } else if (DestTy->isArrayType()) {
10955       PointeeTy = DestTy;
10956     }
10957 
10958     if (PointeeTy == QualType())
10959       continue;
10960 
10961     // Always complain about dynamic classes.
10962     bool IsContained;
10963     if (const CXXRecordDecl *ContainedRD =
10964             getContainedDynamicClass(PointeeTy, IsContained)) {
10965 
10966       unsigned OperationType = 0;
10967       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10968       // "overwritten" if we're warning about the destination for any call
10969       // but memcmp; otherwise a verb appropriate to the call.
10970       if (ArgIdx != 0 || IsCmp) {
10971         if (BId == Builtin::BImemcpy)
10972           OperationType = 1;
10973         else if(BId == Builtin::BImemmove)
10974           OperationType = 2;
10975         else if (IsCmp)
10976           OperationType = 3;
10977       }
10978 
10979       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10980                           PDiag(diag::warn_dyn_class_memaccess)
10981                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10982                               << IsContained << ContainedRD << OperationType
10983                               << Call->getCallee()->getSourceRange());
10984     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10985              BId != Builtin::BImemset)
10986       DiagRuntimeBehavior(
10987         Dest->getExprLoc(), Dest,
10988         PDiag(diag::warn_arc_object_memaccess)
10989           << ArgIdx << FnName << PointeeTy
10990           << Call->getCallee()->getSourceRange());
10991     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10992       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10993           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10994         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10995                             PDiag(diag::warn_cstruct_memaccess)
10996                                 << ArgIdx << FnName << PointeeTy << 0);
10997         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10998       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10999                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11000         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11001                             PDiag(diag::warn_cstruct_memaccess)
11002                                 << ArgIdx << FnName << PointeeTy << 1);
11003         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11004       } else {
11005         continue;
11006       }
11007     } else
11008       continue;
11009 
11010     DiagRuntimeBehavior(
11011       Dest->getExprLoc(), Dest,
11012       PDiag(diag::note_bad_memaccess_silence)
11013         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11014     break;
11015   }
11016 }
11017 
11018 // A little helper routine: ignore addition and subtraction of integer literals.
11019 // This intentionally does not ignore all integer constant expressions because
11020 // we don't want to remove sizeof().
11021 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11022   Ex = Ex->IgnoreParenCasts();
11023 
11024   while (true) {
11025     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11026     if (!BO || !BO->isAdditiveOp())
11027       break;
11028 
11029     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11030     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11031 
11032     if (isa<IntegerLiteral>(RHS))
11033       Ex = LHS;
11034     else if (isa<IntegerLiteral>(LHS))
11035       Ex = RHS;
11036     else
11037       break;
11038   }
11039 
11040   return Ex;
11041 }
11042 
11043 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11044                                                       ASTContext &Context) {
11045   // Only handle constant-sized or VLAs, but not flexible members.
11046   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11047     // Only issue the FIXIT for arrays of size > 1.
11048     if (CAT->getSize().getSExtValue() <= 1)
11049       return false;
11050   } else if (!Ty->isVariableArrayType()) {
11051     return false;
11052   }
11053   return true;
11054 }
11055 
11056 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11057 // be the size of the source, instead of the destination.
11058 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11059                                     IdentifierInfo *FnName) {
11060 
11061   // Don't crash if the user has the wrong number of arguments
11062   unsigned NumArgs = Call->getNumArgs();
11063   if ((NumArgs != 3) && (NumArgs != 4))
11064     return;
11065 
11066   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11067   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11068   const Expr *CompareWithSrc = nullptr;
11069 
11070   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11071                                      Call->getBeginLoc(), Call->getRParenLoc()))
11072     return;
11073 
11074   // Look for 'strlcpy(dst, x, sizeof(x))'
11075   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11076     CompareWithSrc = Ex;
11077   else {
11078     // Look for 'strlcpy(dst, x, strlen(x))'
11079     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11080       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11081           SizeCall->getNumArgs() == 1)
11082         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11083     }
11084   }
11085 
11086   if (!CompareWithSrc)
11087     return;
11088 
11089   // Determine if the argument to sizeof/strlen is equal to the source
11090   // argument.  In principle there's all kinds of things you could do
11091   // here, for instance creating an == expression and evaluating it with
11092   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11093   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11094   if (!SrcArgDRE)
11095     return;
11096 
11097   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11098   if (!CompareWithSrcDRE ||
11099       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11100     return;
11101 
11102   const Expr *OriginalSizeArg = Call->getArg(2);
11103   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11104       << OriginalSizeArg->getSourceRange() << FnName;
11105 
11106   // Output a FIXIT hint if the destination is an array (rather than a
11107   // pointer to an array).  This could be enhanced to handle some
11108   // pointers if we know the actual size, like if DstArg is 'array+2'
11109   // we could say 'sizeof(array)-2'.
11110   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11111   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11112     return;
11113 
11114   SmallString<128> sizeString;
11115   llvm::raw_svector_ostream OS(sizeString);
11116   OS << "sizeof(";
11117   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11118   OS << ")";
11119 
11120   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11121       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11122                                       OS.str());
11123 }
11124 
11125 /// Check if two expressions refer to the same declaration.
11126 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11127   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11128     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11129       return D1->getDecl() == D2->getDecl();
11130   return false;
11131 }
11132 
11133 static const Expr *getStrlenExprArg(const Expr *E) {
11134   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11135     const FunctionDecl *FD = CE->getDirectCallee();
11136     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11137       return nullptr;
11138     return CE->getArg(0)->IgnoreParenCasts();
11139   }
11140   return nullptr;
11141 }
11142 
11143 // Warn on anti-patterns as the 'size' argument to strncat.
11144 // The correct size argument should look like following:
11145 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11146 void Sema::CheckStrncatArguments(const CallExpr *CE,
11147                                  IdentifierInfo *FnName) {
11148   // Don't crash if the user has the wrong number of arguments.
11149   if (CE->getNumArgs() < 3)
11150     return;
11151   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11152   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11153   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11154 
11155   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11156                                      CE->getRParenLoc()))
11157     return;
11158 
11159   // Identify common expressions, which are wrongly used as the size argument
11160   // to strncat and may lead to buffer overflows.
11161   unsigned PatternType = 0;
11162   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11163     // - sizeof(dst)
11164     if (referToTheSameDecl(SizeOfArg, DstArg))
11165       PatternType = 1;
11166     // - sizeof(src)
11167     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11168       PatternType = 2;
11169   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11170     if (BE->getOpcode() == BO_Sub) {
11171       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11172       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11173       // - sizeof(dst) - strlen(dst)
11174       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11175           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11176         PatternType = 1;
11177       // - sizeof(src) - (anything)
11178       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11179         PatternType = 2;
11180     }
11181   }
11182 
11183   if (PatternType == 0)
11184     return;
11185 
11186   // Generate the diagnostic.
11187   SourceLocation SL = LenArg->getBeginLoc();
11188   SourceRange SR = LenArg->getSourceRange();
11189   SourceManager &SM = getSourceManager();
11190 
11191   // If the function is defined as a builtin macro, do not show macro expansion.
11192   if (SM.isMacroArgExpansion(SL)) {
11193     SL = SM.getSpellingLoc(SL);
11194     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11195                      SM.getSpellingLoc(SR.getEnd()));
11196   }
11197 
11198   // Check if the destination is an array (rather than a pointer to an array).
11199   QualType DstTy = DstArg->getType();
11200   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11201                                                                     Context);
11202   if (!isKnownSizeArray) {
11203     if (PatternType == 1)
11204       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11205     else
11206       Diag(SL, diag::warn_strncat_src_size) << SR;
11207     return;
11208   }
11209 
11210   if (PatternType == 1)
11211     Diag(SL, diag::warn_strncat_large_size) << SR;
11212   else
11213     Diag(SL, diag::warn_strncat_src_size) << SR;
11214 
11215   SmallString<128> sizeString;
11216   llvm::raw_svector_ostream OS(sizeString);
11217   OS << "sizeof(";
11218   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11219   OS << ") - ";
11220   OS << "strlen(";
11221   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11222   OS << ") - 1";
11223 
11224   Diag(SL, diag::note_strncat_wrong_size)
11225     << FixItHint::CreateReplacement(SR, OS.str());
11226 }
11227 
11228 namespace {
11229 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11230                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11231   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11232     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11233         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11234     return;
11235   }
11236 }
11237 
11238 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11239                                  const UnaryOperator *UnaryExpr) {
11240   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11241     const Decl *D = Lvalue->getDecl();
11242     if (isa<DeclaratorDecl>(D))
11243       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11244         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11245   }
11246 
11247   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11248     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11249                                       Lvalue->getMemberDecl());
11250 }
11251 
11252 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11253                             const UnaryOperator *UnaryExpr) {
11254   const auto *Lambda = dyn_cast<LambdaExpr>(
11255       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11256   if (!Lambda)
11257     return;
11258 
11259   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11260       << CalleeName << 2 /*object: lambda expression*/;
11261 }
11262 
11263 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11264                                   const DeclRefExpr *Lvalue) {
11265   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11266   if (Var == nullptr)
11267     return;
11268 
11269   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11270       << CalleeName << 0 /*object: */ << Var;
11271 }
11272 
11273 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11274                             const CastExpr *Cast) {
11275   SmallString<128> SizeString;
11276   llvm::raw_svector_ostream OS(SizeString);
11277 
11278   clang::CastKind Kind = Cast->getCastKind();
11279   if (Kind == clang::CK_BitCast &&
11280       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11281     return;
11282   if (Kind == clang::CK_IntegralToPointer &&
11283       !isa<IntegerLiteral>(
11284           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11285     return;
11286 
11287   switch (Cast->getCastKind()) {
11288   case clang::CK_BitCast:
11289   case clang::CK_IntegralToPointer:
11290   case clang::CK_FunctionToPointerDecay:
11291     OS << '\'';
11292     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11293     OS << '\'';
11294     break;
11295   default:
11296     return;
11297   }
11298 
11299   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11300       << CalleeName << 0 /*object: */ << OS.str();
11301 }
11302 } // namespace
11303 
11304 /// Alerts the user that they are attempting to free a non-malloc'd object.
11305 void Sema::CheckFreeArguments(const CallExpr *E) {
11306   const std::string CalleeName =
11307       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11308 
11309   { // Prefer something that doesn't involve a cast to make things simpler.
11310     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11311     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11312       switch (UnaryExpr->getOpcode()) {
11313       case UnaryOperator::Opcode::UO_AddrOf:
11314         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11315       case UnaryOperator::Opcode::UO_Plus:
11316         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11317       default:
11318         break;
11319       }
11320 
11321     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11322       if (Lvalue->getType()->isArrayType())
11323         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11324 
11325     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11326       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11327           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11328       return;
11329     }
11330 
11331     if (isa<BlockExpr>(Arg)) {
11332       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11333           << CalleeName << 1 /*object: block*/;
11334       return;
11335     }
11336   }
11337   // Maybe the cast was important, check after the other cases.
11338   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11339     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11340 }
11341 
11342 void
11343 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11344                          SourceLocation ReturnLoc,
11345                          bool isObjCMethod,
11346                          const AttrVec *Attrs,
11347                          const FunctionDecl *FD) {
11348   // Check if the return value is null but should not be.
11349   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11350        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11351       CheckNonNullExpr(*this, RetValExp))
11352     Diag(ReturnLoc, diag::warn_null_ret)
11353       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11354 
11355   // C++11 [basic.stc.dynamic.allocation]p4:
11356   //   If an allocation function declared with a non-throwing
11357   //   exception-specification fails to allocate storage, it shall return
11358   //   a null pointer. Any other allocation function that fails to allocate
11359   //   storage shall indicate failure only by throwing an exception [...]
11360   if (FD) {
11361     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11362     if (Op == OO_New || Op == OO_Array_New) {
11363       const FunctionProtoType *Proto
11364         = FD->getType()->castAs<FunctionProtoType>();
11365       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11366           CheckNonNullExpr(*this, RetValExp))
11367         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11368           << FD << getLangOpts().CPlusPlus11;
11369     }
11370   }
11371 
11372   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11373   // here prevent the user from using a PPC MMA type as trailing return type.
11374   if (Context.getTargetInfo().getTriple().isPPC64())
11375     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11376 }
11377 
11378 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11379 
11380 /// Check for comparisons of floating point operands using != and ==.
11381 /// Issue a warning if these are no self-comparisons, as they are not likely
11382 /// to do what the programmer intended.
11383 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11384   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11385   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11386 
11387   // Special case: check for x == x (which is OK).
11388   // Do not emit warnings for such cases.
11389   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11390     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11391       if (DRL->getDecl() == DRR->getDecl())
11392         return;
11393 
11394   // Special case: check for comparisons against literals that can be exactly
11395   //  represented by APFloat.  In such cases, do not emit a warning.  This
11396   //  is a heuristic: often comparison against such literals are used to
11397   //  detect if a value in a variable has not changed.  This clearly can
11398   //  lead to false negatives.
11399   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11400     if (FLL->isExact())
11401       return;
11402   } else
11403     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11404       if (FLR->isExact())
11405         return;
11406 
11407   // Check for comparisons with builtin types.
11408   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11409     if (CL->getBuiltinCallee())
11410       return;
11411 
11412   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11413     if (CR->getBuiltinCallee())
11414       return;
11415 
11416   // Emit the diagnostic.
11417   Diag(Loc, diag::warn_floatingpoint_eq)
11418     << LHS->getSourceRange() << RHS->getSourceRange();
11419 }
11420 
11421 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11422 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11423 
11424 namespace {
11425 
11426 /// Structure recording the 'active' range of an integer-valued
11427 /// expression.
11428 struct IntRange {
11429   /// The number of bits active in the int. Note that this includes exactly one
11430   /// sign bit if !NonNegative.
11431   unsigned Width;
11432 
11433   /// True if the int is known not to have negative values. If so, all leading
11434   /// bits before Width are known zero, otherwise they are known to be the
11435   /// same as the MSB within Width.
11436   bool NonNegative;
11437 
11438   IntRange(unsigned Width, bool NonNegative)
11439       : Width(Width), NonNegative(NonNegative) {}
11440 
11441   /// Number of bits excluding the sign bit.
11442   unsigned valueBits() const {
11443     return NonNegative ? Width : Width - 1;
11444   }
11445 
11446   /// Returns the range of the bool type.
11447   static IntRange forBoolType() {
11448     return IntRange(1, true);
11449   }
11450 
11451   /// Returns the range of an opaque value of the given integral type.
11452   static IntRange forValueOfType(ASTContext &C, QualType T) {
11453     return forValueOfCanonicalType(C,
11454                           T->getCanonicalTypeInternal().getTypePtr());
11455   }
11456 
11457   /// Returns the range of an opaque value of a canonical integral type.
11458   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11459     assert(T->isCanonicalUnqualified());
11460 
11461     if (const VectorType *VT = dyn_cast<VectorType>(T))
11462       T = VT->getElementType().getTypePtr();
11463     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11464       T = CT->getElementType().getTypePtr();
11465     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11466       T = AT->getValueType().getTypePtr();
11467 
11468     if (!C.getLangOpts().CPlusPlus) {
11469       // For enum types in C code, use the underlying datatype.
11470       if (const EnumType *ET = dyn_cast<EnumType>(T))
11471         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11472     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11473       // For enum types in C++, use the known bit width of the enumerators.
11474       EnumDecl *Enum = ET->getDecl();
11475       // In C++11, enums can have a fixed underlying type. Use this type to
11476       // compute the range.
11477       if (Enum->isFixed()) {
11478         return IntRange(C.getIntWidth(QualType(T, 0)),
11479                         !ET->isSignedIntegerOrEnumerationType());
11480       }
11481 
11482       unsigned NumPositive = Enum->getNumPositiveBits();
11483       unsigned NumNegative = Enum->getNumNegativeBits();
11484 
11485       if (NumNegative == 0)
11486         return IntRange(NumPositive, true/*NonNegative*/);
11487       else
11488         return IntRange(std::max(NumPositive + 1, NumNegative),
11489                         false/*NonNegative*/);
11490     }
11491 
11492     if (const auto *EIT = dyn_cast<BitIntType>(T))
11493       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11494 
11495     const BuiltinType *BT = cast<BuiltinType>(T);
11496     assert(BT->isInteger());
11497 
11498     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11499   }
11500 
11501   /// Returns the "target" range of a canonical integral type, i.e.
11502   /// the range of values expressible in the type.
11503   ///
11504   /// This matches forValueOfCanonicalType except that enums have the
11505   /// full range of their type, not the range of their enumerators.
11506   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11507     assert(T->isCanonicalUnqualified());
11508 
11509     if (const VectorType *VT = dyn_cast<VectorType>(T))
11510       T = VT->getElementType().getTypePtr();
11511     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11512       T = CT->getElementType().getTypePtr();
11513     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11514       T = AT->getValueType().getTypePtr();
11515     if (const EnumType *ET = dyn_cast<EnumType>(T))
11516       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11517 
11518     if (const auto *EIT = dyn_cast<BitIntType>(T))
11519       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11520 
11521     const BuiltinType *BT = cast<BuiltinType>(T);
11522     assert(BT->isInteger());
11523 
11524     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11525   }
11526 
11527   /// Returns the supremum of two ranges: i.e. their conservative merge.
11528   static IntRange join(IntRange L, IntRange R) {
11529     bool Unsigned = L.NonNegative && R.NonNegative;
11530     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11531                     L.NonNegative && R.NonNegative);
11532   }
11533 
11534   /// Return the range of a bitwise-AND of the two ranges.
11535   static IntRange bit_and(IntRange L, IntRange R) {
11536     unsigned Bits = std::max(L.Width, R.Width);
11537     bool NonNegative = false;
11538     if (L.NonNegative) {
11539       Bits = std::min(Bits, L.Width);
11540       NonNegative = true;
11541     }
11542     if (R.NonNegative) {
11543       Bits = std::min(Bits, R.Width);
11544       NonNegative = true;
11545     }
11546     return IntRange(Bits, NonNegative);
11547   }
11548 
11549   /// Return the range of a sum of the two ranges.
11550   static IntRange sum(IntRange L, IntRange R) {
11551     bool Unsigned = L.NonNegative && R.NonNegative;
11552     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11553                     Unsigned);
11554   }
11555 
11556   /// Return the range of a difference of the two ranges.
11557   static IntRange difference(IntRange L, IntRange R) {
11558     // We need a 1-bit-wider range if:
11559     //   1) LHS can be negative: least value can be reduced.
11560     //   2) RHS can be negative: greatest value can be increased.
11561     bool CanWiden = !L.NonNegative || !R.NonNegative;
11562     bool Unsigned = L.NonNegative && R.Width == 0;
11563     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11564                         !Unsigned,
11565                     Unsigned);
11566   }
11567 
11568   /// Return the range of a product of the two ranges.
11569   static IntRange product(IntRange L, IntRange R) {
11570     // If both LHS and RHS can be negative, we can form
11571     //   -2^L * -2^R = 2^(L + R)
11572     // which requires L + R + 1 value bits to represent.
11573     bool CanWiden = !L.NonNegative && !R.NonNegative;
11574     bool Unsigned = L.NonNegative && R.NonNegative;
11575     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11576                     Unsigned);
11577   }
11578 
11579   /// Return the range of a remainder operation between the two ranges.
11580   static IntRange rem(IntRange L, IntRange R) {
11581     // The result of a remainder can't be larger than the result of
11582     // either side. The sign of the result is the sign of the LHS.
11583     bool Unsigned = L.NonNegative;
11584     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11585                     Unsigned);
11586   }
11587 };
11588 
11589 } // namespace
11590 
11591 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11592                               unsigned MaxWidth) {
11593   if (value.isSigned() && value.isNegative())
11594     return IntRange(value.getMinSignedBits(), false);
11595 
11596   if (value.getBitWidth() > MaxWidth)
11597     value = value.trunc(MaxWidth);
11598 
11599   // isNonNegative() just checks the sign bit without considering
11600   // signedness.
11601   return IntRange(value.getActiveBits(), true);
11602 }
11603 
11604 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11605                               unsigned MaxWidth) {
11606   if (result.isInt())
11607     return GetValueRange(C, result.getInt(), MaxWidth);
11608 
11609   if (result.isVector()) {
11610     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11611     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11612       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11613       R = IntRange::join(R, El);
11614     }
11615     return R;
11616   }
11617 
11618   if (result.isComplexInt()) {
11619     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11620     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11621     return IntRange::join(R, I);
11622   }
11623 
11624   // This can happen with lossless casts to intptr_t of "based" lvalues.
11625   // Assume it might use arbitrary bits.
11626   // FIXME: The only reason we need to pass the type in here is to get
11627   // the sign right on this one case.  It would be nice if APValue
11628   // preserved this.
11629   assert(result.isLValue() || result.isAddrLabelDiff());
11630   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11631 }
11632 
11633 static QualType GetExprType(const Expr *E) {
11634   QualType Ty = E->getType();
11635   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11636     Ty = AtomicRHS->getValueType();
11637   return Ty;
11638 }
11639 
11640 /// Pseudo-evaluate the given integer expression, estimating the
11641 /// range of values it might take.
11642 ///
11643 /// \param MaxWidth The width to which the value will be truncated.
11644 /// \param Approximate If \c true, return a likely range for the result: in
11645 ///        particular, assume that arithmetic on narrower types doesn't leave
11646 ///        those types. If \c false, return a range including all possible
11647 ///        result values.
11648 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11649                              bool InConstantContext, bool Approximate) {
11650   E = E->IgnoreParens();
11651 
11652   // Try a full evaluation first.
11653   Expr::EvalResult result;
11654   if (E->EvaluateAsRValue(result, C, InConstantContext))
11655     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11656 
11657   // I think we only want to look through implicit casts here; if the
11658   // user has an explicit widening cast, we should treat the value as
11659   // being of the new, wider type.
11660   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11661     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11662       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11663                           Approximate);
11664 
11665     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11666 
11667     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11668                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11669 
11670     // Assume that non-integer casts can span the full range of the type.
11671     if (!isIntegerCast)
11672       return OutputTypeRange;
11673 
11674     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11675                                      std::min(MaxWidth, OutputTypeRange.Width),
11676                                      InConstantContext, Approximate);
11677 
11678     // Bail out if the subexpr's range is as wide as the cast type.
11679     if (SubRange.Width >= OutputTypeRange.Width)
11680       return OutputTypeRange;
11681 
11682     // Otherwise, we take the smaller width, and we're non-negative if
11683     // either the output type or the subexpr is.
11684     return IntRange(SubRange.Width,
11685                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11686   }
11687 
11688   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11689     // If we can fold the condition, just take that operand.
11690     bool CondResult;
11691     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11692       return GetExprRange(C,
11693                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11694                           MaxWidth, InConstantContext, Approximate);
11695 
11696     // Otherwise, conservatively merge.
11697     // GetExprRange requires an integer expression, but a throw expression
11698     // results in a void type.
11699     Expr *E = CO->getTrueExpr();
11700     IntRange L = E->getType()->isVoidType()
11701                      ? IntRange{0, true}
11702                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11703     E = CO->getFalseExpr();
11704     IntRange R = E->getType()->isVoidType()
11705                      ? IntRange{0, true}
11706                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11707     return IntRange::join(L, R);
11708   }
11709 
11710   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11711     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11712 
11713     switch (BO->getOpcode()) {
11714     case BO_Cmp:
11715       llvm_unreachable("builtin <=> should have class type");
11716 
11717     // Boolean-valued operations are single-bit and positive.
11718     case BO_LAnd:
11719     case BO_LOr:
11720     case BO_LT:
11721     case BO_GT:
11722     case BO_LE:
11723     case BO_GE:
11724     case BO_EQ:
11725     case BO_NE:
11726       return IntRange::forBoolType();
11727 
11728     // The type of the assignments is the type of the LHS, so the RHS
11729     // is not necessarily the same type.
11730     case BO_MulAssign:
11731     case BO_DivAssign:
11732     case BO_RemAssign:
11733     case BO_AddAssign:
11734     case BO_SubAssign:
11735     case BO_XorAssign:
11736     case BO_OrAssign:
11737       // TODO: bitfields?
11738       return IntRange::forValueOfType(C, GetExprType(E));
11739 
11740     // Simple assignments just pass through the RHS, which will have
11741     // been coerced to the LHS type.
11742     case BO_Assign:
11743       // TODO: bitfields?
11744       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11745                           Approximate);
11746 
11747     // Operations with opaque sources are black-listed.
11748     case BO_PtrMemD:
11749     case BO_PtrMemI:
11750       return IntRange::forValueOfType(C, GetExprType(E));
11751 
11752     // Bitwise-and uses the *infinum* of the two source ranges.
11753     case BO_And:
11754     case BO_AndAssign:
11755       Combine = IntRange::bit_and;
11756       break;
11757 
11758     // Left shift gets black-listed based on a judgement call.
11759     case BO_Shl:
11760       // ...except that we want to treat '1 << (blah)' as logically
11761       // positive.  It's an important idiom.
11762       if (IntegerLiteral *I
11763             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11764         if (I->getValue() == 1) {
11765           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11766           return IntRange(R.Width, /*NonNegative*/ true);
11767         }
11768       }
11769       LLVM_FALLTHROUGH;
11770 
11771     case BO_ShlAssign:
11772       return IntRange::forValueOfType(C, GetExprType(E));
11773 
11774     // Right shift by a constant can narrow its left argument.
11775     case BO_Shr:
11776     case BO_ShrAssign: {
11777       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11778                                 Approximate);
11779 
11780       // If the shift amount is a positive constant, drop the width by
11781       // that much.
11782       if (Optional<llvm::APSInt> shift =
11783               BO->getRHS()->getIntegerConstantExpr(C)) {
11784         if (shift->isNonNegative()) {
11785           unsigned zext = shift->getZExtValue();
11786           if (zext >= L.Width)
11787             L.Width = (L.NonNegative ? 0 : 1);
11788           else
11789             L.Width -= zext;
11790         }
11791       }
11792 
11793       return L;
11794     }
11795 
11796     // Comma acts as its right operand.
11797     case BO_Comma:
11798       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11799                           Approximate);
11800 
11801     case BO_Add:
11802       if (!Approximate)
11803         Combine = IntRange::sum;
11804       break;
11805 
11806     case BO_Sub:
11807       if (BO->getLHS()->getType()->isPointerType())
11808         return IntRange::forValueOfType(C, GetExprType(E));
11809       if (!Approximate)
11810         Combine = IntRange::difference;
11811       break;
11812 
11813     case BO_Mul:
11814       if (!Approximate)
11815         Combine = IntRange::product;
11816       break;
11817 
11818     // The width of a division result is mostly determined by the size
11819     // of the LHS.
11820     case BO_Div: {
11821       // Don't 'pre-truncate' the operands.
11822       unsigned opWidth = C.getIntWidth(GetExprType(E));
11823       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11824                                 Approximate);
11825 
11826       // If the divisor is constant, use that.
11827       if (Optional<llvm::APSInt> divisor =
11828               BO->getRHS()->getIntegerConstantExpr(C)) {
11829         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11830         if (log2 >= L.Width)
11831           L.Width = (L.NonNegative ? 0 : 1);
11832         else
11833           L.Width = std::min(L.Width - log2, MaxWidth);
11834         return L;
11835       }
11836 
11837       // Otherwise, just use the LHS's width.
11838       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11839       // could be -1.
11840       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11841                                 Approximate);
11842       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11843     }
11844 
11845     case BO_Rem:
11846       Combine = IntRange::rem;
11847       break;
11848 
11849     // The default behavior is okay for these.
11850     case BO_Xor:
11851     case BO_Or:
11852       break;
11853     }
11854 
11855     // Combine the two ranges, but limit the result to the type in which we
11856     // performed the computation.
11857     QualType T = GetExprType(E);
11858     unsigned opWidth = C.getIntWidth(T);
11859     IntRange L =
11860         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11861     IntRange R =
11862         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11863     IntRange C = Combine(L, R);
11864     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11865     C.Width = std::min(C.Width, MaxWidth);
11866     return C;
11867   }
11868 
11869   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11870     switch (UO->getOpcode()) {
11871     // Boolean-valued operations are white-listed.
11872     case UO_LNot:
11873       return IntRange::forBoolType();
11874 
11875     // Operations with opaque sources are black-listed.
11876     case UO_Deref:
11877     case UO_AddrOf: // should be impossible
11878       return IntRange::forValueOfType(C, GetExprType(E));
11879 
11880     default:
11881       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11882                           Approximate);
11883     }
11884   }
11885 
11886   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11887     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11888                         Approximate);
11889 
11890   if (const auto *BitField = E->getSourceBitField())
11891     return IntRange(BitField->getBitWidthValue(C),
11892                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11893 
11894   return IntRange::forValueOfType(C, GetExprType(E));
11895 }
11896 
11897 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11898                              bool InConstantContext, bool Approximate) {
11899   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11900                       Approximate);
11901 }
11902 
11903 /// Checks whether the given value, which currently has the given
11904 /// source semantics, has the same value when coerced through the
11905 /// target semantics.
11906 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11907                                  const llvm::fltSemantics &Src,
11908                                  const llvm::fltSemantics &Tgt) {
11909   llvm::APFloat truncated = value;
11910 
11911   bool ignored;
11912   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11913   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11914 
11915   return truncated.bitwiseIsEqual(value);
11916 }
11917 
11918 /// Checks whether the given value, which currently has the given
11919 /// source semantics, has the same value when coerced through the
11920 /// target semantics.
11921 ///
11922 /// The value might be a vector of floats (or a complex number).
11923 static bool IsSameFloatAfterCast(const APValue &value,
11924                                  const llvm::fltSemantics &Src,
11925                                  const llvm::fltSemantics &Tgt) {
11926   if (value.isFloat())
11927     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11928 
11929   if (value.isVector()) {
11930     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11931       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11932         return false;
11933     return true;
11934   }
11935 
11936   assert(value.isComplexFloat());
11937   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11938           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11939 }
11940 
11941 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11942                                        bool IsListInit = false);
11943 
11944 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11945   // Suppress cases where we are comparing against an enum constant.
11946   if (const DeclRefExpr *DR =
11947       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11948     if (isa<EnumConstantDecl>(DR->getDecl()))
11949       return true;
11950 
11951   // Suppress cases where the value is expanded from a macro, unless that macro
11952   // is how a language represents a boolean literal. This is the case in both C
11953   // and Objective-C.
11954   SourceLocation BeginLoc = E->getBeginLoc();
11955   if (BeginLoc.isMacroID()) {
11956     StringRef MacroName = Lexer::getImmediateMacroName(
11957         BeginLoc, S.getSourceManager(), S.getLangOpts());
11958     return MacroName != "YES" && MacroName != "NO" &&
11959            MacroName != "true" && MacroName != "false";
11960   }
11961 
11962   return false;
11963 }
11964 
11965 static bool isKnownToHaveUnsignedValue(Expr *E) {
11966   return E->getType()->isIntegerType() &&
11967          (!E->getType()->isSignedIntegerType() ||
11968           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11969 }
11970 
11971 namespace {
11972 /// The promoted range of values of a type. In general this has the
11973 /// following structure:
11974 ///
11975 ///     |-----------| . . . |-----------|
11976 ///     ^           ^       ^           ^
11977 ///    Min       HoleMin  HoleMax      Max
11978 ///
11979 /// ... where there is only a hole if a signed type is promoted to unsigned
11980 /// (in which case Min and Max are the smallest and largest representable
11981 /// values).
11982 struct PromotedRange {
11983   // Min, or HoleMax if there is a hole.
11984   llvm::APSInt PromotedMin;
11985   // Max, or HoleMin if there is a hole.
11986   llvm::APSInt PromotedMax;
11987 
11988   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11989     if (R.Width == 0)
11990       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11991     else if (R.Width >= BitWidth && !Unsigned) {
11992       // Promotion made the type *narrower*. This happens when promoting
11993       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11994       // Treat all values of 'signed int' as being in range for now.
11995       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11996       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11997     } else {
11998       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11999                         .extOrTrunc(BitWidth);
12000       PromotedMin.setIsUnsigned(Unsigned);
12001 
12002       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12003                         .extOrTrunc(BitWidth);
12004       PromotedMax.setIsUnsigned(Unsigned);
12005     }
12006   }
12007 
12008   // Determine whether this range is contiguous (has no hole).
12009   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12010 
12011   // Where a constant value is within the range.
12012   enum ComparisonResult {
12013     LT = 0x1,
12014     LE = 0x2,
12015     GT = 0x4,
12016     GE = 0x8,
12017     EQ = 0x10,
12018     NE = 0x20,
12019     InRangeFlag = 0x40,
12020 
12021     Less = LE | LT | NE,
12022     Min = LE | InRangeFlag,
12023     InRange = InRangeFlag,
12024     Max = GE | InRangeFlag,
12025     Greater = GE | GT | NE,
12026 
12027     OnlyValue = LE | GE | EQ | InRangeFlag,
12028     InHole = NE
12029   };
12030 
12031   ComparisonResult compare(const llvm::APSInt &Value) const {
12032     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12033            Value.isUnsigned() == PromotedMin.isUnsigned());
12034     if (!isContiguous()) {
12035       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12036       if (Value.isMinValue()) return Min;
12037       if (Value.isMaxValue()) return Max;
12038       if (Value >= PromotedMin) return InRange;
12039       if (Value <= PromotedMax) return InRange;
12040       return InHole;
12041     }
12042 
12043     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12044     case -1: return Less;
12045     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12046     case 1:
12047       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12048       case -1: return InRange;
12049       case 0: return Max;
12050       case 1: return Greater;
12051       }
12052     }
12053 
12054     llvm_unreachable("impossible compare result");
12055   }
12056 
12057   static llvm::Optional<StringRef>
12058   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12059     if (Op == BO_Cmp) {
12060       ComparisonResult LTFlag = LT, GTFlag = GT;
12061       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12062 
12063       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12064       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12065       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12066       return llvm::None;
12067     }
12068 
12069     ComparisonResult TrueFlag, FalseFlag;
12070     if (Op == BO_EQ) {
12071       TrueFlag = EQ;
12072       FalseFlag = NE;
12073     } else if (Op == BO_NE) {
12074       TrueFlag = NE;
12075       FalseFlag = EQ;
12076     } else {
12077       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12078         TrueFlag = LT;
12079         FalseFlag = GE;
12080       } else {
12081         TrueFlag = GT;
12082         FalseFlag = LE;
12083       }
12084       if (Op == BO_GE || Op == BO_LE)
12085         std::swap(TrueFlag, FalseFlag);
12086     }
12087     if (R & TrueFlag)
12088       return StringRef("true");
12089     if (R & FalseFlag)
12090       return StringRef("false");
12091     return llvm::None;
12092   }
12093 };
12094 }
12095 
12096 static bool HasEnumType(Expr *E) {
12097   // Strip off implicit integral promotions.
12098   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12099     if (ICE->getCastKind() != CK_IntegralCast &&
12100         ICE->getCastKind() != CK_NoOp)
12101       break;
12102     E = ICE->getSubExpr();
12103   }
12104 
12105   return E->getType()->isEnumeralType();
12106 }
12107 
12108 static int classifyConstantValue(Expr *Constant) {
12109   // The values of this enumeration are used in the diagnostics
12110   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12111   enum ConstantValueKind {
12112     Miscellaneous = 0,
12113     LiteralTrue,
12114     LiteralFalse
12115   };
12116   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12117     return BL->getValue() ? ConstantValueKind::LiteralTrue
12118                           : ConstantValueKind::LiteralFalse;
12119   return ConstantValueKind::Miscellaneous;
12120 }
12121 
12122 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12123                                         Expr *Constant, Expr *Other,
12124                                         const llvm::APSInt &Value,
12125                                         bool RhsConstant) {
12126   if (S.inTemplateInstantiation())
12127     return false;
12128 
12129   Expr *OriginalOther = Other;
12130 
12131   Constant = Constant->IgnoreParenImpCasts();
12132   Other = Other->IgnoreParenImpCasts();
12133 
12134   // Suppress warnings on tautological comparisons between values of the same
12135   // enumeration type. There are only two ways we could warn on this:
12136   //  - If the constant is outside the range of representable values of
12137   //    the enumeration. In such a case, we should warn about the cast
12138   //    to enumeration type, not about the comparison.
12139   //  - If the constant is the maximum / minimum in-range value. For an
12140   //    enumeratin type, such comparisons can be meaningful and useful.
12141   if (Constant->getType()->isEnumeralType() &&
12142       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12143     return false;
12144 
12145   IntRange OtherValueRange = GetExprRange(
12146       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12147 
12148   QualType OtherT = Other->getType();
12149   if (const auto *AT = OtherT->getAs<AtomicType>())
12150     OtherT = AT->getValueType();
12151   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12152 
12153   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12154   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12155   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12156                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12157                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12158 
12159   // Whether we're treating Other as being a bool because of the form of
12160   // expression despite it having another type (typically 'int' in C).
12161   bool OtherIsBooleanDespiteType =
12162       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12163   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12164     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12165 
12166   // Check if all values in the range of possible values of this expression
12167   // lead to the same comparison outcome.
12168   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12169                                         Value.isUnsigned());
12170   auto Cmp = OtherPromotedValueRange.compare(Value);
12171   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12172   if (!Result)
12173     return false;
12174 
12175   // Also consider the range determined by the type alone. This allows us to
12176   // classify the warning under the proper diagnostic group.
12177   bool TautologicalTypeCompare = false;
12178   {
12179     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12180                                          Value.isUnsigned());
12181     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12182     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12183                                                        RhsConstant)) {
12184       TautologicalTypeCompare = true;
12185       Cmp = TypeCmp;
12186       Result = TypeResult;
12187     }
12188   }
12189 
12190   // Don't warn if the non-constant operand actually always evaluates to the
12191   // same value.
12192   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12193     return false;
12194 
12195   // Suppress the diagnostic for an in-range comparison if the constant comes
12196   // from a macro or enumerator. We don't want to diagnose
12197   //
12198   //   some_long_value <= INT_MAX
12199   //
12200   // when sizeof(int) == sizeof(long).
12201   bool InRange = Cmp & PromotedRange::InRangeFlag;
12202   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12203     return false;
12204 
12205   // A comparison of an unsigned bit-field against 0 is really a type problem,
12206   // even though at the type level the bit-field might promote to 'signed int'.
12207   if (Other->refersToBitField() && InRange && Value == 0 &&
12208       Other->getType()->isUnsignedIntegerOrEnumerationType())
12209     TautologicalTypeCompare = true;
12210 
12211   // If this is a comparison to an enum constant, include that
12212   // constant in the diagnostic.
12213   const EnumConstantDecl *ED = nullptr;
12214   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12215     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12216 
12217   // Should be enough for uint128 (39 decimal digits)
12218   SmallString<64> PrettySourceValue;
12219   llvm::raw_svector_ostream OS(PrettySourceValue);
12220   if (ED) {
12221     OS << '\'' << *ED << "' (" << Value << ")";
12222   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12223                Constant->IgnoreParenImpCasts())) {
12224     OS << (BL->getValue() ? "YES" : "NO");
12225   } else {
12226     OS << Value;
12227   }
12228 
12229   if (!TautologicalTypeCompare) {
12230     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12231         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12232         << E->getOpcodeStr() << OS.str() << *Result
12233         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12234     return true;
12235   }
12236 
12237   if (IsObjCSignedCharBool) {
12238     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12239                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12240                               << OS.str() << *Result);
12241     return true;
12242   }
12243 
12244   // FIXME: We use a somewhat different formatting for the in-range cases and
12245   // cases involving boolean values for historical reasons. We should pick a
12246   // consistent way of presenting these diagnostics.
12247   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12248 
12249     S.DiagRuntimeBehavior(
12250         E->getOperatorLoc(), E,
12251         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12252                          : diag::warn_tautological_bool_compare)
12253             << OS.str() << classifyConstantValue(Constant) << OtherT
12254             << OtherIsBooleanDespiteType << *Result
12255             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12256   } else {
12257     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12258     unsigned Diag =
12259         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12260             ? (HasEnumType(OriginalOther)
12261                    ? diag::warn_unsigned_enum_always_true_comparison
12262                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12263                               : diag::warn_unsigned_always_true_comparison)
12264             : diag::warn_tautological_constant_compare;
12265 
12266     S.Diag(E->getOperatorLoc(), Diag)
12267         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12268         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12269   }
12270 
12271   return true;
12272 }
12273 
12274 /// Analyze the operands of the given comparison.  Implements the
12275 /// fallback case from AnalyzeComparison.
12276 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12277   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12278   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12279 }
12280 
12281 /// Implements -Wsign-compare.
12282 ///
12283 /// \param E the binary operator to check for warnings
12284 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12285   // The type the comparison is being performed in.
12286   QualType T = E->getLHS()->getType();
12287 
12288   // Only analyze comparison operators where both sides have been converted to
12289   // the same type.
12290   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12291     return AnalyzeImpConvsInComparison(S, E);
12292 
12293   // Don't analyze value-dependent comparisons directly.
12294   if (E->isValueDependent())
12295     return AnalyzeImpConvsInComparison(S, E);
12296 
12297   Expr *LHS = E->getLHS();
12298   Expr *RHS = E->getRHS();
12299 
12300   if (T->isIntegralType(S.Context)) {
12301     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12302     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12303 
12304     // We don't care about expressions whose result is a constant.
12305     if (RHSValue && LHSValue)
12306       return AnalyzeImpConvsInComparison(S, E);
12307 
12308     // We only care about expressions where just one side is literal
12309     if ((bool)RHSValue ^ (bool)LHSValue) {
12310       // Is the constant on the RHS or LHS?
12311       const bool RhsConstant = (bool)RHSValue;
12312       Expr *Const = RhsConstant ? RHS : LHS;
12313       Expr *Other = RhsConstant ? LHS : RHS;
12314       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12315 
12316       // Check whether an integer constant comparison results in a value
12317       // of 'true' or 'false'.
12318       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12319         return AnalyzeImpConvsInComparison(S, E);
12320     }
12321   }
12322 
12323   if (!T->hasUnsignedIntegerRepresentation()) {
12324     // We don't do anything special if this isn't an unsigned integral
12325     // comparison:  we're only interested in integral comparisons, and
12326     // signed comparisons only happen in cases we don't care to warn about.
12327     return AnalyzeImpConvsInComparison(S, E);
12328   }
12329 
12330   LHS = LHS->IgnoreParenImpCasts();
12331   RHS = RHS->IgnoreParenImpCasts();
12332 
12333   if (!S.getLangOpts().CPlusPlus) {
12334     // Avoid warning about comparison of integers with different signs when
12335     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12336     // the type of `E`.
12337     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12338       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12339     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12340       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12341   }
12342 
12343   // Check to see if one of the (unmodified) operands is of different
12344   // signedness.
12345   Expr *signedOperand, *unsignedOperand;
12346   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12347     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12348            "unsigned comparison between two signed integer expressions?");
12349     signedOperand = LHS;
12350     unsignedOperand = RHS;
12351   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12352     signedOperand = RHS;
12353     unsignedOperand = LHS;
12354   } else {
12355     return AnalyzeImpConvsInComparison(S, E);
12356   }
12357 
12358   // Otherwise, calculate the effective range of the signed operand.
12359   IntRange signedRange = GetExprRange(
12360       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12361 
12362   // Go ahead and analyze implicit conversions in the operands.  Note
12363   // that we skip the implicit conversions on both sides.
12364   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12365   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12366 
12367   // If the signed range is non-negative, -Wsign-compare won't fire.
12368   if (signedRange.NonNegative)
12369     return;
12370 
12371   // For (in)equality comparisons, if the unsigned operand is a
12372   // constant which cannot collide with a overflowed signed operand,
12373   // then reinterpreting the signed operand as unsigned will not
12374   // change the result of the comparison.
12375   if (E->isEqualityOp()) {
12376     unsigned comparisonWidth = S.Context.getIntWidth(T);
12377     IntRange unsignedRange =
12378         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12379                      /*Approximate*/ true);
12380 
12381     // We should never be unable to prove that the unsigned operand is
12382     // non-negative.
12383     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12384 
12385     if (unsignedRange.Width < comparisonWidth)
12386       return;
12387   }
12388 
12389   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12390                         S.PDiag(diag::warn_mixed_sign_comparison)
12391                             << LHS->getType() << RHS->getType()
12392                             << LHS->getSourceRange() << RHS->getSourceRange());
12393 }
12394 
12395 /// Analyzes an attempt to assign the given value to a bitfield.
12396 ///
12397 /// Returns true if there was something fishy about the attempt.
12398 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12399                                       SourceLocation InitLoc) {
12400   assert(Bitfield->isBitField());
12401   if (Bitfield->isInvalidDecl())
12402     return false;
12403 
12404   // White-list bool bitfields.
12405   QualType BitfieldType = Bitfield->getType();
12406   if (BitfieldType->isBooleanType())
12407      return false;
12408 
12409   if (BitfieldType->isEnumeralType()) {
12410     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12411     // If the underlying enum type was not explicitly specified as an unsigned
12412     // type and the enum contain only positive values, MSVC++ will cause an
12413     // inconsistency by storing this as a signed type.
12414     if (S.getLangOpts().CPlusPlus11 &&
12415         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12416         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12417         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12418       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12419           << BitfieldEnumDecl;
12420     }
12421   }
12422 
12423   if (Bitfield->getType()->isBooleanType())
12424     return false;
12425 
12426   // Ignore value- or type-dependent expressions.
12427   if (Bitfield->getBitWidth()->isValueDependent() ||
12428       Bitfield->getBitWidth()->isTypeDependent() ||
12429       Init->isValueDependent() ||
12430       Init->isTypeDependent())
12431     return false;
12432 
12433   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12434   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12435 
12436   Expr::EvalResult Result;
12437   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12438                                    Expr::SE_AllowSideEffects)) {
12439     // The RHS is not constant.  If the RHS has an enum type, make sure the
12440     // bitfield is wide enough to hold all the values of the enum without
12441     // truncation.
12442     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12443       EnumDecl *ED = EnumTy->getDecl();
12444       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12445 
12446       // Enum types are implicitly signed on Windows, so check if there are any
12447       // negative enumerators to see if the enum was intended to be signed or
12448       // not.
12449       bool SignedEnum = ED->getNumNegativeBits() > 0;
12450 
12451       // Check for surprising sign changes when assigning enum values to a
12452       // bitfield of different signedness.  If the bitfield is signed and we
12453       // have exactly the right number of bits to store this unsigned enum,
12454       // suggest changing the enum to an unsigned type. This typically happens
12455       // on Windows where unfixed enums always use an underlying type of 'int'.
12456       unsigned DiagID = 0;
12457       if (SignedEnum && !SignedBitfield) {
12458         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12459       } else if (SignedBitfield && !SignedEnum &&
12460                  ED->getNumPositiveBits() == FieldWidth) {
12461         DiagID = diag::warn_signed_bitfield_enum_conversion;
12462       }
12463 
12464       if (DiagID) {
12465         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12466         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12467         SourceRange TypeRange =
12468             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12469         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12470             << SignedEnum << TypeRange;
12471       }
12472 
12473       // Compute the required bitwidth. If the enum has negative values, we need
12474       // one more bit than the normal number of positive bits to represent the
12475       // sign bit.
12476       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12477                                                   ED->getNumNegativeBits())
12478                                        : ED->getNumPositiveBits();
12479 
12480       // Check the bitwidth.
12481       if (BitsNeeded > FieldWidth) {
12482         Expr *WidthExpr = Bitfield->getBitWidth();
12483         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12484             << Bitfield << ED;
12485         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12486             << BitsNeeded << ED << WidthExpr->getSourceRange();
12487       }
12488     }
12489 
12490     return false;
12491   }
12492 
12493   llvm::APSInt Value = Result.Val.getInt();
12494 
12495   unsigned OriginalWidth = Value.getBitWidth();
12496 
12497   if (!Value.isSigned() || Value.isNegative())
12498     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12499       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12500         OriginalWidth = Value.getMinSignedBits();
12501 
12502   if (OriginalWidth <= FieldWidth)
12503     return false;
12504 
12505   // Compute the value which the bitfield will contain.
12506   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12507   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12508 
12509   // Check whether the stored value is equal to the original value.
12510   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12511   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12512     return false;
12513 
12514   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12515   // therefore don't strictly fit into a signed bitfield of width 1.
12516   if (FieldWidth == 1 && Value == 1)
12517     return false;
12518 
12519   std::string PrettyValue = toString(Value, 10);
12520   std::string PrettyTrunc = toString(TruncatedValue, 10);
12521 
12522   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12523     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12524     << Init->getSourceRange();
12525 
12526   return true;
12527 }
12528 
12529 /// Analyze the given simple or compound assignment for warning-worthy
12530 /// operations.
12531 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12532   // Just recurse on the LHS.
12533   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12534 
12535   // We want to recurse on the RHS as normal unless we're assigning to
12536   // a bitfield.
12537   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12538     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12539                                   E->getOperatorLoc())) {
12540       // Recurse, ignoring any implicit conversions on the RHS.
12541       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12542                                         E->getOperatorLoc());
12543     }
12544   }
12545 
12546   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12547 
12548   // Diagnose implicitly sequentially-consistent atomic assignment.
12549   if (E->getLHS()->getType()->isAtomicType())
12550     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12551 }
12552 
12553 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12554 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12555                             SourceLocation CContext, unsigned diag,
12556                             bool pruneControlFlow = false) {
12557   if (pruneControlFlow) {
12558     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12559                           S.PDiag(diag)
12560                               << SourceType << T << E->getSourceRange()
12561                               << SourceRange(CContext));
12562     return;
12563   }
12564   S.Diag(E->getExprLoc(), diag)
12565     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12566 }
12567 
12568 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12569 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12570                             SourceLocation CContext,
12571                             unsigned diag, bool pruneControlFlow = false) {
12572   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12573 }
12574 
12575 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12576   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12577       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12578 }
12579 
12580 static void adornObjCBoolConversionDiagWithTernaryFixit(
12581     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12582   Expr *Ignored = SourceExpr->IgnoreImplicit();
12583   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12584     Ignored = OVE->getSourceExpr();
12585   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12586                      isa<BinaryOperator>(Ignored) ||
12587                      isa<CXXOperatorCallExpr>(Ignored);
12588   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12589   if (NeedsParens)
12590     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12591             << FixItHint::CreateInsertion(EndLoc, ")");
12592   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12593 }
12594 
12595 /// Diagnose an implicit cast from a floating point value to an integer value.
12596 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12597                                     SourceLocation CContext) {
12598   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12599   const bool PruneWarnings = S.inTemplateInstantiation();
12600 
12601   Expr *InnerE = E->IgnoreParenImpCasts();
12602   // We also want to warn on, e.g., "int i = -1.234"
12603   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12604     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12605       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12606 
12607   const bool IsLiteral =
12608       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12609 
12610   llvm::APFloat Value(0.0);
12611   bool IsConstant =
12612     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12613   if (!IsConstant) {
12614     if (isObjCSignedCharBool(S, T)) {
12615       return adornObjCBoolConversionDiagWithTernaryFixit(
12616           S, E,
12617           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12618               << E->getType());
12619     }
12620 
12621     return DiagnoseImpCast(S, E, T, CContext,
12622                            diag::warn_impcast_float_integer, PruneWarnings);
12623   }
12624 
12625   bool isExact = false;
12626 
12627   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12628                             T->hasUnsignedIntegerRepresentation());
12629   llvm::APFloat::opStatus Result = Value.convertToInteger(
12630       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12631 
12632   // FIXME: Force the precision of the source value down so we don't print
12633   // digits which are usually useless (we don't really care here if we
12634   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12635   // would automatically print the shortest representation, but it's a bit
12636   // tricky to implement.
12637   SmallString<16> PrettySourceValue;
12638   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12639   precision = (precision * 59 + 195) / 196;
12640   Value.toString(PrettySourceValue, precision);
12641 
12642   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12643     return adornObjCBoolConversionDiagWithTernaryFixit(
12644         S, E,
12645         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12646             << PrettySourceValue);
12647   }
12648 
12649   if (Result == llvm::APFloat::opOK && isExact) {
12650     if (IsLiteral) return;
12651     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12652                            PruneWarnings);
12653   }
12654 
12655   // Conversion of a floating-point value to a non-bool integer where the
12656   // integral part cannot be represented by the integer type is undefined.
12657   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12658     return DiagnoseImpCast(
12659         S, E, T, CContext,
12660         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12661                   : diag::warn_impcast_float_to_integer_out_of_range,
12662         PruneWarnings);
12663 
12664   unsigned DiagID = 0;
12665   if (IsLiteral) {
12666     // Warn on floating point literal to integer.
12667     DiagID = diag::warn_impcast_literal_float_to_integer;
12668   } else if (IntegerValue == 0) {
12669     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12670       return DiagnoseImpCast(S, E, T, CContext,
12671                              diag::warn_impcast_float_integer, PruneWarnings);
12672     }
12673     // Warn on non-zero to zero conversion.
12674     DiagID = diag::warn_impcast_float_to_integer_zero;
12675   } else {
12676     if (IntegerValue.isUnsigned()) {
12677       if (!IntegerValue.isMaxValue()) {
12678         return DiagnoseImpCast(S, E, T, CContext,
12679                                diag::warn_impcast_float_integer, PruneWarnings);
12680       }
12681     } else {  // IntegerValue.isSigned()
12682       if (!IntegerValue.isMaxSignedValue() &&
12683           !IntegerValue.isMinSignedValue()) {
12684         return DiagnoseImpCast(S, E, T, CContext,
12685                                diag::warn_impcast_float_integer, PruneWarnings);
12686       }
12687     }
12688     // Warn on evaluatable floating point expression to integer conversion.
12689     DiagID = diag::warn_impcast_float_to_integer;
12690   }
12691 
12692   SmallString<16> PrettyTargetValue;
12693   if (IsBool)
12694     PrettyTargetValue = Value.isZero() ? "false" : "true";
12695   else
12696     IntegerValue.toString(PrettyTargetValue);
12697 
12698   if (PruneWarnings) {
12699     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12700                           S.PDiag(DiagID)
12701                               << E->getType() << T.getUnqualifiedType()
12702                               << PrettySourceValue << PrettyTargetValue
12703                               << E->getSourceRange() << SourceRange(CContext));
12704   } else {
12705     S.Diag(E->getExprLoc(), DiagID)
12706         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12707         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12708   }
12709 }
12710 
12711 /// Analyze the given compound assignment for the possible losing of
12712 /// floating-point precision.
12713 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12714   assert(isa<CompoundAssignOperator>(E) &&
12715          "Must be compound assignment operation");
12716   // Recurse on the LHS and RHS in here
12717   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12718   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12719 
12720   if (E->getLHS()->getType()->isAtomicType())
12721     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12722 
12723   // Now check the outermost expression
12724   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12725   const auto *RBT = cast<CompoundAssignOperator>(E)
12726                         ->getComputationResultType()
12727                         ->getAs<BuiltinType>();
12728 
12729   // The below checks assume source is floating point.
12730   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12731 
12732   // If source is floating point but target is an integer.
12733   if (ResultBT->isInteger())
12734     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12735                            E->getExprLoc(), diag::warn_impcast_float_integer);
12736 
12737   if (!ResultBT->isFloatingPoint())
12738     return;
12739 
12740   // If both source and target are floating points, warn about losing precision.
12741   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12742       QualType(ResultBT, 0), QualType(RBT, 0));
12743   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12744     // warn about dropping FP rank.
12745     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12746                     diag::warn_impcast_float_result_precision);
12747 }
12748 
12749 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12750                                       IntRange Range) {
12751   if (!Range.Width) return "0";
12752 
12753   llvm::APSInt ValueInRange = Value;
12754   ValueInRange.setIsSigned(!Range.NonNegative);
12755   ValueInRange = ValueInRange.trunc(Range.Width);
12756   return toString(ValueInRange, 10);
12757 }
12758 
12759 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12760   if (!isa<ImplicitCastExpr>(Ex))
12761     return false;
12762 
12763   Expr *InnerE = Ex->IgnoreParenImpCasts();
12764   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12765   const Type *Source =
12766     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12767   if (Target->isDependentType())
12768     return false;
12769 
12770   const BuiltinType *FloatCandidateBT =
12771     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12772   const Type *BoolCandidateType = ToBool ? Target : Source;
12773 
12774   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12775           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12776 }
12777 
12778 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12779                                              SourceLocation CC) {
12780   unsigned NumArgs = TheCall->getNumArgs();
12781   for (unsigned i = 0; i < NumArgs; ++i) {
12782     Expr *CurrA = TheCall->getArg(i);
12783     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12784       continue;
12785 
12786     bool IsSwapped = ((i > 0) &&
12787         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12788     IsSwapped |= ((i < (NumArgs - 1)) &&
12789         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12790     if (IsSwapped) {
12791       // Warn on this floating-point to bool conversion.
12792       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12793                       CurrA->getType(), CC,
12794                       diag::warn_impcast_floating_point_to_bool);
12795     }
12796   }
12797 }
12798 
12799 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12800                                    SourceLocation CC) {
12801   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12802                         E->getExprLoc()))
12803     return;
12804 
12805   // Don't warn on functions which have return type nullptr_t.
12806   if (isa<CallExpr>(E))
12807     return;
12808 
12809   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12810   const Expr::NullPointerConstantKind NullKind =
12811       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12812   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12813     return;
12814 
12815   // Return if target type is a safe conversion.
12816   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12817       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12818     return;
12819 
12820   SourceLocation Loc = E->getSourceRange().getBegin();
12821 
12822   // Venture through the macro stacks to get to the source of macro arguments.
12823   // The new location is a better location than the complete location that was
12824   // passed in.
12825   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12826   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12827 
12828   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12829   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12830     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12831         Loc, S.SourceMgr, S.getLangOpts());
12832     if (MacroName == "NULL")
12833       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12834   }
12835 
12836   // Only warn if the null and context location are in the same macro expansion.
12837   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12838     return;
12839 
12840   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12841       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12842       << FixItHint::CreateReplacement(Loc,
12843                                       S.getFixItZeroLiteralForType(T, Loc));
12844 }
12845 
12846 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12847                                   ObjCArrayLiteral *ArrayLiteral);
12848 
12849 static void
12850 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12851                            ObjCDictionaryLiteral *DictionaryLiteral);
12852 
12853 /// Check a single element within a collection literal against the
12854 /// target element type.
12855 static void checkObjCCollectionLiteralElement(Sema &S,
12856                                               QualType TargetElementType,
12857                                               Expr *Element,
12858                                               unsigned ElementKind) {
12859   // Skip a bitcast to 'id' or qualified 'id'.
12860   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12861     if (ICE->getCastKind() == CK_BitCast &&
12862         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12863       Element = ICE->getSubExpr();
12864   }
12865 
12866   QualType ElementType = Element->getType();
12867   ExprResult ElementResult(Element);
12868   if (ElementType->getAs<ObjCObjectPointerType>() &&
12869       S.CheckSingleAssignmentConstraints(TargetElementType,
12870                                          ElementResult,
12871                                          false, false)
12872         != Sema::Compatible) {
12873     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12874         << ElementType << ElementKind << TargetElementType
12875         << Element->getSourceRange();
12876   }
12877 
12878   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12879     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12880   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12881     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12882 }
12883 
12884 /// Check an Objective-C array literal being converted to the given
12885 /// target type.
12886 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12887                                   ObjCArrayLiteral *ArrayLiteral) {
12888   if (!S.NSArrayDecl)
12889     return;
12890 
12891   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12892   if (!TargetObjCPtr)
12893     return;
12894 
12895   if (TargetObjCPtr->isUnspecialized() ||
12896       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12897         != S.NSArrayDecl->getCanonicalDecl())
12898     return;
12899 
12900   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12901   if (TypeArgs.size() != 1)
12902     return;
12903 
12904   QualType TargetElementType = TypeArgs[0];
12905   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12906     checkObjCCollectionLiteralElement(S, TargetElementType,
12907                                       ArrayLiteral->getElement(I),
12908                                       0);
12909   }
12910 }
12911 
12912 /// Check an Objective-C dictionary literal being converted to the given
12913 /// target type.
12914 static void
12915 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12916                            ObjCDictionaryLiteral *DictionaryLiteral) {
12917   if (!S.NSDictionaryDecl)
12918     return;
12919 
12920   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12921   if (!TargetObjCPtr)
12922     return;
12923 
12924   if (TargetObjCPtr->isUnspecialized() ||
12925       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12926         != S.NSDictionaryDecl->getCanonicalDecl())
12927     return;
12928 
12929   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12930   if (TypeArgs.size() != 2)
12931     return;
12932 
12933   QualType TargetKeyType = TypeArgs[0];
12934   QualType TargetObjectType = TypeArgs[1];
12935   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12936     auto Element = DictionaryLiteral->getKeyValueElement(I);
12937     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12938     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12939   }
12940 }
12941 
12942 // Helper function to filter out cases for constant width constant conversion.
12943 // Don't warn on char array initialization or for non-decimal values.
12944 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12945                                           SourceLocation CC) {
12946   // If initializing from a constant, and the constant starts with '0',
12947   // then it is a binary, octal, or hexadecimal.  Allow these constants
12948   // to fill all the bits, even if there is a sign change.
12949   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12950     const char FirstLiteralCharacter =
12951         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12952     if (FirstLiteralCharacter == '0')
12953       return false;
12954   }
12955 
12956   // If the CC location points to a '{', and the type is char, then assume
12957   // assume it is an array initialization.
12958   if (CC.isValid() && T->isCharType()) {
12959     const char FirstContextCharacter =
12960         S.getSourceManager().getCharacterData(CC)[0];
12961     if (FirstContextCharacter == '{')
12962       return false;
12963   }
12964 
12965   return true;
12966 }
12967 
12968 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12969   const auto *IL = dyn_cast<IntegerLiteral>(E);
12970   if (!IL) {
12971     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12972       if (UO->getOpcode() == UO_Minus)
12973         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12974     }
12975   }
12976 
12977   return IL;
12978 }
12979 
12980 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12981   E = E->IgnoreParenImpCasts();
12982   SourceLocation ExprLoc = E->getExprLoc();
12983 
12984   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12985     BinaryOperator::Opcode Opc = BO->getOpcode();
12986     Expr::EvalResult Result;
12987     // Do not diagnose unsigned shifts.
12988     if (Opc == BO_Shl) {
12989       const auto *LHS = getIntegerLiteral(BO->getLHS());
12990       const auto *RHS = getIntegerLiteral(BO->getRHS());
12991       if (LHS && LHS->getValue() == 0)
12992         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12993       else if (!E->isValueDependent() && LHS && RHS &&
12994                RHS->getValue().isNonNegative() &&
12995                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12996         S.Diag(ExprLoc, diag::warn_left_shift_always)
12997             << (Result.Val.getInt() != 0);
12998       else if (E->getType()->isSignedIntegerType())
12999         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13000     }
13001   }
13002 
13003   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13004     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13005     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13006     if (!LHS || !RHS)
13007       return;
13008     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13009         (RHS->getValue() == 0 || RHS->getValue() == 1))
13010       // Do not diagnose common idioms.
13011       return;
13012     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13013       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13014   }
13015 }
13016 
13017 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13018                                     SourceLocation CC,
13019                                     bool *ICContext = nullptr,
13020                                     bool IsListInit = false) {
13021   if (E->isTypeDependent() || E->isValueDependent()) return;
13022 
13023   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13024   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13025   if (Source == Target) return;
13026   if (Target->isDependentType()) return;
13027 
13028   // If the conversion context location is invalid don't complain. We also
13029   // don't want to emit a warning if the issue occurs from the expansion of
13030   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13031   // delay this check as long as possible. Once we detect we are in that
13032   // scenario, we just return.
13033   if (CC.isInvalid())
13034     return;
13035 
13036   if (Source->isAtomicType())
13037     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13038 
13039   // Diagnose implicit casts to bool.
13040   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13041     if (isa<StringLiteral>(E))
13042       // Warn on string literal to bool.  Checks for string literals in logical
13043       // and expressions, for instance, assert(0 && "error here"), are
13044       // prevented by a check in AnalyzeImplicitConversions().
13045       return DiagnoseImpCast(S, E, T, CC,
13046                              diag::warn_impcast_string_literal_to_bool);
13047     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13048         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13049       // This covers the literal expressions that evaluate to Objective-C
13050       // objects.
13051       return DiagnoseImpCast(S, E, T, CC,
13052                              diag::warn_impcast_objective_c_literal_to_bool);
13053     }
13054     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13055       // Warn on pointer to bool conversion that is always true.
13056       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13057                                      SourceRange(CC));
13058     }
13059   }
13060 
13061   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13062   // is a typedef for signed char (macOS), then that constant value has to be 1
13063   // or 0.
13064   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13065     Expr::EvalResult Result;
13066     if (E->EvaluateAsInt(Result, S.getASTContext(),
13067                          Expr::SE_AllowSideEffects)) {
13068       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13069         adornObjCBoolConversionDiagWithTernaryFixit(
13070             S, E,
13071             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13072                 << toString(Result.Val.getInt(), 10));
13073       }
13074       return;
13075     }
13076   }
13077 
13078   // Check implicit casts from Objective-C collection literals to specialized
13079   // collection types, e.g., NSArray<NSString *> *.
13080   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13081     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13082   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13083     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13084 
13085   // Strip vector types.
13086   if (isa<VectorType>(Source)) {
13087     if (Target->isVLSTBuiltinType() &&
13088         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13089                                          QualType(Source, 0)) ||
13090          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13091                                             QualType(Source, 0))))
13092       return;
13093 
13094     if (!isa<VectorType>(Target)) {
13095       if (S.SourceMgr.isInSystemMacro(CC))
13096         return;
13097       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13098     }
13099 
13100     // If the vector cast is cast between two vectors of the same size, it is
13101     // a bitcast, not a conversion.
13102     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13103       return;
13104 
13105     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13106     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13107   }
13108   if (auto VecTy = dyn_cast<VectorType>(Target))
13109     Target = VecTy->getElementType().getTypePtr();
13110 
13111   // Strip complex types.
13112   if (isa<ComplexType>(Source)) {
13113     if (!isa<ComplexType>(Target)) {
13114       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13115         return;
13116 
13117       return DiagnoseImpCast(S, E, T, CC,
13118                              S.getLangOpts().CPlusPlus
13119                                  ? diag::err_impcast_complex_scalar
13120                                  : diag::warn_impcast_complex_scalar);
13121     }
13122 
13123     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13124     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13125   }
13126 
13127   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13128   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13129 
13130   // If the source is floating point...
13131   if (SourceBT && SourceBT->isFloatingPoint()) {
13132     // ...and the target is floating point...
13133     if (TargetBT && TargetBT->isFloatingPoint()) {
13134       // ...then warn if we're dropping FP rank.
13135 
13136       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13137           QualType(SourceBT, 0), QualType(TargetBT, 0));
13138       if (Order > 0) {
13139         // Don't warn about float constants that are precisely
13140         // representable in the target type.
13141         Expr::EvalResult result;
13142         if (E->EvaluateAsRValue(result, S.Context)) {
13143           // Value might be a float, a float vector, or a float complex.
13144           if (IsSameFloatAfterCast(result.Val,
13145                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13146                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13147             return;
13148         }
13149 
13150         if (S.SourceMgr.isInSystemMacro(CC))
13151           return;
13152 
13153         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13154       }
13155       // ... or possibly if we're increasing rank, too
13156       else if (Order < 0) {
13157         if (S.SourceMgr.isInSystemMacro(CC))
13158           return;
13159 
13160         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13161       }
13162       return;
13163     }
13164 
13165     // If the target is integral, always warn.
13166     if (TargetBT && TargetBT->isInteger()) {
13167       if (S.SourceMgr.isInSystemMacro(CC))
13168         return;
13169 
13170       DiagnoseFloatingImpCast(S, E, T, CC);
13171     }
13172 
13173     // Detect the case where a call result is converted from floating-point to
13174     // to bool, and the final argument to the call is converted from bool, to
13175     // discover this typo:
13176     //
13177     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13178     //
13179     // FIXME: This is an incredibly special case; is there some more general
13180     // way to detect this class of misplaced-parentheses bug?
13181     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13182       // Check last argument of function call to see if it is an
13183       // implicit cast from a type matching the type the result
13184       // is being cast to.
13185       CallExpr *CEx = cast<CallExpr>(E);
13186       if (unsigned NumArgs = CEx->getNumArgs()) {
13187         Expr *LastA = CEx->getArg(NumArgs - 1);
13188         Expr *InnerE = LastA->IgnoreParenImpCasts();
13189         if (isa<ImplicitCastExpr>(LastA) &&
13190             InnerE->getType()->isBooleanType()) {
13191           // Warn on this floating-point to bool conversion
13192           DiagnoseImpCast(S, E, T, CC,
13193                           diag::warn_impcast_floating_point_to_bool);
13194         }
13195       }
13196     }
13197     return;
13198   }
13199 
13200   // Valid casts involving fixed point types should be accounted for here.
13201   if (Source->isFixedPointType()) {
13202     if (Target->isUnsaturatedFixedPointType()) {
13203       Expr::EvalResult Result;
13204       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13205                                   S.isConstantEvaluated())) {
13206         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13207         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13208         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13209         if (Value > MaxVal || Value < MinVal) {
13210           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13211                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13212                                     << Value.toString() << T
13213                                     << E->getSourceRange()
13214                                     << clang::SourceRange(CC));
13215           return;
13216         }
13217       }
13218     } else if (Target->isIntegerType()) {
13219       Expr::EvalResult Result;
13220       if (!S.isConstantEvaluated() &&
13221           E->EvaluateAsFixedPoint(Result, S.Context,
13222                                   Expr::SE_AllowSideEffects)) {
13223         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13224 
13225         bool Overflowed;
13226         llvm::APSInt IntResult = FXResult.convertToInt(
13227             S.Context.getIntWidth(T),
13228             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13229 
13230         if (Overflowed) {
13231           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13232                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13233                                     << FXResult.toString() << T
13234                                     << E->getSourceRange()
13235                                     << clang::SourceRange(CC));
13236           return;
13237         }
13238       }
13239     }
13240   } else if (Target->isUnsaturatedFixedPointType()) {
13241     if (Source->isIntegerType()) {
13242       Expr::EvalResult Result;
13243       if (!S.isConstantEvaluated() &&
13244           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13245         llvm::APSInt Value = Result.Val.getInt();
13246 
13247         bool Overflowed;
13248         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13249             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13250 
13251         if (Overflowed) {
13252           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13253                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13254                                     << toString(Value, /*Radix=*/10) << T
13255                                     << E->getSourceRange()
13256                                     << clang::SourceRange(CC));
13257           return;
13258         }
13259       }
13260     }
13261   }
13262 
13263   // If we are casting an integer type to a floating point type without
13264   // initialization-list syntax, we might lose accuracy if the floating
13265   // point type has a narrower significand than the integer type.
13266   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13267       TargetBT->isFloatingType() && !IsListInit) {
13268     // Determine the number of precision bits in the source integer type.
13269     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13270                                         /*Approximate*/ true);
13271     unsigned int SourcePrecision = SourceRange.Width;
13272 
13273     // Determine the number of precision bits in the
13274     // target floating point type.
13275     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13276         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13277 
13278     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13279         SourcePrecision > TargetPrecision) {
13280 
13281       if (Optional<llvm::APSInt> SourceInt =
13282               E->getIntegerConstantExpr(S.Context)) {
13283         // If the source integer is a constant, convert it to the target
13284         // floating point type. Issue a warning if the value changes
13285         // during the whole conversion.
13286         llvm::APFloat TargetFloatValue(
13287             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13288         llvm::APFloat::opStatus ConversionStatus =
13289             TargetFloatValue.convertFromAPInt(
13290                 *SourceInt, SourceBT->isSignedInteger(),
13291                 llvm::APFloat::rmNearestTiesToEven);
13292 
13293         if (ConversionStatus != llvm::APFloat::opOK) {
13294           SmallString<32> PrettySourceValue;
13295           SourceInt->toString(PrettySourceValue, 10);
13296           SmallString<32> PrettyTargetValue;
13297           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13298 
13299           S.DiagRuntimeBehavior(
13300               E->getExprLoc(), E,
13301               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13302                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13303                   << E->getSourceRange() << clang::SourceRange(CC));
13304         }
13305       } else {
13306         // Otherwise, the implicit conversion may lose precision.
13307         DiagnoseImpCast(S, E, T, CC,
13308                         diag::warn_impcast_integer_float_precision);
13309       }
13310     }
13311   }
13312 
13313   DiagnoseNullConversion(S, E, T, CC);
13314 
13315   S.DiscardMisalignedMemberAddress(Target, E);
13316 
13317   if (Target->isBooleanType())
13318     DiagnoseIntInBoolContext(S, E);
13319 
13320   if (!Source->isIntegerType() || !Target->isIntegerType())
13321     return;
13322 
13323   // TODO: remove this early return once the false positives for constant->bool
13324   // in templates, macros, etc, are reduced or removed.
13325   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13326     return;
13327 
13328   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13329       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13330     return adornObjCBoolConversionDiagWithTernaryFixit(
13331         S, E,
13332         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13333             << E->getType());
13334   }
13335 
13336   IntRange SourceTypeRange =
13337       IntRange::forTargetOfCanonicalType(S.Context, Source);
13338   IntRange LikelySourceRange =
13339       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13340   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13341 
13342   if (LikelySourceRange.Width > TargetRange.Width) {
13343     // If the source is a constant, use a default-on diagnostic.
13344     // TODO: this should happen for bitfield stores, too.
13345     Expr::EvalResult Result;
13346     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13347                          S.isConstantEvaluated())) {
13348       llvm::APSInt Value(32);
13349       Value = Result.Val.getInt();
13350 
13351       if (S.SourceMgr.isInSystemMacro(CC))
13352         return;
13353 
13354       std::string PrettySourceValue = toString(Value, 10);
13355       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13356 
13357       S.DiagRuntimeBehavior(
13358           E->getExprLoc(), E,
13359           S.PDiag(diag::warn_impcast_integer_precision_constant)
13360               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13361               << E->getSourceRange() << SourceRange(CC));
13362       return;
13363     }
13364 
13365     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13366     if (S.SourceMgr.isInSystemMacro(CC))
13367       return;
13368 
13369     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13370       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13371                              /* pruneControlFlow */ true);
13372     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13373   }
13374 
13375   if (TargetRange.Width > SourceTypeRange.Width) {
13376     if (auto *UO = dyn_cast<UnaryOperator>(E))
13377       if (UO->getOpcode() == UO_Minus)
13378         if (Source->isUnsignedIntegerType()) {
13379           if (Target->isUnsignedIntegerType())
13380             return DiagnoseImpCast(S, E, T, CC,
13381                                    diag::warn_impcast_high_order_zero_bits);
13382           if (Target->isSignedIntegerType())
13383             return DiagnoseImpCast(S, E, T, CC,
13384                                    diag::warn_impcast_nonnegative_result);
13385         }
13386   }
13387 
13388   if (TargetRange.Width == LikelySourceRange.Width &&
13389       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13390       Source->isSignedIntegerType()) {
13391     // Warn when doing a signed to signed conversion, warn if the positive
13392     // source value is exactly the width of the target type, which will
13393     // cause a negative value to be stored.
13394 
13395     Expr::EvalResult Result;
13396     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13397         !S.SourceMgr.isInSystemMacro(CC)) {
13398       llvm::APSInt Value = Result.Val.getInt();
13399       if (isSameWidthConstantConversion(S, E, T, CC)) {
13400         std::string PrettySourceValue = toString(Value, 10);
13401         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13402 
13403         S.DiagRuntimeBehavior(
13404             E->getExprLoc(), E,
13405             S.PDiag(diag::warn_impcast_integer_precision_constant)
13406                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13407                 << E->getSourceRange() << SourceRange(CC));
13408         return;
13409       }
13410     }
13411 
13412     // Fall through for non-constants to give a sign conversion warning.
13413   }
13414 
13415   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13416       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13417        LikelySourceRange.Width == TargetRange.Width)) {
13418     if (S.SourceMgr.isInSystemMacro(CC))
13419       return;
13420 
13421     unsigned DiagID = diag::warn_impcast_integer_sign;
13422 
13423     // Traditionally, gcc has warned about this under -Wsign-compare.
13424     // We also want to warn about it in -Wconversion.
13425     // So if -Wconversion is off, use a completely identical diagnostic
13426     // in the sign-compare group.
13427     // The conditional-checking code will
13428     if (ICContext) {
13429       DiagID = diag::warn_impcast_integer_sign_conditional;
13430       *ICContext = true;
13431     }
13432 
13433     return DiagnoseImpCast(S, E, T, CC, DiagID);
13434   }
13435 
13436   // Diagnose conversions between different enumeration types.
13437   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13438   // type, to give us better diagnostics.
13439   QualType SourceType = E->getType();
13440   if (!S.getLangOpts().CPlusPlus) {
13441     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13442       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13443         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13444         SourceType = S.Context.getTypeDeclType(Enum);
13445         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13446       }
13447   }
13448 
13449   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13450     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13451       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13452           TargetEnum->getDecl()->hasNameForLinkage() &&
13453           SourceEnum != TargetEnum) {
13454         if (S.SourceMgr.isInSystemMacro(CC))
13455           return;
13456 
13457         return DiagnoseImpCast(S, E, SourceType, T, CC,
13458                                diag::warn_impcast_different_enum_types);
13459       }
13460 }
13461 
13462 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13463                                      SourceLocation CC, QualType T);
13464 
13465 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13466                                     SourceLocation CC, bool &ICContext) {
13467   E = E->IgnoreParenImpCasts();
13468 
13469   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13470     return CheckConditionalOperator(S, CO, CC, T);
13471 
13472   AnalyzeImplicitConversions(S, E, CC);
13473   if (E->getType() != T)
13474     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13475 }
13476 
13477 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13478                                      SourceLocation CC, QualType T) {
13479   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13480 
13481   Expr *TrueExpr = E->getTrueExpr();
13482   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13483     TrueExpr = BCO->getCommon();
13484 
13485   bool Suspicious = false;
13486   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13487   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13488 
13489   if (T->isBooleanType())
13490     DiagnoseIntInBoolContext(S, E);
13491 
13492   // If -Wconversion would have warned about either of the candidates
13493   // for a signedness conversion to the context type...
13494   if (!Suspicious) return;
13495 
13496   // ...but it's currently ignored...
13497   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13498     return;
13499 
13500   // ...then check whether it would have warned about either of the
13501   // candidates for a signedness conversion to the condition type.
13502   if (E->getType() == T) return;
13503 
13504   Suspicious = false;
13505   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13506                           E->getType(), CC, &Suspicious);
13507   if (!Suspicious)
13508     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13509                             E->getType(), CC, &Suspicious);
13510 }
13511 
13512 /// Check conversion of given expression to boolean.
13513 /// Input argument E is a logical expression.
13514 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13515   if (S.getLangOpts().Bool)
13516     return;
13517   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13518     return;
13519   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13520 }
13521 
13522 namespace {
13523 struct AnalyzeImplicitConversionsWorkItem {
13524   Expr *E;
13525   SourceLocation CC;
13526   bool IsListInit;
13527 };
13528 }
13529 
13530 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13531 /// that should be visited are added to WorkList.
13532 static void AnalyzeImplicitConversions(
13533     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13534     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13535   Expr *OrigE = Item.E;
13536   SourceLocation CC = Item.CC;
13537 
13538   QualType T = OrigE->getType();
13539   Expr *E = OrigE->IgnoreParenImpCasts();
13540 
13541   // Propagate whether we are in a C++ list initialization expression.
13542   // If so, we do not issue warnings for implicit int-float conversion
13543   // precision loss, because C++11 narrowing already handles it.
13544   bool IsListInit = Item.IsListInit ||
13545                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13546 
13547   if (E->isTypeDependent() || E->isValueDependent())
13548     return;
13549 
13550   Expr *SourceExpr = E;
13551   // Examine, but don't traverse into the source expression of an
13552   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13553   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13554   // evaluate it in the context of checking the specific conversion to T though.
13555   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13556     if (auto *Src = OVE->getSourceExpr())
13557       SourceExpr = Src;
13558 
13559   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13560     if (UO->getOpcode() == UO_Not &&
13561         UO->getSubExpr()->isKnownToHaveBooleanValue())
13562       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13563           << OrigE->getSourceRange() << T->isBooleanType()
13564           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13565 
13566   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13567     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13568         BO->getLHS()->isKnownToHaveBooleanValue() &&
13569         BO->getRHS()->isKnownToHaveBooleanValue() &&
13570         BO->getLHS()->HasSideEffects(S.Context) &&
13571         BO->getRHS()->HasSideEffects(S.Context)) {
13572       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13573           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13574           << FixItHint::CreateReplacement(
13575                  BO->getOperatorLoc(),
13576                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13577       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13578     }
13579 
13580   // For conditional operators, we analyze the arguments as if they
13581   // were being fed directly into the output.
13582   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13583     CheckConditionalOperator(S, CO, CC, T);
13584     return;
13585   }
13586 
13587   // Check implicit argument conversions for function calls.
13588   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13589     CheckImplicitArgumentConversions(S, Call, CC);
13590 
13591   // Go ahead and check any implicit conversions we might have skipped.
13592   // The non-canonical typecheck is just an optimization;
13593   // CheckImplicitConversion will filter out dead implicit conversions.
13594   if (SourceExpr->getType() != T)
13595     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13596 
13597   // Now continue drilling into this expression.
13598 
13599   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13600     // The bound subexpressions in a PseudoObjectExpr are not reachable
13601     // as transitive children.
13602     // FIXME: Use a more uniform representation for this.
13603     for (auto *SE : POE->semantics())
13604       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13605         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13606   }
13607 
13608   // Skip past explicit casts.
13609   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13610     E = CE->getSubExpr()->IgnoreParenImpCasts();
13611     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13612       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13613     WorkList.push_back({E, CC, IsListInit});
13614     return;
13615   }
13616 
13617   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13618     // Do a somewhat different check with comparison operators.
13619     if (BO->isComparisonOp())
13620       return AnalyzeComparison(S, BO);
13621 
13622     // And with simple assignments.
13623     if (BO->getOpcode() == BO_Assign)
13624       return AnalyzeAssignment(S, BO);
13625     // And with compound assignments.
13626     if (BO->isAssignmentOp())
13627       return AnalyzeCompoundAssignment(S, BO);
13628   }
13629 
13630   // These break the otherwise-useful invariant below.  Fortunately,
13631   // we don't really need to recurse into them, because any internal
13632   // expressions should have been analyzed already when they were
13633   // built into statements.
13634   if (isa<StmtExpr>(E)) return;
13635 
13636   // Don't descend into unevaluated contexts.
13637   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13638 
13639   // Now just recurse over the expression's children.
13640   CC = E->getExprLoc();
13641   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13642   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13643   for (Stmt *SubStmt : E->children()) {
13644     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13645     if (!ChildExpr)
13646       continue;
13647 
13648     if (IsLogicalAndOperator &&
13649         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13650       // Ignore checking string literals that are in logical and operators.
13651       // This is a common pattern for asserts.
13652       continue;
13653     WorkList.push_back({ChildExpr, CC, IsListInit});
13654   }
13655 
13656   if (BO && BO->isLogicalOp()) {
13657     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13658     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13659       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13660 
13661     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13662     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13663       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13664   }
13665 
13666   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13667     if (U->getOpcode() == UO_LNot) {
13668       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13669     } else if (U->getOpcode() != UO_AddrOf) {
13670       if (U->getSubExpr()->getType()->isAtomicType())
13671         S.Diag(U->getSubExpr()->getBeginLoc(),
13672                diag::warn_atomic_implicit_seq_cst);
13673     }
13674   }
13675 }
13676 
13677 /// AnalyzeImplicitConversions - Find and report any interesting
13678 /// implicit conversions in the given expression.  There are a couple
13679 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13680 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13681                                        bool IsListInit/*= false*/) {
13682   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13683   WorkList.push_back({OrigE, CC, IsListInit});
13684   while (!WorkList.empty())
13685     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13686 }
13687 
13688 /// Diagnose integer type and any valid implicit conversion to it.
13689 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13690   // Taking into account implicit conversions,
13691   // allow any integer.
13692   if (!E->getType()->isIntegerType()) {
13693     S.Diag(E->getBeginLoc(),
13694            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13695     return true;
13696   }
13697   // Potentially emit standard warnings for implicit conversions if enabled
13698   // using -Wconversion.
13699   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13700   return false;
13701 }
13702 
13703 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13704 // Returns true when emitting a warning about taking the address of a reference.
13705 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13706                               const PartialDiagnostic &PD) {
13707   E = E->IgnoreParenImpCasts();
13708 
13709   const FunctionDecl *FD = nullptr;
13710 
13711   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13712     if (!DRE->getDecl()->getType()->isReferenceType())
13713       return false;
13714   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13715     if (!M->getMemberDecl()->getType()->isReferenceType())
13716       return false;
13717   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13718     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13719       return false;
13720     FD = Call->getDirectCallee();
13721   } else {
13722     return false;
13723   }
13724 
13725   SemaRef.Diag(E->getExprLoc(), PD);
13726 
13727   // If possible, point to location of function.
13728   if (FD) {
13729     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13730   }
13731 
13732   return true;
13733 }
13734 
13735 // Returns true if the SourceLocation is expanded from any macro body.
13736 // Returns false if the SourceLocation is invalid, is from not in a macro
13737 // expansion, or is from expanded from a top-level macro argument.
13738 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13739   if (Loc.isInvalid())
13740     return false;
13741 
13742   while (Loc.isMacroID()) {
13743     if (SM.isMacroBodyExpansion(Loc))
13744       return true;
13745     Loc = SM.getImmediateMacroCallerLoc(Loc);
13746   }
13747 
13748   return false;
13749 }
13750 
13751 /// Diagnose pointers that are always non-null.
13752 /// \param E the expression containing the pointer
13753 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13754 /// compared to a null pointer
13755 /// \param IsEqual True when the comparison is equal to a null pointer
13756 /// \param Range Extra SourceRange to highlight in the diagnostic
13757 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13758                                         Expr::NullPointerConstantKind NullKind,
13759                                         bool IsEqual, SourceRange Range) {
13760   if (!E)
13761     return;
13762 
13763   // Don't warn inside macros.
13764   if (E->getExprLoc().isMacroID()) {
13765     const SourceManager &SM = getSourceManager();
13766     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13767         IsInAnyMacroBody(SM, Range.getBegin()))
13768       return;
13769   }
13770   E = E->IgnoreImpCasts();
13771 
13772   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13773 
13774   if (isa<CXXThisExpr>(E)) {
13775     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13776                                 : diag::warn_this_bool_conversion;
13777     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13778     return;
13779   }
13780 
13781   bool IsAddressOf = false;
13782 
13783   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13784     if (UO->getOpcode() != UO_AddrOf)
13785       return;
13786     IsAddressOf = true;
13787     E = UO->getSubExpr();
13788   }
13789 
13790   if (IsAddressOf) {
13791     unsigned DiagID = IsCompare
13792                           ? diag::warn_address_of_reference_null_compare
13793                           : diag::warn_address_of_reference_bool_conversion;
13794     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13795                                          << IsEqual;
13796     if (CheckForReference(*this, E, PD)) {
13797       return;
13798     }
13799   }
13800 
13801   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13802     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13803     std::string Str;
13804     llvm::raw_string_ostream S(Str);
13805     E->printPretty(S, nullptr, getPrintingPolicy());
13806     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13807                                 : diag::warn_cast_nonnull_to_bool;
13808     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13809       << E->getSourceRange() << Range << IsEqual;
13810     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13811   };
13812 
13813   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13814   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13815     if (auto *Callee = Call->getDirectCallee()) {
13816       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13817         ComplainAboutNonnullParamOrCall(A);
13818         return;
13819       }
13820     }
13821   }
13822 
13823   // Expect to find a single Decl.  Skip anything more complicated.
13824   ValueDecl *D = nullptr;
13825   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13826     D = R->getDecl();
13827   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13828     D = M->getMemberDecl();
13829   }
13830 
13831   // Weak Decls can be null.
13832   if (!D || D->isWeak())
13833     return;
13834 
13835   // Check for parameter decl with nonnull attribute
13836   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13837     if (getCurFunction() &&
13838         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13839       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13840         ComplainAboutNonnullParamOrCall(A);
13841         return;
13842       }
13843 
13844       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13845         // Skip function template not specialized yet.
13846         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13847           return;
13848         auto ParamIter = llvm::find(FD->parameters(), PV);
13849         assert(ParamIter != FD->param_end());
13850         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13851 
13852         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13853           if (!NonNull->args_size()) {
13854               ComplainAboutNonnullParamOrCall(NonNull);
13855               return;
13856           }
13857 
13858           for (const ParamIdx &ArgNo : NonNull->args()) {
13859             if (ArgNo.getASTIndex() == ParamNo) {
13860               ComplainAboutNonnullParamOrCall(NonNull);
13861               return;
13862             }
13863           }
13864         }
13865       }
13866     }
13867   }
13868 
13869   QualType T = D->getType();
13870   const bool IsArray = T->isArrayType();
13871   const bool IsFunction = T->isFunctionType();
13872 
13873   // Address of function is used to silence the function warning.
13874   if (IsAddressOf && IsFunction) {
13875     return;
13876   }
13877 
13878   // Found nothing.
13879   if (!IsAddressOf && !IsFunction && !IsArray)
13880     return;
13881 
13882   // Pretty print the expression for the diagnostic.
13883   std::string Str;
13884   llvm::raw_string_ostream S(Str);
13885   E->printPretty(S, nullptr, getPrintingPolicy());
13886 
13887   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13888                               : diag::warn_impcast_pointer_to_bool;
13889   enum {
13890     AddressOf,
13891     FunctionPointer,
13892     ArrayPointer
13893   } DiagType;
13894   if (IsAddressOf)
13895     DiagType = AddressOf;
13896   else if (IsFunction)
13897     DiagType = FunctionPointer;
13898   else if (IsArray)
13899     DiagType = ArrayPointer;
13900   else
13901     llvm_unreachable("Could not determine diagnostic.");
13902   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13903                                 << Range << IsEqual;
13904 
13905   if (!IsFunction)
13906     return;
13907 
13908   // Suggest '&' to silence the function warning.
13909   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13910       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13911 
13912   // Check to see if '()' fixit should be emitted.
13913   QualType ReturnType;
13914   UnresolvedSet<4> NonTemplateOverloads;
13915   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13916   if (ReturnType.isNull())
13917     return;
13918 
13919   if (IsCompare) {
13920     // There are two cases here.  If there is null constant, the only suggest
13921     // for a pointer return type.  If the null is 0, then suggest if the return
13922     // type is a pointer or an integer type.
13923     if (!ReturnType->isPointerType()) {
13924       if (NullKind == Expr::NPCK_ZeroExpression ||
13925           NullKind == Expr::NPCK_ZeroLiteral) {
13926         if (!ReturnType->isIntegerType())
13927           return;
13928       } else {
13929         return;
13930       }
13931     }
13932   } else { // !IsCompare
13933     // For function to bool, only suggest if the function pointer has bool
13934     // return type.
13935     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13936       return;
13937   }
13938   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13939       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13940 }
13941 
13942 /// Diagnoses "dangerous" implicit conversions within the given
13943 /// expression (which is a full expression).  Implements -Wconversion
13944 /// and -Wsign-compare.
13945 ///
13946 /// \param CC the "context" location of the implicit conversion, i.e.
13947 ///   the most location of the syntactic entity requiring the implicit
13948 ///   conversion
13949 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13950   // Don't diagnose in unevaluated contexts.
13951   if (isUnevaluatedContext())
13952     return;
13953 
13954   // Don't diagnose for value- or type-dependent expressions.
13955   if (E->isTypeDependent() || E->isValueDependent())
13956     return;
13957 
13958   // Check for array bounds violations in cases where the check isn't triggered
13959   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13960   // ArraySubscriptExpr is on the RHS of a variable initialization.
13961   CheckArrayAccess(E);
13962 
13963   // This is not the right CC for (e.g.) a variable initialization.
13964   AnalyzeImplicitConversions(*this, E, CC);
13965 }
13966 
13967 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13968 /// Input argument E is a logical expression.
13969 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13970   ::CheckBoolLikeConversion(*this, E, CC);
13971 }
13972 
13973 /// Diagnose when expression is an integer constant expression and its evaluation
13974 /// results in integer overflow
13975 void Sema::CheckForIntOverflow (Expr *E) {
13976   // Use a work list to deal with nested struct initializers.
13977   SmallVector<Expr *, 2> Exprs(1, E);
13978 
13979   do {
13980     Expr *OriginalE = Exprs.pop_back_val();
13981     Expr *E = OriginalE->IgnoreParenCasts();
13982 
13983     if (isa<BinaryOperator>(E)) {
13984       E->EvaluateForOverflow(Context);
13985       continue;
13986     }
13987 
13988     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13989       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13990     else if (isa<ObjCBoxedExpr>(OriginalE))
13991       E->EvaluateForOverflow(Context);
13992     else if (auto Call = dyn_cast<CallExpr>(E))
13993       Exprs.append(Call->arg_begin(), Call->arg_end());
13994     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13995       Exprs.append(Message->arg_begin(), Message->arg_end());
13996   } while (!Exprs.empty());
13997 }
13998 
13999 namespace {
14000 
14001 /// Visitor for expressions which looks for unsequenced operations on the
14002 /// same object.
14003 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14004   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14005 
14006   /// A tree of sequenced regions within an expression. Two regions are
14007   /// unsequenced if one is an ancestor or a descendent of the other. When we
14008   /// finish processing an expression with sequencing, such as a comma
14009   /// expression, we fold its tree nodes into its parent, since they are
14010   /// unsequenced with respect to nodes we will visit later.
14011   class SequenceTree {
14012     struct Value {
14013       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14014       unsigned Parent : 31;
14015       unsigned Merged : 1;
14016     };
14017     SmallVector<Value, 8> Values;
14018 
14019   public:
14020     /// A region within an expression which may be sequenced with respect
14021     /// to some other region.
14022     class Seq {
14023       friend class SequenceTree;
14024 
14025       unsigned Index;
14026 
14027       explicit Seq(unsigned N) : Index(N) {}
14028 
14029     public:
14030       Seq() : Index(0) {}
14031     };
14032 
14033     SequenceTree() { Values.push_back(Value(0)); }
14034     Seq root() const { return Seq(0); }
14035 
14036     /// Create a new sequence of operations, which is an unsequenced
14037     /// subset of \p Parent. This sequence of operations is sequenced with
14038     /// respect to other children of \p Parent.
14039     Seq allocate(Seq Parent) {
14040       Values.push_back(Value(Parent.Index));
14041       return Seq(Values.size() - 1);
14042     }
14043 
14044     /// Merge a sequence of operations into its parent.
14045     void merge(Seq S) {
14046       Values[S.Index].Merged = true;
14047     }
14048 
14049     /// Determine whether two operations are unsequenced. This operation
14050     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14051     /// should have been merged into its parent as appropriate.
14052     bool isUnsequenced(Seq Cur, Seq Old) {
14053       unsigned C = representative(Cur.Index);
14054       unsigned Target = representative(Old.Index);
14055       while (C >= Target) {
14056         if (C == Target)
14057           return true;
14058         C = Values[C].Parent;
14059       }
14060       return false;
14061     }
14062 
14063   private:
14064     /// Pick a representative for a sequence.
14065     unsigned representative(unsigned K) {
14066       if (Values[K].Merged)
14067         // Perform path compression as we go.
14068         return Values[K].Parent = representative(Values[K].Parent);
14069       return K;
14070     }
14071   };
14072 
14073   /// An object for which we can track unsequenced uses.
14074   using Object = const NamedDecl *;
14075 
14076   /// Different flavors of object usage which we track. We only track the
14077   /// least-sequenced usage of each kind.
14078   enum UsageKind {
14079     /// A read of an object. Multiple unsequenced reads are OK.
14080     UK_Use,
14081 
14082     /// A modification of an object which is sequenced before the value
14083     /// computation of the expression, such as ++n in C++.
14084     UK_ModAsValue,
14085 
14086     /// A modification of an object which is not sequenced before the value
14087     /// computation of the expression, such as n++.
14088     UK_ModAsSideEffect,
14089 
14090     UK_Count = UK_ModAsSideEffect + 1
14091   };
14092 
14093   /// Bundle together a sequencing region and the expression corresponding
14094   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14095   struct Usage {
14096     const Expr *UsageExpr;
14097     SequenceTree::Seq Seq;
14098 
14099     Usage() : UsageExpr(nullptr) {}
14100   };
14101 
14102   struct UsageInfo {
14103     Usage Uses[UK_Count];
14104 
14105     /// Have we issued a diagnostic for this object already?
14106     bool Diagnosed;
14107 
14108     UsageInfo() : Diagnosed(false) {}
14109   };
14110   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14111 
14112   Sema &SemaRef;
14113 
14114   /// Sequenced regions within the expression.
14115   SequenceTree Tree;
14116 
14117   /// Declaration modifications and references which we have seen.
14118   UsageInfoMap UsageMap;
14119 
14120   /// The region we are currently within.
14121   SequenceTree::Seq Region;
14122 
14123   /// Filled in with declarations which were modified as a side-effect
14124   /// (that is, post-increment operations).
14125   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14126 
14127   /// Expressions to check later. We defer checking these to reduce
14128   /// stack usage.
14129   SmallVectorImpl<const Expr *> &WorkList;
14130 
14131   /// RAII object wrapping the visitation of a sequenced subexpression of an
14132   /// expression. At the end of this process, the side-effects of the evaluation
14133   /// become sequenced with respect to the value computation of the result, so
14134   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14135   /// UK_ModAsValue.
14136   struct SequencedSubexpression {
14137     SequencedSubexpression(SequenceChecker &Self)
14138       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14139       Self.ModAsSideEffect = &ModAsSideEffect;
14140     }
14141 
14142     ~SequencedSubexpression() {
14143       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14144         // Add a new usage with usage kind UK_ModAsValue, and then restore
14145         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14146         // the previous one was empty).
14147         UsageInfo &UI = Self.UsageMap[M.first];
14148         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14149         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14150         SideEffectUsage = M.second;
14151       }
14152       Self.ModAsSideEffect = OldModAsSideEffect;
14153     }
14154 
14155     SequenceChecker &Self;
14156     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14157     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14158   };
14159 
14160   /// RAII object wrapping the visitation of a subexpression which we might
14161   /// choose to evaluate as a constant. If any subexpression is evaluated and
14162   /// found to be non-constant, this allows us to suppress the evaluation of
14163   /// the outer expression.
14164   class EvaluationTracker {
14165   public:
14166     EvaluationTracker(SequenceChecker &Self)
14167         : Self(Self), Prev(Self.EvalTracker) {
14168       Self.EvalTracker = this;
14169     }
14170 
14171     ~EvaluationTracker() {
14172       Self.EvalTracker = Prev;
14173       if (Prev)
14174         Prev->EvalOK &= EvalOK;
14175     }
14176 
14177     bool evaluate(const Expr *E, bool &Result) {
14178       if (!EvalOK || E->isValueDependent())
14179         return false;
14180       EvalOK = E->EvaluateAsBooleanCondition(
14181           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14182       return EvalOK;
14183     }
14184 
14185   private:
14186     SequenceChecker &Self;
14187     EvaluationTracker *Prev;
14188     bool EvalOK = true;
14189   } *EvalTracker = nullptr;
14190 
14191   /// Find the object which is produced by the specified expression,
14192   /// if any.
14193   Object getObject(const Expr *E, bool Mod) const {
14194     E = E->IgnoreParenCasts();
14195     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14196       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14197         return getObject(UO->getSubExpr(), Mod);
14198     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14199       if (BO->getOpcode() == BO_Comma)
14200         return getObject(BO->getRHS(), Mod);
14201       if (Mod && BO->isAssignmentOp())
14202         return getObject(BO->getLHS(), Mod);
14203     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14204       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14205       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14206         return ME->getMemberDecl();
14207     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14208       // FIXME: If this is a reference, map through to its value.
14209       return DRE->getDecl();
14210     return nullptr;
14211   }
14212 
14213   /// Note that an object \p O was modified or used by an expression
14214   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14215   /// the object \p O as obtained via the \p UsageMap.
14216   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14217     // Get the old usage for the given object and usage kind.
14218     Usage &U = UI.Uses[UK];
14219     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14220       // If we have a modification as side effect and are in a sequenced
14221       // subexpression, save the old Usage so that we can restore it later
14222       // in SequencedSubexpression::~SequencedSubexpression.
14223       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14224         ModAsSideEffect->push_back(std::make_pair(O, U));
14225       // Then record the new usage with the current sequencing region.
14226       U.UsageExpr = UsageExpr;
14227       U.Seq = Region;
14228     }
14229   }
14230 
14231   /// Check whether a modification or use of an object \p O in an expression
14232   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14233   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14234   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14235   /// usage and false we are checking for a mod-use unsequenced usage.
14236   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14237                   UsageKind OtherKind, bool IsModMod) {
14238     if (UI.Diagnosed)
14239       return;
14240 
14241     const Usage &U = UI.Uses[OtherKind];
14242     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14243       return;
14244 
14245     const Expr *Mod = U.UsageExpr;
14246     const Expr *ModOrUse = UsageExpr;
14247     if (OtherKind == UK_Use)
14248       std::swap(Mod, ModOrUse);
14249 
14250     SemaRef.DiagRuntimeBehavior(
14251         Mod->getExprLoc(), {Mod, ModOrUse},
14252         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14253                                : diag::warn_unsequenced_mod_use)
14254             << O << SourceRange(ModOrUse->getExprLoc()));
14255     UI.Diagnosed = true;
14256   }
14257 
14258   // A note on note{Pre, Post}{Use, Mod}:
14259   //
14260   // (It helps to follow the algorithm with an expression such as
14261   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14262   //  operations before C++17 and both are well-defined in C++17).
14263   //
14264   // When visiting a node which uses/modify an object we first call notePreUse
14265   // or notePreMod before visiting its sub-expression(s). At this point the
14266   // children of the current node have not yet been visited and so the eventual
14267   // uses/modifications resulting from the children of the current node have not
14268   // been recorded yet.
14269   //
14270   // We then visit the children of the current node. After that notePostUse or
14271   // notePostMod is called. These will 1) detect an unsequenced modification
14272   // as side effect (as in "k++ + k") and 2) add a new usage with the
14273   // appropriate usage kind.
14274   //
14275   // We also have to be careful that some operation sequences modification as
14276   // side effect as well (for example: || or ,). To account for this we wrap
14277   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14278   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14279   // which record usages which are modifications as side effect, and then
14280   // downgrade them (or more accurately restore the previous usage which was a
14281   // modification as side effect) when exiting the scope of the sequenced
14282   // subexpression.
14283 
14284   void notePreUse(Object O, const Expr *UseExpr) {
14285     UsageInfo &UI = UsageMap[O];
14286     // Uses conflict with other modifications.
14287     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14288   }
14289 
14290   void notePostUse(Object O, const Expr *UseExpr) {
14291     UsageInfo &UI = UsageMap[O];
14292     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14293                /*IsModMod=*/false);
14294     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14295   }
14296 
14297   void notePreMod(Object O, const Expr *ModExpr) {
14298     UsageInfo &UI = UsageMap[O];
14299     // Modifications conflict with other modifications and with uses.
14300     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14301     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14302   }
14303 
14304   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14305     UsageInfo &UI = UsageMap[O];
14306     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14307                /*IsModMod=*/true);
14308     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14309   }
14310 
14311 public:
14312   SequenceChecker(Sema &S, const Expr *E,
14313                   SmallVectorImpl<const Expr *> &WorkList)
14314       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14315     Visit(E);
14316     // Silence a -Wunused-private-field since WorkList is now unused.
14317     // TODO: Evaluate if it can be used, and if not remove it.
14318     (void)this->WorkList;
14319   }
14320 
14321   void VisitStmt(const Stmt *S) {
14322     // Skip all statements which aren't expressions for now.
14323   }
14324 
14325   void VisitExpr(const Expr *E) {
14326     // By default, just recurse to evaluated subexpressions.
14327     Base::VisitStmt(E);
14328   }
14329 
14330   void VisitCastExpr(const CastExpr *E) {
14331     Object O = Object();
14332     if (E->getCastKind() == CK_LValueToRValue)
14333       O = getObject(E->getSubExpr(), false);
14334 
14335     if (O)
14336       notePreUse(O, E);
14337     VisitExpr(E);
14338     if (O)
14339       notePostUse(O, E);
14340   }
14341 
14342   void VisitSequencedExpressions(const Expr *SequencedBefore,
14343                                  const Expr *SequencedAfter) {
14344     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14345     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14346     SequenceTree::Seq OldRegion = Region;
14347 
14348     {
14349       SequencedSubexpression SeqBefore(*this);
14350       Region = BeforeRegion;
14351       Visit(SequencedBefore);
14352     }
14353 
14354     Region = AfterRegion;
14355     Visit(SequencedAfter);
14356 
14357     Region = OldRegion;
14358 
14359     Tree.merge(BeforeRegion);
14360     Tree.merge(AfterRegion);
14361   }
14362 
14363   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14364     // C++17 [expr.sub]p1:
14365     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14366     //   expression E1 is sequenced before the expression E2.
14367     if (SemaRef.getLangOpts().CPlusPlus17)
14368       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14369     else {
14370       Visit(ASE->getLHS());
14371       Visit(ASE->getRHS());
14372     }
14373   }
14374 
14375   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14376   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14377   void VisitBinPtrMem(const BinaryOperator *BO) {
14378     // C++17 [expr.mptr.oper]p4:
14379     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14380     //  the expression E1 is sequenced before the expression E2.
14381     if (SemaRef.getLangOpts().CPlusPlus17)
14382       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14383     else {
14384       Visit(BO->getLHS());
14385       Visit(BO->getRHS());
14386     }
14387   }
14388 
14389   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14390   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14391   void VisitBinShlShr(const BinaryOperator *BO) {
14392     // C++17 [expr.shift]p4:
14393     //  The expression E1 is sequenced before the expression E2.
14394     if (SemaRef.getLangOpts().CPlusPlus17)
14395       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14396     else {
14397       Visit(BO->getLHS());
14398       Visit(BO->getRHS());
14399     }
14400   }
14401 
14402   void VisitBinComma(const BinaryOperator *BO) {
14403     // C++11 [expr.comma]p1:
14404     //   Every value computation and side effect associated with the left
14405     //   expression is sequenced before every value computation and side
14406     //   effect associated with the right expression.
14407     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14408   }
14409 
14410   void VisitBinAssign(const BinaryOperator *BO) {
14411     SequenceTree::Seq RHSRegion;
14412     SequenceTree::Seq LHSRegion;
14413     if (SemaRef.getLangOpts().CPlusPlus17) {
14414       RHSRegion = Tree.allocate(Region);
14415       LHSRegion = Tree.allocate(Region);
14416     } else {
14417       RHSRegion = Region;
14418       LHSRegion = Region;
14419     }
14420     SequenceTree::Seq OldRegion = Region;
14421 
14422     // C++11 [expr.ass]p1:
14423     //  [...] the assignment is sequenced after the value computation
14424     //  of the right and left operands, [...]
14425     //
14426     // so check it before inspecting the operands and update the
14427     // map afterwards.
14428     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14429     if (O)
14430       notePreMod(O, BO);
14431 
14432     if (SemaRef.getLangOpts().CPlusPlus17) {
14433       // C++17 [expr.ass]p1:
14434       //  [...] The right operand is sequenced before the left operand. [...]
14435       {
14436         SequencedSubexpression SeqBefore(*this);
14437         Region = RHSRegion;
14438         Visit(BO->getRHS());
14439       }
14440 
14441       Region = LHSRegion;
14442       Visit(BO->getLHS());
14443 
14444       if (O && isa<CompoundAssignOperator>(BO))
14445         notePostUse(O, BO);
14446 
14447     } else {
14448       // C++11 does not specify any sequencing between the LHS and RHS.
14449       Region = LHSRegion;
14450       Visit(BO->getLHS());
14451 
14452       if (O && isa<CompoundAssignOperator>(BO))
14453         notePostUse(O, BO);
14454 
14455       Region = RHSRegion;
14456       Visit(BO->getRHS());
14457     }
14458 
14459     // C++11 [expr.ass]p1:
14460     //  the assignment is sequenced [...] before the value computation of the
14461     //  assignment expression.
14462     // C11 6.5.16/3 has no such rule.
14463     Region = OldRegion;
14464     if (O)
14465       notePostMod(O, BO,
14466                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14467                                                   : UK_ModAsSideEffect);
14468     if (SemaRef.getLangOpts().CPlusPlus17) {
14469       Tree.merge(RHSRegion);
14470       Tree.merge(LHSRegion);
14471     }
14472   }
14473 
14474   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14475     VisitBinAssign(CAO);
14476   }
14477 
14478   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14479   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14480   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14481     Object O = getObject(UO->getSubExpr(), true);
14482     if (!O)
14483       return VisitExpr(UO);
14484 
14485     notePreMod(O, UO);
14486     Visit(UO->getSubExpr());
14487     // C++11 [expr.pre.incr]p1:
14488     //   the expression ++x is equivalent to x+=1
14489     notePostMod(O, UO,
14490                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14491                                                 : UK_ModAsSideEffect);
14492   }
14493 
14494   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14495   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14496   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14497     Object O = getObject(UO->getSubExpr(), true);
14498     if (!O)
14499       return VisitExpr(UO);
14500 
14501     notePreMod(O, UO);
14502     Visit(UO->getSubExpr());
14503     notePostMod(O, UO, UK_ModAsSideEffect);
14504   }
14505 
14506   void VisitBinLOr(const BinaryOperator *BO) {
14507     // C++11 [expr.log.or]p2:
14508     //  If the second expression is evaluated, every value computation and
14509     //  side effect associated with the first expression is sequenced before
14510     //  every value computation and side effect associated with the
14511     //  second expression.
14512     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14513     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14514     SequenceTree::Seq OldRegion = Region;
14515 
14516     EvaluationTracker Eval(*this);
14517     {
14518       SequencedSubexpression Sequenced(*this);
14519       Region = LHSRegion;
14520       Visit(BO->getLHS());
14521     }
14522 
14523     // C++11 [expr.log.or]p1:
14524     //  [...] the second operand is not evaluated if the first operand
14525     //  evaluates to true.
14526     bool EvalResult = false;
14527     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14528     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14529     if (ShouldVisitRHS) {
14530       Region = RHSRegion;
14531       Visit(BO->getRHS());
14532     }
14533 
14534     Region = OldRegion;
14535     Tree.merge(LHSRegion);
14536     Tree.merge(RHSRegion);
14537   }
14538 
14539   void VisitBinLAnd(const BinaryOperator *BO) {
14540     // C++11 [expr.log.and]p2:
14541     //  If the second expression is evaluated, every value computation and
14542     //  side effect associated with the first expression is sequenced before
14543     //  every value computation and side effect associated with the
14544     //  second expression.
14545     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14546     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14547     SequenceTree::Seq OldRegion = Region;
14548 
14549     EvaluationTracker Eval(*this);
14550     {
14551       SequencedSubexpression Sequenced(*this);
14552       Region = LHSRegion;
14553       Visit(BO->getLHS());
14554     }
14555 
14556     // C++11 [expr.log.and]p1:
14557     //  [...] the second operand is not evaluated if the first operand is false.
14558     bool EvalResult = false;
14559     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14560     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14561     if (ShouldVisitRHS) {
14562       Region = RHSRegion;
14563       Visit(BO->getRHS());
14564     }
14565 
14566     Region = OldRegion;
14567     Tree.merge(LHSRegion);
14568     Tree.merge(RHSRegion);
14569   }
14570 
14571   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14572     // C++11 [expr.cond]p1:
14573     //  [...] Every value computation and side effect associated with the first
14574     //  expression is sequenced before every value computation and side effect
14575     //  associated with the second or third expression.
14576     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14577 
14578     // No sequencing is specified between the true and false expression.
14579     // However since exactly one of both is going to be evaluated we can
14580     // consider them to be sequenced. This is needed to avoid warning on
14581     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14582     // both the true and false expressions because we can't evaluate x.
14583     // This will still allow us to detect an expression like (pre C++17)
14584     // "(x ? y += 1 : y += 2) = y".
14585     //
14586     // We don't wrap the visitation of the true and false expression with
14587     // SequencedSubexpression because we don't want to downgrade modifications
14588     // as side effect in the true and false expressions after the visition
14589     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14590     // not warn between the two "y++", but we should warn between the "y++"
14591     // and the "y".
14592     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14593     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14594     SequenceTree::Seq OldRegion = Region;
14595 
14596     EvaluationTracker Eval(*this);
14597     {
14598       SequencedSubexpression Sequenced(*this);
14599       Region = ConditionRegion;
14600       Visit(CO->getCond());
14601     }
14602 
14603     // C++11 [expr.cond]p1:
14604     // [...] The first expression is contextually converted to bool (Clause 4).
14605     // It is evaluated and if it is true, the result of the conditional
14606     // expression is the value of the second expression, otherwise that of the
14607     // third expression. Only one of the second and third expressions is
14608     // evaluated. [...]
14609     bool EvalResult = false;
14610     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14611     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14612     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14613     if (ShouldVisitTrueExpr) {
14614       Region = TrueRegion;
14615       Visit(CO->getTrueExpr());
14616     }
14617     if (ShouldVisitFalseExpr) {
14618       Region = FalseRegion;
14619       Visit(CO->getFalseExpr());
14620     }
14621 
14622     Region = OldRegion;
14623     Tree.merge(ConditionRegion);
14624     Tree.merge(TrueRegion);
14625     Tree.merge(FalseRegion);
14626   }
14627 
14628   void VisitCallExpr(const CallExpr *CE) {
14629     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14630 
14631     if (CE->isUnevaluatedBuiltinCall(Context))
14632       return;
14633 
14634     // C++11 [intro.execution]p15:
14635     //   When calling a function [...], every value computation and side effect
14636     //   associated with any argument expression, or with the postfix expression
14637     //   designating the called function, is sequenced before execution of every
14638     //   expression or statement in the body of the function [and thus before
14639     //   the value computation of its result].
14640     SequencedSubexpression Sequenced(*this);
14641     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14642       // C++17 [expr.call]p5
14643       //   The postfix-expression is sequenced before each expression in the
14644       //   expression-list and any default argument. [...]
14645       SequenceTree::Seq CalleeRegion;
14646       SequenceTree::Seq OtherRegion;
14647       if (SemaRef.getLangOpts().CPlusPlus17) {
14648         CalleeRegion = Tree.allocate(Region);
14649         OtherRegion = Tree.allocate(Region);
14650       } else {
14651         CalleeRegion = Region;
14652         OtherRegion = Region;
14653       }
14654       SequenceTree::Seq OldRegion = Region;
14655 
14656       // Visit the callee expression first.
14657       Region = CalleeRegion;
14658       if (SemaRef.getLangOpts().CPlusPlus17) {
14659         SequencedSubexpression Sequenced(*this);
14660         Visit(CE->getCallee());
14661       } else {
14662         Visit(CE->getCallee());
14663       }
14664 
14665       // Then visit the argument expressions.
14666       Region = OtherRegion;
14667       for (const Expr *Argument : CE->arguments())
14668         Visit(Argument);
14669 
14670       Region = OldRegion;
14671       if (SemaRef.getLangOpts().CPlusPlus17) {
14672         Tree.merge(CalleeRegion);
14673         Tree.merge(OtherRegion);
14674       }
14675     });
14676   }
14677 
14678   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14679     // C++17 [over.match.oper]p2:
14680     //   [...] the operator notation is first transformed to the equivalent
14681     //   function-call notation as summarized in Table 12 (where @ denotes one
14682     //   of the operators covered in the specified subclause). However, the
14683     //   operands are sequenced in the order prescribed for the built-in
14684     //   operator (Clause 8).
14685     //
14686     // From the above only overloaded binary operators and overloaded call
14687     // operators have sequencing rules in C++17 that we need to handle
14688     // separately.
14689     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14690         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14691       return VisitCallExpr(CXXOCE);
14692 
14693     enum {
14694       NoSequencing,
14695       LHSBeforeRHS,
14696       RHSBeforeLHS,
14697       LHSBeforeRest
14698     } SequencingKind;
14699     switch (CXXOCE->getOperator()) {
14700     case OO_Equal:
14701     case OO_PlusEqual:
14702     case OO_MinusEqual:
14703     case OO_StarEqual:
14704     case OO_SlashEqual:
14705     case OO_PercentEqual:
14706     case OO_CaretEqual:
14707     case OO_AmpEqual:
14708     case OO_PipeEqual:
14709     case OO_LessLessEqual:
14710     case OO_GreaterGreaterEqual:
14711       SequencingKind = RHSBeforeLHS;
14712       break;
14713 
14714     case OO_LessLess:
14715     case OO_GreaterGreater:
14716     case OO_AmpAmp:
14717     case OO_PipePipe:
14718     case OO_Comma:
14719     case OO_ArrowStar:
14720     case OO_Subscript:
14721       SequencingKind = LHSBeforeRHS;
14722       break;
14723 
14724     case OO_Call:
14725       SequencingKind = LHSBeforeRest;
14726       break;
14727 
14728     default:
14729       SequencingKind = NoSequencing;
14730       break;
14731     }
14732 
14733     if (SequencingKind == NoSequencing)
14734       return VisitCallExpr(CXXOCE);
14735 
14736     // This is a call, so all subexpressions are sequenced before the result.
14737     SequencedSubexpression Sequenced(*this);
14738 
14739     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14740       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14741              "Should only get there with C++17 and above!");
14742       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14743              "Should only get there with an overloaded binary operator"
14744              " or an overloaded call operator!");
14745 
14746       if (SequencingKind == LHSBeforeRest) {
14747         assert(CXXOCE->getOperator() == OO_Call &&
14748                "We should only have an overloaded call operator here!");
14749 
14750         // This is very similar to VisitCallExpr, except that we only have the
14751         // C++17 case. The postfix-expression is the first argument of the
14752         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14753         // are in the following arguments.
14754         //
14755         // Note that we intentionally do not visit the callee expression since
14756         // it is just a decayed reference to a function.
14757         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14758         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14759         SequenceTree::Seq OldRegion = Region;
14760 
14761         assert(CXXOCE->getNumArgs() >= 1 &&
14762                "An overloaded call operator must have at least one argument"
14763                " for the postfix-expression!");
14764         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14765         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14766                                           CXXOCE->getNumArgs() - 1);
14767 
14768         // Visit the postfix-expression first.
14769         {
14770           Region = PostfixExprRegion;
14771           SequencedSubexpression Sequenced(*this);
14772           Visit(PostfixExpr);
14773         }
14774 
14775         // Then visit the argument expressions.
14776         Region = ArgsRegion;
14777         for (const Expr *Arg : Args)
14778           Visit(Arg);
14779 
14780         Region = OldRegion;
14781         Tree.merge(PostfixExprRegion);
14782         Tree.merge(ArgsRegion);
14783       } else {
14784         assert(CXXOCE->getNumArgs() == 2 &&
14785                "Should only have two arguments here!");
14786         assert((SequencingKind == LHSBeforeRHS ||
14787                 SequencingKind == RHSBeforeLHS) &&
14788                "Unexpected sequencing kind!");
14789 
14790         // We do not visit the callee expression since it is just a decayed
14791         // reference to a function.
14792         const Expr *E1 = CXXOCE->getArg(0);
14793         const Expr *E2 = CXXOCE->getArg(1);
14794         if (SequencingKind == RHSBeforeLHS)
14795           std::swap(E1, E2);
14796 
14797         return VisitSequencedExpressions(E1, E2);
14798       }
14799     });
14800   }
14801 
14802   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14803     // This is a call, so all subexpressions are sequenced before the result.
14804     SequencedSubexpression Sequenced(*this);
14805 
14806     if (!CCE->isListInitialization())
14807       return VisitExpr(CCE);
14808 
14809     // In C++11, list initializations are sequenced.
14810     SmallVector<SequenceTree::Seq, 32> Elts;
14811     SequenceTree::Seq Parent = Region;
14812     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14813                                               E = CCE->arg_end();
14814          I != E; ++I) {
14815       Region = Tree.allocate(Parent);
14816       Elts.push_back(Region);
14817       Visit(*I);
14818     }
14819 
14820     // Forget that the initializers are sequenced.
14821     Region = Parent;
14822     for (unsigned I = 0; I < Elts.size(); ++I)
14823       Tree.merge(Elts[I]);
14824   }
14825 
14826   void VisitInitListExpr(const InitListExpr *ILE) {
14827     if (!SemaRef.getLangOpts().CPlusPlus11)
14828       return VisitExpr(ILE);
14829 
14830     // In C++11, list initializations are sequenced.
14831     SmallVector<SequenceTree::Seq, 32> Elts;
14832     SequenceTree::Seq Parent = Region;
14833     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14834       const Expr *E = ILE->getInit(I);
14835       if (!E)
14836         continue;
14837       Region = Tree.allocate(Parent);
14838       Elts.push_back(Region);
14839       Visit(E);
14840     }
14841 
14842     // Forget that the initializers are sequenced.
14843     Region = Parent;
14844     for (unsigned I = 0; I < Elts.size(); ++I)
14845       Tree.merge(Elts[I]);
14846   }
14847 };
14848 
14849 } // namespace
14850 
14851 void Sema::CheckUnsequencedOperations(const Expr *E) {
14852   SmallVector<const Expr *, 8> WorkList;
14853   WorkList.push_back(E);
14854   while (!WorkList.empty()) {
14855     const Expr *Item = WorkList.pop_back_val();
14856     SequenceChecker(*this, Item, WorkList);
14857   }
14858 }
14859 
14860 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14861                               bool IsConstexpr) {
14862   llvm::SaveAndRestore<bool> ConstantContext(
14863       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14864   CheckImplicitConversions(E, CheckLoc);
14865   if (!E->isInstantiationDependent())
14866     CheckUnsequencedOperations(E);
14867   if (!IsConstexpr && !E->isValueDependent())
14868     CheckForIntOverflow(E);
14869   DiagnoseMisalignedMembers();
14870 }
14871 
14872 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14873                                        FieldDecl *BitField,
14874                                        Expr *Init) {
14875   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14876 }
14877 
14878 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14879                                          SourceLocation Loc) {
14880   if (!PType->isVariablyModifiedType())
14881     return;
14882   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14883     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14884     return;
14885   }
14886   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14887     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14888     return;
14889   }
14890   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14891     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14892     return;
14893   }
14894 
14895   const ArrayType *AT = S.Context.getAsArrayType(PType);
14896   if (!AT)
14897     return;
14898 
14899   if (AT->getSizeModifier() != ArrayType::Star) {
14900     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14901     return;
14902   }
14903 
14904   S.Diag(Loc, diag::err_array_star_in_function_definition);
14905 }
14906 
14907 /// CheckParmsForFunctionDef - Check that the parameters of the given
14908 /// function are appropriate for the definition of a function. This
14909 /// takes care of any checks that cannot be performed on the
14910 /// declaration itself, e.g., that the types of each of the function
14911 /// parameters are complete.
14912 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14913                                     bool CheckParameterNames) {
14914   bool HasInvalidParm = false;
14915   for (ParmVarDecl *Param : Parameters) {
14916     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14917     // function declarator that is part of a function definition of
14918     // that function shall not have incomplete type.
14919     //
14920     // This is also C++ [dcl.fct]p6.
14921     if (!Param->isInvalidDecl() &&
14922         RequireCompleteType(Param->getLocation(), Param->getType(),
14923                             diag::err_typecheck_decl_incomplete_type)) {
14924       Param->setInvalidDecl();
14925       HasInvalidParm = true;
14926     }
14927 
14928     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14929     // declaration of each parameter shall include an identifier.
14930     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14931         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14932       // Diagnose this as an extension in C17 and earlier.
14933       if (!getLangOpts().C2x)
14934         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14935     }
14936 
14937     // C99 6.7.5.3p12:
14938     //   If the function declarator is not part of a definition of that
14939     //   function, parameters may have incomplete type and may use the [*]
14940     //   notation in their sequences of declarator specifiers to specify
14941     //   variable length array types.
14942     QualType PType = Param->getOriginalType();
14943     // FIXME: This diagnostic should point the '[*]' if source-location
14944     // information is added for it.
14945     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14946 
14947     // If the parameter is a c++ class type and it has to be destructed in the
14948     // callee function, declare the destructor so that it can be called by the
14949     // callee function. Do not perform any direct access check on the dtor here.
14950     if (!Param->isInvalidDecl()) {
14951       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14952         if (!ClassDecl->isInvalidDecl() &&
14953             !ClassDecl->hasIrrelevantDestructor() &&
14954             !ClassDecl->isDependentContext() &&
14955             ClassDecl->isParamDestroyedInCallee()) {
14956           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14957           MarkFunctionReferenced(Param->getLocation(), Destructor);
14958           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14959         }
14960       }
14961     }
14962 
14963     // Parameters with the pass_object_size attribute only need to be marked
14964     // constant at function definitions. Because we lack information about
14965     // whether we're on a declaration or definition when we're instantiating the
14966     // attribute, we need to check for constness here.
14967     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14968       if (!Param->getType().isConstQualified())
14969         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14970             << Attr->getSpelling() << 1;
14971 
14972     // Check for parameter names shadowing fields from the class.
14973     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14974       // The owning context for the parameter should be the function, but we
14975       // want to see if this function's declaration context is a record.
14976       DeclContext *DC = Param->getDeclContext();
14977       if (DC && DC->isFunctionOrMethod()) {
14978         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14979           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14980                                      RD, /*DeclIsField*/ false);
14981       }
14982     }
14983   }
14984 
14985   return HasInvalidParm;
14986 }
14987 
14988 Optional<std::pair<CharUnits, CharUnits>>
14989 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14990 
14991 /// Compute the alignment and offset of the base class object given the
14992 /// derived-to-base cast expression and the alignment and offset of the derived
14993 /// class object.
14994 static std::pair<CharUnits, CharUnits>
14995 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14996                                    CharUnits BaseAlignment, CharUnits Offset,
14997                                    ASTContext &Ctx) {
14998   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14999        ++PathI) {
15000     const CXXBaseSpecifier *Base = *PathI;
15001     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15002     if (Base->isVirtual()) {
15003       // The complete object may have a lower alignment than the non-virtual
15004       // alignment of the base, in which case the base may be misaligned. Choose
15005       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15006       // conservative lower bound of the complete object alignment.
15007       CharUnits NonVirtualAlignment =
15008           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15009       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15010       Offset = CharUnits::Zero();
15011     } else {
15012       const ASTRecordLayout &RL =
15013           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15014       Offset += RL.getBaseClassOffset(BaseDecl);
15015     }
15016     DerivedType = Base->getType();
15017   }
15018 
15019   return std::make_pair(BaseAlignment, Offset);
15020 }
15021 
15022 /// Compute the alignment and offset of a binary additive operator.
15023 static Optional<std::pair<CharUnits, CharUnits>>
15024 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15025                                      bool IsSub, ASTContext &Ctx) {
15026   QualType PointeeType = PtrE->getType()->getPointeeType();
15027 
15028   if (!PointeeType->isConstantSizeType())
15029     return llvm::None;
15030 
15031   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15032 
15033   if (!P)
15034     return llvm::None;
15035 
15036   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15037   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15038     CharUnits Offset = EltSize * IdxRes->getExtValue();
15039     if (IsSub)
15040       Offset = -Offset;
15041     return std::make_pair(P->first, P->second + Offset);
15042   }
15043 
15044   // If the integer expression isn't a constant expression, compute the lower
15045   // bound of the alignment using the alignment and offset of the pointer
15046   // expression and the element size.
15047   return std::make_pair(
15048       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15049       CharUnits::Zero());
15050 }
15051 
15052 /// This helper function takes an lvalue expression and returns the alignment of
15053 /// a VarDecl and a constant offset from the VarDecl.
15054 Optional<std::pair<CharUnits, CharUnits>>
15055 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15056   E = E->IgnoreParens();
15057   switch (E->getStmtClass()) {
15058   default:
15059     break;
15060   case Stmt::CStyleCastExprClass:
15061   case Stmt::CXXStaticCastExprClass:
15062   case Stmt::ImplicitCastExprClass: {
15063     auto *CE = cast<CastExpr>(E);
15064     const Expr *From = CE->getSubExpr();
15065     switch (CE->getCastKind()) {
15066     default:
15067       break;
15068     case CK_NoOp:
15069       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15070     case CK_UncheckedDerivedToBase:
15071     case CK_DerivedToBase: {
15072       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15073       if (!P)
15074         break;
15075       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15076                                                 P->second, Ctx);
15077     }
15078     }
15079     break;
15080   }
15081   case Stmt::ArraySubscriptExprClass: {
15082     auto *ASE = cast<ArraySubscriptExpr>(E);
15083     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15084                                                 false, Ctx);
15085   }
15086   case Stmt::DeclRefExprClass: {
15087     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15088       // FIXME: If VD is captured by copy or is an escaping __block variable,
15089       // use the alignment of VD's type.
15090       if (!VD->getType()->isReferenceType())
15091         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15092       if (VD->hasInit())
15093         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15094     }
15095     break;
15096   }
15097   case Stmt::MemberExprClass: {
15098     auto *ME = cast<MemberExpr>(E);
15099     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15100     if (!FD || FD->getType()->isReferenceType() ||
15101         FD->getParent()->isInvalidDecl())
15102       break;
15103     Optional<std::pair<CharUnits, CharUnits>> P;
15104     if (ME->isArrow())
15105       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15106     else
15107       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15108     if (!P)
15109       break;
15110     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15111     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15112     return std::make_pair(P->first,
15113                           P->second + CharUnits::fromQuantity(Offset));
15114   }
15115   case Stmt::UnaryOperatorClass: {
15116     auto *UO = cast<UnaryOperator>(E);
15117     switch (UO->getOpcode()) {
15118     default:
15119       break;
15120     case UO_Deref:
15121       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15122     }
15123     break;
15124   }
15125   case Stmt::BinaryOperatorClass: {
15126     auto *BO = cast<BinaryOperator>(E);
15127     auto Opcode = BO->getOpcode();
15128     switch (Opcode) {
15129     default:
15130       break;
15131     case BO_Comma:
15132       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15133     }
15134     break;
15135   }
15136   }
15137   return llvm::None;
15138 }
15139 
15140 /// This helper function takes a pointer expression and returns the alignment of
15141 /// a VarDecl and a constant offset from the VarDecl.
15142 Optional<std::pair<CharUnits, CharUnits>>
15143 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15144   E = E->IgnoreParens();
15145   switch (E->getStmtClass()) {
15146   default:
15147     break;
15148   case Stmt::CStyleCastExprClass:
15149   case Stmt::CXXStaticCastExprClass:
15150   case Stmt::ImplicitCastExprClass: {
15151     auto *CE = cast<CastExpr>(E);
15152     const Expr *From = CE->getSubExpr();
15153     switch (CE->getCastKind()) {
15154     default:
15155       break;
15156     case CK_NoOp:
15157       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15158     case CK_ArrayToPointerDecay:
15159       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15160     case CK_UncheckedDerivedToBase:
15161     case CK_DerivedToBase: {
15162       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15163       if (!P)
15164         break;
15165       return getDerivedToBaseAlignmentAndOffset(
15166           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15167     }
15168     }
15169     break;
15170   }
15171   case Stmt::CXXThisExprClass: {
15172     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15173     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15174     return std::make_pair(Alignment, CharUnits::Zero());
15175   }
15176   case Stmt::UnaryOperatorClass: {
15177     auto *UO = cast<UnaryOperator>(E);
15178     if (UO->getOpcode() == UO_AddrOf)
15179       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15180     break;
15181   }
15182   case Stmt::BinaryOperatorClass: {
15183     auto *BO = cast<BinaryOperator>(E);
15184     auto Opcode = BO->getOpcode();
15185     switch (Opcode) {
15186     default:
15187       break;
15188     case BO_Add:
15189     case BO_Sub: {
15190       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15191       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15192         std::swap(LHS, RHS);
15193       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15194                                                   Ctx);
15195     }
15196     case BO_Comma:
15197       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15198     }
15199     break;
15200   }
15201   }
15202   return llvm::None;
15203 }
15204 
15205 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15206   // See if we can compute the alignment of a VarDecl and an offset from it.
15207   Optional<std::pair<CharUnits, CharUnits>> P =
15208       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15209 
15210   if (P)
15211     return P->first.alignmentAtOffset(P->second);
15212 
15213   // If that failed, return the type's alignment.
15214   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15215 }
15216 
15217 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15218 /// pointer cast increases the alignment requirements.
15219 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15220   // This is actually a lot of work to potentially be doing on every
15221   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15222   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15223     return;
15224 
15225   // Ignore dependent types.
15226   if (T->isDependentType() || Op->getType()->isDependentType())
15227     return;
15228 
15229   // Require that the destination be a pointer type.
15230   const PointerType *DestPtr = T->getAs<PointerType>();
15231   if (!DestPtr) return;
15232 
15233   // If the destination has alignment 1, we're done.
15234   QualType DestPointee = DestPtr->getPointeeType();
15235   if (DestPointee->isIncompleteType()) return;
15236   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15237   if (DestAlign.isOne()) return;
15238 
15239   // Require that the source be a pointer type.
15240   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15241   if (!SrcPtr) return;
15242   QualType SrcPointee = SrcPtr->getPointeeType();
15243 
15244   // Explicitly allow casts from cv void*.  We already implicitly
15245   // allowed casts to cv void*, since they have alignment 1.
15246   // Also allow casts involving incomplete types, which implicitly
15247   // includes 'void'.
15248   if (SrcPointee->isIncompleteType()) return;
15249 
15250   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15251 
15252   if (SrcAlign >= DestAlign) return;
15253 
15254   Diag(TRange.getBegin(), diag::warn_cast_align)
15255     << Op->getType() << T
15256     << static_cast<unsigned>(SrcAlign.getQuantity())
15257     << static_cast<unsigned>(DestAlign.getQuantity())
15258     << TRange << Op->getSourceRange();
15259 }
15260 
15261 /// Check whether this array fits the idiom of a size-one tail padded
15262 /// array member of a struct.
15263 ///
15264 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15265 /// commonly used to emulate flexible arrays in C89 code.
15266 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15267                                     const NamedDecl *ND) {
15268   if (Size != 1 || !ND) return false;
15269 
15270   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15271   if (!FD) return false;
15272 
15273   // Don't consider sizes resulting from macro expansions or template argument
15274   // substitution to form C89 tail-padded arrays.
15275 
15276   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15277   while (TInfo) {
15278     TypeLoc TL = TInfo->getTypeLoc();
15279     // Look through typedefs.
15280     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15281       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15282       TInfo = TDL->getTypeSourceInfo();
15283       continue;
15284     }
15285     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15286       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15287       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15288         return false;
15289     }
15290     break;
15291   }
15292 
15293   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15294   if (!RD) return false;
15295   if (RD->isUnion()) return false;
15296   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15297     if (!CRD->isStandardLayout()) return false;
15298   }
15299 
15300   // See if this is the last field decl in the record.
15301   const Decl *D = FD;
15302   while ((D = D->getNextDeclInContext()))
15303     if (isa<FieldDecl>(D))
15304       return false;
15305   return true;
15306 }
15307 
15308 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15309                             const ArraySubscriptExpr *ASE,
15310                             bool AllowOnePastEnd, bool IndexNegated) {
15311   // Already diagnosed by the constant evaluator.
15312   if (isConstantEvaluated())
15313     return;
15314 
15315   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15316   if (IndexExpr->isValueDependent())
15317     return;
15318 
15319   const Type *EffectiveType =
15320       BaseExpr->getType()->getPointeeOrArrayElementType();
15321   BaseExpr = BaseExpr->IgnoreParenCasts();
15322   const ConstantArrayType *ArrayTy =
15323       Context.getAsConstantArrayType(BaseExpr->getType());
15324 
15325   const Type *BaseType =
15326       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15327   bool IsUnboundedArray = (BaseType == nullptr);
15328   if (EffectiveType->isDependentType() ||
15329       (!IsUnboundedArray && BaseType->isDependentType()))
15330     return;
15331 
15332   Expr::EvalResult Result;
15333   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15334     return;
15335 
15336   llvm::APSInt index = Result.Val.getInt();
15337   if (IndexNegated) {
15338     index.setIsUnsigned(false);
15339     index = -index;
15340   }
15341 
15342   const NamedDecl *ND = nullptr;
15343   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15344     ND = DRE->getDecl();
15345   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15346     ND = ME->getMemberDecl();
15347 
15348   if (IsUnboundedArray) {
15349     if (index.isUnsigned() || !index.isNegative()) {
15350       const auto &ASTC = getASTContext();
15351       unsigned AddrBits =
15352           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15353               EffectiveType->getCanonicalTypeInternal()));
15354       if (index.getBitWidth() < AddrBits)
15355         index = index.zext(AddrBits);
15356       Optional<CharUnits> ElemCharUnits =
15357           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15358       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15359       // pointer) bounds-checking isn't meaningful.
15360       if (!ElemCharUnits)
15361         return;
15362       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15363       // If index has more active bits than address space, we already know
15364       // we have a bounds violation to warn about.  Otherwise, compute
15365       // address of (index + 1)th element, and warn about bounds violation
15366       // only if that address exceeds address space.
15367       if (index.getActiveBits() <= AddrBits) {
15368         bool Overflow;
15369         llvm::APInt Product(index);
15370         Product += 1;
15371         Product = Product.umul_ov(ElemBytes, Overflow);
15372         if (!Overflow && Product.getActiveBits() <= AddrBits)
15373           return;
15374       }
15375 
15376       // Need to compute max possible elements in address space, since that
15377       // is included in diag message.
15378       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15379       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15380       MaxElems += 1;
15381       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15382       MaxElems = MaxElems.udiv(ElemBytes);
15383 
15384       unsigned DiagID =
15385           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15386               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15387 
15388       // Diag message shows element size in bits and in "bytes" (platform-
15389       // dependent CharUnits)
15390       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15391                           PDiag(DiagID)
15392                               << toString(index, 10, true) << AddrBits
15393                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15394                               << toString(ElemBytes, 10, false)
15395                               << toString(MaxElems, 10, false)
15396                               << (unsigned)MaxElems.getLimitedValue(~0U)
15397                               << IndexExpr->getSourceRange());
15398 
15399       if (!ND) {
15400         // Try harder to find a NamedDecl to point at in the note.
15401         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15402           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15403         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15404           ND = DRE->getDecl();
15405         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15406           ND = ME->getMemberDecl();
15407       }
15408 
15409       if (ND)
15410         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15411                             PDiag(diag::note_array_declared_here) << ND);
15412     }
15413     return;
15414   }
15415 
15416   if (index.isUnsigned() || !index.isNegative()) {
15417     // It is possible that the type of the base expression after
15418     // IgnoreParenCasts is incomplete, even though the type of the base
15419     // expression before IgnoreParenCasts is complete (see PR39746 for an
15420     // example). In this case we have no information about whether the array
15421     // access exceeds the array bounds. However we can still diagnose an array
15422     // access which precedes the array bounds.
15423     if (BaseType->isIncompleteType())
15424       return;
15425 
15426     llvm::APInt size = ArrayTy->getSize();
15427     if (!size.isStrictlyPositive())
15428       return;
15429 
15430     if (BaseType != EffectiveType) {
15431       // Make sure we're comparing apples to apples when comparing index to size
15432       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15433       uint64_t array_typesize = Context.getTypeSize(BaseType);
15434       // Handle ptrarith_typesize being zero, such as when casting to void*
15435       if (!ptrarith_typesize) ptrarith_typesize = 1;
15436       if (ptrarith_typesize != array_typesize) {
15437         // There's a cast to a different size type involved
15438         uint64_t ratio = array_typesize / ptrarith_typesize;
15439         // TODO: Be smarter about handling cases where array_typesize is not a
15440         // multiple of ptrarith_typesize
15441         if (ptrarith_typesize * ratio == array_typesize)
15442           size *= llvm::APInt(size.getBitWidth(), ratio);
15443       }
15444     }
15445 
15446     if (size.getBitWidth() > index.getBitWidth())
15447       index = index.zext(size.getBitWidth());
15448     else if (size.getBitWidth() < index.getBitWidth())
15449       size = size.zext(index.getBitWidth());
15450 
15451     // For array subscripting the index must be less than size, but for pointer
15452     // arithmetic also allow the index (offset) to be equal to size since
15453     // computing the next address after the end of the array is legal and
15454     // commonly done e.g. in C++ iterators and range-based for loops.
15455     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15456       return;
15457 
15458     // Also don't warn for arrays of size 1 which are members of some
15459     // structure. These are often used to approximate flexible arrays in C89
15460     // code.
15461     if (IsTailPaddedMemberArray(*this, size, ND))
15462       return;
15463 
15464     // Suppress the warning if the subscript expression (as identified by the
15465     // ']' location) and the index expression are both from macro expansions
15466     // within a system header.
15467     if (ASE) {
15468       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15469           ASE->getRBracketLoc());
15470       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15471         SourceLocation IndexLoc =
15472             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15473         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15474           return;
15475       }
15476     }
15477 
15478     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15479                           : diag::warn_ptr_arith_exceeds_bounds;
15480 
15481     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15482                         PDiag(DiagID) << toString(index, 10, true)
15483                                       << toString(size, 10, true)
15484                                       << (unsigned)size.getLimitedValue(~0U)
15485                                       << IndexExpr->getSourceRange());
15486   } else {
15487     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15488     if (!ASE) {
15489       DiagID = diag::warn_ptr_arith_precedes_bounds;
15490       if (index.isNegative()) index = -index;
15491     }
15492 
15493     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15494                         PDiag(DiagID) << toString(index, 10, true)
15495                                       << IndexExpr->getSourceRange());
15496   }
15497 
15498   if (!ND) {
15499     // Try harder to find a NamedDecl to point at in the note.
15500     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15501       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15502     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15503       ND = DRE->getDecl();
15504     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15505       ND = ME->getMemberDecl();
15506   }
15507 
15508   if (ND)
15509     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15510                         PDiag(diag::note_array_declared_here) << ND);
15511 }
15512 
15513 void Sema::CheckArrayAccess(const Expr *expr) {
15514   int AllowOnePastEnd = 0;
15515   while (expr) {
15516     expr = expr->IgnoreParenImpCasts();
15517     switch (expr->getStmtClass()) {
15518       case Stmt::ArraySubscriptExprClass: {
15519         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15520         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15521                          AllowOnePastEnd > 0);
15522         expr = ASE->getBase();
15523         break;
15524       }
15525       case Stmt::MemberExprClass: {
15526         expr = cast<MemberExpr>(expr)->getBase();
15527         break;
15528       }
15529       case Stmt::OMPArraySectionExprClass: {
15530         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15531         if (ASE->getLowerBound())
15532           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15533                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15534         return;
15535       }
15536       case Stmt::UnaryOperatorClass: {
15537         // Only unwrap the * and & unary operators
15538         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15539         expr = UO->getSubExpr();
15540         switch (UO->getOpcode()) {
15541           case UO_AddrOf:
15542             AllowOnePastEnd++;
15543             break;
15544           case UO_Deref:
15545             AllowOnePastEnd--;
15546             break;
15547           default:
15548             return;
15549         }
15550         break;
15551       }
15552       case Stmt::ConditionalOperatorClass: {
15553         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15554         if (const Expr *lhs = cond->getLHS())
15555           CheckArrayAccess(lhs);
15556         if (const Expr *rhs = cond->getRHS())
15557           CheckArrayAccess(rhs);
15558         return;
15559       }
15560       case Stmt::CXXOperatorCallExprClass: {
15561         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15562         for (const auto *Arg : OCE->arguments())
15563           CheckArrayAccess(Arg);
15564         return;
15565       }
15566       default:
15567         return;
15568     }
15569   }
15570 }
15571 
15572 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15573 
15574 namespace {
15575 
15576 struct RetainCycleOwner {
15577   VarDecl *Variable = nullptr;
15578   SourceRange Range;
15579   SourceLocation Loc;
15580   bool Indirect = false;
15581 
15582   RetainCycleOwner() = default;
15583 
15584   void setLocsFrom(Expr *e) {
15585     Loc = e->getExprLoc();
15586     Range = e->getSourceRange();
15587   }
15588 };
15589 
15590 } // namespace
15591 
15592 /// Consider whether capturing the given variable can possibly lead to
15593 /// a retain cycle.
15594 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15595   // In ARC, it's captured strongly iff the variable has __strong
15596   // lifetime.  In MRR, it's captured strongly if the variable is
15597   // __block and has an appropriate type.
15598   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15599     return false;
15600 
15601   owner.Variable = var;
15602   if (ref)
15603     owner.setLocsFrom(ref);
15604   return true;
15605 }
15606 
15607 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15608   while (true) {
15609     e = e->IgnoreParens();
15610     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15611       switch (cast->getCastKind()) {
15612       case CK_BitCast:
15613       case CK_LValueBitCast:
15614       case CK_LValueToRValue:
15615       case CK_ARCReclaimReturnedObject:
15616         e = cast->getSubExpr();
15617         continue;
15618 
15619       default:
15620         return false;
15621       }
15622     }
15623 
15624     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15625       ObjCIvarDecl *ivar = ref->getDecl();
15626       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15627         return false;
15628 
15629       // Try to find a retain cycle in the base.
15630       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15631         return false;
15632 
15633       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15634       owner.Indirect = true;
15635       return true;
15636     }
15637 
15638     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15639       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15640       if (!var) return false;
15641       return considerVariable(var, ref, owner);
15642     }
15643 
15644     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15645       if (member->isArrow()) return false;
15646 
15647       // Don't count this as an indirect ownership.
15648       e = member->getBase();
15649       continue;
15650     }
15651 
15652     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15653       // Only pay attention to pseudo-objects on property references.
15654       ObjCPropertyRefExpr *pre
15655         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15656                                               ->IgnoreParens());
15657       if (!pre) return false;
15658       if (pre->isImplicitProperty()) return false;
15659       ObjCPropertyDecl *property = pre->getExplicitProperty();
15660       if (!property->isRetaining() &&
15661           !(property->getPropertyIvarDecl() &&
15662             property->getPropertyIvarDecl()->getType()
15663               .getObjCLifetime() == Qualifiers::OCL_Strong))
15664           return false;
15665 
15666       owner.Indirect = true;
15667       if (pre->isSuperReceiver()) {
15668         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15669         if (!owner.Variable)
15670           return false;
15671         owner.Loc = pre->getLocation();
15672         owner.Range = pre->getSourceRange();
15673         return true;
15674       }
15675       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15676                               ->getSourceExpr());
15677       continue;
15678     }
15679 
15680     // Array ivars?
15681 
15682     return false;
15683   }
15684 }
15685 
15686 namespace {
15687 
15688   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15689     ASTContext &Context;
15690     VarDecl *Variable;
15691     Expr *Capturer = nullptr;
15692     bool VarWillBeReased = false;
15693 
15694     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15695         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15696           Context(Context), Variable(variable) {}
15697 
15698     void VisitDeclRefExpr(DeclRefExpr *ref) {
15699       if (ref->getDecl() == Variable && !Capturer)
15700         Capturer = ref;
15701     }
15702 
15703     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15704       if (Capturer) return;
15705       Visit(ref->getBase());
15706       if (Capturer && ref->isFreeIvar())
15707         Capturer = ref;
15708     }
15709 
15710     void VisitBlockExpr(BlockExpr *block) {
15711       // Look inside nested blocks
15712       if (block->getBlockDecl()->capturesVariable(Variable))
15713         Visit(block->getBlockDecl()->getBody());
15714     }
15715 
15716     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15717       if (Capturer) return;
15718       if (OVE->getSourceExpr())
15719         Visit(OVE->getSourceExpr());
15720     }
15721 
15722     void VisitBinaryOperator(BinaryOperator *BinOp) {
15723       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15724         return;
15725       Expr *LHS = BinOp->getLHS();
15726       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15727         if (DRE->getDecl() != Variable)
15728           return;
15729         if (Expr *RHS = BinOp->getRHS()) {
15730           RHS = RHS->IgnoreParenCasts();
15731           Optional<llvm::APSInt> Value;
15732           VarWillBeReased =
15733               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15734                *Value == 0);
15735         }
15736       }
15737     }
15738   };
15739 
15740 } // namespace
15741 
15742 /// Check whether the given argument is a block which captures a
15743 /// variable.
15744 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15745   assert(owner.Variable && owner.Loc.isValid());
15746 
15747   e = e->IgnoreParenCasts();
15748 
15749   // Look through [^{...} copy] and Block_copy(^{...}).
15750   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15751     Selector Cmd = ME->getSelector();
15752     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15753       e = ME->getInstanceReceiver();
15754       if (!e)
15755         return nullptr;
15756       e = e->IgnoreParenCasts();
15757     }
15758   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15759     if (CE->getNumArgs() == 1) {
15760       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15761       if (Fn) {
15762         const IdentifierInfo *FnI = Fn->getIdentifier();
15763         if (FnI && FnI->isStr("_Block_copy")) {
15764           e = CE->getArg(0)->IgnoreParenCasts();
15765         }
15766       }
15767     }
15768   }
15769 
15770   BlockExpr *block = dyn_cast<BlockExpr>(e);
15771   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15772     return nullptr;
15773 
15774   FindCaptureVisitor visitor(S.Context, owner.Variable);
15775   visitor.Visit(block->getBlockDecl()->getBody());
15776   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15777 }
15778 
15779 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15780                                 RetainCycleOwner &owner) {
15781   assert(capturer);
15782   assert(owner.Variable && owner.Loc.isValid());
15783 
15784   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15785     << owner.Variable << capturer->getSourceRange();
15786   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15787     << owner.Indirect << owner.Range;
15788 }
15789 
15790 /// Check for a keyword selector that starts with the word 'add' or
15791 /// 'set'.
15792 static bool isSetterLikeSelector(Selector sel) {
15793   if (sel.isUnarySelector()) return false;
15794 
15795   StringRef str = sel.getNameForSlot(0);
15796   while (!str.empty() && str.front() == '_') str = str.substr(1);
15797   if (str.startswith("set"))
15798     str = str.substr(3);
15799   else if (str.startswith("add")) {
15800     // Specially allow 'addOperationWithBlock:'.
15801     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15802       return false;
15803     str = str.substr(3);
15804   }
15805   else
15806     return false;
15807 
15808   if (str.empty()) return true;
15809   return !isLowercase(str.front());
15810 }
15811 
15812 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15813                                                     ObjCMessageExpr *Message) {
15814   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15815                                                 Message->getReceiverInterface(),
15816                                                 NSAPI::ClassId_NSMutableArray);
15817   if (!IsMutableArray) {
15818     return None;
15819   }
15820 
15821   Selector Sel = Message->getSelector();
15822 
15823   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15824     S.NSAPIObj->getNSArrayMethodKind(Sel);
15825   if (!MKOpt) {
15826     return None;
15827   }
15828 
15829   NSAPI::NSArrayMethodKind MK = *MKOpt;
15830 
15831   switch (MK) {
15832     case NSAPI::NSMutableArr_addObject:
15833     case NSAPI::NSMutableArr_insertObjectAtIndex:
15834     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15835       return 0;
15836     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15837       return 1;
15838 
15839     default:
15840       return None;
15841   }
15842 
15843   return None;
15844 }
15845 
15846 static
15847 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15848                                                   ObjCMessageExpr *Message) {
15849   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15850                                             Message->getReceiverInterface(),
15851                                             NSAPI::ClassId_NSMutableDictionary);
15852   if (!IsMutableDictionary) {
15853     return None;
15854   }
15855 
15856   Selector Sel = Message->getSelector();
15857 
15858   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15859     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15860   if (!MKOpt) {
15861     return None;
15862   }
15863 
15864   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15865 
15866   switch (MK) {
15867     case NSAPI::NSMutableDict_setObjectForKey:
15868     case NSAPI::NSMutableDict_setValueForKey:
15869     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15870       return 0;
15871 
15872     default:
15873       return None;
15874   }
15875 
15876   return None;
15877 }
15878 
15879 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15880   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15881                                                 Message->getReceiverInterface(),
15882                                                 NSAPI::ClassId_NSMutableSet);
15883 
15884   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15885                                             Message->getReceiverInterface(),
15886                                             NSAPI::ClassId_NSMutableOrderedSet);
15887   if (!IsMutableSet && !IsMutableOrderedSet) {
15888     return None;
15889   }
15890 
15891   Selector Sel = Message->getSelector();
15892 
15893   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15894   if (!MKOpt) {
15895     return None;
15896   }
15897 
15898   NSAPI::NSSetMethodKind MK = *MKOpt;
15899 
15900   switch (MK) {
15901     case NSAPI::NSMutableSet_addObject:
15902     case NSAPI::NSOrderedSet_setObjectAtIndex:
15903     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15904     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15905       return 0;
15906     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15907       return 1;
15908   }
15909 
15910   return None;
15911 }
15912 
15913 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15914   if (!Message->isInstanceMessage()) {
15915     return;
15916   }
15917 
15918   Optional<int> ArgOpt;
15919 
15920   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15921       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15922       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15923     return;
15924   }
15925 
15926   int ArgIndex = *ArgOpt;
15927 
15928   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15929   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15930     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15931   }
15932 
15933   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15934     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15935       if (ArgRE->isObjCSelfExpr()) {
15936         Diag(Message->getSourceRange().getBegin(),
15937              diag::warn_objc_circular_container)
15938           << ArgRE->getDecl() << StringRef("'super'");
15939       }
15940     }
15941   } else {
15942     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15943 
15944     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15945       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15946     }
15947 
15948     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15949       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15950         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15951           ValueDecl *Decl = ReceiverRE->getDecl();
15952           Diag(Message->getSourceRange().getBegin(),
15953                diag::warn_objc_circular_container)
15954             << Decl << Decl;
15955           if (!ArgRE->isObjCSelfExpr()) {
15956             Diag(Decl->getLocation(),
15957                  diag::note_objc_circular_container_declared_here)
15958               << Decl;
15959           }
15960         }
15961       }
15962     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15963       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15964         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15965           ObjCIvarDecl *Decl = IvarRE->getDecl();
15966           Diag(Message->getSourceRange().getBegin(),
15967                diag::warn_objc_circular_container)
15968             << Decl << Decl;
15969           Diag(Decl->getLocation(),
15970                diag::note_objc_circular_container_declared_here)
15971             << Decl;
15972         }
15973       }
15974     }
15975   }
15976 }
15977 
15978 /// Check a message send to see if it's likely to cause a retain cycle.
15979 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15980   // Only check instance methods whose selector looks like a setter.
15981   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15982     return;
15983 
15984   // Try to find a variable that the receiver is strongly owned by.
15985   RetainCycleOwner owner;
15986   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15987     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15988       return;
15989   } else {
15990     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15991     owner.Variable = getCurMethodDecl()->getSelfDecl();
15992     owner.Loc = msg->getSuperLoc();
15993     owner.Range = msg->getSuperLoc();
15994   }
15995 
15996   // Check whether the receiver is captured by any of the arguments.
15997   const ObjCMethodDecl *MD = msg->getMethodDecl();
15998   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15999     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16000       // noescape blocks should not be retained by the method.
16001       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16002         continue;
16003       return diagnoseRetainCycle(*this, capturer, owner);
16004     }
16005   }
16006 }
16007 
16008 /// Check a property assign to see if it's likely to cause a retain cycle.
16009 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16010   RetainCycleOwner owner;
16011   if (!findRetainCycleOwner(*this, receiver, owner))
16012     return;
16013 
16014   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16015     diagnoseRetainCycle(*this, capturer, owner);
16016 }
16017 
16018 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16019   RetainCycleOwner Owner;
16020   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16021     return;
16022 
16023   // Because we don't have an expression for the variable, we have to set the
16024   // location explicitly here.
16025   Owner.Loc = Var->getLocation();
16026   Owner.Range = Var->getSourceRange();
16027 
16028   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16029     diagnoseRetainCycle(*this, Capturer, Owner);
16030 }
16031 
16032 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16033                                      Expr *RHS, bool isProperty) {
16034   // Check if RHS is an Objective-C object literal, which also can get
16035   // immediately zapped in a weak reference.  Note that we explicitly
16036   // allow ObjCStringLiterals, since those are designed to never really die.
16037   RHS = RHS->IgnoreParenImpCasts();
16038 
16039   // This enum needs to match with the 'select' in
16040   // warn_objc_arc_literal_assign (off-by-1).
16041   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16042   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16043     return false;
16044 
16045   S.Diag(Loc, diag::warn_arc_literal_assign)
16046     << (unsigned) Kind
16047     << (isProperty ? 0 : 1)
16048     << RHS->getSourceRange();
16049 
16050   return true;
16051 }
16052 
16053 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16054                                     Qualifiers::ObjCLifetime LT,
16055                                     Expr *RHS, bool isProperty) {
16056   // Strip off any implicit cast added to get to the one ARC-specific.
16057   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16058     if (cast->getCastKind() == CK_ARCConsumeObject) {
16059       S.Diag(Loc, diag::warn_arc_retained_assign)
16060         << (LT == Qualifiers::OCL_ExplicitNone)
16061         << (isProperty ? 0 : 1)
16062         << RHS->getSourceRange();
16063       return true;
16064     }
16065     RHS = cast->getSubExpr();
16066   }
16067 
16068   if (LT == Qualifiers::OCL_Weak &&
16069       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16070     return true;
16071 
16072   return false;
16073 }
16074 
16075 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16076                               QualType LHS, Expr *RHS) {
16077   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16078 
16079   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16080     return false;
16081 
16082   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16083     return true;
16084 
16085   return false;
16086 }
16087 
16088 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16089                               Expr *LHS, Expr *RHS) {
16090   QualType LHSType;
16091   // PropertyRef on LHS type need be directly obtained from
16092   // its declaration as it has a PseudoType.
16093   ObjCPropertyRefExpr *PRE
16094     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16095   if (PRE && !PRE->isImplicitProperty()) {
16096     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16097     if (PD)
16098       LHSType = PD->getType();
16099   }
16100 
16101   if (LHSType.isNull())
16102     LHSType = LHS->getType();
16103 
16104   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16105 
16106   if (LT == Qualifiers::OCL_Weak) {
16107     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16108       getCurFunction()->markSafeWeakUse(LHS);
16109   }
16110 
16111   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16112     return;
16113 
16114   // FIXME. Check for other life times.
16115   if (LT != Qualifiers::OCL_None)
16116     return;
16117 
16118   if (PRE) {
16119     if (PRE->isImplicitProperty())
16120       return;
16121     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16122     if (!PD)
16123       return;
16124 
16125     unsigned Attributes = PD->getPropertyAttributes();
16126     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16127       // when 'assign' attribute was not explicitly specified
16128       // by user, ignore it and rely on property type itself
16129       // for lifetime info.
16130       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16131       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16132           LHSType->isObjCRetainableType())
16133         return;
16134 
16135       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16136         if (cast->getCastKind() == CK_ARCConsumeObject) {
16137           Diag(Loc, diag::warn_arc_retained_property_assign)
16138           << RHS->getSourceRange();
16139           return;
16140         }
16141         RHS = cast->getSubExpr();
16142       }
16143     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16144       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16145         return;
16146     }
16147   }
16148 }
16149 
16150 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16151 
16152 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16153                                         SourceLocation StmtLoc,
16154                                         const NullStmt *Body) {
16155   // Do not warn if the body is a macro that expands to nothing, e.g:
16156   //
16157   // #define CALL(x)
16158   // if (condition)
16159   //   CALL(0);
16160   if (Body->hasLeadingEmptyMacro())
16161     return false;
16162 
16163   // Get line numbers of statement and body.
16164   bool StmtLineInvalid;
16165   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16166                                                       &StmtLineInvalid);
16167   if (StmtLineInvalid)
16168     return false;
16169 
16170   bool BodyLineInvalid;
16171   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16172                                                       &BodyLineInvalid);
16173   if (BodyLineInvalid)
16174     return false;
16175 
16176   // Warn if null statement and body are on the same line.
16177   if (StmtLine != BodyLine)
16178     return false;
16179 
16180   return true;
16181 }
16182 
16183 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16184                                  const Stmt *Body,
16185                                  unsigned DiagID) {
16186   // Since this is a syntactic check, don't emit diagnostic for template
16187   // instantiations, this just adds noise.
16188   if (CurrentInstantiationScope)
16189     return;
16190 
16191   // The body should be a null statement.
16192   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16193   if (!NBody)
16194     return;
16195 
16196   // Do the usual checks.
16197   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16198     return;
16199 
16200   Diag(NBody->getSemiLoc(), DiagID);
16201   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16202 }
16203 
16204 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16205                                  const Stmt *PossibleBody) {
16206   assert(!CurrentInstantiationScope); // Ensured by caller
16207 
16208   SourceLocation StmtLoc;
16209   const Stmt *Body;
16210   unsigned DiagID;
16211   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16212     StmtLoc = FS->getRParenLoc();
16213     Body = FS->getBody();
16214     DiagID = diag::warn_empty_for_body;
16215   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16216     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16217     Body = WS->getBody();
16218     DiagID = diag::warn_empty_while_body;
16219   } else
16220     return; // Neither `for' nor `while'.
16221 
16222   // The body should be a null statement.
16223   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16224   if (!NBody)
16225     return;
16226 
16227   // Skip expensive checks if diagnostic is disabled.
16228   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16229     return;
16230 
16231   // Do the usual checks.
16232   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16233     return;
16234 
16235   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16236   // noise level low, emit diagnostics only if for/while is followed by a
16237   // CompoundStmt, e.g.:
16238   //    for (int i = 0; i < n; i++);
16239   //    {
16240   //      a(i);
16241   //    }
16242   // or if for/while is followed by a statement with more indentation
16243   // than for/while itself:
16244   //    for (int i = 0; i < n; i++);
16245   //      a(i);
16246   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16247   if (!ProbableTypo) {
16248     bool BodyColInvalid;
16249     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16250         PossibleBody->getBeginLoc(), &BodyColInvalid);
16251     if (BodyColInvalid)
16252       return;
16253 
16254     bool StmtColInvalid;
16255     unsigned StmtCol =
16256         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16257     if (StmtColInvalid)
16258       return;
16259 
16260     if (BodyCol > StmtCol)
16261       ProbableTypo = true;
16262   }
16263 
16264   if (ProbableTypo) {
16265     Diag(NBody->getSemiLoc(), DiagID);
16266     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16267   }
16268 }
16269 
16270 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16271 
16272 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16273 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16274                              SourceLocation OpLoc) {
16275   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16276     return;
16277 
16278   if (inTemplateInstantiation())
16279     return;
16280 
16281   // Strip parens and casts away.
16282   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16283   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16284 
16285   // Check for a call expression
16286   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16287   if (!CE || CE->getNumArgs() != 1)
16288     return;
16289 
16290   // Check for a call to std::move
16291   if (!CE->isCallToStdMove())
16292     return;
16293 
16294   // Get argument from std::move
16295   RHSExpr = CE->getArg(0);
16296 
16297   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16298   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16299 
16300   // Two DeclRefExpr's, check that the decls are the same.
16301   if (LHSDeclRef && RHSDeclRef) {
16302     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16303       return;
16304     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16305         RHSDeclRef->getDecl()->getCanonicalDecl())
16306       return;
16307 
16308     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16309                                         << LHSExpr->getSourceRange()
16310                                         << RHSExpr->getSourceRange();
16311     return;
16312   }
16313 
16314   // Member variables require a different approach to check for self moves.
16315   // MemberExpr's are the same if every nested MemberExpr refers to the same
16316   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16317   // the base Expr's are CXXThisExpr's.
16318   const Expr *LHSBase = LHSExpr;
16319   const Expr *RHSBase = RHSExpr;
16320   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16321   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16322   if (!LHSME || !RHSME)
16323     return;
16324 
16325   while (LHSME && RHSME) {
16326     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16327         RHSME->getMemberDecl()->getCanonicalDecl())
16328       return;
16329 
16330     LHSBase = LHSME->getBase();
16331     RHSBase = RHSME->getBase();
16332     LHSME = dyn_cast<MemberExpr>(LHSBase);
16333     RHSME = dyn_cast<MemberExpr>(RHSBase);
16334   }
16335 
16336   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16337   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16338   if (LHSDeclRef && RHSDeclRef) {
16339     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16340       return;
16341     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16342         RHSDeclRef->getDecl()->getCanonicalDecl())
16343       return;
16344 
16345     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16346                                         << LHSExpr->getSourceRange()
16347                                         << RHSExpr->getSourceRange();
16348     return;
16349   }
16350 
16351   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16352     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16353                                         << LHSExpr->getSourceRange()
16354                                         << RHSExpr->getSourceRange();
16355 }
16356 
16357 //===--- Layout compatibility ----------------------------------------------//
16358 
16359 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16360 
16361 /// Check if two enumeration types are layout-compatible.
16362 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16363   // C++11 [dcl.enum] p8:
16364   // Two enumeration types are layout-compatible if they have the same
16365   // underlying type.
16366   return ED1->isComplete() && ED2->isComplete() &&
16367          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16368 }
16369 
16370 /// Check if two fields are layout-compatible.
16371 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16372                                FieldDecl *Field2) {
16373   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16374     return false;
16375 
16376   if (Field1->isBitField() != Field2->isBitField())
16377     return false;
16378 
16379   if (Field1->isBitField()) {
16380     // Make sure that the bit-fields are the same length.
16381     unsigned Bits1 = Field1->getBitWidthValue(C);
16382     unsigned Bits2 = Field2->getBitWidthValue(C);
16383 
16384     if (Bits1 != Bits2)
16385       return false;
16386   }
16387 
16388   return true;
16389 }
16390 
16391 /// Check if two standard-layout structs are layout-compatible.
16392 /// (C++11 [class.mem] p17)
16393 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16394                                      RecordDecl *RD2) {
16395   // If both records are C++ classes, check that base classes match.
16396   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16397     // If one of records is a CXXRecordDecl we are in C++ mode,
16398     // thus the other one is a CXXRecordDecl, too.
16399     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16400     // Check number of base classes.
16401     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16402       return false;
16403 
16404     // Check the base classes.
16405     for (CXXRecordDecl::base_class_const_iterator
16406                Base1 = D1CXX->bases_begin(),
16407            BaseEnd1 = D1CXX->bases_end(),
16408               Base2 = D2CXX->bases_begin();
16409          Base1 != BaseEnd1;
16410          ++Base1, ++Base2) {
16411       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16412         return false;
16413     }
16414   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16415     // If only RD2 is a C++ class, it should have zero base classes.
16416     if (D2CXX->getNumBases() > 0)
16417       return false;
16418   }
16419 
16420   // Check the fields.
16421   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16422                              Field2End = RD2->field_end(),
16423                              Field1 = RD1->field_begin(),
16424                              Field1End = RD1->field_end();
16425   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16426     if (!isLayoutCompatible(C, *Field1, *Field2))
16427       return false;
16428   }
16429   if (Field1 != Field1End || Field2 != Field2End)
16430     return false;
16431 
16432   return true;
16433 }
16434 
16435 /// Check if two standard-layout unions are layout-compatible.
16436 /// (C++11 [class.mem] p18)
16437 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16438                                     RecordDecl *RD2) {
16439   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16440   for (auto *Field2 : RD2->fields())
16441     UnmatchedFields.insert(Field2);
16442 
16443   for (auto *Field1 : RD1->fields()) {
16444     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16445         I = UnmatchedFields.begin(),
16446         E = UnmatchedFields.end();
16447 
16448     for ( ; I != E; ++I) {
16449       if (isLayoutCompatible(C, Field1, *I)) {
16450         bool Result = UnmatchedFields.erase(*I);
16451         (void) Result;
16452         assert(Result);
16453         break;
16454       }
16455     }
16456     if (I == E)
16457       return false;
16458   }
16459 
16460   return UnmatchedFields.empty();
16461 }
16462 
16463 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16464                                RecordDecl *RD2) {
16465   if (RD1->isUnion() != RD2->isUnion())
16466     return false;
16467 
16468   if (RD1->isUnion())
16469     return isLayoutCompatibleUnion(C, RD1, RD2);
16470   else
16471     return isLayoutCompatibleStruct(C, RD1, RD2);
16472 }
16473 
16474 /// Check if two types are layout-compatible in C++11 sense.
16475 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16476   if (T1.isNull() || T2.isNull())
16477     return false;
16478 
16479   // C++11 [basic.types] p11:
16480   // If two types T1 and T2 are the same type, then T1 and T2 are
16481   // layout-compatible types.
16482   if (C.hasSameType(T1, T2))
16483     return true;
16484 
16485   T1 = T1.getCanonicalType().getUnqualifiedType();
16486   T2 = T2.getCanonicalType().getUnqualifiedType();
16487 
16488   const Type::TypeClass TC1 = T1->getTypeClass();
16489   const Type::TypeClass TC2 = T2->getTypeClass();
16490 
16491   if (TC1 != TC2)
16492     return false;
16493 
16494   if (TC1 == Type::Enum) {
16495     return isLayoutCompatible(C,
16496                               cast<EnumType>(T1)->getDecl(),
16497                               cast<EnumType>(T2)->getDecl());
16498   } else if (TC1 == Type::Record) {
16499     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16500       return false;
16501 
16502     return isLayoutCompatible(C,
16503                               cast<RecordType>(T1)->getDecl(),
16504                               cast<RecordType>(T2)->getDecl());
16505   }
16506 
16507   return false;
16508 }
16509 
16510 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16511 
16512 /// Given a type tag expression find the type tag itself.
16513 ///
16514 /// \param TypeExpr Type tag expression, as it appears in user's code.
16515 ///
16516 /// \param VD Declaration of an identifier that appears in a type tag.
16517 ///
16518 /// \param MagicValue Type tag magic value.
16519 ///
16520 /// \param isConstantEvaluated whether the evalaution should be performed in
16521 
16522 /// constant context.
16523 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16524                             const ValueDecl **VD, uint64_t *MagicValue,
16525                             bool isConstantEvaluated) {
16526   while(true) {
16527     if (!TypeExpr)
16528       return false;
16529 
16530     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16531 
16532     switch (TypeExpr->getStmtClass()) {
16533     case Stmt::UnaryOperatorClass: {
16534       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16535       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16536         TypeExpr = UO->getSubExpr();
16537         continue;
16538       }
16539       return false;
16540     }
16541 
16542     case Stmt::DeclRefExprClass: {
16543       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16544       *VD = DRE->getDecl();
16545       return true;
16546     }
16547 
16548     case Stmt::IntegerLiteralClass: {
16549       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16550       llvm::APInt MagicValueAPInt = IL->getValue();
16551       if (MagicValueAPInt.getActiveBits() <= 64) {
16552         *MagicValue = MagicValueAPInt.getZExtValue();
16553         return true;
16554       } else
16555         return false;
16556     }
16557 
16558     case Stmt::BinaryConditionalOperatorClass:
16559     case Stmt::ConditionalOperatorClass: {
16560       const AbstractConditionalOperator *ACO =
16561           cast<AbstractConditionalOperator>(TypeExpr);
16562       bool Result;
16563       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16564                                                      isConstantEvaluated)) {
16565         if (Result)
16566           TypeExpr = ACO->getTrueExpr();
16567         else
16568           TypeExpr = ACO->getFalseExpr();
16569         continue;
16570       }
16571       return false;
16572     }
16573 
16574     case Stmt::BinaryOperatorClass: {
16575       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16576       if (BO->getOpcode() == BO_Comma) {
16577         TypeExpr = BO->getRHS();
16578         continue;
16579       }
16580       return false;
16581     }
16582 
16583     default:
16584       return false;
16585     }
16586   }
16587 }
16588 
16589 /// Retrieve the C type corresponding to type tag TypeExpr.
16590 ///
16591 /// \param TypeExpr Expression that specifies a type tag.
16592 ///
16593 /// \param MagicValues Registered magic values.
16594 ///
16595 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16596 ///        kind.
16597 ///
16598 /// \param TypeInfo Information about the corresponding C type.
16599 ///
16600 /// \param isConstantEvaluated whether the evalaution should be performed in
16601 /// constant context.
16602 ///
16603 /// \returns true if the corresponding C type was found.
16604 static bool GetMatchingCType(
16605     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16606     const ASTContext &Ctx,
16607     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16608         *MagicValues,
16609     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16610     bool isConstantEvaluated) {
16611   FoundWrongKind = false;
16612 
16613   // Variable declaration that has type_tag_for_datatype attribute.
16614   const ValueDecl *VD = nullptr;
16615 
16616   uint64_t MagicValue;
16617 
16618   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16619     return false;
16620 
16621   if (VD) {
16622     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16623       if (I->getArgumentKind() != ArgumentKind) {
16624         FoundWrongKind = true;
16625         return false;
16626       }
16627       TypeInfo.Type = I->getMatchingCType();
16628       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16629       TypeInfo.MustBeNull = I->getMustBeNull();
16630       return true;
16631     }
16632     return false;
16633   }
16634 
16635   if (!MagicValues)
16636     return false;
16637 
16638   llvm::DenseMap<Sema::TypeTagMagicValue,
16639                  Sema::TypeTagData>::const_iterator I =
16640       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16641   if (I == MagicValues->end())
16642     return false;
16643 
16644   TypeInfo = I->second;
16645   return true;
16646 }
16647 
16648 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16649                                       uint64_t MagicValue, QualType Type,
16650                                       bool LayoutCompatible,
16651                                       bool MustBeNull) {
16652   if (!TypeTagForDatatypeMagicValues)
16653     TypeTagForDatatypeMagicValues.reset(
16654         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16655 
16656   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16657   (*TypeTagForDatatypeMagicValues)[Magic] =
16658       TypeTagData(Type, LayoutCompatible, MustBeNull);
16659 }
16660 
16661 static bool IsSameCharType(QualType T1, QualType T2) {
16662   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16663   if (!BT1)
16664     return false;
16665 
16666   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16667   if (!BT2)
16668     return false;
16669 
16670   BuiltinType::Kind T1Kind = BT1->getKind();
16671   BuiltinType::Kind T2Kind = BT2->getKind();
16672 
16673   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16674          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16675          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16676          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16677 }
16678 
16679 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16680                                     const ArrayRef<const Expr *> ExprArgs,
16681                                     SourceLocation CallSiteLoc) {
16682   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16683   bool IsPointerAttr = Attr->getIsPointer();
16684 
16685   // Retrieve the argument representing the 'type_tag'.
16686   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16687   if (TypeTagIdxAST >= ExprArgs.size()) {
16688     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16689         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16690     return;
16691   }
16692   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16693   bool FoundWrongKind;
16694   TypeTagData TypeInfo;
16695   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16696                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16697                         TypeInfo, isConstantEvaluated())) {
16698     if (FoundWrongKind)
16699       Diag(TypeTagExpr->getExprLoc(),
16700            diag::warn_type_tag_for_datatype_wrong_kind)
16701         << TypeTagExpr->getSourceRange();
16702     return;
16703   }
16704 
16705   // Retrieve the argument representing the 'arg_idx'.
16706   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16707   if (ArgumentIdxAST >= ExprArgs.size()) {
16708     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16709         << 1 << Attr->getArgumentIdx().getSourceIndex();
16710     return;
16711   }
16712   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16713   if (IsPointerAttr) {
16714     // Skip implicit cast of pointer to `void *' (as a function argument).
16715     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16716       if (ICE->getType()->isVoidPointerType() &&
16717           ICE->getCastKind() == CK_BitCast)
16718         ArgumentExpr = ICE->getSubExpr();
16719   }
16720   QualType ArgumentType = ArgumentExpr->getType();
16721 
16722   // Passing a `void*' pointer shouldn't trigger a warning.
16723   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16724     return;
16725 
16726   if (TypeInfo.MustBeNull) {
16727     // Type tag with matching void type requires a null pointer.
16728     if (!ArgumentExpr->isNullPointerConstant(Context,
16729                                              Expr::NPC_ValueDependentIsNotNull)) {
16730       Diag(ArgumentExpr->getExprLoc(),
16731            diag::warn_type_safety_null_pointer_required)
16732           << ArgumentKind->getName()
16733           << ArgumentExpr->getSourceRange()
16734           << TypeTagExpr->getSourceRange();
16735     }
16736     return;
16737   }
16738 
16739   QualType RequiredType = TypeInfo.Type;
16740   if (IsPointerAttr)
16741     RequiredType = Context.getPointerType(RequiredType);
16742 
16743   bool mismatch = false;
16744   if (!TypeInfo.LayoutCompatible) {
16745     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16746 
16747     // C++11 [basic.fundamental] p1:
16748     // Plain char, signed char, and unsigned char are three distinct types.
16749     //
16750     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16751     // char' depending on the current char signedness mode.
16752     if (mismatch)
16753       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16754                                            RequiredType->getPointeeType())) ||
16755           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16756         mismatch = false;
16757   } else
16758     if (IsPointerAttr)
16759       mismatch = !isLayoutCompatible(Context,
16760                                      ArgumentType->getPointeeType(),
16761                                      RequiredType->getPointeeType());
16762     else
16763       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16764 
16765   if (mismatch)
16766     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16767         << ArgumentType << ArgumentKind
16768         << TypeInfo.LayoutCompatible << RequiredType
16769         << ArgumentExpr->getSourceRange()
16770         << TypeTagExpr->getSourceRange();
16771 }
16772 
16773 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16774                                          CharUnits Alignment) {
16775   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16776 }
16777 
16778 void Sema::DiagnoseMisalignedMembers() {
16779   for (MisalignedMember &m : MisalignedMembers) {
16780     const NamedDecl *ND = m.RD;
16781     if (ND->getName().empty()) {
16782       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16783         ND = TD;
16784     }
16785     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16786         << m.MD << ND << m.E->getSourceRange();
16787   }
16788   MisalignedMembers.clear();
16789 }
16790 
16791 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16792   E = E->IgnoreParens();
16793   if (!T->isPointerType() && !T->isIntegerType())
16794     return;
16795   if (isa<UnaryOperator>(E) &&
16796       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16797     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16798     if (isa<MemberExpr>(Op)) {
16799       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16800       if (MA != MisalignedMembers.end() &&
16801           (T->isIntegerType() ||
16802            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16803                                    Context.getTypeAlignInChars(
16804                                        T->getPointeeType()) <= MA->Alignment))))
16805         MisalignedMembers.erase(MA);
16806     }
16807   }
16808 }
16809 
16810 void Sema::RefersToMemberWithReducedAlignment(
16811     Expr *E,
16812     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16813         Action) {
16814   const auto *ME = dyn_cast<MemberExpr>(E);
16815   if (!ME)
16816     return;
16817 
16818   // No need to check expressions with an __unaligned-qualified type.
16819   if (E->getType().getQualifiers().hasUnaligned())
16820     return;
16821 
16822   // For a chain of MemberExpr like "a.b.c.d" this list
16823   // will keep FieldDecl's like [d, c, b].
16824   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16825   const MemberExpr *TopME = nullptr;
16826   bool AnyIsPacked = false;
16827   do {
16828     QualType BaseType = ME->getBase()->getType();
16829     if (BaseType->isDependentType())
16830       return;
16831     if (ME->isArrow())
16832       BaseType = BaseType->getPointeeType();
16833     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16834     if (RD->isInvalidDecl())
16835       return;
16836 
16837     ValueDecl *MD = ME->getMemberDecl();
16838     auto *FD = dyn_cast<FieldDecl>(MD);
16839     // We do not care about non-data members.
16840     if (!FD || FD->isInvalidDecl())
16841       return;
16842 
16843     AnyIsPacked =
16844         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16845     ReverseMemberChain.push_back(FD);
16846 
16847     TopME = ME;
16848     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16849   } while (ME);
16850   assert(TopME && "We did not compute a topmost MemberExpr!");
16851 
16852   // Not the scope of this diagnostic.
16853   if (!AnyIsPacked)
16854     return;
16855 
16856   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16857   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16858   // TODO: The innermost base of the member expression may be too complicated.
16859   // For now, just disregard these cases. This is left for future
16860   // improvement.
16861   if (!DRE && !isa<CXXThisExpr>(TopBase))
16862       return;
16863 
16864   // Alignment expected by the whole expression.
16865   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16866 
16867   // No need to do anything else with this case.
16868   if (ExpectedAlignment.isOne())
16869     return;
16870 
16871   // Synthesize offset of the whole access.
16872   CharUnits Offset;
16873   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16874     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16875 
16876   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16877   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16878       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16879 
16880   // The base expression of the innermost MemberExpr may give
16881   // stronger guarantees than the class containing the member.
16882   if (DRE && !TopME->isArrow()) {
16883     const ValueDecl *VD = DRE->getDecl();
16884     if (!VD->getType()->isReferenceType())
16885       CompleteObjectAlignment =
16886           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16887   }
16888 
16889   // Check if the synthesized offset fulfills the alignment.
16890   if (Offset % ExpectedAlignment != 0 ||
16891       // It may fulfill the offset it but the effective alignment may still be
16892       // lower than the expected expression alignment.
16893       CompleteObjectAlignment < ExpectedAlignment) {
16894     // If this happens, we want to determine a sensible culprit of this.
16895     // Intuitively, watching the chain of member expressions from right to
16896     // left, we start with the required alignment (as required by the field
16897     // type) but some packed attribute in that chain has reduced the alignment.
16898     // It may happen that another packed structure increases it again. But if
16899     // we are here such increase has not been enough. So pointing the first
16900     // FieldDecl that either is packed or else its RecordDecl is,
16901     // seems reasonable.
16902     FieldDecl *FD = nullptr;
16903     CharUnits Alignment;
16904     for (FieldDecl *FDI : ReverseMemberChain) {
16905       if (FDI->hasAttr<PackedAttr>() ||
16906           FDI->getParent()->hasAttr<PackedAttr>()) {
16907         FD = FDI;
16908         Alignment = std::min(
16909             Context.getTypeAlignInChars(FD->getType()),
16910             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16911         break;
16912       }
16913     }
16914     assert(FD && "We did not find a packed FieldDecl!");
16915     Action(E, FD->getParent(), FD, Alignment);
16916   }
16917 }
16918 
16919 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16920   using namespace std::placeholders;
16921 
16922   RefersToMemberWithReducedAlignment(
16923       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16924                      _2, _3, _4));
16925 }
16926 
16927 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16928 // not a valid type, emit an error message and return true. Otherwise return
16929 // false.
16930 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16931                                         QualType Ty) {
16932   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16933     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16934         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16935     return true;
16936   }
16937   return false;
16938 }
16939 
16940 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
16941   if (checkArgCount(*this, TheCall, 1))
16942     return true;
16943 
16944   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16945   if (A.isInvalid())
16946     return true;
16947 
16948   TheCall->setArg(0, A.get());
16949   QualType TyA = A.get()->getType();
16950 
16951   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16952     return true;
16953 
16954   TheCall->setType(TyA);
16955   return false;
16956 }
16957 
16958 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16959   if (checkArgCount(*this, TheCall, 2))
16960     return true;
16961 
16962   ExprResult A = TheCall->getArg(0);
16963   ExprResult B = TheCall->getArg(1);
16964   // Do standard promotions between the two arguments, returning their common
16965   // type.
16966   QualType Res =
16967       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16968   if (A.isInvalid() || B.isInvalid())
16969     return true;
16970 
16971   QualType TyA = A.get()->getType();
16972   QualType TyB = B.get()->getType();
16973 
16974   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16975     return Diag(A.get()->getBeginLoc(),
16976                 diag::err_typecheck_call_different_arg_types)
16977            << TyA << TyB;
16978 
16979   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16980     return true;
16981 
16982   TheCall->setArg(0, A.get());
16983   TheCall->setArg(1, B.get());
16984   TheCall->setType(Res);
16985   return false;
16986 }
16987 
16988 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16989   if (checkArgCount(*this, TheCall, 1))
16990     return true;
16991 
16992   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16993   if (A.isInvalid())
16994     return true;
16995 
16996   TheCall->setArg(0, A.get());
16997   return false;
16998 }
16999 
17000 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17001                                             ExprResult CallResult) {
17002   if (checkArgCount(*this, TheCall, 1))
17003     return ExprError();
17004 
17005   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17006   if (MatrixArg.isInvalid())
17007     return MatrixArg;
17008   Expr *Matrix = MatrixArg.get();
17009 
17010   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17011   if (!MType) {
17012     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17013         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17014     return ExprError();
17015   }
17016 
17017   // Create returned matrix type by swapping rows and columns of the argument
17018   // matrix type.
17019   QualType ResultType = Context.getConstantMatrixType(
17020       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17021 
17022   // Change the return type to the type of the returned matrix.
17023   TheCall->setType(ResultType);
17024 
17025   // Update call argument to use the possibly converted matrix argument.
17026   TheCall->setArg(0, Matrix);
17027   return CallResult;
17028 }
17029 
17030 // Get and verify the matrix dimensions.
17031 static llvm::Optional<unsigned>
17032 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17033   SourceLocation ErrorPos;
17034   Optional<llvm::APSInt> Value =
17035       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17036   if (!Value) {
17037     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17038         << Name;
17039     return {};
17040   }
17041   uint64_t Dim = Value->getZExtValue();
17042   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17043     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17044         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17045     return {};
17046   }
17047   return Dim;
17048 }
17049 
17050 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17051                                                   ExprResult CallResult) {
17052   if (!getLangOpts().MatrixTypes) {
17053     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17054     return ExprError();
17055   }
17056 
17057   if (checkArgCount(*this, TheCall, 4))
17058     return ExprError();
17059 
17060   unsigned PtrArgIdx = 0;
17061   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17062   Expr *RowsExpr = TheCall->getArg(1);
17063   Expr *ColumnsExpr = TheCall->getArg(2);
17064   Expr *StrideExpr = TheCall->getArg(3);
17065 
17066   bool ArgError = false;
17067 
17068   // Check pointer argument.
17069   {
17070     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17071     if (PtrConv.isInvalid())
17072       return PtrConv;
17073     PtrExpr = PtrConv.get();
17074     TheCall->setArg(0, PtrExpr);
17075     if (PtrExpr->isTypeDependent()) {
17076       TheCall->setType(Context.DependentTy);
17077       return TheCall;
17078     }
17079   }
17080 
17081   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17082   QualType ElementTy;
17083   if (!PtrTy) {
17084     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17085         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17086     ArgError = true;
17087   } else {
17088     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17089 
17090     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17091       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17092           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17093           << PtrExpr->getType();
17094       ArgError = true;
17095     }
17096   }
17097 
17098   // Apply default Lvalue conversions and convert the expression to size_t.
17099   auto ApplyArgumentConversions = [this](Expr *E) {
17100     ExprResult Conv = DefaultLvalueConversion(E);
17101     if (Conv.isInvalid())
17102       return Conv;
17103 
17104     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17105   };
17106 
17107   // Apply conversion to row and column expressions.
17108   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17109   if (!RowsConv.isInvalid()) {
17110     RowsExpr = RowsConv.get();
17111     TheCall->setArg(1, RowsExpr);
17112   } else
17113     RowsExpr = nullptr;
17114 
17115   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17116   if (!ColumnsConv.isInvalid()) {
17117     ColumnsExpr = ColumnsConv.get();
17118     TheCall->setArg(2, ColumnsExpr);
17119   } else
17120     ColumnsExpr = nullptr;
17121 
17122   // If any any part of the result matrix type is still pending, just use
17123   // Context.DependentTy, until all parts are resolved.
17124   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17125       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17126     TheCall->setType(Context.DependentTy);
17127     return CallResult;
17128   }
17129 
17130   // Check row and column dimensions.
17131   llvm::Optional<unsigned> MaybeRows;
17132   if (RowsExpr)
17133     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17134 
17135   llvm::Optional<unsigned> MaybeColumns;
17136   if (ColumnsExpr)
17137     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17138 
17139   // Check stride argument.
17140   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17141   if (StrideConv.isInvalid())
17142     return ExprError();
17143   StrideExpr = StrideConv.get();
17144   TheCall->setArg(3, StrideExpr);
17145 
17146   if (MaybeRows) {
17147     if (Optional<llvm::APSInt> Value =
17148             StrideExpr->getIntegerConstantExpr(Context)) {
17149       uint64_t Stride = Value->getZExtValue();
17150       if (Stride < *MaybeRows) {
17151         Diag(StrideExpr->getBeginLoc(),
17152              diag::err_builtin_matrix_stride_too_small);
17153         ArgError = true;
17154       }
17155     }
17156   }
17157 
17158   if (ArgError || !MaybeRows || !MaybeColumns)
17159     return ExprError();
17160 
17161   TheCall->setType(
17162       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17163   return CallResult;
17164 }
17165 
17166 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17167                                                    ExprResult CallResult) {
17168   if (checkArgCount(*this, TheCall, 3))
17169     return ExprError();
17170 
17171   unsigned PtrArgIdx = 1;
17172   Expr *MatrixExpr = TheCall->getArg(0);
17173   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17174   Expr *StrideExpr = TheCall->getArg(2);
17175 
17176   bool ArgError = false;
17177 
17178   {
17179     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17180     if (MatrixConv.isInvalid())
17181       return MatrixConv;
17182     MatrixExpr = MatrixConv.get();
17183     TheCall->setArg(0, MatrixExpr);
17184   }
17185   if (MatrixExpr->isTypeDependent()) {
17186     TheCall->setType(Context.DependentTy);
17187     return TheCall;
17188   }
17189 
17190   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17191   if (!MatrixTy) {
17192     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17193         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17194     ArgError = true;
17195   }
17196 
17197   {
17198     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17199     if (PtrConv.isInvalid())
17200       return PtrConv;
17201     PtrExpr = PtrConv.get();
17202     TheCall->setArg(1, PtrExpr);
17203     if (PtrExpr->isTypeDependent()) {
17204       TheCall->setType(Context.DependentTy);
17205       return TheCall;
17206     }
17207   }
17208 
17209   // Check pointer argument.
17210   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17211   if (!PtrTy) {
17212     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17213         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17214     ArgError = true;
17215   } else {
17216     QualType ElementTy = PtrTy->getPointeeType();
17217     if (ElementTy.isConstQualified()) {
17218       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17219       ArgError = true;
17220     }
17221     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17222     if (MatrixTy &&
17223         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17224       Diag(PtrExpr->getBeginLoc(),
17225            diag::err_builtin_matrix_pointer_arg_mismatch)
17226           << ElementTy << MatrixTy->getElementType();
17227       ArgError = true;
17228     }
17229   }
17230 
17231   // Apply default Lvalue conversions and convert the stride expression to
17232   // size_t.
17233   {
17234     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17235     if (StrideConv.isInvalid())
17236       return StrideConv;
17237 
17238     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17239     if (StrideConv.isInvalid())
17240       return StrideConv;
17241     StrideExpr = StrideConv.get();
17242     TheCall->setArg(2, StrideExpr);
17243   }
17244 
17245   // Check stride argument.
17246   if (MatrixTy) {
17247     if (Optional<llvm::APSInt> Value =
17248             StrideExpr->getIntegerConstantExpr(Context)) {
17249       uint64_t Stride = Value->getZExtValue();
17250       if (Stride < MatrixTy->getNumRows()) {
17251         Diag(StrideExpr->getBeginLoc(),
17252              diag::err_builtin_matrix_stride_too_small);
17253         ArgError = true;
17254       }
17255     }
17256   }
17257 
17258   if (ArgError)
17259     return ExprError();
17260 
17261   return CallResult;
17262 }
17263 
17264 /// \brief Enforce the bounds of a TCB
17265 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17266 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17267 /// and enforce_tcb_leaf attributes.
17268 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17269                                const FunctionDecl *Callee) {
17270   const FunctionDecl *Caller = getCurFunctionDecl();
17271 
17272   // Calls to builtins are not enforced.
17273   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17274       Callee->getBuiltinID() != 0)
17275     return;
17276 
17277   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17278   // all TCBs the callee is a part of.
17279   llvm::StringSet<> CalleeTCBs;
17280   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17281            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17282   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17283            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17284 
17285   // Go through the TCBs the caller is a part of and emit warnings if Caller
17286   // is in a TCB that the Callee is not.
17287   for_each(
17288       Caller->specific_attrs<EnforceTCBAttr>(),
17289       [&](const auto *A) {
17290         StringRef CallerTCB = A->getTCBName();
17291         if (CalleeTCBs.count(CallerTCB) == 0) {
17292           this->Diag(TheCall->getExprLoc(),
17293                      diag::warn_tcb_enforcement_violation) << Callee
17294                                                            << CallerTCB;
17295         }
17296       });
17297 }
17298