1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << toString(ObjectSize, /*Radix=*/10)
776                           << toString(UsedSize.getValue(), /*Radix=*/10));
777 }
778 
779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844     return true;
845   }
846   return false;
847 }
848 
849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850   if (checkArgCount(S, TheCall, 2))
851     return true;
852 
853   if (checkOpenCLSubgroupExt(S, TheCall))
854     return true;
855 
856   // First argument is an ndrange_t type.
857   Expr *NDRangeArg = TheCall->getArg(0);
858   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860         << TheCall->getDirectCallee() << "'ndrange_t'";
861     return true;
862   }
863 
864   Expr *BlockArg = TheCall->getArg(1);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874 /// get_kernel_work_group_size
875 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877   if (checkArgCount(S, TheCall, 1))
878     return true;
879 
880   Expr *BlockArg = TheCall->getArg(0);
881   if (!isBlockPointer(BlockArg)) {
882     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883         << TheCall->getDirectCallee() << "block";
884     return true;
885   }
886   return checkOpenCLBlockArgs(S, BlockArg);
887 }
888 
889 /// Diagnose integer type and any valid implicit conversion to it.
890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891                                       const QualType &IntType);
892 
893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894                                             unsigned Start, unsigned End) {
895   bool IllegalParams = false;
896   for (unsigned I = Start; I <= End; ++I)
897     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898                                               S.Context.getSizeType());
899   return IllegalParams;
900 }
901 
902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903 /// 'local void*' parameter of passed block.
904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905                                            Expr *BlockArg,
906                                            unsigned NumNonVarArgs) {
907   const BlockPointerType *BPT =
908       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909   unsigned NumBlockParams =
910       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911   unsigned TotalNumArgs = TheCall->getNumArgs();
912 
913   // For each argument passed to the block, a corresponding uint needs to
914   // be passed to describe the size of the local memory.
915   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916     S.Diag(TheCall->getBeginLoc(),
917            diag::err_opencl_enqueue_kernel_local_size_args);
918     return true;
919   }
920 
921   // Check that the sizes of the local memory are specified by integers.
922   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923                                          TotalNumArgs - 1);
924 }
925 
926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927 /// overload formats specified in Table 6.13.17.1.
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    void (^block)(void))
932 /// int enqueue_kernel(queue_t queue,
933 ///                    kernel_enqueue_flags_t flags,
934 ///                    const ndrange_t ndrange,
935 ///                    uint num_events_in_wait_list,
936 ///                    clk_event_t *event_wait_list,
937 ///                    clk_event_t *event_ret,
938 ///                    void (^block)(void))
939 /// int enqueue_kernel(queue_t queue,
940 ///                    kernel_enqueue_flags_t flags,
941 ///                    const ndrange_t ndrange,
942 ///                    void (^block)(local void*, ...),
943 ///                    uint size0, ...)
944 /// int enqueue_kernel(queue_t queue,
945 ///                    kernel_enqueue_flags_t flags,
946 ///                    const ndrange_t ndrange,
947 ///                    uint num_events_in_wait_list,
948 ///                    clk_event_t *event_wait_list,
949 ///                    clk_event_t *event_ret,
950 ///                    void (^block)(local void*, ...),
951 ///                    uint size0, ...)
952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953   unsigned NumArgs = TheCall->getNumArgs();
954 
955   if (NumArgs < 4) {
956     S.Diag(TheCall->getBeginLoc(),
957            diag::err_typecheck_call_too_few_args_at_least)
958         << 0 << 4 << NumArgs;
959     return true;
960   }
961 
962   Expr *Arg0 = TheCall->getArg(0);
963   Expr *Arg1 = TheCall->getArg(1);
964   Expr *Arg2 = TheCall->getArg(2);
965   Expr *Arg3 = TheCall->getArg(3);
966 
967   // First argument always needs to be a queue_t type.
968   if (!Arg0->getType()->isQueueT()) {
969     S.Diag(TheCall->getArg(0)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972     return true;
973   }
974 
975   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976   if (!Arg1->getType()->isIntegerType()) {
977     S.Diag(TheCall->getArg(1)->getBeginLoc(),
978            diag::err_opencl_builtin_expected_type)
979         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980     return true;
981   }
982 
983   // Third argument is always an ndrange_t type.
984   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985     S.Diag(TheCall->getArg(2)->getBeginLoc(),
986            diag::err_opencl_builtin_expected_type)
987         << TheCall->getDirectCallee() << "'ndrange_t'";
988     return true;
989   }
990 
991   // With four arguments, there is only one form that the function could be
992   // called in: no events and no variable arguments.
993   if (NumArgs == 4) {
994     // check that the last argument is the right block type.
995     if (!isBlockPointer(Arg3)) {
996       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997           << TheCall->getDirectCallee() << "block";
998       return true;
999     }
1000     // we have a block type, check the prototype
1001     const BlockPointerType *BPT =
1002         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004       S.Diag(Arg3->getBeginLoc(),
1005              diag::err_opencl_enqueue_kernel_blocks_no_args);
1006       return true;
1007     }
1008     return false;
1009   }
1010   // we can have block + varargs.
1011   if (isBlockPointer(Arg3))
1012     return (checkOpenCLBlockArgs(S, Arg3) ||
1013             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014   // last two cases with either exactly 7 args or 7 args and varargs.
1015   if (NumArgs >= 7) {
1016     // check common block argument.
1017     Expr *Arg6 = TheCall->getArg(6);
1018     if (!isBlockPointer(Arg6)) {
1019       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020           << TheCall->getDirectCallee() << "block";
1021       return true;
1022     }
1023     if (checkOpenCLBlockArgs(S, Arg6))
1024       return true;
1025 
1026     // Forth argument has to be any integer type.
1027     if (!Arg3->getType()->isIntegerType()) {
1028       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029              diag::err_opencl_builtin_expected_type)
1030           << TheCall->getDirectCallee() << "integer";
1031       return true;
1032     }
1033     // check remaining common arguments.
1034     Expr *Arg4 = TheCall->getArg(4);
1035     Expr *Arg5 = TheCall->getArg(5);
1036 
1037     // Fifth argument is always passed as a pointer to clk_event_t.
1038     if (!Arg4->isNullPointerConstant(S.Context,
1039                                      Expr::NPC_ValueDependentIsNotNull) &&
1040         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042              diag::err_opencl_builtin_expected_type)
1043           << TheCall->getDirectCallee()
1044           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045       return true;
1046     }
1047 
1048     // Sixth argument is always passed as a pointer to clk_event_t.
1049     if (!Arg5->isNullPointerConstant(S.Context,
1050                                      Expr::NPC_ValueDependentIsNotNull) &&
1051         !(Arg5->getType()->isPointerType() &&
1052           Arg5->getType()->getPointeeType()->isClkEventT())) {
1053       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054              diag::err_opencl_builtin_expected_type)
1055           << TheCall->getDirectCallee()
1056           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057       return true;
1058     }
1059 
1060     if (NumArgs == 7)
1061       return false;
1062 
1063     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064   }
1065 
1066   // None of the specific case has been detected, give generic error
1067   S.Diag(TheCall->getBeginLoc(),
1068          diag::err_opencl_enqueue_kernel_incorrect_args);
1069   return true;
1070 }
1071 
1072 /// Returns OpenCL access qual.
1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074     return D->getAttr<OpenCLAccessAttr>();
1075 }
1076 
1077 /// Returns true if pipe element type is different from the pointer.
1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079   const Expr *Arg0 = Call->getArg(0);
1080   // First argument type should always be pipe.
1081   if (!Arg0->getType()->isPipeType()) {
1082     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083         << Call->getDirectCallee() << Arg0->getSourceRange();
1084     return true;
1085   }
1086   OpenCLAccessAttr *AccessQual =
1087       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088   // Validates the access qualifier is compatible with the call.
1089   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090   // read_only and write_only, and assumed to be read_only if no qualifier is
1091   // specified.
1092   switch (Call->getDirectCallee()->getBuiltinID()) {
1093   case Builtin::BIread_pipe:
1094   case Builtin::BIreserve_read_pipe:
1095   case Builtin::BIcommit_read_pipe:
1096   case Builtin::BIwork_group_reserve_read_pipe:
1097   case Builtin::BIsub_group_reserve_read_pipe:
1098   case Builtin::BIwork_group_commit_read_pipe:
1099   case Builtin::BIsub_group_commit_read_pipe:
1100     if (!(!AccessQual || AccessQual->isReadOnly())) {
1101       S.Diag(Arg0->getBeginLoc(),
1102              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103           << "read_only" << Arg0->getSourceRange();
1104       return true;
1105     }
1106     break;
1107   case Builtin::BIwrite_pipe:
1108   case Builtin::BIreserve_write_pipe:
1109   case Builtin::BIcommit_write_pipe:
1110   case Builtin::BIwork_group_reserve_write_pipe:
1111   case Builtin::BIsub_group_reserve_write_pipe:
1112   case Builtin::BIwork_group_commit_write_pipe:
1113   case Builtin::BIsub_group_commit_write_pipe:
1114     if (!(AccessQual && AccessQual->isWriteOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "write_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   default:
1122     break;
1123   }
1124   return false;
1125 }
1126 
1127 /// Returns true if pipe element type is different from the pointer.
1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129   const Expr *Arg0 = Call->getArg(0);
1130   const Expr *ArgIdx = Call->getArg(Idx);
1131   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132   const QualType EltTy = PipeTy->getElementType();
1133   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134   // The Idx argument should be a pointer and the type of the pointer and
1135   // the type of pipe element should also be the same.
1136   if (!ArgTy ||
1137       !S.Context.hasSameType(
1138           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141         << ArgIdx->getType() << ArgIdx->getSourceRange();
1142     return true;
1143   }
1144   return false;
1145 }
1146 
1147 // Performs semantic analysis for the read/write_pipe call.
1148 // \param S Reference to the semantic analyzer.
1149 // \param Call A pointer to the builtin call.
1150 // \return True if a semantic error has been found, false otherwise.
1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153   // functions have two forms.
1154   switch (Call->getNumArgs()) {
1155   case 2:
1156     if (checkOpenCLPipeArg(S, Call))
1157       return true;
1158     // The call with 2 arguments should be
1159     // read/write_pipe(pipe T, T*).
1160     // Check packet type T.
1161     if (checkOpenCLPipePacketType(S, Call, 1))
1162       return true;
1163     break;
1164 
1165   case 4: {
1166     if (checkOpenCLPipeArg(S, Call))
1167       return true;
1168     // The call with 4 arguments should be
1169     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170     // Check reserve_id_t.
1171     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175       return true;
1176     }
1177 
1178     // Check the index.
1179     const Expr *Arg2 = Call->getArg(2);
1180     if (!Arg2->getType()->isIntegerType() &&
1181         !Arg2->getType()->isUnsignedIntegerType()) {
1182       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184           << Arg2->getType() << Arg2->getSourceRange();
1185       return true;
1186     }
1187 
1188     // Check packet type T.
1189     if (checkOpenCLPipePacketType(S, Call, 3))
1190       return true;
1191   } break;
1192   default:
1193     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194         << Call->getDirectCallee() << Call->getSourceRange();
1195     return true;
1196   }
1197 
1198   return false;
1199 }
1200 
1201 // Performs a semantic analysis on the {work_group_/sub_group_
1202 //        /_}reserve_{read/write}_pipe
1203 // \param S Reference to the semantic analyzer.
1204 // \param Call The call to the builtin function to be analyzed.
1205 // \return True if a semantic error was found, false otherwise.
1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207   if (checkArgCount(S, Call, 2))
1208     return true;
1209 
1210   if (checkOpenCLPipeArg(S, Call))
1211     return true;
1212 
1213   // Check the reserve size.
1214   if (!Call->getArg(1)->getType()->isIntegerType() &&
1215       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219     return true;
1220   }
1221 
1222   // Since return type of reserve_read/write_pipe built-in function is
1223   // reserve_id_t, which is not defined in the builtin def file , we used int
1224   // as return type and need to override the return type of these functions.
1225   Call->setType(S.Context.OCLReserveIDTy);
1226 
1227   return false;
1228 }
1229 
1230 // Performs a semantic analysis on {work_group_/sub_group_
1231 //        /_}commit_{read/write}_pipe
1232 // \param S Reference to the semantic analyzer.
1233 // \param Call The call to the builtin function to be analyzed.
1234 // \return True if a semantic error was found, false otherwise.
1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236   if (checkArgCount(S, Call, 2))
1237     return true;
1238 
1239   if (checkOpenCLPipeArg(S, Call))
1240     return true;
1241 
1242   // Check reserve_id_t.
1243   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247     return true;
1248   }
1249 
1250   return false;
1251 }
1252 
1253 // Performs a semantic analysis on the call to built-in Pipe
1254 //        Query Functions.
1255 // \param S Reference to the semantic analyzer.
1256 // \param Call The call to the builtin function to be analyzed.
1257 // \return True if a semantic error was found, false otherwise.
1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259   if (checkArgCount(S, Call, 1))
1260     return true;
1261 
1262   if (!Call->getArg(0)->getType()->isPipeType()) {
1263     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265     return true;
1266   }
1267 
1268   return false;
1269 }
1270 
1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272 // Performs semantic analysis for the to_global/local/private call.
1273 // \param S Reference to the semantic analyzer.
1274 // \param BuiltinID ID of the builtin function.
1275 // \param Call A pointer to the builtin call.
1276 // \return True if a semantic error has been found, false otherwise.
1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278                                     CallExpr *Call) {
1279   if (checkArgCount(S, Call, 1))
1280     return true;
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppcle:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   case llvm::Triple::riscv32:
1434   case llvm::Triple::riscv64:
1435     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436   }
1437 }
1438 
1439 ExprResult
1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441                                CallExpr *TheCall) {
1442   ExprResult TheCallResult(TheCall);
1443 
1444   // Find out if any arguments are required to be integer constant expressions.
1445   unsigned ICEArguments = 0;
1446   ASTContext::GetBuiltinTypeError Error;
1447   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448   if (Error != ASTContext::GE_None)
1449     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1450 
1451   // If any arguments are required to be ICE's, check and diagnose.
1452   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453     // Skip arguments not required to be ICE's.
1454     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455 
1456     llvm::APSInt Result;
1457     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458       return true;
1459     ICEArguments &= ~(1 << ArgNo);
1460   }
1461 
1462   switch (BuiltinID) {
1463   case Builtin::BI__builtin___CFStringMakeConstantString:
1464     assert(TheCall->getNumArgs() == 1 &&
1465            "Wrong # arguments to builtin CFStringMakeConstantString");
1466     if (CheckObjCString(TheCall->getArg(0)))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_ms_va_start:
1470   case Builtin::BI__builtin_stdarg_start:
1471   case Builtin::BI__builtin_va_start:
1472     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BI__va_start: {
1476     switch (Context.getTargetInfo().getTriple().getArch()) {
1477     case llvm::Triple::aarch64:
1478     case llvm::Triple::arm:
1479     case llvm::Triple::thumb:
1480       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481         return ExprError();
1482       break;
1483     default:
1484       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485         return ExprError();
1486       break;
1487     }
1488     break;
1489   }
1490 
1491   // The acquire, release, and no fence variants are ARM and AArch64 only.
1492   case Builtin::BI_interlockedbittestandset_acq:
1493   case Builtin::BI_interlockedbittestandset_rel:
1494   case Builtin::BI_interlockedbittestandset_nf:
1495   case Builtin::BI_interlockedbittestandreset_acq:
1496   case Builtin::BI_interlockedbittestandreset_rel:
1497   case Builtin::BI_interlockedbittestandreset_nf:
1498     if (CheckBuiltinTargetSupport(
1499             *this, BuiltinID, TheCall,
1500             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501       return ExprError();
1502     break;
1503 
1504   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505   case Builtin::BI_bittest64:
1506   case Builtin::BI_bittestandcomplement64:
1507   case Builtin::BI_bittestandreset64:
1508   case Builtin::BI_bittestandset64:
1509   case Builtin::BI_interlockedbittestandreset64:
1510   case Builtin::BI_interlockedbittestandset64:
1511     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1513                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1514       return ExprError();
1515     break;
1516 
1517   case Builtin::BI__builtin_isgreater:
1518   case Builtin::BI__builtin_isgreaterequal:
1519   case Builtin::BI__builtin_isless:
1520   case Builtin::BI__builtin_islessequal:
1521   case Builtin::BI__builtin_islessgreater:
1522   case Builtin::BI__builtin_isunordered:
1523     if (SemaBuiltinUnorderedCompare(TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_fpclassify:
1527     if (SemaBuiltinFPClassification(TheCall, 6))
1528       return ExprError();
1529     break;
1530   case Builtin::BI__builtin_isfinite:
1531   case Builtin::BI__builtin_isinf:
1532   case Builtin::BI__builtin_isinf_sign:
1533   case Builtin::BI__builtin_isnan:
1534   case Builtin::BI__builtin_isnormal:
1535   case Builtin::BI__builtin_signbit:
1536   case Builtin::BI__builtin_signbitf:
1537   case Builtin::BI__builtin_signbitl:
1538     if (SemaBuiltinFPClassification(TheCall, 1))
1539       return ExprError();
1540     break;
1541   case Builtin::BI__builtin_shufflevector:
1542     return SemaBuiltinShuffleVector(TheCall);
1543     // TheCall will be freed by the smart pointer here, but that's fine, since
1544     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545   case Builtin::BI__builtin_prefetch:
1546     if (SemaBuiltinPrefetch(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_alloca_with_align:
1550     if (SemaBuiltinAllocaWithAlign(TheCall))
1551       return ExprError();
1552     LLVM_FALLTHROUGH;
1553   case Builtin::BI__builtin_alloca:
1554     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555         << TheCall->getDirectCallee();
1556     break;
1557   case Builtin::BI__arithmetic_fence:
1558     if (SemaBuiltinArithmeticFence(TheCall))
1559       return ExprError();
1560     break;
1561   case Builtin::BI__assume:
1562   case Builtin::BI__builtin_assume:
1563     if (SemaBuiltinAssume(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_assume_aligned:
1567     if (SemaBuiltinAssumeAligned(TheCall))
1568       return ExprError();
1569     break;
1570   case Builtin::BI__builtin_dynamic_object_size:
1571   case Builtin::BI__builtin_object_size:
1572     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_longjmp:
1576     if (SemaBuiltinLongjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_setjmp:
1580     if (SemaBuiltinSetjmp(TheCall))
1581       return ExprError();
1582     break;
1583   case Builtin::BI__builtin_classify_type:
1584     if (checkArgCount(*this, TheCall, 1)) return true;
1585     TheCall->setType(Context.IntTy);
1586     break;
1587   case Builtin::BI__builtin_complex:
1588     if (SemaBuiltinComplex(TheCall))
1589       return ExprError();
1590     break;
1591   case Builtin::BI__builtin_constant_p: {
1592     if (checkArgCount(*this, TheCall, 1)) return true;
1593     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1594     if (Arg.isInvalid()) return true;
1595     TheCall->setArg(0, Arg.get());
1596     TheCall->setType(Context.IntTy);
1597     break;
1598   }
1599   case Builtin::BI__builtin_launder:
1600     return SemaBuiltinLaunder(*this, TheCall);
1601   case Builtin::BI__sync_fetch_and_add:
1602   case Builtin::BI__sync_fetch_and_add_1:
1603   case Builtin::BI__sync_fetch_and_add_2:
1604   case Builtin::BI__sync_fetch_and_add_4:
1605   case Builtin::BI__sync_fetch_and_add_8:
1606   case Builtin::BI__sync_fetch_and_add_16:
1607   case Builtin::BI__sync_fetch_and_sub:
1608   case Builtin::BI__sync_fetch_and_sub_1:
1609   case Builtin::BI__sync_fetch_and_sub_2:
1610   case Builtin::BI__sync_fetch_and_sub_4:
1611   case Builtin::BI__sync_fetch_and_sub_8:
1612   case Builtin::BI__sync_fetch_and_sub_16:
1613   case Builtin::BI__sync_fetch_and_or:
1614   case Builtin::BI__sync_fetch_and_or_1:
1615   case Builtin::BI__sync_fetch_and_or_2:
1616   case Builtin::BI__sync_fetch_and_or_4:
1617   case Builtin::BI__sync_fetch_and_or_8:
1618   case Builtin::BI__sync_fetch_and_or_16:
1619   case Builtin::BI__sync_fetch_and_and:
1620   case Builtin::BI__sync_fetch_and_and_1:
1621   case Builtin::BI__sync_fetch_and_and_2:
1622   case Builtin::BI__sync_fetch_and_and_4:
1623   case Builtin::BI__sync_fetch_and_and_8:
1624   case Builtin::BI__sync_fetch_and_and_16:
1625   case Builtin::BI__sync_fetch_and_xor:
1626   case Builtin::BI__sync_fetch_and_xor_1:
1627   case Builtin::BI__sync_fetch_and_xor_2:
1628   case Builtin::BI__sync_fetch_and_xor_4:
1629   case Builtin::BI__sync_fetch_and_xor_8:
1630   case Builtin::BI__sync_fetch_and_xor_16:
1631   case Builtin::BI__sync_fetch_and_nand:
1632   case Builtin::BI__sync_fetch_and_nand_1:
1633   case Builtin::BI__sync_fetch_and_nand_2:
1634   case Builtin::BI__sync_fetch_and_nand_4:
1635   case Builtin::BI__sync_fetch_and_nand_8:
1636   case Builtin::BI__sync_fetch_and_nand_16:
1637   case Builtin::BI__sync_add_and_fetch:
1638   case Builtin::BI__sync_add_and_fetch_1:
1639   case Builtin::BI__sync_add_and_fetch_2:
1640   case Builtin::BI__sync_add_and_fetch_4:
1641   case Builtin::BI__sync_add_and_fetch_8:
1642   case Builtin::BI__sync_add_and_fetch_16:
1643   case Builtin::BI__sync_sub_and_fetch:
1644   case Builtin::BI__sync_sub_and_fetch_1:
1645   case Builtin::BI__sync_sub_and_fetch_2:
1646   case Builtin::BI__sync_sub_and_fetch_4:
1647   case Builtin::BI__sync_sub_and_fetch_8:
1648   case Builtin::BI__sync_sub_and_fetch_16:
1649   case Builtin::BI__sync_and_and_fetch:
1650   case Builtin::BI__sync_and_and_fetch_1:
1651   case Builtin::BI__sync_and_and_fetch_2:
1652   case Builtin::BI__sync_and_and_fetch_4:
1653   case Builtin::BI__sync_and_and_fetch_8:
1654   case Builtin::BI__sync_and_and_fetch_16:
1655   case Builtin::BI__sync_or_and_fetch:
1656   case Builtin::BI__sync_or_and_fetch_1:
1657   case Builtin::BI__sync_or_and_fetch_2:
1658   case Builtin::BI__sync_or_and_fetch_4:
1659   case Builtin::BI__sync_or_and_fetch_8:
1660   case Builtin::BI__sync_or_and_fetch_16:
1661   case Builtin::BI__sync_xor_and_fetch:
1662   case Builtin::BI__sync_xor_and_fetch_1:
1663   case Builtin::BI__sync_xor_and_fetch_2:
1664   case Builtin::BI__sync_xor_and_fetch_4:
1665   case Builtin::BI__sync_xor_and_fetch_8:
1666   case Builtin::BI__sync_xor_and_fetch_16:
1667   case Builtin::BI__sync_nand_and_fetch:
1668   case Builtin::BI__sync_nand_and_fetch_1:
1669   case Builtin::BI__sync_nand_and_fetch_2:
1670   case Builtin::BI__sync_nand_and_fetch_4:
1671   case Builtin::BI__sync_nand_and_fetch_8:
1672   case Builtin::BI__sync_nand_and_fetch_16:
1673   case Builtin::BI__sync_val_compare_and_swap:
1674   case Builtin::BI__sync_val_compare_and_swap_1:
1675   case Builtin::BI__sync_val_compare_and_swap_2:
1676   case Builtin::BI__sync_val_compare_and_swap_4:
1677   case Builtin::BI__sync_val_compare_and_swap_8:
1678   case Builtin::BI__sync_val_compare_and_swap_16:
1679   case Builtin::BI__sync_bool_compare_and_swap:
1680   case Builtin::BI__sync_bool_compare_and_swap_1:
1681   case Builtin::BI__sync_bool_compare_and_swap_2:
1682   case Builtin::BI__sync_bool_compare_and_swap_4:
1683   case Builtin::BI__sync_bool_compare_and_swap_8:
1684   case Builtin::BI__sync_bool_compare_and_swap_16:
1685   case Builtin::BI__sync_lock_test_and_set:
1686   case Builtin::BI__sync_lock_test_and_set_1:
1687   case Builtin::BI__sync_lock_test_and_set_2:
1688   case Builtin::BI__sync_lock_test_and_set_4:
1689   case Builtin::BI__sync_lock_test_and_set_8:
1690   case Builtin::BI__sync_lock_test_and_set_16:
1691   case Builtin::BI__sync_lock_release:
1692   case Builtin::BI__sync_lock_release_1:
1693   case Builtin::BI__sync_lock_release_2:
1694   case Builtin::BI__sync_lock_release_4:
1695   case Builtin::BI__sync_lock_release_8:
1696   case Builtin::BI__sync_lock_release_16:
1697   case Builtin::BI__sync_swap:
1698   case Builtin::BI__sync_swap_1:
1699   case Builtin::BI__sync_swap_2:
1700   case Builtin::BI__sync_swap_4:
1701   case Builtin::BI__sync_swap_8:
1702   case Builtin::BI__sync_swap_16:
1703     return SemaBuiltinAtomicOverloaded(TheCallResult);
1704   case Builtin::BI__sync_synchronize:
1705     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1706         << TheCall->getCallee()->getSourceRange();
1707     break;
1708   case Builtin::BI__builtin_nontemporal_load:
1709   case Builtin::BI__builtin_nontemporal_store:
1710     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1711   case Builtin::BI__builtin_memcpy_inline: {
1712     clang::Expr *SizeOp = TheCall->getArg(2);
1713     // We warn about copying to or from `nullptr` pointers when `size` is
1714     // greater than 0. When `size` is value dependent we cannot evaluate its
1715     // value so we bail out.
1716     if (SizeOp->isValueDependent())
1717       break;
1718     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1719       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1720       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1721     }
1722     break;
1723   }
1724 #define BUILTIN(ID, TYPE, ATTRS)
1725 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1726   case Builtin::BI##ID: \
1727     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1728 #include "clang/Basic/Builtins.def"
1729   case Builtin::BI__annotation:
1730     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_annotation:
1734     if (SemaBuiltinAnnotation(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_addressof:
1738     if (SemaBuiltinAddressof(*this, TheCall))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__builtin_is_aligned:
1742   case Builtin::BI__builtin_align_up:
1743   case Builtin::BI__builtin_align_down:
1744     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_add_overflow:
1748   case Builtin::BI__builtin_sub_overflow:
1749   case Builtin::BI__builtin_mul_overflow:
1750     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1751       return ExprError();
1752     break;
1753   case Builtin::BI__builtin_operator_new:
1754   case Builtin::BI__builtin_operator_delete: {
1755     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1756     ExprResult Res =
1757         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1758     if (Res.isInvalid())
1759       CorrectDelayedTyposInExpr(TheCallResult.get());
1760     return Res;
1761   }
1762   case Builtin::BI__builtin_dump_struct: {
1763     // We first want to ensure we are called with 2 arguments
1764     if (checkArgCount(*this, TheCall, 2))
1765       return ExprError();
1766     // Ensure that the first argument is of type 'struct XX *'
1767     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1768     const QualType PtrArgType = PtrArg->getType();
1769     if (!PtrArgType->isPointerType() ||
1770         !PtrArgType->getPointeeType()->isRecordType()) {
1771       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1773           << "structure pointer";
1774       return ExprError();
1775     }
1776 
1777     // Ensure that the second argument is of type 'FunctionType'
1778     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1779     const QualType FnPtrArgType = FnPtrArg->getType();
1780     if (!FnPtrArgType->isPointerType()) {
1781       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1782           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1783           << FnPtrArgType << "'int (*)(const char *, ...)'";
1784       return ExprError();
1785     }
1786 
1787     const auto *FuncType =
1788         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1789 
1790     if (!FuncType) {
1791       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1792           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1793           << FnPtrArgType << "'int (*)(const char *, ...)'";
1794       return ExprError();
1795     }
1796 
1797     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1798       if (!FT->getNumParams()) {
1799         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1800             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1801             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1802         return ExprError();
1803       }
1804       QualType PT = FT->getParamType(0);
1805       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1806           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1807           !PT->getPointeeType().isConstQualified()) {
1808         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1809             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1810             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1811         return ExprError();
1812       }
1813     }
1814 
1815     TheCall->setType(Context.IntTy);
1816     break;
1817   }
1818   case Builtin::BI__builtin_expect_with_probability: {
1819     // We first want to ensure we are called with 3 arguments
1820     if (checkArgCount(*this, TheCall, 3))
1821       return ExprError();
1822     // then check probability is constant float in range [0.0, 1.0]
1823     const Expr *ProbArg = TheCall->getArg(2);
1824     SmallVector<PartialDiagnosticAt, 8> Notes;
1825     Expr::EvalResult Eval;
1826     Eval.Diag = &Notes;
1827     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1828         !Eval.Val.isFloat()) {
1829       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1830           << ProbArg->getSourceRange();
1831       for (const PartialDiagnosticAt &PDiag : Notes)
1832         Diag(PDiag.first, PDiag.second);
1833       return ExprError();
1834     }
1835     llvm::APFloat Probability = Eval.Val.getFloat();
1836     bool LoseInfo = false;
1837     Probability.convert(llvm::APFloat::IEEEdouble(),
1838                         llvm::RoundingMode::Dynamic, &LoseInfo);
1839     if (!(Probability >= llvm::APFloat(0.0) &&
1840           Probability <= llvm::APFloat(1.0))) {
1841       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1842           << ProbArg->getSourceRange();
1843       return ExprError();
1844     }
1845     break;
1846   }
1847   case Builtin::BI__builtin_preserve_access_index:
1848     if (SemaBuiltinPreserveAI(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__builtin_call_with_static_chain:
1852     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1853       return ExprError();
1854     break;
1855   case Builtin::BI__exception_code:
1856   case Builtin::BI_exception_code:
1857     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1858                                  diag::err_seh___except_block))
1859       return ExprError();
1860     break;
1861   case Builtin::BI__exception_info:
1862   case Builtin::BI_exception_info:
1863     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1864                                  diag::err_seh___except_filter))
1865       return ExprError();
1866     break;
1867   case Builtin::BI__GetExceptionInfo:
1868     if (checkArgCount(*this, TheCall, 1))
1869       return ExprError();
1870 
1871     if (CheckCXXThrowOperand(
1872             TheCall->getBeginLoc(),
1873             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1874             TheCall))
1875       return ExprError();
1876 
1877     TheCall->setType(Context.VoidPtrTy);
1878     break;
1879   // OpenCL v2.0, s6.13.16 - Pipe functions
1880   case Builtin::BIread_pipe:
1881   case Builtin::BIwrite_pipe:
1882     // Since those two functions are declared with var args, we need a semantic
1883     // check for the argument.
1884     if (SemaBuiltinRWPipe(*this, TheCall))
1885       return ExprError();
1886     break;
1887   case Builtin::BIreserve_read_pipe:
1888   case Builtin::BIreserve_write_pipe:
1889   case Builtin::BIwork_group_reserve_read_pipe:
1890   case Builtin::BIwork_group_reserve_write_pipe:
1891     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1892       return ExprError();
1893     break;
1894   case Builtin::BIsub_group_reserve_read_pipe:
1895   case Builtin::BIsub_group_reserve_write_pipe:
1896     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1897         SemaBuiltinReserveRWPipe(*this, TheCall))
1898       return ExprError();
1899     break;
1900   case Builtin::BIcommit_read_pipe:
1901   case Builtin::BIcommit_write_pipe:
1902   case Builtin::BIwork_group_commit_read_pipe:
1903   case Builtin::BIwork_group_commit_write_pipe:
1904     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1905       return ExprError();
1906     break;
1907   case Builtin::BIsub_group_commit_read_pipe:
1908   case Builtin::BIsub_group_commit_write_pipe:
1909     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1910         SemaBuiltinCommitRWPipe(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIget_pipe_num_packets:
1914   case Builtin::BIget_pipe_max_packets:
1915     if (SemaBuiltinPipePackets(*this, TheCall))
1916       return ExprError();
1917     break;
1918   case Builtin::BIto_global:
1919   case Builtin::BIto_local:
1920   case Builtin::BIto_private:
1921     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1922       return ExprError();
1923     break;
1924   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1925   case Builtin::BIenqueue_kernel:
1926     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_work_group_size:
1930   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1931     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1935   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1936     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1937       return ExprError();
1938     break;
1939   case Builtin::BI__builtin_os_log_format:
1940     Cleanup.setExprNeedsCleanups(true);
1941     LLVM_FALLTHROUGH;
1942   case Builtin::BI__builtin_os_log_format_buffer_size:
1943     if (SemaBuiltinOSLogFormat(TheCall))
1944       return ExprError();
1945     break;
1946   case Builtin::BI__builtin_frame_address:
1947   case Builtin::BI__builtin_return_address: {
1948     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1949       return ExprError();
1950 
1951     // -Wframe-address warning if non-zero passed to builtin
1952     // return/frame address.
1953     Expr::EvalResult Result;
1954     if (!TheCall->getArg(0)->isValueDependent() &&
1955         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1956         Result.Val.getInt() != 0)
1957       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1958           << ((BuiltinID == Builtin::BI__builtin_return_address)
1959                   ? "__builtin_return_address"
1960                   : "__builtin_frame_address")
1961           << TheCall->getSourceRange();
1962     break;
1963   }
1964 
1965   case Builtin::BI__builtin_matrix_transpose:
1966     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1967 
1968   case Builtin::BI__builtin_matrix_column_major_load:
1969     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1970 
1971   case Builtin::BI__builtin_matrix_column_major_store:
1972     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1973 
1974   case Builtin::BI__builtin_get_device_side_mangled_name: {
1975     auto Check = [](CallExpr *TheCall) {
1976       if (TheCall->getNumArgs() != 1)
1977         return false;
1978       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1979       if (!DRE)
1980         return false;
1981       auto *D = DRE->getDecl();
1982       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1983         return false;
1984       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1985              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1986     };
1987     if (!Check(TheCall)) {
1988       Diag(TheCall->getBeginLoc(),
1989            diag::err_hip_invalid_args_builtin_mangled_name);
1990       return ExprError();
1991     }
1992   }
1993   }
1994 
1995   // Since the target specific builtins for each arch overlap, only check those
1996   // of the arch we are compiling for.
1997   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1998     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1999       assert(Context.getAuxTargetInfo() &&
2000              "Aux Target Builtin, but not an aux target?");
2001 
2002       if (CheckTSBuiltinFunctionCall(
2003               *Context.getAuxTargetInfo(),
2004               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2005         return ExprError();
2006     } else {
2007       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2008                                      TheCall))
2009         return ExprError();
2010     }
2011   }
2012 
2013   return TheCallResult;
2014 }
2015 
2016 // Get the valid immediate range for the specified NEON type code.
2017 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2018   NeonTypeFlags Type(t);
2019   int IsQuad = ForceQuad ? true : Type.isQuad();
2020   switch (Type.getEltType()) {
2021   case NeonTypeFlags::Int8:
2022   case NeonTypeFlags::Poly8:
2023     return shift ? 7 : (8 << IsQuad) - 1;
2024   case NeonTypeFlags::Int16:
2025   case NeonTypeFlags::Poly16:
2026     return shift ? 15 : (4 << IsQuad) - 1;
2027   case NeonTypeFlags::Int32:
2028     return shift ? 31 : (2 << IsQuad) - 1;
2029   case NeonTypeFlags::Int64:
2030   case NeonTypeFlags::Poly64:
2031     return shift ? 63 : (1 << IsQuad) - 1;
2032   case NeonTypeFlags::Poly128:
2033     return shift ? 127 : (1 << IsQuad) - 1;
2034   case NeonTypeFlags::Float16:
2035     assert(!shift && "cannot shift float types!");
2036     return (4 << IsQuad) - 1;
2037   case NeonTypeFlags::Float32:
2038     assert(!shift && "cannot shift float types!");
2039     return (2 << IsQuad) - 1;
2040   case NeonTypeFlags::Float64:
2041     assert(!shift && "cannot shift float types!");
2042     return (1 << IsQuad) - 1;
2043   case NeonTypeFlags::BFloat16:
2044     assert(!shift && "cannot shift float types!");
2045     return (4 << IsQuad) - 1;
2046   }
2047   llvm_unreachable("Invalid NeonTypeFlag!");
2048 }
2049 
2050 /// getNeonEltType - Return the QualType corresponding to the elements of
2051 /// the vector type specified by the NeonTypeFlags.  This is used to check
2052 /// the pointer arguments for Neon load/store intrinsics.
2053 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2054                                bool IsPolyUnsigned, bool IsInt64Long) {
2055   switch (Flags.getEltType()) {
2056   case NeonTypeFlags::Int8:
2057     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2058   case NeonTypeFlags::Int16:
2059     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2060   case NeonTypeFlags::Int32:
2061     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2062   case NeonTypeFlags::Int64:
2063     if (IsInt64Long)
2064       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2065     else
2066       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2067                                 : Context.LongLongTy;
2068   case NeonTypeFlags::Poly8:
2069     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2070   case NeonTypeFlags::Poly16:
2071     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2072   case NeonTypeFlags::Poly64:
2073     if (IsInt64Long)
2074       return Context.UnsignedLongTy;
2075     else
2076       return Context.UnsignedLongLongTy;
2077   case NeonTypeFlags::Poly128:
2078     break;
2079   case NeonTypeFlags::Float16:
2080     return Context.HalfTy;
2081   case NeonTypeFlags::Float32:
2082     return Context.FloatTy;
2083   case NeonTypeFlags::Float64:
2084     return Context.DoubleTy;
2085   case NeonTypeFlags::BFloat16:
2086     return Context.BFloat16Ty;
2087   }
2088   llvm_unreachable("Invalid NeonTypeFlag!");
2089 }
2090 
2091 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2092   // Range check SVE intrinsics that take immediate values.
2093   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2094 
2095   switch (BuiltinID) {
2096   default:
2097     return false;
2098 #define GET_SVE_IMMEDIATE_CHECK
2099 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2100 #undef GET_SVE_IMMEDIATE_CHECK
2101   }
2102 
2103   // Perform all the immediate checks for this builtin call.
2104   bool HasError = false;
2105   for (auto &I : ImmChecks) {
2106     int ArgNum, CheckTy, ElementSizeInBits;
2107     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2108 
2109     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2110 
2111     // Function that checks whether the operand (ArgNum) is an immediate
2112     // that is one of the predefined values.
2113     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2114                                    int ErrDiag) -> bool {
2115       // We can't check the value of a dependent argument.
2116       Expr *Arg = TheCall->getArg(ArgNum);
2117       if (Arg->isTypeDependent() || Arg->isValueDependent())
2118         return false;
2119 
2120       // Check constant-ness first.
2121       llvm::APSInt Imm;
2122       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2123         return true;
2124 
2125       if (!CheckImm(Imm.getSExtValue()))
2126         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2127       return false;
2128     };
2129 
2130     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2131     case SVETypeFlags::ImmCheck0_31:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck0_13:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck1_16:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheck0_7:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2145         HasError = true;
2146       break;
2147     case SVETypeFlags::ImmCheckExtract:
2148       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2149                                       (2048 / ElementSizeInBits) - 1))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRight:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2154         HasError = true;
2155       break;
2156     case SVETypeFlags::ImmCheckShiftRightNarrow:
2157       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2158                                       ElementSizeInBits / 2))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckShiftLeft:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       ElementSizeInBits - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckLaneIndex:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2168                                       (128 / (1 * ElementSizeInBits)) - 1))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2173                                       (128 / (2 * ElementSizeInBits)) - 1))
2174         HasError = true;
2175       break;
2176     case SVETypeFlags::ImmCheckLaneIndexDot:
2177       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2178                                       (128 / (4 * ElementSizeInBits)) - 1))
2179         HasError = true;
2180       break;
2181     case SVETypeFlags::ImmCheckComplexRot90_270:
2182       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2183                               diag::err_rotation_argument_to_cadd))
2184         HasError = true;
2185       break;
2186     case SVETypeFlags::ImmCheckComplexRotAll90:
2187       if (CheckImmediateInSet(
2188               [](int64_t V) {
2189                 return V == 0 || V == 90 || V == 180 || V == 270;
2190               },
2191               diag::err_rotation_argument_to_cmla))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_1:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_2:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2200         HasError = true;
2201       break;
2202     case SVETypeFlags::ImmCheck0_3:
2203       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2204         HasError = true;
2205       break;
2206     }
2207   }
2208 
2209   return HasError;
2210 }
2211 
2212 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2213                                         unsigned BuiltinID, CallExpr *TheCall) {
2214   llvm::APSInt Result;
2215   uint64_t mask = 0;
2216   unsigned TV = 0;
2217   int PtrArgNum = -1;
2218   bool HasConstPtr = false;
2219   switch (BuiltinID) {
2220 #define GET_NEON_OVERLOAD_CHECK
2221 #include "clang/Basic/arm_neon.inc"
2222 #include "clang/Basic/arm_fp16.inc"
2223 #undef GET_NEON_OVERLOAD_CHECK
2224   }
2225 
2226   // For NEON intrinsics which are overloaded on vector element type, validate
2227   // the immediate which specifies which variant to emit.
2228   unsigned ImmArg = TheCall->getNumArgs()-1;
2229   if (mask) {
2230     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2231       return true;
2232 
2233     TV = Result.getLimitedValue(64);
2234     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2235       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2236              << TheCall->getArg(ImmArg)->getSourceRange();
2237   }
2238 
2239   if (PtrArgNum >= 0) {
2240     // Check that pointer arguments have the specified type.
2241     Expr *Arg = TheCall->getArg(PtrArgNum);
2242     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2243       Arg = ICE->getSubExpr();
2244     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2245     QualType RHSTy = RHS.get()->getType();
2246 
2247     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2248     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2249                           Arch == llvm::Triple::aarch64_32 ||
2250                           Arch == llvm::Triple::aarch64_be;
2251     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2252     QualType EltTy =
2253         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2254     if (HasConstPtr)
2255       EltTy = EltTy.withConst();
2256     QualType LHSTy = Context.getPointerType(EltTy);
2257     AssignConvertType ConvTy;
2258     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2259     if (RHS.isInvalid())
2260       return true;
2261     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2262                                  RHS.get(), AA_Assigning))
2263       return true;
2264   }
2265 
2266   // For NEON intrinsics which take an immediate value as part of the
2267   // instruction, range check them here.
2268   unsigned i = 0, l = 0, u = 0;
2269   switch (BuiltinID) {
2270   default:
2271     return false;
2272   #define GET_NEON_IMMEDIATE_CHECK
2273   #include "clang/Basic/arm_neon.inc"
2274   #include "clang/Basic/arm_fp16.inc"
2275   #undef GET_NEON_IMMEDIATE_CHECK
2276   }
2277 
2278   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2279 }
2280 
2281 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2282   switch (BuiltinID) {
2283   default:
2284     return false;
2285   #include "clang/Basic/arm_mve_builtin_sema.inc"
2286   }
2287 }
2288 
2289 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2290                                        CallExpr *TheCall) {
2291   bool Err = false;
2292   switch (BuiltinID) {
2293   default:
2294     return false;
2295 #include "clang/Basic/arm_cde_builtin_sema.inc"
2296   }
2297 
2298   if (Err)
2299     return true;
2300 
2301   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2302 }
2303 
2304 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2305                                         const Expr *CoprocArg, bool WantCDE) {
2306   if (isConstantEvaluated())
2307     return false;
2308 
2309   // We can't check the value of a dependent argument.
2310   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2311     return false;
2312 
2313   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2314   int64_t CoprocNo = CoprocNoAP.getExtValue();
2315   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2316 
2317   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2318   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2319 
2320   if (IsCDECoproc != WantCDE)
2321     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2322            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2323 
2324   return false;
2325 }
2326 
2327 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2328                                         unsigned MaxWidth) {
2329   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2330           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2331           BuiltinID == ARM::BI__builtin_arm_strex ||
2332           BuiltinID == ARM::BI__builtin_arm_stlex ||
2333           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2334           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2335           BuiltinID == AArch64::BI__builtin_arm_strex ||
2336           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2337          "unexpected ARM builtin");
2338   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2339                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2340                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2341                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2342 
2343   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2344 
2345   // Ensure that we have the proper number of arguments.
2346   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2347     return true;
2348 
2349   // Inspect the pointer argument of the atomic builtin.  This should always be
2350   // a pointer type, whose element is an integral scalar or pointer type.
2351   // Because it is a pointer type, we don't have to worry about any implicit
2352   // casts here.
2353   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2354   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2355   if (PointerArgRes.isInvalid())
2356     return true;
2357   PointerArg = PointerArgRes.get();
2358 
2359   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2360   if (!pointerType) {
2361     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2362         << PointerArg->getType() << PointerArg->getSourceRange();
2363     return true;
2364   }
2365 
2366   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2367   // task is to insert the appropriate casts into the AST. First work out just
2368   // what the appropriate type is.
2369   QualType ValType = pointerType->getPointeeType();
2370   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2371   if (IsLdrex)
2372     AddrType.addConst();
2373 
2374   // Issue a warning if the cast is dodgy.
2375   CastKind CastNeeded = CK_NoOp;
2376   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2377     CastNeeded = CK_BitCast;
2378     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2379         << PointerArg->getType() << Context.getPointerType(AddrType)
2380         << AA_Passing << PointerArg->getSourceRange();
2381   }
2382 
2383   // Finally, do the cast and replace the argument with the corrected version.
2384   AddrType = Context.getPointerType(AddrType);
2385   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2386   if (PointerArgRes.isInvalid())
2387     return true;
2388   PointerArg = PointerArgRes.get();
2389 
2390   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2391 
2392   // In general, we allow ints, floats and pointers to be loaded and stored.
2393   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2394       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2395     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2396         << PointerArg->getType() << PointerArg->getSourceRange();
2397     return true;
2398   }
2399 
2400   // But ARM doesn't have instructions to deal with 128-bit versions.
2401   if (Context.getTypeSize(ValType) > MaxWidth) {
2402     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2403     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2404         << PointerArg->getType() << PointerArg->getSourceRange();
2405     return true;
2406   }
2407 
2408   switch (ValType.getObjCLifetime()) {
2409   case Qualifiers::OCL_None:
2410   case Qualifiers::OCL_ExplicitNone:
2411     // okay
2412     break;
2413 
2414   case Qualifiers::OCL_Weak:
2415   case Qualifiers::OCL_Strong:
2416   case Qualifiers::OCL_Autoreleasing:
2417     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2418         << ValType << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   if (IsLdrex) {
2423     TheCall->setType(ValType);
2424     return false;
2425   }
2426 
2427   // Initialize the argument to be stored.
2428   ExprResult ValArg = TheCall->getArg(0);
2429   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2430       Context, ValType, /*consume*/ false);
2431   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2432   if (ValArg.isInvalid())
2433     return true;
2434   TheCall->setArg(0, ValArg.get());
2435 
2436   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2437   // but the custom checker bypasses all default analysis.
2438   TheCall->setType(Context.IntTy);
2439   return false;
2440 }
2441 
2442 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2443                                        CallExpr *TheCall) {
2444   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2445       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2446       BuiltinID == ARM::BI__builtin_arm_strex ||
2447       BuiltinID == ARM::BI__builtin_arm_stlex) {
2448     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2449   }
2450 
2451   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2452     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2453       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2454   }
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2457       BuiltinID == ARM::BI__builtin_arm_wsr64)
2458     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2459 
2460   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2461       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2462       BuiltinID == ARM::BI__builtin_arm_wsr ||
2463       BuiltinID == ARM::BI__builtin_arm_wsrp)
2464     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2465 
2466   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2469     return true;
2470   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2471     return true;
2472 
2473   // For intrinsics which take an immediate value as part of the instruction,
2474   // range check them here.
2475   // FIXME: VFP Intrinsics should error if VFP not present.
2476   switch (BuiltinID) {
2477   default: return false;
2478   case ARM::BI__builtin_arm_ssat:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2480   case ARM::BI__builtin_arm_usat:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2482   case ARM::BI__builtin_arm_ssat16:
2483     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2484   case ARM::BI__builtin_arm_usat16:
2485     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2486   case ARM::BI__builtin_arm_vcvtr_f:
2487   case ARM::BI__builtin_arm_vcvtr_d:
2488     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2489   case ARM::BI__builtin_arm_dmb:
2490   case ARM::BI__builtin_arm_dsb:
2491   case ARM::BI__builtin_arm_isb:
2492   case ARM::BI__builtin_arm_dbg:
2493     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2494   case ARM::BI__builtin_arm_cdp:
2495   case ARM::BI__builtin_arm_cdp2:
2496   case ARM::BI__builtin_arm_mcr:
2497   case ARM::BI__builtin_arm_mcr2:
2498   case ARM::BI__builtin_arm_mrc:
2499   case ARM::BI__builtin_arm_mrc2:
2500   case ARM::BI__builtin_arm_mcrr:
2501   case ARM::BI__builtin_arm_mcrr2:
2502   case ARM::BI__builtin_arm_mrrc:
2503   case ARM::BI__builtin_arm_mrrc2:
2504   case ARM::BI__builtin_arm_ldc:
2505   case ARM::BI__builtin_arm_ldcl:
2506   case ARM::BI__builtin_arm_ldc2:
2507   case ARM::BI__builtin_arm_ldc2l:
2508   case ARM::BI__builtin_arm_stc:
2509   case ARM::BI__builtin_arm_stcl:
2510   case ARM::BI__builtin_arm_stc2:
2511   case ARM::BI__builtin_arm_stc2l:
2512     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2513            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2514                                         /*WantCDE*/ false);
2515   }
2516 }
2517 
2518 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2519                                            unsigned BuiltinID,
2520                                            CallExpr *TheCall) {
2521   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2522       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2523       BuiltinID == AArch64::BI__builtin_arm_strex ||
2524       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2525     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2526   }
2527 
2528   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2529     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2530       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2531       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2532       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2533   }
2534 
2535   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2536       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2537     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2538 
2539   // Memory Tagging Extensions (MTE) Intrinsics
2540   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2541       BuiltinID == AArch64::BI__builtin_arm_addg ||
2542       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2543       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2544       BuiltinID == AArch64::BI__builtin_arm_stg ||
2545       BuiltinID == AArch64::BI__builtin_arm_subp) {
2546     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2550       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2551       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2552       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2553     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2554 
2555   // Only check the valid encoding range. Any constant in this range would be
2556   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2557   // an exception for incorrect registers. This matches MSVC behavior.
2558   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2559       BuiltinID == AArch64::BI_WriteStatusReg)
2560     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2561 
2562   if (BuiltinID == AArch64::BI__getReg)
2563     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2564 
2565   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2566     return true;
2567 
2568   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2569     return true;
2570 
2571   // For intrinsics which take an immediate value as part of the instruction,
2572   // range check them here.
2573   unsigned i = 0, l = 0, u = 0;
2574   switch (BuiltinID) {
2575   default: return false;
2576   case AArch64::BI__builtin_arm_dmb:
2577   case AArch64::BI__builtin_arm_dsb:
2578   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2579   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2580   }
2581 
2582   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2583 }
2584 
2585 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2586   if (Arg->getType()->getAsPlaceholderType())
2587     return false;
2588 
2589   // The first argument needs to be a record field access.
2590   // If it is an array element access, we delay decision
2591   // to BPF backend to check whether the access is a
2592   // field access or not.
2593   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2594           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2595           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2596 }
2597 
2598 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2599                             QualType VectorTy, QualType EltTy) {
2600   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2601   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2602     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2603         << Call->getSourceRange() << VectorEltTy << EltTy;
2604     return false;
2605   }
2606   return true;
2607 }
2608 
2609 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2610   QualType ArgType = Arg->getType();
2611   if (ArgType->getAsPlaceholderType())
2612     return false;
2613 
2614   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2615   // format:
2616   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2617   //   2. <type> var;
2618   //      __builtin_preserve_type_info(var, flag);
2619   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2620       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2621     return false;
2622 
2623   // Typedef type.
2624   if (ArgType->getAs<TypedefType>())
2625     return true;
2626 
2627   // Record type or Enum type.
2628   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2629   if (const auto *RT = Ty->getAs<RecordType>()) {
2630     if (!RT->getDecl()->getDeclName().isEmpty())
2631       return true;
2632   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2633     if (!ET->getDecl()->getDeclName().isEmpty())
2634       return true;
2635   }
2636 
2637   return false;
2638 }
2639 
2640 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2641   QualType ArgType = Arg->getType();
2642   if (ArgType->getAsPlaceholderType())
2643     return false;
2644 
2645   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2646   // format:
2647   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2648   //                                 flag);
2649   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2650   if (!UO)
2651     return false;
2652 
2653   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2654   if (!CE)
2655     return false;
2656   if (CE->getCastKind() != CK_IntegralToPointer &&
2657       CE->getCastKind() != CK_NullToPointer)
2658     return false;
2659 
2660   // The integer must be from an EnumConstantDecl.
2661   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2662   if (!DR)
2663     return false;
2664 
2665   const EnumConstantDecl *Enumerator =
2666       dyn_cast<EnumConstantDecl>(DR->getDecl());
2667   if (!Enumerator)
2668     return false;
2669 
2670   // The type must be EnumType.
2671   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2672   const auto *ET = Ty->getAs<EnumType>();
2673   if (!ET)
2674     return false;
2675 
2676   // The enum value must be supported.
2677   for (auto *EDI : ET->getDecl()->enumerators()) {
2678     if (EDI == Enumerator)
2679       return true;
2680   }
2681 
2682   return false;
2683 }
2684 
2685 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2686                                        CallExpr *TheCall) {
2687   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2688           BuiltinID == BPF::BI__builtin_btf_type_id ||
2689           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2690           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2691          "unexpected BPF builtin");
2692 
2693   if (checkArgCount(*this, TheCall, 2))
2694     return true;
2695 
2696   // The second argument needs to be a constant int
2697   Expr *Arg = TheCall->getArg(1);
2698   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2699   diag::kind kind;
2700   if (!Value) {
2701     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2702       kind = diag::err_preserve_field_info_not_const;
2703     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2704       kind = diag::err_btf_type_id_not_const;
2705     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2706       kind = diag::err_preserve_type_info_not_const;
2707     else
2708       kind = diag::err_preserve_enum_value_not_const;
2709     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2710     return true;
2711   }
2712 
2713   // The first argument
2714   Arg = TheCall->getArg(0);
2715   bool InvalidArg = false;
2716   bool ReturnUnsignedInt = true;
2717   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2718     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2719       InvalidArg = true;
2720       kind = diag::err_preserve_field_info_not_field;
2721     }
2722   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2723     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2724       InvalidArg = true;
2725       kind = diag::err_preserve_type_info_invalid;
2726     }
2727   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2728     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2729       InvalidArg = true;
2730       kind = diag::err_preserve_enum_value_invalid;
2731     }
2732     ReturnUnsignedInt = false;
2733   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2734     ReturnUnsignedInt = false;
2735   }
2736 
2737   if (InvalidArg) {
2738     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2739     return true;
2740   }
2741 
2742   if (ReturnUnsignedInt)
2743     TheCall->setType(Context.UnsignedIntTy);
2744   else
2745     TheCall->setType(Context.UnsignedLongTy);
2746   return false;
2747 }
2748 
2749 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2750   struct ArgInfo {
2751     uint8_t OpNum;
2752     bool IsSigned;
2753     uint8_t BitWidth;
2754     uint8_t Align;
2755   };
2756   struct BuiltinInfo {
2757     unsigned BuiltinID;
2758     ArgInfo Infos[2];
2759   };
2760 
2761   static BuiltinInfo Infos[] = {
2762     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2763     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2764     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2765     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2766     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2767     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2768     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2769     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2770     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2771     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2772     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2773 
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2777     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2779     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2785 
2786     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2838                                                       {{ 1, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2846                                                       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2853                                                        { 2, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2855                                                        { 2, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2857                                                        { 3, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2859                                                        { 3, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2876                                                       {{ 2, false, 4,  0 },
2877                                                        { 3, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2879                                                       {{ 2, false, 4,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2882                                                       {{ 2, false, 4,  0 },
2883                                                        { 3, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2885                                                       {{ 2, false, 4,  0 },
2886                                                        { 3, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2898                                                        { 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2900                                                        { 2, false, 6,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2910                                                       {{ 1, false, 4,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2913                                                       {{ 1, false, 4,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2934                                                       {{ 3, false, 1,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2939                                                       {{ 3, false, 1,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2944                                                       {{ 3, false, 1,  0 }} },
2945   };
2946 
2947   // Use a dynamically initialized static to sort the table exactly once on
2948   // first run.
2949   static const bool SortOnce =
2950       (llvm::sort(Infos,
2951                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2952                    return LHS.BuiltinID < RHS.BuiltinID;
2953                  }),
2954        true);
2955   (void)SortOnce;
2956 
2957   const BuiltinInfo *F = llvm::partition_point(
2958       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2959   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2960     return false;
2961 
2962   bool Error = false;
2963 
2964   for (const ArgInfo &A : F->Infos) {
2965     // Ignore empty ArgInfo elements.
2966     if (A.BitWidth == 0)
2967       continue;
2968 
2969     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2970     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2971     if (!A.Align) {
2972       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2973     } else {
2974       unsigned M = 1 << A.Align;
2975       Min *= M;
2976       Max *= M;
2977       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2978                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2979     }
2980   }
2981   return Error;
2982 }
2983 
2984 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2985                                            CallExpr *TheCall) {
2986   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2987 }
2988 
2989 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2990                                         unsigned BuiltinID, CallExpr *TheCall) {
2991   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2992          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2993 }
2994 
2995 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2996                                CallExpr *TheCall) {
2997 
2998   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2999       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3000     if (!TI.hasFeature("dsp"))
3001       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3002   }
3003 
3004   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3005       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3006     if (!TI.hasFeature("dspr2"))
3007       return Diag(TheCall->getBeginLoc(),
3008                   diag::err_mips_builtin_requires_dspr2);
3009   }
3010 
3011   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3012       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3013     if (!TI.hasFeature("msa"))
3014       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3015   }
3016 
3017   return false;
3018 }
3019 
3020 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3021 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3022 // ordering for DSP is unspecified. MSA is ordered by the data format used
3023 // by the underlying instruction i.e., df/m, df/n and then by size.
3024 //
3025 // FIXME: The size tests here should instead be tablegen'd along with the
3026 //        definitions from include/clang/Basic/BuiltinsMips.def.
3027 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3028 //        be too.
3029 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3030   unsigned i = 0, l = 0, u = 0, m = 0;
3031   switch (BuiltinID) {
3032   default: return false;
3033   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3034   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3035   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3036   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3037   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3038   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3039   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3040   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3041   // df/m field.
3042   // These intrinsics take an unsigned 3 bit immediate.
3043   case Mips::BI__builtin_msa_bclri_b:
3044   case Mips::BI__builtin_msa_bnegi_b:
3045   case Mips::BI__builtin_msa_bseti_b:
3046   case Mips::BI__builtin_msa_sat_s_b:
3047   case Mips::BI__builtin_msa_sat_u_b:
3048   case Mips::BI__builtin_msa_slli_b:
3049   case Mips::BI__builtin_msa_srai_b:
3050   case Mips::BI__builtin_msa_srari_b:
3051   case Mips::BI__builtin_msa_srli_b:
3052   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3053   case Mips::BI__builtin_msa_binsli_b:
3054   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3055   // These intrinsics take an unsigned 4 bit immediate.
3056   case Mips::BI__builtin_msa_bclri_h:
3057   case Mips::BI__builtin_msa_bnegi_h:
3058   case Mips::BI__builtin_msa_bseti_h:
3059   case Mips::BI__builtin_msa_sat_s_h:
3060   case Mips::BI__builtin_msa_sat_u_h:
3061   case Mips::BI__builtin_msa_slli_h:
3062   case Mips::BI__builtin_msa_srai_h:
3063   case Mips::BI__builtin_msa_srari_h:
3064   case Mips::BI__builtin_msa_srli_h:
3065   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3066   case Mips::BI__builtin_msa_binsli_h:
3067   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3068   // These intrinsics take an unsigned 5 bit immediate.
3069   // The first block of intrinsics actually have an unsigned 5 bit field,
3070   // not a df/n field.
3071   case Mips::BI__builtin_msa_cfcmsa:
3072   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3073   case Mips::BI__builtin_msa_clei_u_b:
3074   case Mips::BI__builtin_msa_clei_u_h:
3075   case Mips::BI__builtin_msa_clei_u_w:
3076   case Mips::BI__builtin_msa_clei_u_d:
3077   case Mips::BI__builtin_msa_clti_u_b:
3078   case Mips::BI__builtin_msa_clti_u_h:
3079   case Mips::BI__builtin_msa_clti_u_w:
3080   case Mips::BI__builtin_msa_clti_u_d:
3081   case Mips::BI__builtin_msa_maxi_u_b:
3082   case Mips::BI__builtin_msa_maxi_u_h:
3083   case Mips::BI__builtin_msa_maxi_u_w:
3084   case Mips::BI__builtin_msa_maxi_u_d:
3085   case Mips::BI__builtin_msa_mini_u_b:
3086   case Mips::BI__builtin_msa_mini_u_h:
3087   case Mips::BI__builtin_msa_mini_u_w:
3088   case Mips::BI__builtin_msa_mini_u_d:
3089   case Mips::BI__builtin_msa_addvi_b:
3090   case Mips::BI__builtin_msa_addvi_h:
3091   case Mips::BI__builtin_msa_addvi_w:
3092   case Mips::BI__builtin_msa_addvi_d:
3093   case Mips::BI__builtin_msa_bclri_w:
3094   case Mips::BI__builtin_msa_bnegi_w:
3095   case Mips::BI__builtin_msa_bseti_w:
3096   case Mips::BI__builtin_msa_sat_s_w:
3097   case Mips::BI__builtin_msa_sat_u_w:
3098   case Mips::BI__builtin_msa_slli_w:
3099   case Mips::BI__builtin_msa_srai_w:
3100   case Mips::BI__builtin_msa_srari_w:
3101   case Mips::BI__builtin_msa_srli_w:
3102   case Mips::BI__builtin_msa_srlri_w:
3103   case Mips::BI__builtin_msa_subvi_b:
3104   case Mips::BI__builtin_msa_subvi_h:
3105   case Mips::BI__builtin_msa_subvi_w:
3106   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3107   case Mips::BI__builtin_msa_binsli_w:
3108   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3109   // These intrinsics take an unsigned 6 bit immediate.
3110   case Mips::BI__builtin_msa_bclri_d:
3111   case Mips::BI__builtin_msa_bnegi_d:
3112   case Mips::BI__builtin_msa_bseti_d:
3113   case Mips::BI__builtin_msa_sat_s_d:
3114   case Mips::BI__builtin_msa_sat_u_d:
3115   case Mips::BI__builtin_msa_slli_d:
3116   case Mips::BI__builtin_msa_srai_d:
3117   case Mips::BI__builtin_msa_srari_d:
3118   case Mips::BI__builtin_msa_srli_d:
3119   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3120   case Mips::BI__builtin_msa_binsli_d:
3121   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3122   // These intrinsics take a signed 5 bit immediate.
3123   case Mips::BI__builtin_msa_ceqi_b:
3124   case Mips::BI__builtin_msa_ceqi_h:
3125   case Mips::BI__builtin_msa_ceqi_w:
3126   case Mips::BI__builtin_msa_ceqi_d:
3127   case Mips::BI__builtin_msa_clti_s_b:
3128   case Mips::BI__builtin_msa_clti_s_h:
3129   case Mips::BI__builtin_msa_clti_s_w:
3130   case Mips::BI__builtin_msa_clti_s_d:
3131   case Mips::BI__builtin_msa_clei_s_b:
3132   case Mips::BI__builtin_msa_clei_s_h:
3133   case Mips::BI__builtin_msa_clei_s_w:
3134   case Mips::BI__builtin_msa_clei_s_d:
3135   case Mips::BI__builtin_msa_maxi_s_b:
3136   case Mips::BI__builtin_msa_maxi_s_h:
3137   case Mips::BI__builtin_msa_maxi_s_w:
3138   case Mips::BI__builtin_msa_maxi_s_d:
3139   case Mips::BI__builtin_msa_mini_s_b:
3140   case Mips::BI__builtin_msa_mini_s_h:
3141   case Mips::BI__builtin_msa_mini_s_w:
3142   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3143   // These intrinsics take an unsigned 8 bit immediate.
3144   case Mips::BI__builtin_msa_andi_b:
3145   case Mips::BI__builtin_msa_nori_b:
3146   case Mips::BI__builtin_msa_ori_b:
3147   case Mips::BI__builtin_msa_shf_b:
3148   case Mips::BI__builtin_msa_shf_h:
3149   case Mips::BI__builtin_msa_shf_w:
3150   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3151   case Mips::BI__builtin_msa_bseli_b:
3152   case Mips::BI__builtin_msa_bmnzi_b:
3153   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3154   // df/n format
3155   // These intrinsics take an unsigned 4 bit immediate.
3156   case Mips::BI__builtin_msa_copy_s_b:
3157   case Mips::BI__builtin_msa_copy_u_b:
3158   case Mips::BI__builtin_msa_insve_b:
3159   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3160   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3161   // These intrinsics take an unsigned 3 bit immediate.
3162   case Mips::BI__builtin_msa_copy_s_h:
3163   case Mips::BI__builtin_msa_copy_u_h:
3164   case Mips::BI__builtin_msa_insve_h:
3165   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3166   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3167   // These intrinsics take an unsigned 2 bit immediate.
3168   case Mips::BI__builtin_msa_copy_s_w:
3169   case Mips::BI__builtin_msa_copy_u_w:
3170   case Mips::BI__builtin_msa_insve_w:
3171   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3172   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3173   // These intrinsics take an unsigned 1 bit immediate.
3174   case Mips::BI__builtin_msa_copy_s_d:
3175   case Mips::BI__builtin_msa_copy_u_d:
3176   case Mips::BI__builtin_msa_insve_d:
3177   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3178   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3179   // Memory offsets and immediate loads.
3180   // These intrinsics take a signed 10 bit immediate.
3181   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3182   case Mips::BI__builtin_msa_ldi_h:
3183   case Mips::BI__builtin_msa_ldi_w:
3184   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3185   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3186   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3187   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3188   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3189   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3190   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3191   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3192   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3193   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3194   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3195   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3196   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3197   }
3198 
3199   if (!m)
3200     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3201 
3202   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3203          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3204 }
3205 
3206 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3207 /// advancing the pointer over the consumed characters. The decoded type is
3208 /// returned. If the decoded type represents a constant integer with a
3209 /// constraint on its value then Mask is set to that value. The type descriptors
3210 /// used in Str are specific to PPC MMA builtins and are documented in the file
3211 /// defining the PPC builtins.
3212 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3213                                         unsigned &Mask) {
3214   bool RequireICE = false;
3215   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3216   switch (*Str++) {
3217   case 'V':
3218     return Context.getVectorType(Context.UnsignedCharTy, 16,
3219                                  VectorType::VectorKind::AltiVecVector);
3220   case 'i': {
3221     char *End;
3222     unsigned size = strtoul(Str, &End, 10);
3223     assert(End != Str && "Missing constant parameter constraint");
3224     Str = End;
3225     Mask = size;
3226     return Context.IntTy;
3227   }
3228   case 'W': {
3229     char *End;
3230     unsigned size = strtoul(Str, &End, 10);
3231     assert(End != Str && "Missing PowerPC MMA type size");
3232     Str = End;
3233     QualType Type;
3234     switch (size) {
3235   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3236     case size: Type = Context.Id##Ty; break;
3237   #include "clang/Basic/PPCTypes.def"
3238     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3239     }
3240     bool CheckVectorArgs = false;
3241     while (!CheckVectorArgs) {
3242       switch (*Str++) {
3243       case '*':
3244         Type = Context.getPointerType(Type);
3245         break;
3246       case 'C':
3247         Type = Type.withConst();
3248         break;
3249       default:
3250         CheckVectorArgs = true;
3251         --Str;
3252         break;
3253       }
3254     }
3255     return Type;
3256   }
3257   default:
3258     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3259   }
3260 }
3261 
3262 static bool isPPC_64Builtin(unsigned BuiltinID) {
3263   // These builtins only work on PPC 64bit targets.
3264   switch (BuiltinID) {
3265   case PPC::BI__builtin_divde:
3266   case PPC::BI__builtin_divdeu:
3267   case PPC::BI__builtin_bpermd:
3268   case PPC::BI__builtin_ppc_ldarx:
3269   case PPC::BI__builtin_ppc_stdcx:
3270   case PPC::BI__builtin_ppc_tdw:
3271   case PPC::BI__builtin_ppc_trapd:
3272   case PPC::BI__builtin_ppc_cmpeqb:
3273   case PPC::BI__builtin_ppc_setb:
3274   case PPC::BI__builtin_ppc_mulhd:
3275   case PPC::BI__builtin_ppc_mulhdu:
3276   case PPC::BI__builtin_ppc_maddhd:
3277   case PPC::BI__builtin_ppc_maddhdu:
3278   case PPC::BI__builtin_ppc_maddld:
3279     return true;
3280   }
3281   return false;
3282 }
3283 
3284 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3285                              StringRef FeatureToCheck, unsigned DiagID,
3286                              StringRef DiagArg = "") {
3287   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3288     return false;
3289 
3290   if (DiagArg.empty())
3291     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3292   else
3293     S.Diag(TheCall->getBeginLoc(), DiagID)
3294         << DiagArg << TheCall->getSourceRange();
3295 
3296   return true;
3297 }
3298 
3299 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3300                                        CallExpr *TheCall) {
3301   unsigned i = 0, l = 0, u = 0;
3302   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3303 
3304   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3305     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3306            << TheCall->getSourceRange();
3307 
3308   switch (BuiltinID) {
3309   default: return false;
3310   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3311   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3312     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3313            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3314   case PPC::BI__builtin_altivec_dss:
3315     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3316   case PPC::BI__builtin_tbegin:
3317   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3318   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3319   case PPC::BI__builtin_tabortwc:
3320   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3321   case PPC::BI__builtin_tabortwci:
3322   case PPC::BI__builtin_tabortdci:
3323     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3324            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3325   case PPC::BI__builtin_altivec_dst:
3326   case PPC::BI__builtin_altivec_dstt:
3327   case PPC::BI__builtin_altivec_dstst:
3328   case PPC::BI__builtin_altivec_dststt:
3329     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3330   case PPC::BI__builtin_vsx_xxpermdi:
3331   case PPC::BI__builtin_vsx_xxsldwi:
3332     return SemaBuiltinVSX(TheCall);
3333   case PPC::BI__builtin_divwe:
3334   case PPC::BI__builtin_divweu:
3335   case PPC::BI__builtin_divde:
3336   case PPC::BI__builtin_divdeu:
3337     return SemaFeatureCheck(*this, TheCall, "extdiv",
3338                             diag::err_ppc_builtin_only_on_arch, "7");
3339   case PPC::BI__builtin_bpermd:
3340     return SemaFeatureCheck(*this, TheCall, "bpermd",
3341                             diag::err_ppc_builtin_only_on_arch, "7");
3342   case PPC::BI__builtin_unpack_vector_int128:
3343     return SemaFeatureCheck(*this, TheCall, "vsx",
3344                             diag::err_ppc_builtin_only_on_arch, "7") ||
3345            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3346   case PPC::BI__builtin_pack_vector_int128:
3347     return SemaFeatureCheck(*this, TheCall, "vsx",
3348                             diag::err_ppc_builtin_only_on_arch, "7");
3349   case PPC::BI__builtin_altivec_vgnb:
3350      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3351   case PPC::BI__builtin_altivec_vec_replace_elt:
3352   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3353     QualType VecTy = TheCall->getArg(0)->getType();
3354     QualType EltTy = TheCall->getArg(1)->getType();
3355     unsigned Width = Context.getIntWidth(EltTy);
3356     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3357            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3358   }
3359   case PPC::BI__builtin_vsx_xxeval:
3360      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3361   case PPC::BI__builtin_altivec_vsldbi:
3362      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3363   case PPC::BI__builtin_altivec_vsrdbi:
3364      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3365   case PPC::BI__builtin_vsx_xxpermx:
3366      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3367   case PPC::BI__builtin_ppc_tw:
3368   case PPC::BI__builtin_ppc_tdw:
3369     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3370   case PPC::BI__builtin_ppc_cmpeqb:
3371   case PPC::BI__builtin_ppc_setb:
3372   case PPC::BI__builtin_ppc_maddhd:
3373   case PPC::BI__builtin_ppc_maddhdu:
3374   case PPC::BI__builtin_ppc_maddld:
3375     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3376                             diag::err_ppc_builtin_only_on_arch, "9");
3377   case PPC::BI__builtin_ppc_cmprb:
3378     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3379                             diag::err_ppc_builtin_only_on_arch, "9") ||
3380            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3381 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3382   case PPC::BI__builtin_##Name: \
3383     return SemaBuiltinPPCMMACall(TheCall, Types);
3384 #include "clang/Basic/BuiltinsPPC.def"
3385   }
3386   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3387 }
3388 
3389 // Check if the given type is a non-pointer PPC MMA type. This function is used
3390 // in Sema to prevent invalid uses of restricted PPC MMA types.
3391 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3392   if (Type->isPointerType() || Type->isArrayType())
3393     return false;
3394 
3395   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3396 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3397   if (false
3398 #include "clang/Basic/PPCTypes.def"
3399      ) {
3400     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3401     return true;
3402   }
3403   return false;
3404 }
3405 
3406 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3407                                           CallExpr *TheCall) {
3408   // position of memory order and scope arguments in the builtin
3409   unsigned OrderIndex, ScopeIndex;
3410   switch (BuiltinID) {
3411   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3412   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3413   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3414   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3415     OrderIndex = 2;
3416     ScopeIndex = 3;
3417     break;
3418   case AMDGPU::BI__builtin_amdgcn_fence:
3419     OrderIndex = 0;
3420     ScopeIndex = 1;
3421     break;
3422   default:
3423     return false;
3424   }
3425 
3426   ExprResult Arg = TheCall->getArg(OrderIndex);
3427   auto ArgExpr = Arg.get();
3428   Expr::EvalResult ArgResult;
3429 
3430   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3431     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3432            << ArgExpr->getType();
3433   auto Ord = ArgResult.Val.getInt().getZExtValue();
3434 
3435   // Check valididty of memory ordering as per C11 / C++11's memody model.
3436   // Only fence needs check. Atomic dec/inc allow all memory orders.
3437   if (!llvm::isValidAtomicOrderingCABI(Ord))
3438     return Diag(ArgExpr->getBeginLoc(),
3439                 diag::warn_atomic_op_has_invalid_memory_order)
3440            << ArgExpr->getSourceRange();
3441   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3442   case llvm::AtomicOrderingCABI::relaxed:
3443   case llvm::AtomicOrderingCABI::consume:
3444     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3445       return Diag(ArgExpr->getBeginLoc(),
3446                   diag::warn_atomic_op_has_invalid_memory_order)
3447              << ArgExpr->getSourceRange();
3448     break;
3449   case llvm::AtomicOrderingCABI::acquire:
3450   case llvm::AtomicOrderingCABI::release:
3451   case llvm::AtomicOrderingCABI::acq_rel:
3452   case llvm::AtomicOrderingCABI::seq_cst:
3453     break;
3454   }
3455 
3456   Arg = TheCall->getArg(ScopeIndex);
3457   ArgExpr = Arg.get();
3458   Expr::EvalResult ArgResult1;
3459   // Check that sync scope is a constant literal
3460   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3461     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3462            << ArgExpr->getType();
3463 
3464   return false;
3465 }
3466 
3467 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3468   llvm::APSInt Result;
3469 
3470   // We can't check the value of a dependent argument.
3471   Expr *Arg = TheCall->getArg(ArgNum);
3472   if (Arg->isTypeDependent() || Arg->isValueDependent())
3473     return false;
3474 
3475   // Check constant-ness first.
3476   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3477     return true;
3478 
3479   int64_t Val = Result.getSExtValue();
3480   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3481     return false;
3482 
3483   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3484          << Arg->getSourceRange();
3485 }
3486 
3487 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3488                                          unsigned BuiltinID,
3489                                          CallExpr *TheCall) {
3490   // CodeGenFunction can also detect this, but this gives a better error
3491   // message.
3492   bool FeatureMissing = false;
3493   SmallVector<StringRef> ReqFeatures;
3494   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3495   Features.split(ReqFeatures, ',');
3496 
3497   // Check if each required feature is included
3498   for (StringRef F : ReqFeatures) {
3499     if (TI.hasFeature(F))
3500       continue;
3501 
3502     // If the feature is 64bit, alter the string so it will print better in
3503     // the diagnostic.
3504     if (F == "64bit")
3505       F = "RV64";
3506 
3507     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3508     F.consume_front("experimental-");
3509     std::string FeatureStr = F.str();
3510     FeatureStr[0] = std::toupper(FeatureStr[0]);
3511 
3512     // Error message
3513     FeatureMissing = true;
3514     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3515         << TheCall->getSourceRange() << StringRef(FeatureStr);
3516   }
3517 
3518   if (FeatureMissing)
3519     return true;
3520 
3521   switch (BuiltinID) {
3522   case RISCV::BI__builtin_rvv_vsetvli:
3523     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3524            CheckRISCVLMUL(TheCall, 2);
3525   case RISCV::BI__builtin_rvv_vsetvlimax:
3526     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3527            CheckRISCVLMUL(TheCall, 1);
3528   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3529   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3530   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3531   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3532   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3533   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3534   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3535   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3536   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3537   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3538   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3539   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3540   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3541   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3542   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3543   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3544   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3545   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3546   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3547   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3548   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3549   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3550   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3551   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3552   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3553   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3554   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3555   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3556   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3557   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3558     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3559   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3560   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3561   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3562   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3563   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3564   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3565   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3566   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3567   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3568   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3569   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3570   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3571   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3572   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3573   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3574   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3575   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3576   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3577   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3578   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3579     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3580   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3581   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3582   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3583   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3584   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3585   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3586   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3587   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3588   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3589   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3590     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3591   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3592   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3593   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3594   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3595   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3596   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3597   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3598   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3599   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3600   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3601   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3602   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3603   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3604   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3605   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3606   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3607   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3608   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3609   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3610   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3611   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3612   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3613   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3614   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3615   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3616   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3617   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3618   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3619   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3620   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3621     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3622   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3623   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3624   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3625   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3626   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3627   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3628   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3629   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3630   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3631   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3632   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3633   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3634   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3635   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3636   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3637   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3638   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3639   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3640   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3641   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3642     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3643   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3644   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3645   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3646   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3647   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3648   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3649   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3650   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3651   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3652   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3653     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3654   }
3655 
3656   return false;
3657 }
3658 
3659 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3660                                            CallExpr *TheCall) {
3661   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3662     Expr *Arg = TheCall->getArg(0);
3663     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3664       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3665         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3666                << Arg->getSourceRange();
3667   }
3668 
3669   // For intrinsics which take an immediate value as part of the instruction,
3670   // range check them here.
3671   unsigned i = 0, l = 0, u = 0;
3672   switch (BuiltinID) {
3673   default: return false;
3674   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3675   case SystemZ::BI__builtin_s390_verimb:
3676   case SystemZ::BI__builtin_s390_verimh:
3677   case SystemZ::BI__builtin_s390_verimf:
3678   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3679   case SystemZ::BI__builtin_s390_vfaeb:
3680   case SystemZ::BI__builtin_s390_vfaeh:
3681   case SystemZ::BI__builtin_s390_vfaef:
3682   case SystemZ::BI__builtin_s390_vfaebs:
3683   case SystemZ::BI__builtin_s390_vfaehs:
3684   case SystemZ::BI__builtin_s390_vfaefs:
3685   case SystemZ::BI__builtin_s390_vfaezb:
3686   case SystemZ::BI__builtin_s390_vfaezh:
3687   case SystemZ::BI__builtin_s390_vfaezf:
3688   case SystemZ::BI__builtin_s390_vfaezbs:
3689   case SystemZ::BI__builtin_s390_vfaezhs:
3690   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3691   case SystemZ::BI__builtin_s390_vfisb:
3692   case SystemZ::BI__builtin_s390_vfidb:
3693     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3694            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3695   case SystemZ::BI__builtin_s390_vftcisb:
3696   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3697   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3698   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3699   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3700   case SystemZ::BI__builtin_s390_vstrcb:
3701   case SystemZ::BI__builtin_s390_vstrch:
3702   case SystemZ::BI__builtin_s390_vstrcf:
3703   case SystemZ::BI__builtin_s390_vstrczb:
3704   case SystemZ::BI__builtin_s390_vstrczh:
3705   case SystemZ::BI__builtin_s390_vstrczf:
3706   case SystemZ::BI__builtin_s390_vstrcbs:
3707   case SystemZ::BI__builtin_s390_vstrchs:
3708   case SystemZ::BI__builtin_s390_vstrcfs:
3709   case SystemZ::BI__builtin_s390_vstrczbs:
3710   case SystemZ::BI__builtin_s390_vstrczhs:
3711   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3712   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3713   case SystemZ::BI__builtin_s390_vfminsb:
3714   case SystemZ::BI__builtin_s390_vfmaxsb:
3715   case SystemZ::BI__builtin_s390_vfmindb:
3716   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3717   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3718   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3719   }
3720   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3721 }
3722 
3723 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3724 /// This checks that the target supports __builtin_cpu_supports and
3725 /// that the string argument is constant and valid.
3726 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3727                                    CallExpr *TheCall) {
3728   Expr *Arg = TheCall->getArg(0);
3729 
3730   // Check if the argument is a string literal.
3731   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3732     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3733            << Arg->getSourceRange();
3734 
3735   // Check the contents of the string.
3736   StringRef Feature =
3737       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3738   if (!TI.validateCpuSupports(Feature))
3739     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3740            << Arg->getSourceRange();
3741   return false;
3742 }
3743 
3744 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3745 /// This checks that the target supports __builtin_cpu_is and
3746 /// that the string argument is constant and valid.
3747 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3748   Expr *Arg = TheCall->getArg(0);
3749 
3750   // Check if the argument is a string literal.
3751   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3752     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3753            << Arg->getSourceRange();
3754 
3755   // Check the contents of the string.
3756   StringRef Feature =
3757       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3758   if (!TI.validateCpuIs(Feature))
3759     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3760            << Arg->getSourceRange();
3761   return false;
3762 }
3763 
3764 // Check if the rounding mode is legal.
3765 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3766   // Indicates if this instruction has rounding control or just SAE.
3767   bool HasRC = false;
3768 
3769   unsigned ArgNum = 0;
3770   switch (BuiltinID) {
3771   default:
3772     return false;
3773   case X86::BI__builtin_ia32_vcvttsd2si32:
3774   case X86::BI__builtin_ia32_vcvttsd2si64:
3775   case X86::BI__builtin_ia32_vcvttsd2usi32:
3776   case X86::BI__builtin_ia32_vcvttsd2usi64:
3777   case X86::BI__builtin_ia32_vcvttss2si32:
3778   case X86::BI__builtin_ia32_vcvttss2si64:
3779   case X86::BI__builtin_ia32_vcvttss2usi32:
3780   case X86::BI__builtin_ia32_vcvttss2usi64:
3781     ArgNum = 1;
3782     break;
3783   case X86::BI__builtin_ia32_maxpd512:
3784   case X86::BI__builtin_ia32_maxps512:
3785   case X86::BI__builtin_ia32_minpd512:
3786   case X86::BI__builtin_ia32_minps512:
3787     ArgNum = 2;
3788     break;
3789   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3790   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3791   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3792   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3793   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3794   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3795   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3796   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3797   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3798   case X86::BI__builtin_ia32_exp2pd_mask:
3799   case X86::BI__builtin_ia32_exp2ps_mask:
3800   case X86::BI__builtin_ia32_getexppd512_mask:
3801   case X86::BI__builtin_ia32_getexpps512_mask:
3802   case X86::BI__builtin_ia32_rcp28pd_mask:
3803   case X86::BI__builtin_ia32_rcp28ps_mask:
3804   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3805   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3806   case X86::BI__builtin_ia32_vcomisd:
3807   case X86::BI__builtin_ia32_vcomiss:
3808   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3809     ArgNum = 3;
3810     break;
3811   case X86::BI__builtin_ia32_cmppd512_mask:
3812   case X86::BI__builtin_ia32_cmpps512_mask:
3813   case X86::BI__builtin_ia32_cmpsd_mask:
3814   case X86::BI__builtin_ia32_cmpss_mask:
3815   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3816   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3817   case X86::BI__builtin_ia32_getexpss128_round_mask:
3818   case X86::BI__builtin_ia32_getmantpd512_mask:
3819   case X86::BI__builtin_ia32_getmantps512_mask:
3820   case X86::BI__builtin_ia32_maxsd_round_mask:
3821   case X86::BI__builtin_ia32_maxss_round_mask:
3822   case X86::BI__builtin_ia32_minsd_round_mask:
3823   case X86::BI__builtin_ia32_minss_round_mask:
3824   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3825   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3826   case X86::BI__builtin_ia32_reducepd512_mask:
3827   case X86::BI__builtin_ia32_reduceps512_mask:
3828   case X86::BI__builtin_ia32_rndscalepd_mask:
3829   case X86::BI__builtin_ia32_rndscaleps_mask:
3830   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3831   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3832     ArgNum = 4;
3833     break;
3834   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3835   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3836   case X86::BI__builtin_ia32_fixupimmps512_mask:
3837   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3838   case X86::BI__builtin_ia32_fixupimmsd_mask:
3839   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3840   case X86::BI__builtin_ia32_fixupimmss_mask:
3841   case X86::BI__builtin_ia32_fixupimmss_maskz:
3842   case X86::BI__builtin_ia32_getmantsd_round_mask:
3843   case X86::BI__builtin_ia32_getmantss_round_mask:
3844   case X86::BI__builtin_ia32_rangepd512_mask:
3845   case X86::BI__builtin_ia32_rangeps512_mask:
3846   case X86::BI__builtin_ia32_rangesd128_round_mask:
3847   case X86::BI__builtin_ia32_rangess128_round_mask:
3848   case X86::BI__builtin_ia32_reducesd_mask:
3849   case X86::BI__builtin_ia32_reducess_mask:
3850   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3851   case X86::BI__builtin_ia32_rndscaless_round_mask:
3852     ArgNum = 5;
3853     break;
3854   case X86::BI__builtin_ia32_vcvtsd2si64:
3855   case X86::BI__builtin_ia32_vcvtsd2si32:
3856   case X86::BI__builtin_ia32_vcvtsd2usi32:
3857   case X86::BI__builtin_ia32_vcvtsd2usi64:
3858   case X86::BI__builtin_ia32_vcvtss2si32:
3859   case X86::BI__builtin_ia32_vcvtss2si64:
3860   case X86::BI__builtin_ia32_vcvtss2usi32:
3861   case X86::BI__builtin_ia32_vcvtss2usi64:
3862   case X86::BI__builtin_ia32_sqrtpd512:
3863   case X86::BI__builtin_ia32_sqrtps512:
3864     ArgNum = 1;
3865     HasRC = true;
3866     break;
3867   case X86::BI__builtin_ia32_addpd512:
3868   case X86::BI__builtin_ia32_addps512:
3869   case X86::BI__builtin_ia32_divpd512:
3870   case X86::BI__builtin_ia32_divps512:
3871   case X86::BI__builtin_ia32_mulpd512:
3872   case X86::BI__builtin_ia32_mulps512:
3873   case X86::BI__builtin_ia32_subpd512:
3874   case X86::BI__builtin_ia32_subps512:
3875   case X86::BI__builtin_ia32_cvtsi2sd64:
3876   case X86::BI__builtin_ia32_cvtsi2ss32:
3877   case X86::BI__builtin_ia32_cvtsi2ss64:
3878   case X86::BI__builtin_ia32_cvtusi2sd64:
3879   case X86::BI__builtin_ia32_cvtusi2ss32:
3880   case X86::BI__builtin_ia32_cvtusi2ss64:
3881     ArgNum = 2;
3882     HasRC = true;
3883     break;
3884   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3885   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3886   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3887   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3888   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3889   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3890   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3891   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3892   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3893   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3894   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3895   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3896   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3897   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3898   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3899     ArgNum = 3;
3900     HasRC = true;
3901     break;
3902   case X86::BI__builtin_ia32_addss_round_mask:
3903   case X86::BI__builtin_ia32_addsd_round_mask:
3904   case X86::BI__builtin_ia32_divss_round_mask:
3905   case X86::BI__builtin_ia32_divsd_round_mask:
3906   case X86::BI__builtin_ia32_mulss_round_mask:
3907   case X86::BI__builtin_ia32_mulsd_round_mask:
3908   case X86::BI__builtin_ia32_subss_round_mask:
3909   case X86::BI__builtin_ia32_subsd_round_mask:
3910   case X86::BI__builtin_ia32_scalefpd512_mask:
3911   case X86::BI__builtin_ia32_scalefps512_mask:
3912   case X86::BI__builtin_ia32_scalefsd_round_mask:
3913   case X86::BI__builtin_ia32_scalefss_round_mask:
3914   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3915   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3916   case X86::BI__builtin_ia32_sqrtss_round_mask:
3917   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3918   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3919   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3920   case X86::BI__builtin_ia32_vfmaddss3_mask:
3921   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3922   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3923   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3924   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3925   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3926   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3927   case X86::BI__builtin_ia32_vfmaddps512_mask:
3928   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3929   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3930   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3931   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3932   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3933   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3934   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3935   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3936   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3937   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3938   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3939     ArgNum = 4;
3940     HasRC = true;
3941     break;
3942   }
3943 
3944   llvm::APSInt Result;
3945 
3946   // We can't check the value of a dependent argument.
3947   Expr *Arg = TheCall->getArg(ArgNum);
3948   if (Arg->isTypeDependent() || Arg->isValueDependent())
3949     return false;
3950 
3951   // Check constant-ness first.
3952   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3953     return true;
3954 
3955   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3956   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3957   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3958   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3959   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3960       Result == 8/*ROUND_NO_EXC*/ ||
3961       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3962       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3963     return false;
3964 
3965   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3966          << Arg->getSourceRange();
3967 }
3968 
3969 // Check if the gather/scatter scale is legal.
3970 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3971                                              CallExpr *TheCall) {
3972   unsigned ArgNum = 0;
3973   switch (BuiltinID) {
3974   default:
3975     return false;
3976   case X86::BI__builtin_ia32_gatherpfdpd:
3977   case X86::BI__builtin_ia32_gatherpfdps:
3978   case X86::BI__builtin_ia32_gatherpfqpd:
3979   case X86::BI__builtin_ia32_gatherpfqps:
3980   case X86::BI__builtin_ia32_scatterpfdpd:
3981   case X86::BI__builtin_ia32_scatterpfdps:
3982   case X86::BI__builtin_ia32_scatterpfqpd:
3983   case X86::BI__builtin_ia32_scatterpfqps:
3984     ArgNum = 3;
3985     break;
3986   case X86::BI__builtin_ia32_gatherd_pd:
3987   case X86::BI__builtin_ia32_gatherd_pd256:
3988   case X86::BI__builtin_ia32_gatherq_pd:
3989   case X86::BI__builtin_ia32_gatherq_pd256:
3990   case X86::BI__builtin_ia32_gatherd_ps:
3991   case X86::BI__builtin_ia32_gatherd_ps256:
3992   case X86::BI__builtin_ia32_gatherq_ps:
3993   case X86::BI__builtin_ia32_gatherq_ps256:
3994   case X86::BI__builtin_ia32_gatherd_q:
3995   case X86::BI__builtin_ia32_gatherd_q256:
3996   case X86::BI__builtin_ia32_gatherq_q:
3997   case X86::BI__builtin_ia32_gatherq_q256:
3998   case X86::BI__builtin_ia32_gatherd_d:
3999   case X86::BI__builtin_ia32_gatherd_d256:
4000   case X86::BI__builtin_ia32_gatherq_d:
4001   case X86::BI__builtin_ia32_gatherq_d256:
4002   case X86::BI__builtin_ia32_gather3div2df:
4003   case X86::BI__builtin_ia32_gather3div2di:
4004   case X86::BI__builtin_ia32_gather3div4df:
4005   case X86::BI__builtin_ia32_gather3div4di:
4006   case X86::BI__builtin_ia32_gather3div4sf:
4007   case X86::BI__builtin_ia32_gather3div4si:
4008   case X86::BI__builtin_ia32_gather3div8sf:
4009   case X86::BI__builtin_ia32_gather3div8si:
4010   case X86::BI__builtin_ia32_gather3siv2df:
4011   case X86::BI__builtin_ia32_gather3siv2di:
4012   case X86::BI__builtin_ia32_gather3siv4df:
4013   case X86::BI__builtin_ia32_gather3siv4di:
4014   case X86::BI__builtin_ia32_gather3siv4sf:
4015   case X86::BI__builtin_ia32_gather3siv4si:
4016   case X86::BI__builtin_ia32_gather3siv8sf:
4017   case X86::BI__builtin_ia32_gather3siv8si:
4018   case X86::BI__builtin_ia32_gathersiv8df:
4019   case X86::BI__builtin_ia32_gathersiv16sf:
4020   case X86::BI__builtin_ia32_gatherdiv8df:
4021   case X86::BI__builtin_ia32_gatherdiv16sf:
4022   case X86::BI__builtin_ia32_gathersiv8di:
4023   case X86::BI__builtin_ia32_gathersiv16si:
4024   case X86::BI__builtin_ia32_gatherdiv8di:
4025   case X86::BI__builtin_ia32_gatherdiv16si:
4026   case X86::BI__builtin_ia32_scatterdiv2df:
4027   case X86::BI__builtin_ia32_scatterdiv2di:
4028   case X86::BI__builtin_ia32_scatterdiv4df:
4029   case X86::BI__builtin_ia32_scatterdiv4di:
4030   case X86::BI__builtin_ia32_scatterdiv4sf:
4031   case X86::BI__builtin_ia32_scatterdiv4si:
4032   case X86::BI__builtin_ia32_scatterdiv8sf:
4033   case X86::BI__builtin_ia32_scatterdiv8si:
4034   case X86::BI__builtin_ia32_scattersiv2df:
4035   case X86::BI__builtin_ia32_scattersiv2di:
4036   case X86::BI__builtin_ia32_scattersiv4df:
4037   case X86::BI__builtin_ia32_scattersiv4di:
4038   case X86::BI__builtin_ia32_scattersiv4sf:
4039   case X86::BI__builtin_ia32_scattersiv4si:
4040   case X86::BI__builtin_ia32_scattersiv8sf:
4041   case X86::BI__builtin_ia32_scattersiv8si:
4042   case X86::BI__builtin_ia32_scattersiv8df:
4043   case X86::BI__builtin_ia32_scattersiv16sf:
4044   case X86::BI__builtin_ia32_scatterdiv8df:
4045   case X86::BI__builtin_ia32_scatterdiv16sf:
4046   case X86::BI__builtin_ia32_scattersiv8di:
4047   case X86::BI__builtin_ia32_scattersiv16si:
4048   case X86::BI__builtin_ia32_scatterdiv8di:
4049   case X86::BI__builtin_ia32_scatterdiv16si:
4050     ArgNum = 4;
4051     break;
4052   }
4053 
4054   llvm::APSInt Result;
4055 
4056   // We can't check the value of a dependent argument.
4057   Expr *Arg = TheCall->getArg(ArgNum);
4058   if (Arg->isTypeDependent() || Arg->isValueDependent())
4059     return false;
4060 
4061   // Check constant-ness first.
4062   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4063     return true;
4064 
4065   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4066     return false;
4067 
4068   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4069          << Arg->getSourceRange();
4070 }
4071 
4072 enum { TileRegLow = 0, TileRegHigh = 7 };
4073 
4074 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4075                                              ArrayRef<int> ArgNums) {
4076   for (int ArgNum : ArgNums) {
4077     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4078       return true;
4079   }
4080   return false;
4081 }
4082 
4083 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4084                                         ArrayRef<int> ArgNums) {
4085   // Because the max number of tile register is TileRegHigh + 1, so here we use
4086   // each bit to represent the usage of them in bitset.
4087   std::bitset<TileRegHigh + 1> ArgValues;
4088   for (int ArgNum : ArgNums) {
4089     Expr *Arg = TheCall->getArg(ArgNum);
4090     if (Arg->isTypeDependent() || Arg->isValueDependent())
4091       continue;
4092 
4093     llvm::APSInt Result;
4094     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4095       return true;
4096     int ArgExtValue = Result.getExtValue();
4097     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4098            "Incorrect tile register num.");
4099     if (ArgValues.test(ArgExtValue))
4100       return Diag(TheCall->getBeginLoc(),
4101                   diag::err_x86_builtin_tile_arg_duplicate)
4102              << TheCall->getArg(ArgNum)->getSourceRange();
4103     ArgValues.set(ArgExtValue);
4104   }
4105   return false;
4106 }
4107 
4108 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4109                                                 ArrayRef<int> ArgNums) {
4110   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4111          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4112 }
4113 
4114 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4115   switch (BuiltinID) {
4116   default:
4117     return false;
4118   case X86::BI__builtin_ia32_tileloadd64:
4119   case X86::BI__builtin_ia32_tileloaddt164:
4120   case X86::BI__builtin_ia32_tilestored64:
4121   case X86::BI__builtin_ia32_tilezero:
4122     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4123   case X86::BI__builtin_ia32_tdpbssd:
4124   case X86::BI__builtin_ia32_tdpbsud:
4125   case X86::BI__builtin_ia32_tdpbusd:
4126   case X86::BI__builtin_ia32_tdpbuud:
4127   case X86::BI__builtin_ia32_tdpbf16ps:
4128     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4129   }
4130 }
4131 static bool isX86_32Builtin(unsigned BuiltinID) {
4132   // These builtins only work on x86-32 targets.
4133   switch (BuiltinID) {
4134   case X86::BI__builtin_ia32_readeflags_u32:
4135   case X86::BI__builtin_ia32_writeeflags_u32:
4136     return true;
4137   }
4138 
4139   return false;
4140 }
4141 
4142 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4143                                        CallExpr *TheCall) {
4144   if (BuiltinID == X86::BI__builtin_cpu_supports)
4145     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4146 
4147   if (BuiltinID == X86::BI__builtin_cpu_is)
4148     return SemaBuiltinCpuIs(*this, TI, TheCall);
4149 
4150   // Check for 32-bit only builtins on a 64-bit target.
4151   const llvm::Triple &TT = TI.getTriple();
4152   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4153     return Diag(TheCall->getCallee()->getBeginLoc(),
4154                 diag::err_32_bit_builtin_64_bit_tgt);
4155 
4156   // If the intrinsic has rounding or SAE make sure its valid.
4157   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4158     return true;
4159 
4160   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4161   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4162     return true;
4163 
4164   // If the intrinsic has a tile arguments, make sure they are valid.
4165   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4166     return true;
4167 
4168   // For intrinsics which take an immediate value as part of the instruction,
4169   // range check them here.
4170   int i = 0, l = 0, u = 0;
4171   switch (BuiltinID) {
4172   default:
4173     return false;
4174   case X86::BI__builtin_ia32_vec_ext_v2si:
4175   case X86::BI__builtin_ia32_vec_ext_v2di:
4176   case X86::BI__builtin_ia32_vextractf128_pd256:
4177   case X86::BI__builtin_ia32_vextractf128_ps256:
4178   case X86::BI__builtin_ia32_vextractf128_si256:
4179   case X86::BI__builtin_ia32_extract128i256:
4180   case X86::BI__builtin_ia32_extractf64x4_mask:
4181   case X86::BI__builtin_ia32_extracti64x4_mask:
4182   case X86::BI__builtin_ia32_extractf32x8_mask:
4183   case X86::BI__builtin_ia32_extracti32x8_mask:
4184   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4185   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4186   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4187   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4188     i = 1; l = 0; u = 1;
4189     break;
4190   case X86::BI__builtin_ia32_vec_set_v2di:
4191   case X86::BI__builtin_ia32_vinsertf128_pd256:
4192   case X86::BI__builtin_ia32_vinsertf128_ps256:
4193   case X86::BI__builtin_ia32_vinsertf128_si256:
4194   case X86::BI__builtin_ia32_insert128i256:
4195   case X86::BI__builtin_ia32_insertf32x8:
4196   case X86::BI__builtin_ia32_inserti32x8:
4197   case X86::BI__builtin_ia32_insertf64x4:
4198   case X86::BI__builtin_ia32_inserti64x4:
4199   case X86::BI__builtin_ia32_insertf64x2_256:
4200   case X86::BI__builtin_ia32_inserti64x2_256:
4201   case X86::BI__builtin_ia32_insertf32x4_256:
4202   case X86::BI__builtin_ia32_inserti32x4_256:
4203     i = 2; l = 0; u = 1;
4204     break;
4205   case X86::BI__builtin_ia32_vpermilpd:
4206   case X86::BI__builtin_ia32_vec_ext_v4hi:
4207   case X86::BI__builtin_ia32_vec_ext_v4si:
4208   case X86::BI__builtin_ia32_vec_ext_v4sf:
4209   case X86::BI__builtin_ia32_vec_ext_v4di:
4210   case X86::BI__builtin_ia32_extractf32x4_mask:
4211   case X86::BI__builtin_ia32_extracti32x4_mask:
4212   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4213   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4214     i = 1; l = 0; u = 3;
4215     break;
4216   case X86::BI_mm_prefetch:
4217   case X86::BI__builtin_ia32_vec_ext_v8hi:
4218   case X86::BI__builtin_ia32_vec_ext_v8si:
4219     i = 1; l = 0; u = 7;
4220     break;
4221   case X86::BI__builtin_ia32_sha1rnds4:
4222   case X86::BI__builtin_ia32_blendpd:
4223   case X86::BI__builtin_ia32_shufpd:
4224   case X86::BI__builtin_ia32_vec_set_v4hi:
4225   case X86::BI__builtin_ia32_vec_set_v4si:
4226   case X86::BI__builtin_ia32_vec_set_v4di:
4227   case X86::BI__builtin_ia32_shuf_f32x4_256:
4228   case X86::BI__builtin_ia32_shuf_f64x2_256:
4229   case X86::BI__builtin_ia32_shuf_i32x4_256:
4230   case X86::BI__builtin_ia32_shuf_i64x2_256:
4231   case X86::BI__builtin_ia32_insertf64x2_512:
4232   case X86::BI__builtin_ia32_inserti64x2_512:
4233   case X86::BI__builtin_ia32_insertf32x4:
4234   case X86::BI__builtin_ia32_inserti32x4:
4235     i = 2; l = 0; u = 3;
4236     break;
4237   case X86::BI__builtin_ia32_vpermil2pd:
4238   case X86::BI__builtin_ia32_vpermil2pd256:
4239   case X86::BI__builtin_ia32_vpermil2ps:
4240   case X86::BI__builtin_ia32_vpermil2ps256:
4241     i = 3; l = 0; u = 3;
4242     break;
4243   case X86::BI__builtin_ia32_cmpb128_mask:
4244   case X86::BI__builtin_ia32_cmpw128_mask:
4245   case X86::BI__builtin_ia32_cmpd128_mask:
4246   case X86::BI__builtin_ia32_cmpq128_mask:
4247   case X86::BI__builtin_ia32_cmpb256_mask:
4248   case X86::BI__builtin_ia32_cmpw256_mask:
4249   case X86::BI__builtin_ia32_cmpd256_mask:
4250   case X86::BI__builtin_ia32_cmpq256_mask:
4251   case X86::BI__builtin_ia32_cmpb512_mask:
4252   case X86::BI__builtin_ia32_cmpw512_mask:
4253   case X86::BI__builtin_ia32_cmpd512_mask:
4254   case X86::BI__builtin_ia32_cmpq512_mask:
4255   case X86::BI__builtin_ia32_ucmpb128_mask:
4256   case X86::BI__builtin_ia32_ucmpw128_mask:
4257   case X86::BI__builtin_ia32_ucmpd128_mask:
4258   case X86::BI__builtin_ia32_ucmpq128_mask:
4259   case X86::BI__builtin_ia32_ucmpb256_mask:
4260   case X86::BI__builtin_ia32_ucmpw256_mask:
4261   case X86::BI__builtin_ia32_ucmpd256_mask:
4262   case X86::BI__builtin_ia32_ucmpq256_mask:
4263   case X86::BI__builtin_ia32_ucmpb512_mask:
4264   case X86::BI__builtin_ia32_ucmpw512_mask:
4265   case X86::BI__builtin_ia32_ucmpd512_mask:
4266   case X86::BI__builtin_ia32_ucmpq512_mask:
4267   case X86::BI__builtin_ia32_vpcomub:
4268   case X86::BI__builtin_ia32_vpcomuw:
4269   case X86::BI__builtin_ia32_vpcomud:
4270   case X86::BI__builtin_ia32_vpcomuq:
4271   case X86::BI__builtin_ia32_vpcomb:
4272   case X86::BI__builtin_ia32_vpcomw:
4273   case X86::BI__builtin_ia32_vpcomd:
4274   case X86::BI__builtin_ia32_vpcomq:
4275   case X86::BI__builtin_ia32_vec_set_v8hi:
4276   case X86::BI__builtin_ia32_vec_set_v8si:
4277     i = 2; l = 0; u = 7;
4278     break;
4279   case X86::BI__builtin_ia32_vpermilpd256:
4280   case X86::BI__builtin_ia32_roundps:
4281   case X86::BI__builtin_ia32_roundpd:
4282   case X86::BI__builtin_ia32_roundps256:
4283   case X86::BI__builtin_ia32_roundpd256:
4284   case X86::BI__builtin_ia32_getmantpd128_mask:
4285   case X86::BI__builtin_ia32_getmantpd256_mask:
4286   case X86::BI__builtin_ia32_getmantps128_mask:
4287   case X86::BI__builtin_ia32_getmantps256_mask:
4288   case X86::BI__builtin_ia32_getmantpd512_mask:
4289   case X86::BI__builtin_ia32_getmantps512_mask:
4290   case X86::BI__builtin_ia32_vec_ext_v16qi:
4291   case X86::BI__builtin_ia32_vec_ext_v16hi:
4292     i = 1; l = 0; u = 15;
4293     break;
4294   case X86::BI__builtin_ia32_pblendd128:
4295   case X86::BI__builtin_ia32_blendps:
4296   case X86::BI__builtin_ia32_blendpd256:
4297   case X86::BI__builtin_ia32_shufpd256:
4298   case X86::BI__builtin_ia32_roundss:
4299   case X86::BI__builtin_ia32_roundsd:
4300   case X86::BI__builtin_ia32_rangepd128_mask:
4301   case X86::BI__builtin_ia32_rangepd256_mask:
4302   case X86::BI__builtin_ia32_rangepd512_mask:
4303   case X86::BI__builtin_ia32_rangeps128_mask:
4304   case X86::BI__builtin_ia32_rangeps256_mask:
4305   case X86::BI__builtin_ia32_rangeps512_mask:
4306   case X86::BI__builtin_ia32_getmantsd_round_mask:
4307   case X86::BI__builtin_ia32_getmantss_round_mask:
4308   case X86::BI__builtin_ia32_vec_set_v16qi:
4309   case X86::BI__builtin_ia32_vec_set_v16hi:
4310     i = 2; l = 0; u = 15;
4311     break;
4312   case X86::BI__builtin_ia32_vec_ext_v32qi:
4313     i = 1; l = 0; u = 31;
4314     break;
4315   case X86::BI__builtin_ia32_cmpps:
4316   case X86::BI__builtin_ia32_cmpss:
4317   case X86::BI__builtin_ia32_cmppd:
4318   case X86::BI__builtin_ia32_cmpsd:
4319   case X86::BI__builtin_ia32_cmpps256:
4320   case X86::BI__builtin_ia32_cmppd256:
4321   case X86::BI__builtin_ia32_cmpps128_mask:
4322   case X86::BI__builtin_ia32_cmppd128_mask:
4323   case X86::BI__builtin_ia32_cmpps256_mask:
4324   case X86::BI__builtin_ia32_cmppd256_mask:
4325   case X86::BI__builtin_ia32_cmpps512_mask:
4326   case X86::BI__builtin_ia32_cmppd512_mask:
4327   case X86::BI__builtin_ia32_cmpsd_mask:
4328   case X86::BI__builtin_ia32_cmpss_mask:
4329   case X86::BI__builtin_ia32_vec_set_v32qi:
4330     i = 2; l = 0; u = 31;
4331     break;
4332   case X86::BI__builtin_ia32_permdf256:
4333   case X86::BI__builtin_ia32_permdi256:
4334   case X86::BI__builtin_ia32_permdf512:
4335   case X86::BI__builtin_ia32_permdi512:
4336   case X86::BI__builtin_ia32_vpermilps:
4337   case X86::BI__builtin_ia32_vpermilps256:
4338   case X86::BI__builtin_ia32_vpermilpd512:
4339   case X86::BI__builtin_ia32_vpermilps512:
4340   case X86::BI__builtin_ia32_pshufd:
4341   case X86::BI__builtin_ia32_pshufd256:
4342   case X86::BI__builtin_ia32_pshufd512:
4343   case X86::BI__builtin_ia32_pshufhw:
4344   case X86::BI__builtin_ia32_pshufhw256:
4345   case X86::BI__builtin_ia32_pshufhw512:
4346   case X86::BI__builtin_ia32_pshuflw:
4347   case X86::BI__builtin_ia32_pshuflw256:
4348   case X86::BI__builtin_ia32_pshuflw512:
4349   case X86::BI__builtin_ia32_vcvtps2ph:
4350   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4351   case X86::BI__builtin_ia32_vcvtps2ph256:
4352   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4353   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4354   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4355   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4356   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4357   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4358   case X86::BI__builtin_ia32_rndscaleps_mask:
4359   case X86::BI__builtin_ia32_rndscalepd_mask:
4360   case X86::BI__builtin_ia32_reducepd128_mask:
4361   case X86::BI__builtin_ia32_reducepd256_mask:
4362   case X86::BI__builtin_ia32_reducepd512_mask:
4363   case X86::BI__builtin_ia32_reduceps128_mask:
4364   case X86::BI__builtin_ia32_reduceps256_mask:
4365   case X86::BI__builtin_ia32_reduceps512_mask:
4366   case X86::BI__builtin_ia32_prold512:
4367   case X86::BI__builtin_ia32_prolq512:
4368   case X86::BI__builtin_ia32_prold128:
4369   case X86::BI__builtin_ia32_prold256:
4370   case X86::BI__builtin_ia32_prolq128:
4371   case X86::BI__builtin_ia32_prolq256:
4372   case X86::BI__builtin_ia32_prord512:
4373   case X86::BI__builtin_ia32_prorq512:
4374   case X86::BI__builtin_ia32_prord128:
4375   case X86::BI__builtin_ia32_prord256:
4376   case X86::BI__builtin_ia32_prorq128:
4377   case X86::BI__builtin_ia32_prorq256:
4378   case X86::BI__builtin_ia32_fpclasspd128_mask:
4379   case X86::BI__builtin_ia32_fpclasspd256_mask:
4380   case X86::BI__builtin_ia32_fpclassps128_mask:
4381   case X86::BI__builtin_ia32_fpclassps256_mask:
4382   case X86::BI__builtin_ia32_fpclassps512_mask:
4383   case X86::BI__builtin_ia32_fpclasspd512_mask:
4384   case X86::BI__builtin_ia32_fpclasssd_mask:
4385   case X86::BI__builtin_ia32_fpclassss_mask:
4386   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4387   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4388   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4389   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4390   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4391   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4392   case X86::BI__builtin_ia32_kshiftliqi:
4393   case X86::BI__builtin_ia32_kshiftlihi:
4394   case X86::BI__builtin_ia32_kshiftlisi:
4395   case X86::BI__builtin_ia32_kshiftlidi:
4396   case X86::BI__builtin_ia32_kshiftriqi:
4397   case X86::BI__builtin_ia32_kshiftrihi:
4398   case X86::BI__builtin_ia32_kshiftrisi:
4399   case X86::BI__builtin_ia32_kshiftridi:
4400     i = 1; l = 0; u = 255;
4401     break;
4402   case X86::BI__builtin_ia32_vperm2f128_pd256:
4403   case X86::BI__builtin_ia32_vperm2f128_ps256:
4404   case X86::BI__builtin_ia32_vperm2f128_si256:
4405   case X86::BI__builtin_ia32_permti256:
4406   case X86::BI__builtin_ia32_pblendw128:
4407   case X86::BI__builtin_ia32_pblendw256:
4408   case X86::BI__builtin_ia32_blendps256:
4409   case X86::BI__builtin_ia32_pblendd256:
4410   case X86::BI__builtin_ia32_palignr128:
4411   case X86::BI__builtin_ia32_palignr256:
4412   case X86::BI__builtin_ia32_palignr512:
4413   case X86::BI__builtin_ia32_alignq512:
4414   case X86::BI__builtin_ia32_alignd512:
4415   case X86::BI__builtin_ia32_alignd128:
4416   case X86::BI__builtin_ia32_alignd256:
4417   case X86::BI__builtin_ia32_alignq128:
4418   case X86::BI__builtin_ia32_alignq256:
4419   case X86::BI__builtin_ia32_vcomisd:
4420   case X86::BI__builtin_ia32_vcomiss:
4421   case X86::BI__builtin_ia32_shuf_f32x4:
4422   case X86::BI__builtin_ia32_shuf_f64x2:
4423   case X86::BI__builtin_ia32_shuf_i32x4:
4424   case X86::BI__builtin_ia32_shuf_i64x2:
4425   case X86::BI__builtin_ia32_shufpd512:
4426   case X86::BI__builtin_ia32_shufps:
4427   case X86::BI__builtin_ia32_shufps256:
4428   case X86::BI__builtin_ia32_shufps512:
4429   case X86::BI__builtin_ia32_dbpsadbw128:
4430   case X86::BI__builtin_ia32_dbpsadbw256:
4431   case X86::BI__builtin_ia32_dbpsadbw512:
4432   case X86::BI__builtin_ia32_vpshldd128:
4433   case X86::BI__builtin_ia32_vpshldd256:
4434   case X86::BI__builtin_ia32_vpshldd512:
4435   case X86::BI__builtin_ia32_vpshldq128:
4436   case X86::BI__builtin_ia32_vpshldq256:
4437   case X86::BI__builtin_ia32_vpshldq512:
4438   case X86::BI__builtin_ia32_vpshldw128:
4439   case X86::BI__builtin_ia32_vpshldw256:
4440   case X86::BI__builtin_ia32_vpshldw512:
4441   case X86::BI__builtin_ia32_vpshrdd128:
4442   case X86::BI__builtin_ia32_vpshrdd256:
4443   case X86::BI__builtin_ia32_vpshrdd512:
4444   case X86::BI__builtin_ia32_vpshrdq128:
4445   case X86::BI__builtin_ia32_vpshrdq256:
4446   case X86::BI__builtin_ia32_vpshrdq512:
4447   case X86::BI__builtin_ia32_vpshrdw128:
4448   case X86::BI__builtin_ia32_vpshrdw256:
4449   case X86::BI__builtin_ia32_vpshrdw512:
4450     i = 2; l = 0; u = 255;
4451     break;
4452   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4453   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4454   case X86::BI__builtin_ia32_fixupimmps512_mask:
4455   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4456   case X86::BI__builtin_ia32_fixupimmsd_mask:
4457   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4458   case X86::BI__builtin_ia32_fixupimmss_mask:
4459   case X86::BI__builtin_ia32_fixupimmss_maskz:
4460   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4461   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4462   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4463   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4464   case X86::BI__builtin_ia32_fixupimmps128_mask:
4465   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4466   case X86::BI__builtin_ia32_fixupimmps256_mask:
4467   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4468   case X86::BI__builtin_ia32_pternlogd512_mask:
4469   case X86::BI__builtin_ia32_pternlogd512_maskz:
4470   case X86::BI__builtin_ia32_pternlogq512_mask:
4471   case X86::BI__builtin_ia32_pternlogq512_maskz:
4472   case X86::BI__builtin_ia32_pternlogd128_mask:
4473   case X86::BI__builtin_ia32_pternlogd128_maskz:
4474   case X86::BI__builtin_ia32_pternlogd256_mask:
4475   case X86::BI__builtin_ia32_pternlogd256_maskz:
4476   case X86::BI__builtin_ia32_pternlogq128_mask:
4477   case X86::BI__builtin_ia32_pternlogq128_maskz:
4478   case X86::BI__builtin_ia32_pternlogq256_mask:
4479   case X86::BI__builtin_ia32_pternlogq256_maskz:
4480     i = 3; l = 0; u = 255;
4481     break;
4482   case X86::BI__builtin_ia32_gatherpfdpd:
4483   case X86::BI__builtin_ia32_gatherpfdps:
4484   case X86::BI__builtin_ia32_gatherpfqpd:
4485   case X86::BI__builtin_ia32_gatherpfqps:
4486   case X86::BI__builtin_ia32_scatterpfdpd:
4487   case X86::BI__builtin_ia32_scatterpfdps:
4488   case X86::BI__builtin_ia32_scatterpfqpd:
4489   case X86::BI__builtin_ia32_scatterpfqps:
4490     i = 4; l = 2; u = 3;
4491     break;
4492   case X86::BI__builtin_ia32_reducesd_mask:
4493   case X86::BI__builtin_ia32_reducess_mask:
4494   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4495   case X86::BI__builtin_ia32_rndscaless_round_mask:
4496     i = 4; l = 0; u = 255;
4497     break;
4498   }
4499 
4500   // Note that we don't force a hard error on the range check here, allowing
4501   // template-generated or macro-generated dead code to potentially have out-of-
4502   // range values. These need to code generate, but don't need to necessarily
4503   // make any sense. We use a warning that defaults to an error.
4504   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4505 }
4506 
4507 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4508 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4509 /// Returns true when the format fits the function and the FormatStringInfo has
4510 /// been populated.
4511 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4512                                FormatStringInfo *FSI) {
4513   FSI->HasVAListArg = Format->getFirstArg() == 0;
4514   FSI->FormatIdx = Format->getFormatIdx() - 1;
4515   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4516 
4517   // The way the format attribute works in GCC, the implicit this argument
4518   // of member functions is counted. However, it doesn't appear in our own
4519   // lists, so decrement format_idx in that case.
4520   if (IsCXXMember) {
4521     if(FSI->FormatIdx == 0)
4522       return false;
4523     --FSI->FormatIdx;
4524     if (FSI->FirstDataArg != 0)
4525       --FSI->FirstDataArg;
4526   }
4527   return true;
4528 }
4529 
4530 /// Checks if a the given expression evaluates to null.
4531 ///
4532 /// Returns true if the value evaluates to null.
4533 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4534   // If the expression has non-null type, it doesn't evaluate to null.
4535   if (auto nullability
4536         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4537     if (*nullability == NullabilityKind::NonNull)
4538       return false;
4539   }
4540 
4541   // As a special case, transparent unions initialized with zero are
4542   // considered null for the purposes of the nonnull attribute.
4543   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4544     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4545       if (const CompoundLiteralExpr *CLE =
4546           dyn_cast<CompoundLiteralExpr>(Expr))
4547         if (const InitListExpr *ILE =
4548             dyn_cast<InitListExpr>(CLE->getInitializer()))
4549           Expr = ILE->getInit(0);
4550   }
4551 
4552   bool Result;
4553   return (!Expr->isValueDependent() &&
4554           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4555           !Result);
4556 }
4557 
4558 static void CheckNonNullArgument(Sema &S,
4559                                  const Expr *ArgExpr,
4560                                  SourceLocation CallSiteLoc) {
4561   if (CheckNonNullExpr(S, ArgExpr))
4562     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4563                           S.PDiag(diag::warn_null_arg)
4564                               << ArgExpr->getSourceRange());
4565 }
4566 
4567 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4568   FormatStringInfo FSI;
4569   if ((GetFormatStringType(Format) == FST_NSString) &&
4570       getFormatStringInfo(Format, false, &FSI)) {
4571     Idx = FSI.FormatIdx;
4572     return true;
4573   }
4574   return false;
4575 }
4576 
4577 /// Diagnose use of %s directive in an NSString which is being passed
4578 /// as formatting string to formatting method.
4579 static void
4580 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4581                                         const NamedDecl *FDecl,
4582                                         Expr **Args,
4583                                         unsigned NumArgs) {
4584   unsigned Idx = 0;
4585   bool Format = false;
4586   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4587   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4588     Idx = 2;
4589     Format = true;
4590   }
4591   else
4592     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4593       if (S.GetFormatNSStringIdx(I, Idx)) {
4594         Format = true;
4595         break;
4596       }
4597     }
4598   if (!Format || NumArgs <= Idx)
4599     return;
4600   const Expr *FormatExpr = Args[Idx];
4601   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4602     FormatExpr = CSCE->getSubExpr();
4603   const StringLiteral *FormatString;
4604   if (const ObjCStringLiteral *OSL =
4605       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4606     FormatString = OSL->getString();
4607   else
4608     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4609   if (!FormatString)
4610     return;
4611   if (S.FormatStringHasSArg(FormatString)) {
4612     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4613       << "%s" << 1 << 1;
4614     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4615       << FDecl->getDeclName();
4616   }
4617 }
4618 
4619 /// Determine whether the given type has a non-null nullability annotation.
4620 static bool isNonNullType(ASTContext &ctx, QualType type) {
4621   if (auto nullability = type->getNullability(ctx))
4622     return *nullability == NullabilityKind::NonNull;
4623 
4624   return false;
4625 }
4626 
4627 static void CheckNonNullArguments(Sema &S,
4628                                   const NamedDecl *FDecl,
4629                                   const FunctionProtoType *Proto,
4630                                   ArrayRef<const Expr *> Args,
4631                                   SourceLocation CallSiteLoc) {
4632   assert((FDecl || Proto) && "Need a function declaration or prototype");
4633 
4634   // Already checked by by constant evaluator.
4635   if (S.isConstantEvaluated())
4636     return;
4637   // Check the attributes attached to the method/function itself.
4638   llvm::SmallBitVector NonNullArgs;
4639   if (FDecl) {
4640     // Handle the nonnull attribute on the function/method declaration itself.
4641     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4642       if (!NonNull->args_size()) {
4643         // Easy case: all pointer arguments are nonnull.
4644         for (const auto *Arg : Args)
4645           if (S.isValidPointerAttrType(Arg->getType()))
4646             CheckNonNullArgument(S, Arg, CallSiteLoc);
4647         return;
4648       }
4649 
4650       for (const ParamIdx &Idx : NonNull->args()) {
4651         unsigned IdxAST = Idx.getASTIndex();
4652         if (IdxAST >= Args.size())
4653           continue;
4654         if (NonNullArgs.empty())
4655           NonNullArgs.resize(Args.size());
4656         NonNullArgs.set(IdxAST);
4657       }
4658     }
4659   }
4660 
4661   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4662     // Handle the nonnull attribute on the parameters of the
4663     // function/method.
4664     ArrayRef<ParmVarDecl*> parms;
4665     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4666       parms = FD->parameters();
4667     else
4668       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4669 
4670     unsigned ParamIndex = 0;
4671     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4672          I != E; ++I, ++ParamIndex) {
4673       const ParmVarDecl *PVD = *I;
4674       if (PVD->hasAttr<NonNullAttr>() ||
4675           isNonNullType(S.Context, PVD->getType())) {
4676         if (NonNullArgs.empty())
4677           NonNullArgs.resize(Args.size());
4678 
4679         NonNullArgs.set(ParamIndex);
4680       }
4681     }
4682   } else {
4683     // If we have a non-function, non-method declaration but no
4684     // function prototype, try to dig out the function prototype.
4685     if (!Proto) {
4686       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4687         QualType type = VD->getType().getNonReferenceType();
4688         if (auto pointerType = type->getAs<PointerType>())
4689           type = pointerType->getPointeeType();
4690         else if (auto blockType = type->getAs<BlockPointerType>())
4691           type = blockType->getPointeeType();
4692         // FIXME: data member pointers?
4693 
4694         // Dig out the function prototype, if there is one.
4695         Proto = type->getAs<FunctionProtoType>();
4696       }
4697     }
4698 
4699     // Fill in non-null argument information from the nullability
4700     // information on the parameter types (if we have them).
4701     if (Proto) {
4702       unsigned Index = 0;
4703       for (auto paramType : Proto->getParamTypes()) {
4704         if (isNonNullType(S.Context, paramType)) {
4705           if (NonNullArgs.empty())
4706             NonNullArgs.resize(Args.size());
4707 
4708           NonNullArgs.set(Index);
4709         }
4710 
4711         ++Index;
4712       }
4713     }
4714   }
4715 
4716   // Check for non-null arguments.
4717   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4718        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4719     if (NonNullArgs[ArgIndex])
4720       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4721   }
4722 }
4723 
4724 /// Warn if a pointer or reference argument passed to a function points to an
4725 /// object that is less aligned than the parameter. This can happen when
4726 /// creating a typedef with a lower alignment than the original type and then
4727 /// calling functions defined in terms of the original type.
4728 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4729                              StringRef ParamName, QualType ArgTy,
4730                              QualType ParamTy) {
4731 
4732   // If a function accepts a pointer or reference type
4733   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4734     return;
4735 
4736   // If the parameter is a pointer type, get the pointee type for the
4737   // argument too. If the parameter is a reference type, don't try to get
4738   // the pointee type for the argument.
4739   if (ParamTy->isPointerType())
4740     ArgTy = ArgTy->getPointeeType();
4741 
4742   // Remove reference or pointer
4743   ParamTy = ParamTy->getPointeeType();
4744 
4745   // Find expected alignment, and the actual alignment of the passed object.
4746   // getTypeAlignInChars requires complete types
4747   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4748       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4749       ArgTy->isUndeducedType())
4750     return;
4751 
4752   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4753   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4754 
4755   // If the argument is less aligned than the parameter, there is a
4756   // potential alignment issue.
4757   if (ArgAlign < ParamAlign)
4758     Diag(Loc, diag::warn_param_mismatched_alignment)
4759         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4760         << ParamName << FDecl;
4761 }
4762 
4763 /// Handles the checks for format strings, non-POD arguments to vararg
4764 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4765 /// attributes.
4766 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4767                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4768                      bool IsMemberFunction, SourceLocation Loc,
4769                      SourceRange Range, VariadicCallType CallType) {
4770   // FIXME: We should check as much as we can in the template definition.
4771   if (CurContext->isDependentContext())
4772     return;
4773 
4774   // Printf and scanf checking.
4775   llvm::SmallBitVector CheckedVarArgs;
4776   if (FDecl) {
4777     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4778       // Only create vector if there are format attributes.
4779       CheckedVarArgs.resize(Args.size());
4780 
4781       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4782                            CheckedVarArgs);
4783     }
4784   }
4785 
4786   // Refuse POD arguments that weren't caught by the format string
4787   // checks above.
4788   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4789   if (CallType != VariadicDoesNotApply &&
4790       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4791     unsigned NumParams = Proto ? Proto->getNumParams()
4792                        : FDecl && isa<FunctionDecl>(FDecl)
4793                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4794                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4795                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4796                        : 0;
4797 
4798     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4799       // Args[ArgIdx] can be null in malformed code.
4800       if (const Expr *Arg = Args[ArgIdx]) {
4801         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4802           checkVariadicArgument(Arg, CallType);
4803       }
4804     }
4805   }
4806 
4807   if (FDecl || Proto) {
4808     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4809 
4810     // Type safety checking.
4811     if (FDecl) {
4812       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4813         CheckArgumentWithTypeTag(I, Args, Loc);
4814     }
4815   }
4816 
4817   // Check that passed arguments match the alignment of original arguments.
4818   // Try to get the missing prototype from the declaration.
4819   if (!Proto && FDecl) {
4820     const auto *FT = FDecl->getFunctionType();
4821     if (isa_and_nonnull<FunctionProtoType>(FT))
4822       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4823   }
4824   if (Proto) {
4825     // For variadic functions, we may have more args than parameters.
4826     // For some K&R functions, we may have less args than parameters.
4827     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4828     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4829       // Args[ArgIdx] can be null in malformed code.
4830       if (const Expr *Arg = Args[ArgIdx]) {
4831         if (Arg->containsErrors())
4832           continue;
4833 
4834         QualType ParamTy = Proto->getParamType(ArgIdx);
4835         QualType ArgTy = Arg->getType();
4836         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4837                           ArgTy, ParamTy);
4838       }
4839     }
4840   }
4841 
4842   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4843     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4844     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4845     if (!Arg->isValueDependent()) {
4846       Expr::EvalResult Align;
4847       if (Arg->EvaluateAsInt(Align, Context)) {
4848         const llvm::APSInt &I = Align.Val.getInt();
4849         if (!I.isPowerOf2())
4850           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4851               << Arg->getSourceRange();
4852 
4853         if (I > Sema::MaximumAlignment)
4854           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4855               << Arg->getSourceRange() << Sema::MaximumAlignment;
4856       }
4857     }
4858   }
4859 
4860   if (FD)
4861     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4862 }
4863 
4864 /// CheckConstructorCall - Check a constructor call for correctness and safety
4865 /// properties not enforced by the C type system.
4866 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4867                                 ArrayRef<const Expr *> Args,
4868                                 const FunctionProtoType *Proto,
4869                                 SourceLocation Loc) {
4870   VariadicCallType CallType =
4871       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4872 
4873   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4874   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4875                     Context.getPointerType(Ctor->getThisObjectType()));
4876 
4877   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4878             Loc, SourceRange(), CallType);
4879 }
4880 
4881 /// CheckFunctionCall - Check a direct function call for various correctness
4882 /// and safety properties not strictly enforced by the C type system.
4883 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4884                              const FunctionProtoType *Proto) {
4885   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4886                               isa<CXXMethodDecl>(FDecl);
4887   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4888                           IsMemberOperatorCall;
4889   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4890                                                   TheCall->getCallee());
4891   Expr** Args = TheCall->getArgs();
4892   unsigned NumArgs = TheCall->getNumArgs();
4893 
4894   Expr *ImplicitThis = nullptr;
4895   if (IsMemberOperatorCall) {
4896     // If this is a call to a member operator, hide the first argument
4897     // from checkCall.
4898     // FIXME: Our choice of AST representation here is less than ideal.
4899     ImplicitThis = Args[0];
4900     ++Args;
4901     --NumArgs;
4902   } else if (IsMemberFunction)
4903     ImplicitThis =
4904         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4905 
4906   if (ImplicitThis) {
4907     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4908     // used.
4909     QualType ThisType = ImplicitThis->getType();
4910     if (!ThisType->isPointerType()) {
4911       assert(!ThisType->isReferenceType());
4912       ThisType = Context.getPointerType(ThisType);
4913     }
4914 
4915     QualType ThisTypeFromDecl =
4916         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4917 
4918     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4919                       ThisTypeFromDecl);
4920   }
4921 
4922   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4923             IsMemberFunction, TheCall->getRParenLoc(),
4924             TheCall->getCallee()->getSourceRange(), CallType);
4925 
4926   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4927   // None of the checks below are needed for functions that don't have
4928   // simple names (e.g., C++ conversion functions).
4929   if (!FnInfo)
4930     return false;
4931 
4932   CheckTCBEnforcement(TheCall, FDecl);
4933 
4934   CheckAbsoluteValueFunction(TheCall, FDecl);
4935   CheckMaxUnsignedZero(TheCall, FDecl);
4936 
4937   if (getLangOpts().ObjC)
4938     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4939 
4940   unsigned CMId = FDecl->getMemoryFunctionKind();
4941 
4942   // Handle memory setting and copying functions.
4943   switch (CMId) {
4944   case 0:
4945     return false;
4946   case Builtin::BIstrlcpy: // fallthrough
4947   case Builtin::BIstrlcat:
4948     CheckStrlcpycatArguments(TheCall, FnInfo);
4949     break;
4950   case Builtin::BIstrncat:
4951     CheckStrncatArguments(TheCall, FnInfo);
4952     break;
4953   case Builtin::BIfree:
4954     CheckFreeArguments(TheCall);
4955     break;
4956   default:
4957     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4958   }
4959 
4960   return false;
4961 }
4962 
4963 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4964                                ArrayRef<const Expr *> Args) {
4965   VariadicCallType CallType =
4966       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4967 
4968   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4969             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4970             CallType);
4971 
4972   return false;
4973 }
4974 
4975 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4976                             const FunctionProtoType *Proto) {
4977   QualType Ty;
4978   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4979     Ty = V->getType().getNonReferenceType();
4980   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4981     Ty = F->getType().getNonReferenceType();
4982   else
4983     return false;
4984 
4985   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4986       !Ty->isFunctionProtoType())
4987     return false;
4988 
4989   VariadicCallType CallType;
4990   if (!Proto || !Proto->isVariadic()) {
4991     CallType = VariadicDoesNotApply;
4992   } else if (Ty->isBlockPointerType()) {
4993     CallType = VariadicBlock;
4994   } else { // Ty->isFunctionPointerType()
4995     CallType = VariadicFunction;
4996   }
4997 
4998   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4999             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5000             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5001             TheCall->getCallee()->getSourceRange(), CallType);
5002 
5003   return false;
5004 }
5005 
5006 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5007 /// such as function pointers returned from functions.
5008 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5009   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5010                                                   TheCall->getCallee());
5011   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5012             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5013             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5014             TheCall->getCallee()->getSourceRange(), CallType);
5015 
5016   return false;
5017 }
5018 
5019 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5020   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5021     return false;
5022 
5023   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5024   switch (Op) {
5025   case AtomicExpr::AO__c11_atomic_init:
5026   case AtomicExpr::AO__opencl_atomic_init:
5027     llvm_unreachable("There is no ordering argument for an init");
5028 
5029   case AtomicExpr::AO__c11_atomic_load:
5030   case AtomicExpr::AO__opencl_atomic_load:
5031   case AtomicExpr::AO__atomic_load_n:
5032   case AtomicExpr::AO__atomic_load:
5033     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5034            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5035 
5036   case AtomicExpr::AO__c11_atomic_store:
5037   case AtomicExpr::AO__opencl_atomic_store:
5038   case AtomicExpr::AO__atomic_store:
5039   case AtomicExpr::AO__atomic_store_n:
5040     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5041            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5042            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5043 
5044   default:
5045     return true;
5046   }
5047 }
5048 
5049 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5050                                          AtomicExpr::AtomicOp Op) {
5051   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5052   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5053   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5054   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5055                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5056                          Op);
5057 }
5058 
5059 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5060                                  SourceLocation RParenLoc, MultiExprArg Args,
5061                                  AtomicExpr::AtomicOp Op,
5062                                  AtomicArgumentOrder ArgOrder) {
5063   // All the non-OpenCL operations take one of the following forms.
5064   // The OpenCL operations take the __c11 forms with one extra argument for
5065   // synchronization scope.
5066   enum {
5067     // C    __c11_atomic_init(A *, C)
5068     Init,
5069 
5070     // C    __c11_atomic_load(A *, int)
5071     Load,
5072 
5073     // void __atomic_load(A *, CP, int)
5074     LoadCopy,
5075 
5076     // void __atomic_store(A *, CP, int)
5077     Copy,
5078 
5079     // C    __c11_atomic_add(A *, M, int)
5080     Arithmetic,
5081 
5082     // C    __atomic_exchange_n(A *, CP, int)
5083     Xchg,
5084 
5085     // void __atomic_exchange(A *, C *, CP, int)
5086     GNUXchg,
5087 
5088     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5089     C11CmpXchg,
5090 
5091     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5092     GNUCmpXchg
5093   } Form = Init;
5094 
5095   const unsigned NumForm = GNUCmpXchg + 1;
5096   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5097   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5098   // where:
5099   //   C is an appropriate type,
5100   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5101   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5102   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5103   //   the int parameters are for orderings.
5104 
5105   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5106       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5107       "need to update code for modified forms");
5108   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5109                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5110                         AtomicExpr::AO__atomic_load,
5111                 "need to update code for modified C11 atomics");
5112   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5113                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5114   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5115                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5116                IsOpenCL;
5117   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5118              Op == AtomicExpr::AO__atomic_store_n ||
5119              Op == AtomicExpr::AO__atomic_exchange_n ||
5120              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5121   bool IsAddSub = false;
5122 
5123   switch (Op) {
5124   case AtomicExpr::AO__c11_atomic_init:
5125   case AtomicExpr::AO__opencl_atomic_init:
5126     Form = Init;
5127     break;
5128 
5129   case AtomicExpr::AO__c11_atomic_load:
5130   case AtomicExpr::AO__opencl_atomic_load:
5131   case AtomicExpr::AO__atomic_load_n:
5132     Form = Load;
5133     break;
5134 
5135   case AtomicExpr::AO__atomic_load:
5136     Form = LoadCopy;
5137     break;
5138 
5139   case AtomicExpr::AO__c11_atomic_store:
5140   case AtomicExpr::AO__opencl_atomic_store:
5141   case AtomicExpr::AO__atomic_store:
5142   case AtomicExpr::AO__atomic_store_n:
5143     Form = Copy;
5144     break;
5145 
5146   case AtomicExpr::AO__c11_atomic_fetch_add:
5147   case AtomicExpr::AO__c11_atomic_fetch_sub:
5148   case AtomicExpr::AO__opencl_atomic_fetch_add:
5149   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5150   case AtomicExpr::AO__atomic_fetch_add:
5151   case AtomicExpr::AO__atomic_fetch_sub:
5152   case AtomicExpr::AO__atomic_add_fetch:
5153   case AtomicExpr::AO__atomic_sub_fetch:
5154     IsAddSub = true;
5155     Form = Arithmetic;
5156     break;
5157   case AtomicExpr::AO__c11_atomic_fetch_and:
5158   case AtomicExpr::AO__c11_atomic_fetch_or:
5159   case AtomicExpr::AO__c11_atomic_fetch_xor:
5160   case AtomicExpr::AO__opencl_atomic_fetch_and:
5161   case AtomicExpr::AO__opencl_atomic_fetch_or:
5162   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5163   case AtomicExpr::AO__atomic_fetch_and:
5164   case AtomicExpr::AO__atomic_fetch_or:
5165   case AtomicExpr::AO__atomic_fetch_xor:
5166   case AtomicExpr::AO__atomic_fetch_nand:
5167   case AtomicExpr::AO__atomic_and_fetch:
5168   case AtomicExpr::AO__atomic_or_fetch:
5169   case AtomicExpr::AO__atomic_xor_fetch:
5170   case AtomicExpr::AO__atomic_nand_fetch:
5171     Form = Arithmetic;
5172     break;
5173   case AtomicExpr::AO__c11_atomic_fetch_min:
5174   case AtomicExpr::AO__c11_atomic_fetch_max:
5175   case AtomicExpr::AO__opencl_atomic_fetch_min:
5176   case AtomicExpr::AO__opencl_atomic_fetch_max:
5177   case AtomicExpr::AO__atomic_min_fetch:
5178   case AtomicExpr::AO__atomic_max_fetch:
5179   case AtomicExpr::AO__atomic_fetch_min:
5180   case AtomicExpr::AO__atomic_fetch_max:
5181     Form = Arithmetic;
5182     break;
5183 
5184   case AtomicExpr::AO__c11_atomic_exchange:
5185   case AtomicExpr::AO__opencl_atomic_exchange:
5186   case AtomicExpr::AO__atomic_exchange_n:
5187     Form = Xchg;
5188     break;
5189 
5190   case AtomicExpr::AO__atomic_exchange:
5191     Form = GNUXchg;
5192     break;
5193 
5194   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5195   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5196   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5197   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5198     Form = C11CmpXchg;
5199     break;
5200 
5201   case AtomicExpr::AO__atomic_compare_exchange:
5202   case AtomicExpr::AO__atomic_compare_exchange_n:
5203     Form = GNUCmpXchg;
5204     break;
5205   }
5206 
5207   unsigned AdjustedNumArgs = NumArgs[Form];
5208   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5209     ++AdjustedNumArgs;
5210   // Check we have the right number of arguments.
5211   if (Args.size() < AdjustedNumArgs) {
5212     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5213         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5214         << ExprRange;
5215     return ExprError();
5216   } else if (Args.size() > AdjustedNumArgs) {
5217     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5218          diag::err_typecheck_call_too_many_args)
5219         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5220         << ExprRange;
5221     return ExprError();
5222   }
5223 
5224   // Inspect the first argument of the atomic operation.
5225   Expr *Ptr = Args[0];
5226   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5227   if (ConvertedPtr.isInvalid())
5228     return ExprError();
5229 
5230   Ptr = ConvertedPtr.get();
5231   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5232   if (!pointerType) {
5233     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5234         << Ptr->getType() << Ptr->getSourceRange();
5235     return ExprError();
5236   }
5237 
5238   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5239   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5240   QualType ValType = AtomTy; // 'C'
5241   if (IsC11) {
5242     if (!AtomTy->isAtomicType()) {
5243       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5244           << Ptr->getType() << Ptr->getSourceRange();
5245       return ExprError();
5246     }
5247     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5248         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5249       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5250           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5251           << Ptr->getSourceRange();
5252       return ExprError();
5253     }
5254     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5255   } else if (Form != Load && Form != LoadCopy) {
5256     if (ValType.isConstQualified()) {
5257       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5258           << Ptr->getType() << Ptr->getSourceRange();
5259       return ExprError();
5260     }
5261   }
5262 
5263   // For an arithmetic operation, the implied arithmetic must be well-formed.
5264   if (Form == Arithmetic) {
5265     // gcc does not enforce these rules for GNU atomics, but we do so for
5266     // sanity.
5267     auto IsAllowedValueType = [&](QualType ValType) {
5268       if (ValType->isIntegerType())
5269         return true;
5270       if (ValType->isPointerType())
5271         return true;
5272       if (!ValType->isFloatingType())
5273         return false;
5274       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5275       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5276           &Context.getTargetInfo().getLongDoubleFormat() ==
5277               &llvm::APFloat::x87DoubleExtended())
5278         return false;
5279       return true;
5280     };
5281     if (IsAddSub && !IsAllowedValueType(ValType)) {
5282       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5283           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5284       return ExprError();
5285     }
5286     if (!IsAddSub && !ValType->isIntegerType()) {
5287       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5288           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5289       return ExprError();
5290     }
5291     if (IsC11 && ValType->isPointerType() &&
5292         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5293                             diag::err_incomplete_type)) {
5294       return ExprError();
5295     }
5296   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5297     // For __atomic_*_n operations, the value type must be a scalar integral or
5298     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5299     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5300         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5301     return ExprError();
5302   }
5303 
5304   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5305       !AtomTy->isScalarType()) {
5306     // For GNU atomics, require a trivially-copyable type. This is not part of
5307     // the GNU atomics specification, but we enforce it for sanity.
5308     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5309         << Ptr->getType() << Ptr->getSourceRange();
5310     return ExprError();
5311   }
5312 
5313   switch (ValType.getObjCLifetime()) {
5314   case Qualifiers::OCL_None:
5315   case Qualifiers::OCL_ExplicitNone:
5316     // okay
5317     break;
5318 
5319   case Qualifiers::OCL_Weak:
5320   case Qualifiers::OCL_Strong:
5321   case Qualifiers::OCL_Autoreleasing:
5322     // FIXME: Can this happen? By this point, ValType should be known
5323     // to be trivially copyable.
5324     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5325         << ValType << Ptr->getSourceRange();
5326     return ExprError();
5327   }
5328 
5329   // All atomic operations have an overload which takes a pointer to a volatile
5330   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5331   // into the result or the other operands. Similarly atomic_load takes a
5332   // pointer to a const 'A'.
5333   ValType.removeLocalVolatile();
5334   ValType.removeLocalConst();
5335   QualType ResultType = ValType;
5336   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5337       Form == Init)
5338     ResultType = Context.VoidTy;
5339   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5340     ResultType = Context.BoolTy;
5341 
5342   // The type of a parameter passed 'by value'. In the GNU atomics, such
5343   // arguments are actually passed as pointers.
5344   QualType ByValType = ValType; // 'CP'
5345   bool IsPassedByAddress = false;
5346   if (!IsC11 && !IsN) {
5347     ByValType = Ptr->getType();
5348     IsPassedByAddress = true;
5349   }
5350 
5351   SmallVector<Expr *, 5> APIOrderedArgs;
5352   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5353     APIOrderedArgs.push_back(Args[0]);
5354     switch (Form) {
5355     case Init:
5356     case Load:
5357       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5358       break;
5359     case LoadCopy:
5360     case Copy:
5361     case Arithmetic:
5362     case Xchg:
5363       APIOrderedArgs.push_back(Args[2]); // Val1
5364       APIOrderedArgs.push_back(Args[1]); // Order
5365       break;
5366     case GNUXchg:
5367       APIOrderedArgs.push_back(Args[2]); // Val1
5368       APIOrderedArgs.push_back(Args[3]); // Val2
5369       APIOrderedArgs.push_back(Args[1]); // Order
5370       break;
5371     case C11CmpXchg:
5372       APIOrderedArgs.push_back(Args[2]); // Val1
5373       APIOrderedArgs.push_back(Args[4]); // Val2
5374       APIOrderedArgs.push_back(Args[1]); // Order
5375       APIOrderedArgs.push_back(Args[3]); // OrderFail
5376       break;
5377     case GNUCmpXchg:
5378       APIOrderedArgs.push_back(Args[2]); // Val1
5379       APIOrderedArgs.push_back(Args[4]); // Val2
5380       APIOrderedArgs.push_back(Args[5]); // Weak
5381       APIOrderedArgs.push_back(Args[1]); // Order
5382       APIOrderedArgs.push_back(Args[3]); // OrderFail
5383       break;
5384     }
5385   } else
5386     APIOrderedArgs.append(Args.begin(), Args.end());
5387 
5388   // The first argument's non-CV pointer type is used to deduce the type of
5389   // subsequent arguments, except for:
5390   //  - weak flag (always converted to bool)
5391   //  - memory order (always converted to int)
5392   //  - scope  (always converted to int)
5393   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5394     QualType Ty;
5395     if (i < NumVals[Form] + 1) {
5396       switch (i) {
5397       case 0:
5398         // The first argument is always a pointer. It has a fixed type.
5399         // It is always dereferenced, a nullptr is undefined.
5400         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5401         // Nothing else to do: we already know all we want about this pointer.
5402         continue;
5403       case 1:
5404         // The second argument is the non-atomic operand. For arithmetic, this
5405         // is always passed by value, and for a compare_exchange it is always
5406         // passed by address. For the rest, GNU uses by-address and C11 uses
5407         // by-value.
5408         assert(Form != Load);
5409         if (Form == Arithmetic && ValType->isPointerType())
5410           Ty = Context.getPointerDiffType();
5411         else if (Form == Init || Form == Arithmetic)
5412           Ty = ValType;
5413         else if (Form == Copy || Form == Xchg) {
5414           if (IsPassedByAddress) {
5415             // The value pointer is always dereferenced, a nullptr is undefined.
5416             CheckNonNullArgument(*this, APIOrderedArgs[i],
5417                                  ExprRange.getBegin());
5418           }
5419           Ty = ByValType;
5420         } else {
5421           Expr *ValArg = APIOrderedArgs[i];
5422           // The value pointer is always dereferenced, a nullptr is undefined.
5423           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5424           LangAS AS = LangAS::Default;
5425           // Keep address space of non-atomic pointer type.
5426           if (const PointerType *PtrTy =
5427                   ValArg->getType()->getAs<PointerType>()) {
5428             AS = PtrTy->getPointeeType().getAddressSpace();
5429           }
5430           Ty = Context.getPointerType(
5431               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5432         }
5433         break;
5434       case 2:
5435         // The third argument to compare_exchange / GNU exchange is the desired
5436         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5437         if (IsPassedByAddress)
5438           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5439         Ty = ByValType;
5440         break;
5441       case 3:
5442         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5443         Ty = Context.BoolTy;
5444         break;
5445       }
5446     } else {
5447       // The order(s) and scope are always converted to int.
5448       Ty = Context.IntTy;
5449     }
5450 
5451     InitializedEntity Entity =
5452         InitializedEntity::InitializeParameter(Context, Ty, false);
5453     ExprResult Arg = APIOrderedArgs[i];
5454     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5455     if (Arg.isInvalid())
5456       return true;
5457     APIOrderedArgs[i] = Arg.get();
5458   }
5459 
5460   // Permute the arguments into a 'consistent' order.
5461   SmallVector<Expr*, 5> SubExprs;
5462   SubExprs.push_back(Ptr);
5463   switch (Form) {
5464   case Init:
5465     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5466     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5467     break;
5468   case Load:
5469     SubExprs.push_back(APIOrderedArgs[1]); // Order
5470     break;
5471   case LoadCopy:
5472   case Copy:
5473   case Arithmetic:
5474   case Xchg:
5475     SubExprs.push_back(APIOrderedArgs[2]); // Order
5476     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5477     break;
5478   case GNUXchg:
5479     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5480     SubExprs.push_back(APIOrderedArgs[3]); // Order
5481     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5482     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5483     break;
5484   case C11CmpXchg:
5485     SubExprs.push_back(APIOrderedArgs[3]); // Order
5486     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5487     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5488     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5489     break;
5490   case GNUCmpXchg:
5491     SubExprs.push_back(APIOrderedArgs[4]); // Order
5492     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5493     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5494     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5495     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5496     break;
5497   }
5498 
5499   if (SubExprs.size() >= 2 && Form != Init) {
5500     if (Optional<llvm::APSInt> Result =
5501             SubExprs[1]->getIntegerConstantExpr(Context))
5502       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5503         Diag(SubExprs[1]->getBeginLoc(),
5504              diag::warn_atomic_op_has_invalid_memory_order)
5505             << SubExprs[1]->getSourceRange();
5506   }
5507 
5508   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5509     auto *Scope = Args[Args.size() - 1];
5510     if (Optional<llvm::APSInt> Result =
5511             Scope->getIntegerConstantExpr(Context)) {
5512       if (!ScopeModel->isValid(Result->getZExtValue()))
5513         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5514             << Scope->getSourceRange();
5515     }
5516     SubExprs.push_back(Scope);
5517   }
5518 
5519   AtomicExpr *AE = new (Context)
5520       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5521 
5522   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5523        Op == AtomicExpr::AO__c11_atomic_store ||
5524        Op == AtomicExpr::AO__opencl_atomic_load ||
5525        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5526       Context.AtomicUsesUnsupportedLibcall(AE))
5527     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5528         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5529              Op == AtomicExpr::AO__opencl_atomic_load)
5530                 ? 0
5531                 : 1);
5532 
5533   if (ValType->isExtIntType()) {
5534     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5535     return ExprError();
5536   }
5537 
5538   return AE;
5539 }
5540 
5541 /// checkBuiltinArgument - Given a call to a builtin function, perform
5542 /// normal type-checking on the given argument, updating the call in
5543 /// place.  This is useful when a builtin function requires custom
5544 /// type-checking for some of its arguments but not necessarily all of
5545 /// them.
5546 ///
5547 /// Returns true on error.
5548 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5549   FunctionDecl *Fn = E->getDirectCallee();
5550   assert(Fn && "builtin call without direct callee!");
5551 
5552   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5553   InitializedEntity Entity =
5554     InitializedEntity::InitializeParameter(S.Context, Param);
5555 
5556   ExprResult Arg = E->getArg(0);
5557   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5558   if (Arg.isInvalid())
5559     return true;
5560 
5561   E->setArg(ArgIndex, Arg.get());
5562   return false;
5563 }
5564 
5565 /// We have a call to a function like __sync_fetch_and_add, which is an
5566 /// overloaded function based on the pointer type of its first argument.
5567 /// The main BuildCallExpr routines have already promoted the types of
5568 /// arguments because all of these calls are prototyped as void(...).
5569 ///
5570 /// This function goes through and does final semantic checking for these
5571 /// builtins, as well as generating any warnings.
5572 ExprResult
5573 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5574   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5575   Expr *Callee = TheCall->getCallee();
5576   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5577   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5578 
5579   // Ensure that we have at least one argument to do type inference from.
5580   if (TheCall->getNumArgs() < 1) {
5581     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5582         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5583     return ExprError();
5584   }
5585 
5586   // Inspect the first argument of the atomic builtin.  This should always be
5587   // a pointer type, whose element is an integral scalar or pointer type.
5588   // Because it is a pointer type, we don't have to worry about any implicit
5589   // casts here.
5590   // FIXME: We don't allow floating point scalars as input.
5591   Expr *FirstArg = TheCall->getArg(0);
5592   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5593   if (FirstArgResult.isInvalid())
5594     return ExprError();
5595   FirstArg = FirstArgResult.get();
5596   TheCall->setArg(0, FirstArg);
5597 
5598   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5599   if (!pointerType) {
5600     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5601         << FirstArg->getType() << FirstArg->getSourceRange();
5602     return ExprError();
5603   }
5604 
5605   QualType ValType = pointerType->getPointeeType();
5606   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5607       !ValType->isBlockPointerType()) {
5608     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5609         << FirstArg->getType() << FirstArg->getSourceRange();
5610     return ExprError();
5611   }
5612 
5613   if (ValType.isConstQualified()) {
5614     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5615         << FirstArg->getType() << FirstArg->getSourceRange();
5616     return ExprError();
5617   }
5618 
5619   switch (ValType.getObjCLifetime()) {
5620   case Qualifiers::OCL_None:
5621   case Qualifiers::OCL_ExplicitNone:
5622     // okay
5623     break;
5624 
5625   case Qualifiers::OCL_Weak:
5626   case Qualifiers::OCL_Strong:
5627   case Qualifiers::OCL_Autoreleasing:
5628     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5629         << ValType << FirstArg->getSourceRange();
5630     return ExprError();
5631   }
5632 
5633   // Strip any qualifiers off ValType.
5634   ValType = ValType.getUnqualifiedType();
5635 
5636   // The majority of builtins return a value, but a few have special return
5637   // types, so allow them to override appropriately below.
5638   QualType ResultType = ValType;
5639 
5640   // We need to figure out which concrete builtin this maps onto.  For example,
5641   // __sync_fetch_and_add with a 2 byte object turns into
5642   // __sync_fetch_and_add_2.
5643 #define BUILTIN_ROW(x) \
5644   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5645     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5646 
5647   static const unsigned BuiltinIndices[][5] = {
5648     BUILTIN_ROW(__sync_fetch_and_add),
5649     BUILTIN_ROW(__sync_fetch_and_sub),
5650     BUILTIN_ROW(__sync_fetch_and_or),
5651     BUILTIN_ROW(__sync_fetch_and_and),
5652     BUILTIN_ROW(__sync_fetch_and_xor),
5653     BUILTIN_ROW(__sync_fetch_and_nand),
5654 
5655     BUILTIN_ROW(__sync_add_and_fetch),
5656     BUILTIN_ROW(__sync_sub_and_fetch),
5657     BUILTIN_ROW(__sync_and_and_fetch),
5658     BUILTIN_ROW(__sync_or_and_fetch),
5659     BUILTIN_ROW(__sync_xor_and_fetch),
5660     BUILTIN_ROW(__sync_nand_and_fetch),
5661 
5662     BUILTIN_ROW(__sync_val_compare_and_swap),
5663     BUILTIN_ROW(__sync_bool_compare_and_swap),
5664     BUILTIN_ROW(__sync_lock_test_and_set),
5665     BUILTIN_ROW(__sync_lock_release),
5666     BUILTIN_ROW(__sync_swap)
5667   };
5668 #undef BUILTIN_ROW
5669 
5670   // Determine the index of the size.
5671   unsigned SizeIndex;
5672   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5673   case 1: SizeIndex = 0; break;
5674   case 2: SizeIndex = 1; break;
5675   case 4: SizeIndex = 2; break;
5676   case 8: SizeIndex = 3; break;
5677   case 16: SizeIndex = 4; break;
5678   default:
5679     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5680         << FirstArg->getType() << FirstArg->getSourceRange();
5681     return ExprError();
5682   }
5683 
5684   // Each of these builtins has one pointer argument, followed by some number of
5685   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5686   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5687   // as the number of fixed args.
5688   unsigned BuiltinID = FDecl->getBuiltinID();
5689   unsigned BuiltinIndex, NumFixed = 1;
5690   bool WarnAboutSemanticsChange = false;
5691   switch (BuiltinID) {
5692   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5693   case Builtin::BI__sync_fetch_and_add:
5694   case Builtin::BI__sync_fetch_and_add_1:
5695   case Builtin::BI__sync_fetch_and_add_2:
5696   case Builtin::BI__sync_fetch_and_add_4:
5697   case Builtin::BI__sync_fetch_and_add_8:
5698   case Builtin::BI__sync_fetch_and_add_16:
5699     BuiltinIndex = 0;
5700     break;
5701 
5702   case Builtin::BI__sync_fetch_and_sub:
5703   case Builtin::BI__sync_fetch_and_sub_1:
5704   case Builtin::BI__sync_fetch_and_sub_2:
5705   case Builtin::BI__sync_fetch_and_sub_4:
5706   case Builtin::BI__sync_fetch_and_sub_8:
5707   case Builtin::BI__sync_fetch_and_sub_16:
5708     BuiltinIndex = 1;
5709     break;
5710 
5711   case Builtin::BI__sync_fetch_and_or:
5712   case Builtin::BI__sync_fetch_and_or_1:
5713   case Builtin::BI__sync_fetch_and_or_2:
5714   case Builtin::BI__sync_fetch_and_or_4:
5715   case Builtin::BI__sync_fetch_and_or_8:
5716   case Builtin::BI__sync_fetch_and_or_16:
5717     BuiltinIndex = 2;
5718     break;
5719 
5720   case Builtin::BI__sync_fetch_and_and:
5721   case Builtin::BI__sync_fetch_and_and_1:
5722   case Builtin::BI__sync_fetch_and_and_2:
5723   case Builtin::BI__sync_fetch_and_and_4:
5724   case Builtin::BI__sync_fetch_and_and_8:
5725   case Builtin::BI__sync_fetch_and_and_16:
5726     BuiltinIndex = 3;
5727     break;
5728 
5729   case Builtin::BI__sync_fetch_and_xor:
5730   case Builtin::BI__sync_fetch_and_xor_1:
5731   case Builtin::BI__sync_fetch_and_xor_2:
5732   case Builtin::BI__sync_fetch_and_xor_4:
5733   case Builtin::BI__sync_fetch_and_xor_8:
5734   case Builtin::BI__sync_fetch_and_xor_16:
5735     BuiltinIndex = 4;
5736     break;
5737 
5738   case Builtin::BI__sync_fetch_and_nand:
5739   case Builtin::BI__sync_fetch_and_nand_1:
5740   case Builtin::BI__sync_fetch_and_nand_2:
5741   case Builtin::BI__sync_fetch_and_nand_4:
5742   case Builtin::BI__sync_fetch_and_nand_8:
5743   case Builtin::BI__sync_fetch_and_nand_16:
5744     BuiltinIndex = 5;
5745     WarnAboutSemanticsChange = true;
5746     break;
5747 
5748   case Builtin::BI__sync_add_and_fetch:
5749   case Builtin::BI__sync_add_and_fetch_1:
5750   case Builtin::BI__sync_add_and_fetch_2:
5751   case Builtin::BI__sync_add_and_fetch_4:
5752   case Builtin::BI__sync_add_and_fetch_8:
5753   case Builtin::BI__sync_add_and_fetch_16:
5754     BuiltinIndex = 6;
5755     break;
5756 
5757   case Builtin::BI__sync_sub_and_fetch:
5758   case Builtin::BI__sync_sub_and_fetch_1:
5759   case Builtin::BI__sync_sub_and_fetch_2:
5760   case Builtin::BI__sync_sub_and_fetch_4:
5761   case Builtin::BI__sync_sub_and_fetch_8:
5762   case Builtin::BI__sync_sub_and_fetch_16:
5763     BuiltinIndex = 7;
5764     break;
5765 
5766   case Builtin::BI__sync_and_and_fetch:
5767   case Builtin::BI__sync_and_and_fetch_1:
5768   case Builtin::BI__sync_and_and_fetch_2:
5769   case Builtin::BI__sync_and_and_fetch_4:
5770   case Builtin::BI__sync_and_and_fetch_8:
5771   case Builtin::BI__sync_and_and_fetch_16:
5772     BuiltinIndex = 8;
5773     break;
5774 
5775   case Builtin::BI__sync_or_and_fetch:
5776   case Builtin::BI__sync_or_and_fetch_1:
5777   case Builtin::BI__sync_or_and_fetch_2:
5778   case Builtin::BI__sync_or_and_fetch_4:
5779   case Builtin::BI__sync_or_and_fetch_8:
5780   case Builtin::BI__sync_or_and_fetch_16:
5781     BuiltinIndex = 9;
5782     break;
5783 
5784   case Builtin::BI__sync_xor_and_fetch:
5785   case Builtin::BI__sync_xor_and_fetch_1:
5786   case Builtin::BI__sync_xor_and_fetch_2:
5787   case Builtin::BI__sync_xor_and_fetch_4:
5788   case Builtin::BI__sync_xor_and_fetch_8:
5789   case Builtin::BI__sync_xor_and_fetch_16:
5790     BuiltinIndex = 10;
5791     break;
5792 
5793   case Builtin::BI__sync_nand_and_fetch:
5794   case Builtin::BI__sync_nand_and_fetch_1:
5795   case Builtin::BI__sync_nand_and_fetch_2:
5796   case Builtin::BI__sync_nand_and_fetch_4:
5797   case Builtin::BI__sync_nand_and_fetch_8:
5798   case Builtin::BI__sync_nand_and_fetch_16:
5799     BuiltinIndex = 11;
5800     WarnAboutSemanticsChange = true;
5801     break;
5802 
5803   case Builtin::BI__sync_val_compare_and_swap:
5804   case Builtin::BI__sync_val_compare_and_swap_1:
5805   case Builtin::BI__sync_val_compare_and_swap_2:
5806   case Builtin::BI__sync_val_compare_and_swap_4:
5807   case Builtin::BI__sync_val_compare_and_swap_8:
5808   case Builtin::BI__sync_val_compare_and_swap_16:
5809     BuiltinIndex = 12;
5810     NumFixed = 2;
5811     break;
5812 
5813   case Builtin::BI__sync_bool_compare_and_swap:
5814   case Builtin::BI__sync_bool_compare_and_swap_1:
5815   case Builtin::BI__sync_bool_compare_and_swap_2:
5816   case Builtin::BI__sync_bool_compare_and_swap_4:
5817   case Builtin::BI__sync_bool_compare_and_swap_8:
5818   case Builtin::BI__sync_bool_compare_and_swap_16:
5819     BuiltinIndex = 13;
5820     NumFixed = 2;
5821     ResultType = Context.BoolTy;
5822     break;
5823 
5824   case Builtin::BI__sync_lock_test_and_set:
5825   case Builtin::BI__sync_lock_test_and_set_1:
5826   case Builtin::BI__sync_lock_test_and_set_2:
5827   case Builtin::BI__sync_lock_test_and_set_4:
5828   case Builtin::BI__sync_lock_test_and_set_8:
5829   case Builtin::BI__sync_lock_test_and_set_16:
5830     BuiltinIndex = 14;
5831     break;
5832 
5833   case Builtin::BI__sync_lock_release:
5834   case Builtin::BI__sync_lock_release_1:
5835   case Builtin::BI__sync_lock_release_2:
5836   case Builtin::BI__sync_lock_release_4:
5837   case Builtin::BI__sync_lock_release_8:
5838   case Builtin::BI__sync_lock_release_16:
5839     BuiltinIndex = 15;
5840     NumFixed = 0;
5841     ResultType = Context.VoidTy;
5842     break;
5843 
5844   case Builtin::BI__sync_swap:
5845   case Builtin::BI__sync_swap_1:
5846   case Builtin::BI__sync_swap_2:
5847   case Builtin::BI__sync_swap_4:
5848   case Builtin::BI__sync_swap_8:
5849   case Builtin::BI__sync_swap_16:
5850     BuiltinIndex = 16;
5851     break;
5852   }
5853 
5854   // Now that we know how many fixed arguments we expect, first check that we
5855   // have at least that many.
5856   if (TheCall->getNumArgs() < 1+NumFixed) {
5857     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5858         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5859         << Callee->getSourceRange();
5860     return ExprError();
5861   }
5862 
5863   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5864       << Callee->getSourceRange();
5865 
5866   if (WarnAboutSemanticsChange) {
5867     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5868         << Callee->getSourceRange();
5869   }
5870 
5871   // Get the decl for the concrete builtin from this, we can tell what the
5872   // concrete integer type we should convert to is.
5873   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5874   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5875   FunctionDecl *NewBuiltinDecl;
5876   if (NewBuiltinID == BuiltinID)
5877     NewBuiltinDecl = FDecl;
5878   else {
5879     // Perform builtin lookup to avoid redeclaring it.
5880     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5881     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5882     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5883     assert(Res.getFoundDecl());
5884     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5885     if (!NewBuiltinDecl)
5886       return ExprError();
5887   }
5888 
5889   // The first argument --- the pointer --- has a fixed type; we
5890   // deduce the types of the rest of the arguments accordingly.  Walk
5891   // the remaining arguments, converting them to the deduced value type.
5892   for (unsigned i = 0; i != NumFixed; ++i) {
5893     ExprResult Arg = TheCall->getArg(i+1);
5894 
5895     // GCC does an implicit conversion to the pointer or integer ValType.  This
5896     // can fail in some cases (1i -> int**), check for this error case now.
5897     // Initialize the argument.
5898     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5899                                                    ValType, /*consume*/ false);
5900     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5901     if (Arg.isInvalid())
5902       return ExprError();
5903 
5904     // Okay, we have something that *can* be converted to the right type.  Check
5905     // to see if there is a potentially weird extension going on here.  This can
5906     // happen when you do an atomic operation on something like an char* and
5907     // pass in 42.  The 42 gets converted to char.  This is even more strange
5908     // for things like 45.123 -> char, etc.
5909     // FIXME: Do this check.
5910     TheCall->setArg(i+1, Arg.get());
5911   }
5912 
5913   // Create a new DeclRefExpr to refer to the new decl.
5914   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5915       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5916       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5917       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5918 
5919   // Set the callee in the CallExpr.
5920   // FIXME: This loses syntactic information.
5921   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5922   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5923                                               CK_BuiltinFnToFnPtr);
5924   TheCall->setCallee(PromotedCall.get());
5925 
5926   // Change the result type of the call to match the original value type. This
5927   // is arbitrary, but the codegen for these builtins ins design to handle it
5928   // gracefully.
5929   TheCall->setType(ResultType);
5930 
5931   // Prohibit use of _ExtInt with atomic builtins.
5932   // The arguments would have already been converted to the first argument's
5933   // type, so only need to check the first argument.
5934   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5935   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5936     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5937     return ExprError();
5938   }
5939 
5940   return TheCallResult;
5941 }
5942 
5943 /// SemaBuiltinNontemporalOverloaded - We have a call to
5944 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5945 /// overloaded function based on the pointer type of its last argument.
5946 ///
5947 /// This function goes through and does final semantic checking for these
5948 /// builtins.
5949 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5950   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5951   DeclRefExpr *DRE =
5952       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5953   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5954   unsigned BuiltinID = FDecl->getBuiltinID();
5955   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5956           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5957          "Unexpected nontemporal load/store builtin!");
5958   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5959   unsigned numArgs = isStore ? 2 : 1;
5960 
5961   // Ensure that we have the proper number of arguments.
5962   if (checkArgCount(*this, TheCall, numArgs))
5963     return ExprError();
5964 
5965   // Inspect the last argument of the nontemporal builtin.  This should always
5966   // be a pointer type, from which we imply the type of the memory access.
5967   // Because it is a pointer type, we don't have to worry about any implicit
5968   // casts here.
5969   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5970   ExprResult PointerArgResult =
5971       DefaultFunctionArrayLvalueConversion(PointerArg);
5972 
5973   if (PointerArgResult.isInvalid())
5974     return ExprError();
5975   PointerArg = PointerArgResult.get();
5976   TheCall->setArg(numArgs - 1, PointerArg);
5977 
5978   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5979   if (!pointerType) {
5980     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5981         << PointerArg->getType() << PointerArg->getSourceRange();
5982     return ExprError();
5983   }
5984 
5985   QualType ValType = pointerType->getPointeeType();
5986 
5987   // Strip any qualifiers off ValType.
5988   ValType = ValType.getUnqualifiedType();
5989   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5990       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5991       !ValType->isVectorType()) {
5992     Diag(DRE->getBeginLoc(),
5993          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5994         << PointerArg->getType() << PointerArg->getSourceRange();
5995     return ExprError();
5996   }
5997 
5998   if (!isStore) {
5999     TheCall->setType(ValType);
6000     return TheCallResult;
6001   }
6002 
6003   ExprResult ValArg = TheCall->getArg(0);
6004   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6005       Context, ValType, /*consume*/ false);
6006   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6007   if (ValArg.isInvalid())
6008     return ExprError();
6009 
6010   TheCall->setArg(0, ValArg.get());
6011   TheCall->setType(Context.VoidTy);
6012   return TheCallResult;
6013 }
6014 
6015 /// CheckObjCString - Checks that the argument to the builtin
6016 /// CFString constructor is correct
6017 /// Note: It might also make sense to do the UTF-16 conversion here (would
6018 /// simplify the backend).
6019 bool Sema::CheckObjCString(Expr *Arg) {
6020   Arg = Arg->IgnoreParenCasts();
6021   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6022 
6023   if (!Literal || !Literal->isAscii()) {
6024     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6025         << Arg->getSourceRange();
6026     return true;
6027   }
6028 
6029   if (Literal->containsNonAsciiOrNull()) {
6030     StringRef String = Literal->getString();
6031     unsigned NumBytes = String.size();
6032     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6033     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6034     llvm::UTF16 *ToPtr = &ToBuf[0];
6035 
6036     llvm::ConversionResult Result =
6037         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6038                                  ToPtr + NumBytes, llvm::strictConversion);
6039     // Check for conversion failure.
6040     if (Result != llvm::conversionOK)
6041       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6042           << Arg->getSourceRange();
6043   }
6044   return false;
6045 }
6046 
6047 /// CheckObjCString - Checks that the format string argument to the os_log()
6048 /// and os_trace() functions is correct, and converts it to const char *.
6049 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6050   Arg = Arg->IgnoreParenCasts();
6051   auto *Literal = dyn_cast<StringLiteral>(Arg);
6052   if (!Literal) {
6053     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6054       Literal = ObjcLiteral->getString();
6055     }
6056   }
6057 
6058   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6059     return ExprError(
6060         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6061         << Arg->getSourceRange());
6062   }
6063 
6064   ExprResult Result(Literal);
6065   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6066   InitializedEntity Entity =
6067       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6068   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6069   return Result;
6070 }
6071 
6072 /// Check that the user is calling the appropriate va_start builtin for the
6073 /// target and calling convention.
6074 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6075   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6076   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6077   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6078                     TT.getArch() == llvm::Triple::aarch64_32);
6079   bool IsWindows = TT.isOSWindows();
6080   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6081   if (IsX64 || IsAArch64) {
6082     CallingConv CC = CC_C;
6083     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6084       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6085     if (IsMSVAStart) {
6086       // Don't allow this in System V ABI functions.
6087       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6088         return S.Diag(Fn->getBeginLoc(),
6089                       diag::err_ms_va_start_used_in_sysv_function);
6090     } else {
6091       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6092       // On x64 Windows, don't allow this in System V ABI functions.
6093       // (Yes, that means there's no corresponding way to support variadic
6094       // System V ABI functions on Windows.)
6095       if ((IsWindows && CC == CC_X86_64SysV) ||
6096           (!IsWindows && CC == CC_Win64))
6097         return S.Diag(Fn->getBeginLoc(),
6098                       diag::err_va_start_used_in_wrong_abi_function)
6099                << !IsWindows;
6100     }
6101     return false;
6102   }
6103 
6104   if (IsMSVAStart)
6105     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6106   return false;
6107 }
6108 
6109 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6110                                              ParmVarDecl **LastParam = nullptr) {
6111   // Determine whether the current function, block, or obj-c method is variadic
6112   // and get its parameter list.
6113   bool IsVariadic = false;
6114   ArrayRef<ParmVarDecl *> Params;
6115   DeclContext *Caller = S.CurContext;
6116   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6117     IsVariadic = Block->isVariadic();
6118     Params = Block->parameters();
6119   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6120     IsVariadic = FD->isVariadic();
6121     Params = FD->parameters();
6122   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6123     IsVariadic = MD->isVariadic();
6124     // FIXME: This isn't correct for methods (results in bogus warning).
6125     Params = MD->parameters();
6126   } else if (isa<CapturedDecl>(Caller)) {
6127     // We don't support va_start in a CapturedDecl.
6128     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6129     return true;
6130   } else {
6131     // This must be some other declcontext that parses exprs.
6132     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6133     return true;
6134   }
6135 
6136   if (!IsVariadic) {
6137     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6138     return true;
6139   }
6140 
6141   if (LastParam)
6142     *LastParam = Params.empty() ? nullptr : Params.back();
6143 
6144   return false;
6145 }
6146 
6147 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6148 /// for validity.  Emit an error and return true on failure; return false
6149 /// on success.
6150 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6151   Expr *Fn = TheCall->getCallee();
6152 
6153   if (checkVAStartABI(*this, BuiltinID, Fn))
6154     return true;
6155 
6156   if (checkArgCount(*this, TheCall, 2))
6157     return true;
6158 
6159   // Type-check the first argument normally.
6160   if (checkBuiltinArgument(*this, TheCall, 0))
6161     return true;
6162 
6163   // Check that the current function is variadic, and get its last parameter.
6164   ParmVarDecl *LastParam;
6165   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6166     return true;
6167 
6168   // Verify that the second argument to the builtin is the last argument of the
6169   // current function or method.
6170   bool SecondArgIsLastNamedArgument = false;
6171   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6172 
6173   // These are valid if SecondArgIsLastNamedArgument is false after the next
6174   // block.
6175   QualType Type;
6176   SourceLocation ParamLoc;
6177   bool IsCRegister = false;
6178 
6179   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6180     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6181       SecondArgIsLastNamedArgument = PV == LastParam;
6182 
6183       Type = PV->getType();
6184       ParamLoc = PV->getLocation();
6185       IsCRegister =
6186           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6187     }
6188   }
6189 
6190   if (!SecondArgIsLastNamedArgument)
6191     Diag(TheCall->getArg(1)->getBeginLoc(),
6192          diag::warn_second_arg_of_va_start_not_last_named_param);
6193   else if (IsCRegister || Type->isReferenceType() ||
6194            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6195              // Promotable integers are UB, but enumerations need a bit of
6196              // extra checking to see what their promotable type actually is.
6197              if (!Type->isPromotableIntegerType())
6198                return false;
6199              if (!Type->isEnumeralType())
6200                return true;
6201              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6202              return !(ED &&
6203                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6204            }()) {
6205     unsigned Reason = 0;
6206     if (Type->isReferenceType())  Reason = 1;
6207     else if (IsCRegister)         Reason = 2;
6208     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6209     Diag(ParamLoc, diag::note_parameter_type) << Type;
6210   }
6211 
6212   TheCall->setType(Context.VoidTy);
6213   return false;
6214 }
6215 
6216 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6217   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6218   //                 const char *named_addr);
6219 
6220   Expr *Func = Call->getCallee();
6221 
6222   if (Call->getNumArgs() < 3)
6223     return Diag(Call->getEndLoc(),
6224                 diag::err_typecheck_call_too_few_args_at_least)
6225            << 0 /*function call*/ << 3 << Call->getNumArgs();
6226 
6227   // Type-check the first argument normally.
6228   if (checkBuiltinArgument(*this, Call, 0))
6229     return true;
6230 
6231   // Check that the current function is variadic.
6232   if (checkVAStartIsInVariadicFunction(*this, Func))
6233     return true;
6234 
6235   // __va_start on Windows does not validate the parameter qualifiers
6236 
6237   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6238   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6239 
6240   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6241   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6242 
6243   const QualType &ConstCharPtrTy =
6244       Context.getPointerType(Context.CharTy.withConst());
6245   if (!Arg1Ty->isPointerType() ||
6246       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6247     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6248         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6249         << 0                                      /* qualifier difference */
6250         << 3                                      /* parameter mismatch */
6251         << 2 << Arg1->getType() << ConstCharPtrTy;
6252 
6253   const QualType SizeTy = Context.getSizeType();
6254   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6255     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6256         << Arg2->getType() << SizeTy << 1 /* different class */
6257         << 0                              /* qualifier difference */
6258         << 3                              /* parameter mismatch */
6259         << 3 << Arg2->getType() << SizeTy;
6260 
6261   return false;
6262 }
6263 
6264 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6265 /// friends.  This is declared to take (...), so we have to check everything.
6266 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6267   if (checkArgCount(*this, TheCall, 2))
6268     return true;
6269 
6270   ExprResult OrigArg0 = TheCall->getArg(0);
6271   ExprResult OrigArg1 = TheCall->getArg(1);
6272 
6273   // Do standard promotions between the two arguments, returning their common
6274   // type.
6275   QualType Res = UsualArithmeticConversions(
6276       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6277   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6278     return true;
6279 
6280   // Make sure any conversions are pushed back into the call; this is
6281   // type safe since unordered compare builtins are declared as "_Bool
6282   // foo(...)".
6283   TheCall->setArg(0, OrigArg0.get());
6284   TheCall->setArg(1, OrigArg1.get());
6285 
6286   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6287     return false;
6288 
6289   // If the common type isn't a real floating type, then the arguments were
6290   // invalid for this operation.
6291   if (Res.isNull() || !Res->isRealFloatingType())
6292     return Diag(OrigArg0.get()->getBeginLoc(),
6293                 diag::err_typecheck_call_invalid_ordered_compare)
6294            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6295            << SourceRange(OrigArg0.get()->getBeginLoc(),
6296                           OrigArg1.get()->getEndLoc());
6297 
6298   return false;
6299 }
6300 
6301 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6302 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6303 /// to check everything. We expect the last argument to be a floating point
6304 /// value.
6305 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6306   if (checkArgCount(*this, TheCall, NumArgs))
6307     return true;
6308 
6309   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6310   // on all preceding parameters just being int.  Try all of those.
6311   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6312     Expr *Arg = TheCall->getArg(i);
6313 
6314     if (Arg->isTypeDependent())
6315       return false;
6316 
6317     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6318 
6319     if (Res.isInvalid())
6320       return true;
6321     TheCall->setArg(i, Res.get());
6322   }
6323 
6324   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6325 
6326   if (OrigArg->isTypeDependent())
6327     return false;
6328 
6329   // Usual Unary Conversions will convert half to float, which we want for
6330   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6331   // type how it is, but do normal L->Rvalue conversions.
6332   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6333     OrigArg = UsualUnaryConversions(OrigArg).get();
6334   else
6335     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6336   TheCall->setArg(NumArgs - 1, OrigArg);
6337 
6338   // This operation requires a non-_Complex floating-point number.
6339   if (!OrigArg->getType()->isRealFloatingType())
6340     return Diag(OrigArg->getBeginLoc(),
6341                 diag::err_typecheck_call_invalid_unary_fp)
6342            << OrigArg->getType() << OrigArg->getSourceRange();
6343 
6344   return false;
6345 }
6346 
6347 /// Perform semantic analysis for a call to __builtin_complex.
6348 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6349   if (checkArgCount(*this, TheCall, 2))
6350     return true;
6351 
6352   bool Dependent = false;
6353   for (unsigned I = 0; I != 2; ++I) {
6354     Expr *Arg = TheCall->getArg(I);
6355     QualType T = Arg->getType();
6356     if (T->isDependentType()) {
6357       Dependent = true;
6358       continue;
6359     }
6360 
6361     // Despite supporting _Complex int, GCC requires a real floating point type
6362     // for the operands of __builtin_complex.
6363     if (!T->isRealFloatingType()) {
6364       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6365              << Arg->getType() << Arg->getSourceRange();
6366     }
6367 
6368     ExprResult Converted = DefaultLvalueConversion(Arg);
6369     if (Converted.isInvalid())
6370       return true;
6371     TheCall->setArg(I, Converted.get());
6372   }
6373 
6374   if (Dependent) {
6375     TheCall->setType(Context.DependentTy);
6376     return false;
6377   }
6378 
6379   Expr *Real = TheCall->getArg(0);
6380   Expr *Imag = TheCall->getArg(1);
6381   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6382     return Diag(Real->getBeginLoc(),
6383                 diag::err_typecheck_call_different_arg_types)
6384            << Real->getType() << Imag->getType()
6385            << Real->getSourceRange() << Imag->getSourceRange();
6386   }
6387 
6388   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6389   // don't allow this builtin to form those types either.
6390   // FIXME: Should we allow these types?
6391   if (Real->getType()->isFloat16Type())
6392     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6393            << "_Float16";
6394   if (Real->getType()->isHalfType())
6395     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6396            << "half";
6397 
6398   TheCall->setType(Context.getComplexType(Real->getType()));
6399   return false;
6400 }
6401 
6402 // Customized Sema Checking for VSX builtins that have the following signature:
6403 // vector [...] builtinName(vector [...], vector [...], const int);
6404 // Which takes the same type of vectors (any legal vector type) for the first
6405 // two arguments and takes compile time constant for the third argument.
6406 // Example builtins are :
6407 // vector double vec_xxpermdi(vector double, vector double, int);
6408 // vector short vec_xxsldwi(vector short, vector short, int);
6409 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6410   unsigned ExpectedNumArgs = 3;
6411   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6412     return true;
6413 
6414   // Check the third argument is a compile time constant
6415   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6416     return Diag(TheCall->getBeginLoc(),
6417                 diag::err_vsx_builtin_nonconstant_argument)
6418            << 3 /* argument index */ << TheCall->getDirectCallee()
6419            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6420                           TheCall->getArg(2)->getEndLoc());
6421 
6422   QualType Arg1Ty = TheCall->getArg(0)->getType();
6423   QualType Arg2Ty = TheCall->getArg(1)->getType();
6424 
6425   // Check the type of argument 1 and argument 2 are vectors.
6426   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6427   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6428       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6429     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6430            << TheCall->getDirectCallee()
6431            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6432                           TheCall->getArg(1)->getEndLoc());
6433   }
6434 
6435   // Check the first two arguments are the same type.
6436   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6437     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6438            << TheCall->getDirectCallee()
6439            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6440                           TheCall->getArg(1)->getEndLoc());
6441   }
6442 
6443   // When default clang type checking is turned off and the customized type
6444   // checking is used, the returning type of the function must be explicitly
6445   // set. Otherwise it is _Bool by default.
6446   TheCall->setType(Arg1Ty);
6447 
6448   return false;
6449 }
6450 
6451 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6452 // This is declared to take (...), so we have to check everything.
6453 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6454   if (TheCall->getNumArgs() < 2)
6455     return ExprError(Diag(TheCall->getEndLoc(),
6456                           diag::err_typecheck_call_too_few_args_at_least)
6457                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6458                      << TheCall->getSourceRange());
6459 
6460   // Determine which of the following types of shufflevector we're checking:
6461   // 1) unary, vector mask: (lhs, mask)
6462   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6463   QualType resType = TheCall->getArg(0)->getType();
6464   unsigned numElements = 0;
6465 
6466   if (!TheCall->getArg(0)->isTypeDependent() &&
6467       !TheCall->getArg(1)->isTypeDependent()) {
6468     QualType LHSType = TheCall->getArg(0)->getType();
6469     QualType RHSType = TheCall->getArg(1)->getType();
6470 
6471     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6472       return ExprError(
6473           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6474           << TheCall->getDirectCallee()
6475           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6476                          TheCall->getArg(1)->getEndLoc()));
6477 
6478     numElements = LHSType->castAs<VectorType>()->getNumElements();
6479     unsigned numResElements = TheCall->getNumArgs() - 2;
6480 
6481     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6482     // with mask.  If so, verify that RHS is an integer vector type with the
6483     // same number of elts as lhs.
6484     if (TheCall->getNumArgs() == 2) {
6485       if (!RHSType->hasIntegerRepresentation() ||
6486           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6487         return ExprError(Diag(TheCall->getBeginLoc(),
6488                               diag::err_vec_builtin_incompatible_vector)
6489                          << TheCall->getDirectCallee()
6490                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6491                                         TheCall->getArg(1)->getEndLoc()));
6492     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6493       return ExprError(Diag(TheCall->getBeginLoc(),
6494                             diag::err_vec_builtin_incompatible_vector)
6495                        << TheCall->getDirectCallee()
6496                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6497                                       TheCall->getArg(1)->getEndLoc()));
6498     } else if (numElements != numResElements) {
6499       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6500       resType = Context.getVectorType(eltType, numResElements,
6501                                       VectorType::GenericVector);
6502     }
6503   }
6504 
6505   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6506     if (TheCall->getArg(i)->isTypeDependent() ||
6507         TheCall->getArg(i)->isValueDependent())
6508       continue;
6509 
6510     Optional<llvm::APSInt> Result;
6511     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6512       return ExprError(Diag(TheCall->getBeginLoc(),
6513                             diag::err_shufflevector_nonconstant_argument)
6514                        << TheCall->getArg(i)->getSourceRange());
6515 
6516     // Allow -1 which will be translated to undef in the IR.
6517     if (Result->isSigned() && Result->isAllOnesValue())
6518       continue;
6519 
6520     if (Result->getActiveBits() > 64 ||
6521         Result->getZExtValue() >= numElements * 2)
6522       return ExprError(Diag(TheCall->getBeginLoc(),
6523                             diag::err_shufflevector_argument_too_large)
6524                        << TheCall->getArg(i)->getSourceRange());
6525   }
6526 
6527   SmallVector<Expr*, 32> exprs;
6528 
6529   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6530     exprs.push_back(TheCall->getArg(i));
6531     TheCall->setArg(i, nullptr);
6532   }
6533 
6534   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6535                                          TheCall->getCallee()->getBeginLoc(),
6536                                          TheCall->getRParenLoc());
6537 }
6538 
6539 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6540 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6541                                        SourceLocation BuiltinLoc,
6542                                        SourceLocation RParenLoc) {
6543   ExprValueKind VK = VK_PRValue;
6544   ExprObjectKind OK = OK_Ordinary;
6545   QualType DstTy = TInfo->getType();
6546   QualType SrcTy = E->getType();
6547 
6548   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6549     return ExprError(Diag(BuiltinLoc,
6550                           diag::err_convertvector_non_vector)
6551                      << E->getSourceRange());
6552   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6553     return ExprError(Diag(BuiltinLoc,
6554                           diag::err_convertvector_non_vector_type));
6555 
6556   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6557     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6558     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6559     if (SrcElts != DstElts)
6560       return ExprError(Diag(BuiltinLoc,
6561                             diag::err_convertvector_incompatible_vector)
6562                        << E->getSourceRange());
6563   }
6564 
6565   return new (Context)
6566       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6567 }
6568 
6569 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6570 // This is declared to take (const void*, ...) and can take two
6571 // optional constant int args.
6572 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6573   unsigned NumArgs = TheCall->getNumArgs();
6574 
6575   if (NumArgs > 3)
6576     return Diag(TheCall->getEndLoc(),
6577                 diag::err_typecheck_call_too_many_args_at_most)
6578            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6579 
6580   // Argument 0 is checked for us and the remaining arguments must be
6581   // constant integers.
6582   for (unsigned i = 1; i != NumArgs; ++i)
6583     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6584       return true;
6585 
6586   return false;
6587 }
6588 
6589 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6590 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6591   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6592     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6593            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6594   if (checkArgCount(*this, TheCall, 1))
6595     return true;
6596   Expr *Arg = TheCall->getArg(0);
6597   if (Arg->isInstantiationDependent())
6598     return false;
6599 
6600   QualType ArgTy = Arg->getType();
6601   if (!ArgTy->hasFloatingRepresentation())
6602     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6603            << ArgTy;
6604   if (Arg->isLValue()) {
6605     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6606     TheCall->setArg(0, FirstArg.get());
6607   }
6608   TheCall->setType(TheCall->getArg(0)->getType());
6609   return false;
6610 }
6611 
6612 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6613 // __assume does not evaluate its arguments, and should warn if its argument
6614 // has side effects.
6615 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6616   Expr *Arg = TheCall->getArg(0);
6617   if (Arg->isInstantiationDependent()) return false;
6618 
6619   if (Arg->HasSideEffects(Context))
6620     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6621         << Arg->getSourceRange()
6622         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6623 
6624   return false;
6625 }
6626 
6627 /// Handle __builtin_alloca_with_align. This is declared
6628 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6629 /// than 8.
6630 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6631   // The alignment must be a constant integer.
6632   Expr *Arg = TheCall->getArg(1);
6633 
6634   // We can't check the value of a dependent argument.
6635   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6636     if (const auto *UE =
6637             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6638       if (UE->getKind() == UETT_AlignOf ||
6639           UE->getKind() == UETT_PreferredAlignOf)
6640         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6641             << Arg->getSourceRange();
6642 
6643     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6644 
6645     if (!Result.isPowerOf2())
6646       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6647              << Arg->getSourceRange();
6648 
6649     if (Result < Context.getCharWidth())
6650       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6651              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6652 
6653     if (Result > std::numeric_limits<int32_t>::max())
6654       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6655              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6656   }
6657 
6658   return false;
6659 }
6660 
6661 /// Handle __builtin_assume_aligned. This is declared
6662 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6663 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6664   unsigned NumArgs = TheCall->getNumArgs();
6665 
6666   if (NumArgs > 3)
6667     return Diag(TheCall->getEndLoc(),
6668                 diag::err_typecheck_call_too_many_args_at_most)
6669            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6670 
6671   // The alignment must be a constant integer.
6672   Expr *Arg = TheCall->getArg(1);
6673 
6674   // We can't check the value of a dependent argument.
6675   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6676     llvm::APSInt Result;
6677     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6678       return true;
6679 
6680     if (!Result.isPowerOf2())
6681       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6682              << Arg->getSourceRange();
6683 
6684     if (Result > Sema::MaximumAlignment)
6685       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6686           << Arg->getSourceRange() << Sema::MaximumAlignment;
6687   }
6688 
6689   if (NumArgs > 2) {
6690     ExprResult Arg(TheCall->getArg(2));
6691     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6692       Context.getSizeType(), false);
6693     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6694     if (Arg.isInvalid()) return true;
6695     TheCall->setArg(2, Arg.get());
6696   }
6697 
6698   return false;
6699 }
6700 
6701 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6702   unsigned BuiltinID =
6703       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6704   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6705 
6706   unsigned NumArgs = TheCall->getNumArgs();
6707   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6708   if (NumArgs < NumRequiredArgs) {
6709     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6710            << 0 /* function call */ << NumRequiredArgs << NumArgs
6711            << TheCall->getSourceRange();
6712   }
6713   if (NumArgs >= NumRequiredArgs + 0x100) {
6714     return Diag(TheCall->getEndLoc(),
6715                 diag::err_typecheck_call_too_many_args_at_most)
6716            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6717            << TheCall->getSourceRange();
6718   }
6719   unsigned i = 0;
6720 
6721   // For formatting call, check buffer arg.
6722   if (!IsSizeCall) {
6723     ExprResult Arg(TheCall->getArg(i));
6724     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6725         Context, Context.VoidPtrTy, false);
6726     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6727     if (Arg.isInvalid())
6728       return true;
6729     TheCall->setArg(i, Arg.get());
6730     i++;
6731   }
6732 
6733   // Check string literal arg.
6734   unsigned FormatIdx = i;
6735   {
6736     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6737     if (Arg.isInvalid())
6738       return true;
6739     TheCall->setArg(i, Arg.get());
6740     i++;
6741   }
6742 
6743   // Make sure variadic args are scalar.
6744   unsigned FirstDataArg = i;
6745   while (i < NumArgs) {
6746     ExprResult Arg = DefaultVariadicArgumentPromotion(
6747         TheCall->getArg(i), VariadicFunction, nullptr);
6748     if (Arg.isInvalid())
6749       return true;
6750     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6751     if (ArgSize.getQuantity() >= 0x100) {
6752       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6753              << i << (int)ArgSize.getQuantity() << 0xff
6754              << TheCall->getSourceRange();
6755     }
6756     TheCall->setArg(i, Arg.get());
6757     i++;
6758   }
6759 
6760   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6761   // call to avoid duplicate diagnostics.
6762   if (!IsSizeCall) {
6763     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6764     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6765     bool Success = CheckFormatArguments(
6766         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6767         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6768         CheckedVarArgs);
6769     if (!Success)
6770       return true;
6771   }
6772 
6773   if (IsSizeCall) {
6774     TheCall->setType(Context.getSizeType());
6775   } else {
6776     TheCall->setType(Context.VoidPtrTy);
6777   }
6778   return false;
6779 }
6780 
6781 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6782 /// TheCall is a constant expression.
6783 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6784                                   llvm::APSInt &Result) {
6785   Expr *Arg = TheCall->getArg(ArgNum);
6786   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6787   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6788 
6789   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6790 
6791   Optional<llvm::APSInt> R;
6792   if (!(R = Arg->getIntegerConstantExpr(Context)))
6793     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6794            << FDecl->getDeclName() << Arg->getSourceRange();
6795   Result = *R;
6796   return false;
6797 }
6798 
6799 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6800 /// TheCall is a constant expression in the range [Low, High].
6801 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6802                                        int Low, int High, bool RangeIsError) {
6803   if (isConstantEvaluated())
6804     return false;
6805   llvm::APSInt Result;
6806 
6807   // We can't check the value of a dependent argument.
6808   Expr *Arg = TheCall->getArg(ArgNum);
6809   if (Arg->isTypeDependent() || Arg->isValueDependent())
6810     return false;
6811 
6812   // Check constant-ness first.
6813   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6814     return true;
6815 
6816   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6817     if (RangeIsError)
6818       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6819              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6820     else
6821       // Defer the warning until we know if the code will be emitted so that
6822       // dead code can ignore this.
6823       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6824                           PDiag(diag::warn_argument_invalid_range)
6825                               << toString(Result, 10) << Low << High
6826                               << Arg->getSourceRange());
6827   }
6828 
6829   return false;
6830 }
6831 
6832 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6833 /// TheCall is a constant expression is a multiple of Num..
6834 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6835                                           unsigned Num) {
6836   llvm::APSInt Result;
6837 
6838   // We can't check the value of a dependent argument.
6839   Expr *Arg = TheCall->getArg(ArgNum);
6840   if (Arg->isTypeDependent() || Arg->isValueDependent())
6841     return false;
6842 
6843   // Check constant-ness first.
6844   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6845     return true;
6846 
6847   if (Result.getSExtValue() % Num != 0)
6848     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6849            << Num << Arg->getSourceRange();
6850 
6851   return false;
6852 }
6853 
6854 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6855 /// constant expression representing a power of 2.
6856 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6857   llvm::APSInt Result;
6858 
6859   // We can't check the value of a dependent argument.
6860   Expr *Arg = TheCall->getArg(ArgNum);
6861   if (Arg->isTypeDependent() || Arg->isValueDependent())
6862     return false;
6863 
6864   // Check constant-ness first.
6865   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6866     return true;
6867 
6868   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6869   // and only if x is a power of 2.
6870   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6871     return false;
6872 
6873   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6874          << Arg->getSourceRange();
6875 }
6876 
6877 static bool IsShiftedByte(llvm::APSInt Value) {
6878   if (Value.isNegative())
6879     return false;
6880 
6881   // Check if it's a shifted byte, by shifting it down
6882   while (true) {
6883     // If the value fits in the bottom byte, the check passes.
6884     if (Value < 0x100)
6885       return true;
6886 
6887     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6888     // fails.
6889     if ((Value & 0xFF) != 0)
6890       return false;
6891 
6892     // If the bottom 8 bits are all 0, but something above that is nonzero,
6893     // then shifting the value right by 8 bits won't affect whether it's a
6894     // shifted byte or not. So do that, and go round again.
6895     Value >>= 8;
6896   }
6897 }
6898 
6899 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6900 /// a constant expression representing an arbitrary byte value shifted left by
6901 /// a multiple of 8 bits.
6902 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6903                                              unsigned ArgBits) {
6904   llvm::APSInt Result;
6905 
6906   // We can't check the value of a dependent argument.
6907   Expr *Arg = TheCall->getArg(ArgNum);
6908   if (Arg->isTypeDependent() || Arg->isValueDependent())
6909     return false;
6910 
6911   // Check constant-ness first.
6912   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6913     return true;
6914 
6915   // Truncate to the given size.
6916   Result = Result.getLoBits(ArgBits);
6917   Result.setIsUnsigned(true);
6918 
6919   if (IsShiftedByte(Result))
6920     return false;
6921 
6922   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6923          << Arg->getSourceRange();
6924 }
6925 
6926 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6927 /// TheCall is a constant expression representing either a shifted byte value,
6928 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6929 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6930 /// Arm MVE intrinsics.
6931 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6932                                                    int ArgNum,
6933                                                    unsigned ArgBits) {
6934   llvm::APSInt Result;
6935 
6936   // We can't check the value of a dependent argument.
6937   Expr *Arg = TheCall->getArg(ArgNum);
6938   if (Arg->isTypeDependent() || Arg->isValueDependent())
6939     return false;
6940 
6941   // Check constant-ness first.
6942   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6943     return true;
6944 
6945   // Truncate to the given size.
6946   Result = Result.getLoBits(ArgBits);
6947   Result.setIsUnsigned(true);
6948 
6949   // Check to see if it's in either of the required forms.
6950   if (IsShiftedByte(Result) ||
6951       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6952     return false;
6953 
6954   return Diag(TheCall->getBeginLoc(),
6955               diag::err_argument_not_shifted_byte_or_xxff)
6956          << Arg->getSourceRange();
6957 }
6958 
6959 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6960 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6961   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6962     if (checkArgCount(*this, TheCall, 2))
6963       return true;
6964     Expr *Arg0 = TheCall->getArg(0);
6965     Expr *Arg1 = TheCall->getArg(1);
6966 
6967     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6968     if (FirstArg.isInvalid())
6969       return true;
6970     QualType FirstArgType = FirstArg.get()->getType();
6971     if (!FirstArgType->isAnyPointerType())
6972       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6973                << "first" << FirstArgType << Arg0->getSourceRange();
6974     TheCall->setArg(0, FirstArg.get());
6975 
6976     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6977     if (SecArg.isInvalid())
6978       return true;
6979     QualType SecArgType = SecArg.get()->getType();
6980     if (!SecArgType->isIntegerType())
6981       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6982                << "second" << SecArgType << Arg1->getSourceRange();
6983 
6984     // Derive the return type from the pointer argument.
6985     TheCall->setType(FirstArgType);
6986     return false;
6987   }
6988 
6989   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6990     if (checkArgCount(*this, TheCall, 2))
6991       return true;
6992 
6993     Expr *Arg0 = TheCall->getArg(0);
6994     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6995     if (FirstArg.isInvalid())
6996       return true;
6997     QualType FirstArgType = FirstArg.get()->getType();
6998     if (!FirstArgType->isAnyPointerType())
6999       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7000                << "first" << FirstArgType << Arg0->getSourceRange();
7001     TheCall->setArg(0, FirstArg.get());
7002 
7003     // Derive the return type from the pointer argument.
7004     TheCall->setType(FirstArgType);
7005 
7006     // Second arg must be an constant in range [0,15]
7007     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7008   }
7009 
7010   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7011     if (checkArgCount(*this, TheCall, 2))
7012       return true;
7013     Expr *Arg0 = TheCall->getArg(0);
7014     Expr *Arg1 = TheCall->getArg(1);
7015 
7016     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7017     if (FirstArg.isInvalid())
7018       return true;
7019     QualType FirstArgType = FirstArg.get()->getType();
7020     if (!FirstArgType->isAnyPointerType())
7021       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7022                << "first" << FirstArgType << Arg0->getSourceRange();
7023 
7024     QualType SecArgType = Arg1->getType();
7025     if (!SecArgType->isIntegerType())
7026       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7027                << "second" << SecArgType << Arg1->getSourceRange();
7028     TheCall->setType(Context.IntTy);
7029     return false;
7030   }
7031 
7032   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7033       BuiltinID == AArch64::BI__builtin_arm_stg) {
7034     if (checkArgCount(*this, TheCall, 1))
7035       return true;
7036     Expr *Arg0 = TheCall->getArg(0);
7037     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7038     if (FirstArg.isInvalid())
7039       return true;
7040 
7041     QualType FirstArgType = FirstArg.get()->getType();
7042     if (!FirstArgType->isAnyPointerType())
7043       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7044                << "first" << FirstArgType << Arg0->getSourceRange();
7045     TheCall->setArg(0, FirstArg.get());
7046 
7047     // Derive the return type from the pointer argument.
7048     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7049       TheCall->setType(FirstArgType);
7050     return false;
7051   }
7052 
7053   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7054     Expr *ArgA = TheCall->getArg(0);
7055     Expr *ArgB = TheCall->getArg(1);
7056 
7057     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7058     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7059 
7060     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7061       return true;
7062 
7063     QualType ArgTypeA = ArgExprA.get()->getType();
7064     QualType ArgTypeB = ArgExprB.get()->getType();
7065 
7066     auto isNull = [&] (Expr *E) -> bool {
7067       return E->isNullPointerConstant(
7068                         Context, Expr::NPC_ValueDependentIsNotNull); };
7069 
7070     // argument should be either a pointer or null
7071     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7072       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7073         << "first" << ArgTypeA << ArgA->getSourceRange();
7074 
7075     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7076       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7077         << "second" << ArgTypeB << ArgB->getSourceRange();
7078 
7079     // Ensure Pointee types are compatible
7080     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7081         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7082       QualType pointeeA = ArgTypeA->getPointeeType();
7083       QualType pointeeB = ArgTypeB->getPointeeType();
7084       if (!Context.typesAreCompatible(
7085              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7086              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7087         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7088           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7089           << ArgB->getSourceRange();
7090       }
7091     }
7092 
7093     // at least one argument should be pointer type
7094     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7095       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7096         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7097 
7098     if (isNull(ArgA)) // adopt type of the other pointer
7099       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7100 
7101     if (isNull(ArgB))
7102       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7103 
7104     TheCall->setArg(0, ArgExprA.get());
7105     TheCall->setArg(1, ArgExprB.get());
7106     TheCall->setType(Context.LongLongTy);
7107     return false;
7108   }
7109   assert(false && "Unhandled ARM MTE intrinsic");
7110   return true;
7111 }
7112 
7113 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7114 /// TheCall is an ARM/AArch64 special register string literal.
7115 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7116                                     int ArgNum, unsigned ExpectedFieldNum,
7117                                     bool AllowName) {
7118   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7119                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7120                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7121                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7122                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7123                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7124   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7125                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7126                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7127                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7128                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7129                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7130   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7131 
7132   // We can't check the value of a dependent argument.
7133   Expr *Arg = TheCall->getArg(ArgNum);
7134   if (Arg->isTypeDependent() || Arg->isValueDependent())
7135     return false;
7136 
7137   // Check if the argument is a string literal.
7138   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7139     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7140            << Arg->getSourceRange();
7141 
7142   // Check the type of special register given.
7143   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7144   SmallVector<StringRef, 6> Fields;
7145   Reg.split(Fields, ":");
7146 
7147   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7148     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7149            << Arg->getSourceRange();
7150 
7151   // If the string is the name of a register then we cannot check that it is
7152   // valid here but if the string is of one the forms described in ACLE then we
7153   // can check that the supplied fields are integers and within the valid
7154   // ranges.
7155   if (Fields.size() > 1) {
7156     bool FiveFields = Fields.size() == 5;
7157 
7158     bool ValidString = true;
7159     if (IsARMBuiltin) {
7160       ValidString &= Fields[0].startswith_insensitive("cp") ||
7161                      Fields[0].startswith_insensitive("p");
7162       if (ValidString)
7163         Fields[0] = Fields[0].drop_front(
7164             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7165 
7166       ValidString &= Fields[2].startswith_insensitive("c");
7167       if (ValidString)
7168         Fields[2] = Fields[2].drop_front(1);
7169 
7170       if (FiveFields) {
7171         ValidString &= Fields[3].startswith_insensitive("c");
7172         if (ValidString)
7173           Fields[3] = Fields[3].drop_front(1);
7174       }
7175     }
7176 
7177     SmallVector<int, 5> Ranges;
7178     if (FiveFields)
7179       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7180     else
7181       Ranges.append({15, 7, 15});
7182 
7183     for (unsigned i=0; i<Fields.size(); ++i) {
7184       int IntField;
7185       ValidString &= !Fields[i].getAsInteger(10, IntField);
7186       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7187     }
7188 
7189     if (!ValidString)
7190       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7191              << Arg->getSourceRange();
7192   } else if (IsAArch64Builtin && Fields.size() == 1) {
7193     // If the register name is one of those that appear in the condition below
7194     // and the special register builtin being used is one of the write builtins,
7195     // then we require that the argument provided for writing to the register
7196     // is an integer constant expression. This is because it will be lowered to
7197     // an MSR (immediate) instruction, so we need to know the immediate at
7198     // compile time.
7199     if (TheCall->getNumArgs() != 2)
7200       return false;
7201 
7202     std::string RegLower = Reg.lower();
7203     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7204         RegLower != "pan" && RegLower != "uao")
7205       return false;
7206 
7207     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7208   }
7209 
7210   return false;
7211 }
7212 
7213 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7214 /// Emit an error and return true on failure; return false on success.
7215 /// TypeStr is a string containing the type descriptor of the value returned by
7216 /// the builtin and the descriptors of the expected type of the arguments.
7217 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7218 
7219   assert((TypeStr[0] != '\0') &&
7220          "Invalid types in PPC MMA builtin declaration");
7221 
7222   unsigned Mask = 0;
7223   unsigned ArgNum = 0;
7224 
7225   // The first type in TypeStr is the type of the value returned by the
7226   // builtin. So we first read that type and change the type of TheCall.
7227   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7228   TheCall->setType(type);
7229 
7230   while (*TypeStr != '\0') {
7231     Mask = 0;
7232     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7233     if (ArgNum >= TheCall->getNumArgs()) {
7234       ArgNum++;
7235       break;
7236     }
7237 
7238     Expr *Arg = TheCall->getArg(ArgNum);
7239     QualType ArgType = Arg->getType();
7240 
7241     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7242         (!ExpectedType->isVoidPointerType() &&
7243            ArgType.getCanonicalType() != ExpectedType))
7244       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7245              << ArgType << ExpectedType << 1 << 0 << 0;
7246 
7247     // If the value of the Mask is not 0, we have a constraint in the size of
7248     // the integer argument so here we ensure the argument is a constant that
7249     // is in the valid range.
7250     if (Mask != 0 &&
7251         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7252       return true;
7253 
7254     ArgNum++;
7255   }
7256 
7257   // In case we exited early from the previous loop, there are other types to
7258   // read from TypeStr. So we need to read them all to ensure we have the right
7259   // number of arguments in TheCall and if it is not the case, to display a
7260   // better error message.
7261   while (*TypeStr != '\0') {
7262     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7263     ArgNum++;
7264   }
7265   if (checkArgCount(*this, TheCall, ArgNum))
7266     return true;
7267 
7268   return false;
7269 }
7270 
7271 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7272 /// This checks that the target supports __builtin_longjmp and
7273 /// that val is a constant 1.
7274 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7275   if (!Context.getTargetInfo().hasSjLjLowering())
7276     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7277            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7278 
7279   Expr *Arg = TheCall->getArg(1);
7280   llvm::APSInt Result;
7281 
7282   // TODO: This is less than ideal. Overload this to take a value.
7283   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7284     return true;
7285 
7286   if (Result != 1)
7287     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7288            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7289 
7290   return false;
7291 }
7292 
7293 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7294 /// This checks that the target supports __builtin_setjmp.
7295 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7296   if (!Context.getTargetInfo().hasSjLjLowering())
7297     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7298            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7299   return false;
7300 }
7301 
7302 namespace {
7303 
7304 class UncoveredArgHandler {
7305   enum { Unknown = -1, AllCovered = -2 };
7306 
7307   signed FirstUncoveredArg = Unknown;
7308   SmallVector<const Expr *, 4> DiagnosticExprs;
7309 
7310 public:
7311   UncoveredArgHandler() = default;
7312 
7313   bool hasUncoveredArg() const {
7314     return (FirstUncoveredArg >= 0);
7315   }
7316 
7317   unsigned getUncoveredArg() const {
7318     assert(hasUncoveredArg() && "no uncovered argument");
7319     return FirstUncoveredArg;
7320   }
7321 
7322   void setAllCovered() {
7323     // A string has been found with all arguments covered, so clear out
7324     // the diagnostics.
7325     DiagnosticExprs.clear();
7326     FirstUncoveredArg = AllCovered;
7327   }
7328 
7329   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7330     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7331 
7332     // Don't update if a previous string covers all arguments.
7333     if (FirstUncoveredArg == AllCovered)
7334       return;
7335 
7336     // UncoveredArgHandler tracks the highest uncovered argument index
7337     // and with it all the strings that match this index.
7338     if (NewFirstUncoveredArg == FirstUncoveredArg)
7339       DiagnosticExprs.push_back(StrExpr);
7340     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7341       DiagnosticExprs.clear();
7342       DiagnosticExprs.push_back(StrExpr);
7343       FirstUncoveredArg = NewFirstUncoveredArg;
7344     }
7345   }
7346 
7347   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7348 };
7349 
7350 enum StringLiteralCheckType {
7351   SLCT_NotALiteral,
7352   SLCT_UncheckedLiteral,
7353   SLCT_CheckedLiteral
7354 };
7355 
7356 } // namespace
7357 
7358 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7359                                      BinaryOperatorKind BinOpKind,
7360                                      bool AddendIsRight) {
7361   unsigned BitWidth = Offset.getBitWidth();
7362   unsigned AddendBitWidth = Addend.getBitWidth();
7363   // There might be negative interim results.
7364   if (Addend.isUnsigned()) {
7365     Addend = Addend.zext(++AddendBitWidth);
7366     Addend.setIsSigned(true);
7367   }
7368   // Adjust the bit width of the APSInts.
7369   if (AddendBitWidth > BitWidth) {
7370     Offset = Offset.sext(AddendBitWidth);
7371     BitWidth = AddendBitWidth;
7372   } else if (BitWidth > AddendBitWidth) {
7373     Addend = Addend.sext(BitWidth);
7374   }
7375 
7376   bool Ov = false;
7377   llvm::APSInt ResOffset = Offset;
7378   if (BinOpKind == BO_Add)
7379     ResOffset = Offset.sadd_ov(Addend, Ov);
7380   else {
7381     assert(AddendIsRight && BinOpKind == BO_Sub &&
7382            "operator must be add or sub with addend on the right");
7383     ResOffset = Offset.ssub_ov(Addend, Ov);
7384   }
7385 
7386   // We add an offset to a pointer here so we should support an offset as big as
7387   // possible.
7388   if (Ov) {
7389     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7390            "index (intermediate) result too big");
7391     Offset = Offset.sext(2 * BitWidth);
7392     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7393     return;
7394   }
7395 
7396   Offset = ResOffset;
7397 }
7398 
7399 namespace {
7400 
7401 // This is a wrapper class around StringLiteral to support offsetted string
7402 // literals as format strings. It takes the offset into account when returning
7403 // the string and its length or the source locations to display notes correctly.
7404 class FormatStringLiteral {
7405   const StringLiteral *FExpr;
7406   int64_t Offset;
7407 
7408  public:
7409   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7410       : FExpr(fexpr), Offset(Offset) {}
7411 
7412   StringRef getString() const {
7413     return FExpr->getString().drop_front(Offset);
7414   }
7415 
7416   unsigned getByteLength() const {
7417     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7418   }
7419 
7420   unsigned getLength() const { return FExpr->getLength() - Offset; }
7421   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7422 
7423   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7424 
7425   QualType getType() const { return FExpr->getType(); }
7426 
7427   bool isAscii() const { return FExpr->isAscii(); }
7428   bool isWide() const { return FExpr->isWide(); }
7429   bool isUTF8() const { return FExpr->isUTF8(); }
7430   bool isUTF16() const { return FExpr->isUTF16(); }
7431   bool isUTF32() const { return FExpr->isUTF32(); }
7432   bool isPascal() const { return FExpr->isPascal(); }
7433 
7434   SourceLocation getLocationOfByte(
7435       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7436       const TargetInfo &Target, unsigned *StartToken = nullptr,
7437       unsigned *StartTokenByteOffset = nullptr) const {
7438     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7439                                     StartToken, StartTokenByteOffset);
7440   }
7441 
7442   SourceLocation getBeginLoc() const LLVM_READONLY {
7443     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7444   }
7445 
7446   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7447 };
7448 
7449 }  // namespace
7450 
7451 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7452                               const Expr *OrigFormatExpr,
7453                               ArrayRef<const Expr *> Args,
7454                               bool HasVAListArg, unsigned format_idx,
7455                               unsigned firstDataArg,
7456                               Sema::FormatStringType Type,
7457                               bool inFunctionCall,
7458                               Sema::VariadicCallType CallType,
7459                               llvm::SmallBitVector &CheckedVarArgs,
7460                               UncoveredArgHandler &UncoveredArg,
7461                               bool IgnoreStringsWithoutSpecifiers);
7462 
7463 // Determine if an expression is a string literal or constant string.
7464 // If this function returns false on the arguments to a function expecting a
7465 // format string, we will usually need to emit a warning.
7466 // True string literals are then checked by CheckFormatString.
7467 static StringLiteralCheckType
7468 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7469                       bool HasVAListArg, unsigned format_idx,
7470                       unsigned firstDataArg, Sema::FormatStringType Type,
7471                       Sema::VariadicCallType CallType, bool InFunctionCall,
7472                       llvm::SmallBitVector &CheckedVarArgs,
7473                       UncoveredArgHandler &UncoveredArg,
7474                       llvm::APSInt Offset,
7475                       bool IgnoreStringsWithoutSpecifiers = false) {
7476   if (S.isConstantEvaluated())
7477     return SLCT_NotALiteral;
7478  tryAgain:
7479   assert(Offset.isSigned() && "invalid offset");
7480 
7481   if (E->isTypeDependent() || E->isValueDependent())
7482     return SLCT_NotALiteral;
7483 
7484   E = E->IgnoreParenCasts();
7485 
7486   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7487     // Technically -Wformat-nonliteral does not warn about this case.
7488     // The behavior of printf and friends in this case is implementation
7489     // dependent.  Ideally if the format string cannot be null then
7490     // it should have a 'nonnull' attribute in the function prototype.
7491     return SLCT_UncheckedLiteral;
7492 
7493   switch (E->getStmtClass()) {
7494   case Stmt::BinaryConditionalOperatorClass:
7495   case Stmt::ConditionalOperatorClass: {
7496     // The expression is a literal if both sub-expressions were, and it was
7497     // completely checked only if both sub-expressions were checked.
7498     const AbstractConditionalOperator *C =
7499         cast<AbstractConditionalOperator>(E);
7500 
7501     // Determine whether it is necessary to check both sub-expressions, for
7502     // example, because the condition expression is a constant that can be
7503     // evaluated at compile time.
7504     bool CheckLeft = true, CheckRight = true;
7505 
7506     bool Cond;
7507     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7508                                                  S.isConstantEvaluated())) {
7509       if (Cond)
7510         CheckRight = false;
7511       else
7512         CheckLeft = false;
7513     }
7514 
7515     // We need to maintain the offsets for the right and the left hand side
7516     // separately to check if every possible indexed expression is a valid
7517     // string literal. They might have different offsets for different string
7518     // literals in the end.
7519     StringLiteralCheckType Left;
7520     if (!CheckLeft)
7521       Left = SLCT_UncheckedLiteral;
7522     else {
7523       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7524                                    HasVAListArg, format_idx, firstDataArg,
7525                                    Type, CallType, InFunctionCall,
7526                                    CheckedVarArgs, UncoveredArg, Offset,
7527                                    IgnoreStringsWithoutSpecifiers);
7528       if (Left == SLCT_NotALiteral || !CheckRight) {
7529         return Left;
7530       }
7531     }
7532 
7533     StringLiteralCheckType Right = checkFormatStringExpr(
7534         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7535         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7536         IgnoreStringsWithoutSpecifiers);
7537 
7538     return (CheckLeft && Left < Right) ? Left : Right;
7539   }
7540 
7541   case Stmt::ImplicitCastExprClass:
7542     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7543     goto tryAgain;
7544 
7545   case Stmt::OpaqueValueExprClass:
7546     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7547       E = src;
7548       goto tryAgain;
7549     }
7550     return SLCT_NotALiteral;
7551 
7552   case Stmt::PredefinedExprClass:
7553     // While __func__, etc., are technically not string literals, they
7554     // cannot contain format specifiers and thus are not a security
7555     // liability.
7556     return SLCT_UncheckedLiteral;
7557 
7558   case Stmt::DeclRefExprClass: {
7559     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7560 
7561     // As an exception, do not flag errors for variables binding to
7562     // const string literals.
7563     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7564       bool isConstant = false;
7565       QualType T = DR->getType();
7566 
7567       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7568         isConstant = AT->getElementType().isConstant(S.Context);
7569       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7570         isConstant = T.isConstant(S.Context) &&
7571                      PT->getPointeeType().isConstant(S.Context);
7572       } else if (T->isObjCObjectPointerType()) {
7573         // In ObjC, there is usually no "const ObjectPointer" type,
7574         // so don't check if the pointee type is constant.
7575         isConstant = T.isConstant(S.Context);
7576       }
7577 
7578       if (isConstant) {
7579         if (const Expr *Init = VD->getAnyInitializer()) {
7580           // Look through initializers like const char c[] = { "foo" }
7581           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7582             if (InitList->isStringLiteralInit())
7583               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7584           }
7585           return checkFormatStringExpr(S, Init, Args,
7586                                        HasVAListArg, format_idx,
7587                                        firstDataArg, Type, CallType,
7588                                        /*InFunctionCall*/ false, CheckedVarArgs,
7589                                        UncoveredArg, Offset);
7590         }
7591       }
7592 
7593       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7594       // special check to see if the format string is a function parameter
7595       // of the function calling the printf function.  If the function
7596       // has an attribute indicating it is a printf-like function, then we
7597       // should suppress warnings concerning non-literals being used in a call
7598       // to a vprintf function.  For example:
7599       //
7600       // void
7601       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7602       //      va_list ap;
7603       //      va_start(ap, fmt);
7604       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7605       //      ...
7606       // }
7607       if (HasVAListArg) {
7608         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7609           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7610             int PVIndex = PV->getFunctionScopeIndex() + 1;
7611             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7612               // adjust for implicit parameter
7613               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7614                 if (MD->isInstance())
7615                   ++PVIndex;
7616               // We also check if the formats are compatible.
7617               // We can't pass a 'scanf' string to a 'printf' function.
7618               if (PVIndex == PVFormat->getFormatIdx() &&
7619                   Type == S.GetFormatStringType(PVFormat))
7620                 return SLCT_UncheckedLiteral;
7621             }
7622           }
7623         }
7624       }
7625     }
7626 
7627     return SLCT_NotALiteral;
7628   }
7629 
7630   case Stmt::CallExprClass:
7631   case Stmt::CXXMemberCallExprClass: {
7632     const CallExpr *CE = cast<CallExpr>(E);
7633     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7634       bool IsFirst = true;
7635       StringLiteralCheckType CommonResult;
7636       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7637         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7638         StringLiteralCheckType Result = checkFormatStringExpr(
7639             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7640             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7641             IgnoreStringsWithoutSpecifiers);
7642         if (IsFirst) {
7643           CommonResult = Result;
7644           IsFirst = false;
7645         }
7646       }
7647       if (!IsFirst)
7648         return CommonResult;
7649 
7650       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7651         unsigned BuiltinID = FD->getBuiltinID();
7652         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7653             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7654           const Expr *Arg = CE->getArg(0);
7655           return checkFormatStringExpr(S, Arg, Args,
7656                                        HasVAListArg, format_idx,
7657                                        firstDataArg, Type, CallType,
7658                                        InFunctionCall, CheckedVarArgs,
7659                                        UncoveredArg, Offset,
7660                                        IgnoreStringsWithoutSpecifiers);
7661         }
7662       }
7663     }
7664 
7665     return SLCT_NotALiteral;
7666   }
7667   case Stmt::ObjCMessageExprClass: {
7668     const auto *ME = cast<ObjCMessageExpr>(E);
7669     if (const auto *MD = ME->getMethodDecl()) {
7670       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7671         // As a special case heuristic, if we're using the method -[NSBundle
7672         // localizedStringForKey:value:table:], ignore any key strings that lack
7673         // format specifiers. The idea is that if the key doesn't have any
7674         // format specifiers then its probably just a key to map to the
7675         // localized strings. If it does have format specifiers though, then its
7676         // likely that the text of the key is the format string in the
7677         // programmer's language, and should be checked.
7678         const ObjCInterfaceDecl *IFace;
7679         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7680             IFace->getIdentifier()->isStr("NSBundle") &&
7681             MD->getSelector().isKeywordSelector(
7682                 {"localizedStringForKey", "value", "table"})) {
7683           IgnoreStringsWithoutSpecifiers = true;
7684         }
7685 
7686         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7687         return checkFormatStringExpr(
7688             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7689             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7690             IgnoreStringsWithoutSpecifiers);
7691       }
7692     }
7693 
7694     return SLCT_NotALiteral;
7695   }
7696   case Stmt::ObjCStringLiteralClass:
7697   case Stmt::StringLiteralClass: {
7698     const StringLiteral *StrE = nullptr;
7699 
7700     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7701       StrE = ObjCFExpr->getString();
7702     else
7703       StrE = cast<StringLiteral>(E);
7704 
7705     if (StrE) {
7706       if (Offset.isNegative() || Offset > StrE->getLength()) {
7707         // TODO: It would be better to have an explicit warning for out of
7708         // bounds literals.
7709         return SLCT_NotALiteral;
7710       }
7711       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7712       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7713                         firstDataArg, Type, InFunctionCall, CallType,
7714                         CheckedVarArgs, UncoveredArg,
7715                         IgnoreStringsWithoutSpecifiers);
7716       return SLCT_CheckedLiteral;
7717     }
7718 
7719     return SLCT_NotALiteral;
7720   }
7721   case Stmt::BinaryOperatorClass: {
7722     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7723 
7724     // A string literal + an int offset is still a string literal.
7725     if (BinOp->isAdditiveOp()) {
7726       Expr::EvalResult LResult, RResult;
7727 
7728       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7729           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7730       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7731           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7732 
7733       if (LIsInt != RIsInt) {
7734         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7735 
7736         if (LIsInt) {
7737           if (BinOpKind == BO_Add) {
7738             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7739             E = BinOp->getRHS();
7740             goto tryAgain;
7741           }
7742         } else {
7743           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7744           E = BinOp->getLHS();
7745           goto tryAgain;
7746         }
7747       }
7748     }
7749 
7750     return SLCT_NotALiteral;
7751   }
7752   case Stmt::UnaryOperatorClass: {
7753     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7754     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7755     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7756       Expr::EvalResult IndexResult;
7757       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7758                                        Expr::SE_NoSideEffects,
7759                                        S.isConstantEvaluated())) {
7760         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7761                    /*RHS is int*/ true);
7762         E = ASE->getBase();
7763         goto tryAgain;
7764       }
7765     }
7766 
7767     return SLCT_NotALiteral;
7768   }
7769 
7770   default:
7771     return SLCT_NotALiteral;
7772   }
7773 }
7774 
7775 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7776   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7777       .Case("scanf", FST_Scanf)
7778       .Cases("printf", "printf0", FST_Printf)
7779       .Cases("NSString", "CFString", FST_NSString)
7780       .Case("strftime", FST_Strftime)
7781       .Case("strfmon", FST_Strfmon)
7782       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7783       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7784       .Case("os_trace", FST_OSLog)
7785       .Case("os_log", FST_OSLog)
7786       .Default(FST_Unknown);
7787 }
7788 
7789 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7790 /// functions) for correct use of format strings.
7791 /// Returns true if a format string has been fully checked.
7792 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7793                                 ArrayRef<const Expr *> Args,
7794                                 bool IsCXXMember,
7795                                 VariadicCallType CallType,
7796                                 SourceLocation Loc, SourceRange Range,
7797                                 llvm::SmallBitVector &CheckedVarArgs) {
7798   FormatStringInfo FSI;
7799   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7800     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7801                                 FSI.FirstDataArg, GetFormatStringType(Format),
7802                                 CallType, Loc, Range, CheckedVarArgs);
7803   return false;
7804 }
7805 
7806 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7807                                 bool HasVAListArg, unsigned format_idx,
7808                                 unsigned firstDataArg, FormatStringType Type,
7809                                 VariadicCallType CallType,
7810                                 SourceLocation Loc, SourceRange Range,
7811                                 llvm::SmallBitVector &CheckedVarArgs) {
7812   // CHECK: printf/scanf-like function is called with no format string.
7813   if (format_idx >= Args.size()) {
7814     Diag(Loc, diag::warn_missing_format_string) << Range;
7815     return false;
7816   }
7817 
7818   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7819 
7820   // CHECK: format string is not a string literal.
7821   //
7822   // Dynamically generated format strings are difficult to
7823   // automatically vet at compile time.  Requiring that format strings
7824   // are string literals: (1) permits the checking of format strings by
7825   // the compiler and thereby (2) can practically remove the source of
7826   // many format string exploits.
7827 
7828   // Format string can be either ObjC string (e.g. @"%d") or
7829   // C string (e.g. "%d")
7830   // ObjC string uses the same format specifiers as C string, so we can use
7831   // the same format string checking logic for both ObjC and C strings.
7832   UncoveredArgHandler UncoveredArg;
7833   StringLiteralCheckType CT =
7834       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7835                             format_idx, firstDataArg, Type, CallType,
7836                             /*IsFunctionCall*/ true, CheckedVarArgs,
7837                             UncoveredArg,
7838                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7839 
7840   // Generate a diagnostic where an uncovered argument is detected.
7841   if (UncoveredArg.hasUncoveredArg()) {
7842     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7843     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7844     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7845   }
7846 
7847   if (CT != SLCT_NotALiteral)
7848     // Literal format string found, check done!
7849     return CT == SLCT_CheckedLiteral;
7850 
7851   // Strftime is particular as it always uses a single 'time' argument,
7852   // so it is safe to pass a non-literal string.
7853   if (Type == FST_Strftime)
7854     return false;
7855 
7856   // Do not emit diag when the string param is a macro expansion and the
7857   // format is either NSString or CFString. This is a hack to prevent
7858   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7859   // which are usually used in place of NS and CF string literals.
7860   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7861   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7862     return false;
7863 
7864   // If there are no arguments specified, warn with -Wformat-security, otherwise
7865   // warn only with -Wformat-nonliteral.
7866   if (Args.size() == firstDataArg) {
7867     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7868       << OrigFormatExpr->getSourceRange();
7869     switch (Type) {
7870     default:
7871       break;
7872     case FST_Kprintf:
7873     case FST_FreeBSDKPrintf:
7874     case FST_Printf:
7875       Diag(FormatLoc, diag::note_format_security_fixit)
7876         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7877       break;
7878     case FST_NSString:
7879       Diag(FormatLoc, diag::note_format_security_fixit)
7880         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7881       break;
7882     }
7883   } else {
7884     Diag(FormatLoc, diag::warn_format_nonliteral)
7885       << OrigFormatExpr->getSourceRange();
7886   }
7887   return false;
7888 }
7889 
7890 namespace {
7891 
7892 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7893 protected:
7894   Sema &S;
7895   const FormatStringLiteral *FExpr;
7896   const Expr *OrigFormatExpr;
7897   const Sema::FormatStringType FSType;
7898   const unsigned FirstDataArg;
7899   const unsigned NumDataArgs;
7900   const char *Beg; // Start of format string.
7901   const bool HasVAListArg;
7902   ArrayRef<const Expr *> Args;
7903   unsigned FormatIdx;
7904   llvm::SmallBitVector CoveredArgs;
7905   bool usesPositionalArgs = false;
7906   bool atFirstArg = true;
7907   bool inFunctionCall;
7908   Sema::VariadicCallType CallType;
7909   llvm::SmallBitVector &CheckedVarArgs;
7910   UncoveredArgHandler &UncoveredArg;
7911 
7912 public:
7913   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7914                      const Expr *origFormatExpr,
7915                      const Sema::FormatStringType type, unsigned firstDataArg,
7916                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7917                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7918                      bool inFunctionCall, Sema::VariadicCallType callType,
7919                      llvm::SmallBitVector &CheckedVarArgs,
7920                      UncoveredArgHandler &UncoveredArg)
7921       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7922         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7923         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7924         inFunctionCall(inFunctionCall), CallType(callType),
7925         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7926     CoveredArgs.resize(numDataArgs);
7927     CoveredArgs.reset();
7928   }
7929 
7930   void DoneProcessing();
7931 
7932   void HandleIncompleteSpecifier(const char *startSpecifier,
7933                                  unsigned specifierLen) override;
7934 
7935   void HandleInvalidLengthModifier(
7936                            const analyze_format_string::FormatSpecifier &FS,
7937                            const analyze_format_string::ConversionSpecifier &CS,
7938                            const char *startSpecifier, unsigned specifierLen,
7939                            unsigned DiagID);
7940 
7941   void HandleNonStandardLengthModifier(
7942                     const analyze_format_string::FormatSpecifier &FS,
7943                     const char *startSpecifier, unsigned specifierLen);
7944 
7945   void HandleNonStandardConversionSpecifier(
7946                     const analyze_format_string::ConversionSpecifier &CS,
7947                     const char *startSpecifier, unsigned specifierLen);
7948 
7949   void HandlePosition(const char *startPos, unsigned posLen) override;
7950 
7951   void HandleInvalidPosition(const char *startSpecifier,
7952                              unsigned specifierLen,
7953                              analyze_format_string::PositionContext p) override;
7954 
7955   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7956 
7957   void HandleNullChar(const char *nullCharacter) override;
7958 
7959   template <typename Range>
7960   static void
7961   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7962                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7963                        bool IsStringLocation, Range StringRange,
7964                        ArrayRef<FixItHint> Fixit = None);
7965 
7966 protected:
7967   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7968                                         const char *startSpec,
7969                                         unsigned specifierLen,
7970                                         const char *csStart, unsigned csLen);
7971 
7972   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7973                                          const char *startSpec,
7974                                          unsigned specifierLen);
7975 
7976   SourceRange getFormatStringRange();
7977   CharSourceRange getSpecifierRange(const char *startSpecifier,
7978                                     unsigned specifierLen);
7979   SourceLocation getLocationOfByte(const char *x);
7980 
7981   const Expr *getDataArg(unsigned i) const;
7982 
7983   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7984                     const analyze_format_string::ConversionSpecifier &CS,
7985                     const char *startSpecifier, unsigned specifierLen,
7986                     unsigned argIndex);
7987 
7988   template <typename Range>
7989   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7990                             bool IsStringLocation, Range StringRange,
7991                             ArrayRef<FixItHint> Fixit = None);
7992 };
7993 
7994 } // namespace
7995 
7996 SourceRange CheckFormatHandler::getFormatStringRange() {
7997   return OrigFormatExpr->getSourceRange();
7998 }
7999 
8000 CharSourceRange CheckFormatHandler::
8001 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8002   SourceLocation Start = getLocationOfByte(startSpecifier);
8003   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8004 
8005   // Advance the end SourceLocation by one due to half-open ranges.
8006   End = End.getLocWithOffset(1);
8007 
8008   return CharSourceRange::getCharRange(Start, End);
8009 }
8010 
8011 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8012   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8013                                   S.getLangOpts(), S.Context.getTargetInfo());
8014 }
8015 
8016 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8017                                                    unsigned specifierLen){
8018   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8019                        getLocationOfByte(startSpecifier),
8020                        /*IsStringLocation*/true,
8021                        getSpecifierRange(startSpecifier, specifierLen));
8022 }
8023 
8024 void CheckFormatHandler::HandleInvalidLengthModifier(
8025     const analyze_format_string::FormatSpecifier &FS,
8026     const analyze_format_string::ConversionSpecifier &CS,
8027     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8028   using namespace analyze_format_string;
8029 
8030   const LengthModifier &LM = FS.getLengthModifier();
8031   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8032 
8033   // See if we know how to fix this length modifier.
8034   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8035   if (FixedLM) {
8036     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8037                          getLocationOfByte(LM.getStart()),
8038                          /*IsStringLocation*/true,
8039                          getSpecifierRange(startSpecifier, specifierLen));
8040 
8041     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8042       << FixedLM->toString()
8043       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8044 
8045   } else {
8046     FixItHint Hint;
8047     if (DiagID == diag::warn_format_nonsensical_length)
8048       Hint = FixItHint::CreateRemoval(LMRange);
8049 
8050     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8051                          getLocationOfByte(LM.getStart()),
8052                          /*IsStringLocation*/true,
8053                          getSpecifierRange(startSpecifier, specifierLen),
8054                          Hint);
8055   }
8056 }
8057 
8058 void CheckFormatHandler::HandleNonStandardLengthModifier(
8059     const analyze_format_string::FormatSpecifier &FS,
8060     const char *startSpecifier, unsigned specifierLen) {
8061   using namespace analyze_format_string;
8062 
8063   const LengthModifier &LM = FS.getLengthModifier();
8064   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8065 
8066   // See if we know how to fix this length modifier.
8067   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8068   if (FixedLM) {
8069     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8070                            << LM.toString() << 0,
8071                          getLocationOfByte(LM.getStart()),
8072                          /*IsStringLocation*/true,
8073                          getSpecifierRange(startSpecifier, specifierLen));
8074 
8075     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8076       << FixedLM->toString()
8077       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8078 
8079   } else {
8080     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8081                            << LM.toString() << 0,
8082                          getLocationOfByte(LM.getStart()),
8083                          /*IsStringLocation*/true,
8084                          getSpecifierRange(startSpecifier, specifierLen));
8085   }
8086 }
8087 
8088 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8089     const analyze_format_string::ConversionSpecifier &CS,
8090     const char *startSpecifier, unsigned specifierLen) {
8091   using namespace analyze_format_string;
8092 
8093   // See if we know how to fix this conversion specifier.
8094   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8095   if (FixedCS) {
8096     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8097                           << CS.toString() << /*conversion specifier*/1,
8098                          getLocationOfByte(CS.getStart()),
8099                          /*IsStringLocation*/true,
8100                          getSpecifierRange(startSpecifier, specifierLen));
8101 
8102     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8103     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8104       << FixedCS->toString()
8105       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8106   } else {
8107     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8108                           << CS.toString() << /*conversion specifier*/1,
8109                          getLocationOfByte(CS.getStart()),
8110                          /*IsStringLocation*/true,
8111                          getSpecifierRange(startSpecifier, specifierLen));
8112   }
8113 }
8114 
8115 void CheckFormatHandler::HandlePosition(const char *startPos,
8116                                         unsigned posLen) {
8117   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8118                                getLocationOfByte(startPos),
8119                                /*IsStringLocation*/true,
8120                                getSpecifierRange(startPos, posLen));
8121 }
8122 
8123 void
8124 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8125                                      analyze_format_string::PositionContext p) {
8126   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8127                          << (unsigned) p,
8128                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8129                        getSpecifierRange(startPos, posLen));
8130 }
8131 
8132 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8133                                             unsigned posLen) {
8134   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8135                                getLocationOfByte(startPos),
8136                                /*IsStringLocation*/true,
8137                                getSpecifierRange(startPos, posLen));
8138 }
8139 
8140 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8141   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8142     // The presence of a null character is likely an error.
8143     EmitFormatDiagnostic(
8144       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8145       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8146       getFormatStringRange());
8147   }
8148 }
8149 
8150 // Note that this may return NULL if there was an error parsing or building
8151 // one of the argument expressions.
8152 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8153   return Args[FirstDataArg + i];
8154 }
8155 
8156 void CheckFormatHandler::DoneProcessing() {
8157   // Does the number of data arguments exceed the number of
8158   // format conversions in the format string?
8159   if (!HasVAListArg) {
8160       // Find any arguments that weren't covered.
8161     CoveredArgs.flip();
8162     signed notCoveredArg = CoveredArgs.find_first();
8163     if (notCoveredArg >= 0) {
8164       assert((unsigned)notCoveredArg < NumDataArgs);
8165       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8166     } else {
8167       UncoveredArg.setAllCovered();
8168     }
8169   }
8170 }
8171 
8172 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8173                                    const Expr *ArgExpr) {
8174   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8175          "Invalid state");
8176 
8177   if (!ArgExpr)
8178     return;
8179 
8180   SourceLocation Loc = ArgExpr->getBeginLoc();
8181 
8182   if (S.getSourceManager().isInSystemMacro(Loc))
8183     return;
8184 
8185   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8186   for (auto E : DiagnosticExprs)
8187     PDiag << E->getSourceRange();
8188 
8189   CheckFormatHandler::EmitFormatDiagnostic(
8190                                   S, IsFunctionCall, DiagnosticExprs[0],
8191                                   PDiag, Loc, /*IsStringLocation*/false,
8192                                   DiagnosticExprs[0]->getSourceRange());
8193 }
8194 
8195 bool
8196 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8197                                                      SourceLocation Loc,
8198                                                      const char *startSpec,
8199                                                      unsigned specifierLen,
8200                                                      const char *csStart,
8201                                                      unsigned csLen) {
8202   bool keepGoing = true;
8203   if (argIndex < NumDataArgs) {
8204     // Consider the argument coverered, even though the specifier doesn't
8205     // make sense.
8206     CoveredArgs.set(argIndex);
8207   }
8208   else {
8209     // If argIndex exceeds the number of data arguments we
8210     // don't issue a warning because that is just a cascade of warnings (and
8211     // they may have intended '%%' anyway). We don't want to continue processing
8212     // the format string after this point, however, as we will like just get
8213     // gibberish when trying to match arguments.
8214     keepGoing = false;
8215   }
8216 
8217   StringRef Specifier(csStart, csLen);
8218 
8219   // If the specifier in non-printable, it could be the first byte of a UTF-8
8220   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8221   // hex value.
8222   std::string CodePointStr;
8223   if (!llvm::sys::locale::isPrint(*csStart)) {
8224     llvm::UTF32 CodePoint;
8225     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8226     const llvm::UTF8 *E =
8227         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8228     llvm::ConversionResult Result =
8229         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8230 
8231     if (Result != llvm::conversionOK) {
8232       unsigned char FirstChar = *csStart;
8233       CodePoint = (llvm::UTF32)FirstChar;
8234     }
8235 
8236     llvm::raw_string_ostream OS(CodePointStr);
8237     if (CodePoint < 256)
8238       OS << "\\x" << llvm::format("%02x", CodePoint);
8239     else if (CodePoint <= 0xFFFF)
8240       OS << "\\u" << llvm::format("%04x", CodePoint);
8241     else
8242       OS << "\\U" << llvm::format("%08x", CodePoint);
8243     OS.flush();
8244     Specifier = CodePointStr;
8245   }
8246 
8247   EmitFormatDiagnostic(
8248       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8249       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8250 
8251   return keepGoing;
8252 }
8253 
8254 void
8255 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8256                                                       const char *startSpec,
8257                                                       unsigned specifierLen) {
8258   EmitFormatDiagnostic(
8259     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8260     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8261 }
8262 
8263 bool
8264 CheckFormatHandler::CheckNumArgs(
8265   const analyze_format_string::FormatSpecifier &FS,
8266   const analyze_format_string::ConversionSpecifier &CS,
8267   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8268 
8269   if (argIndex >= NumDataArgs) {
8270     PartialDiagnostic PDiag = FS.usesPositionalArg()
8271       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8272            << (argIndex+1) << NumDataArgs)
8273       : S.PDiag(diag::warn_printf_insufficient_data_args);
8274     EmitFormatDiagnostic(
8275       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8276       getSpecifierRange(startSpecifier, specifierLen));
8277 
8278     // Since more arguments than conversion tokens are given, by extension
8279     // all arguments are covered, so mark this as so.
8280     UncoveredArg.setAllCovered();
8281     return false;
8282   }
8283   return true;
8284 }
8285 
8286 template<typename Range>
8287 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8288                                               SourceLocation Loc,
8289                                               bool IsStringLocation,
8290                                               Range StringRange,
8291                                               ArrayRef<FixItHint> FixIt) {
8292   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8293                        Loc, IsStringLocation, StringRange, FixIt);
8294 }
8295 
8296 /// If the format string is not within the function call, emit a note
8297 /// so that the function call and string are in diagnostic messages.
8298 ///
8299 /// \param InFunctionCall if true, the format string is within the function
8300 /// call and only one diagnostic message will be produced.  Otherwise, an
8301 /// extra note will be emitted pointing to location of the format string.
8302 ///
8303 /// \param ArgumentExpr the expression that is passed as the format string
8304 /// argument in the function call.  Used for getting locations when two
8305 /// diagnostics are emitted.
8306 ///
8307 /// \param PDiag the callee should already have provided any strings for the
8308 /// diagnostic message.  This function only adds locations and fixits
8309 /// to diagnostics.
8310 ///
8311 /// \param Loc primary location for diagnostic.  If two diagnostics are
8312 /// required, one will be at Loc and a new SourceLocation will be created for
8313 /// the other one.
8314 ///
8315 /// \param IsStringLocation if true, Loc points to the format string should be
8316 /// used for the note.  Otherwise, Loc points to the argument list and will
8317 /// be used with PDiag.
8318 ///
8319 /// \param StringRange some or all of the string to highlight.  This is
8320 /// templated so it can accept either a CharSourceRange or a SourceRange.
8321 ///
8322 /// \param FixIt optional fix it hint for the format string.
8323 template <typename Range>
8324 void CheckFormatHandler::EmitFormatDiagnostic(
8325     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8326     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8327     Range StringRange, ArrayRef<FixItHint> FixIt) {
8328   if (InFunctionCall) {
8329     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8330     D << StringRange;
8331     D << FixIt;
8332   } else {
8333     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8334       << ArgumentExpr->getSourceRange();
8335 
8336     const Sema::SemaDiagnosticBuilder &Note =
8337       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8338              diag::note_format_string_defined);
8339 
8340     Note << StringRange;
8341     Note << FixIt;
8342   }
8343 }
8344 
8345 //===--- CHECK: Printf format string checking ------------------------------===//
8346 
8347 namespace {
8348 
8349 class CheckPrintfHandler : public CheckFormatHandler {
8350 public:
8351   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8352                      const Expr *origFormatExpr,
8353                      const Sema::FormatStringType type, unsigned firstDataArg,
8354                      unsigned numDataArgs, bool isObjC, const char *beg,
8355                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8356                      unsigned formatIdx, bool inFunctionCall,
8357                      Sema::VariadicCallType CallType,
8358                      llvm::SmallBitVector &CheckedVarArgs,
8359                      UncoveredArgHandler &UncoveredArg)
8360       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8361                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8362                            inFunctionCall, CallType, CheckedVarArgs,
8363                            UncoveredArg) {}
8364 
8365   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8366 
8367   /// Returns true if '%@' specifiers are allowed in the format string.
8368   bool allowsObjCArg() const {
8369     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8370            FSType == Sema::FST_OSTrace;
8371   }
8372 
8373   bool HandleInvalidPrintfConversionSpecifier(
8374                                       const analyze_printf::PrintfSpecifier &FS,
8375                                       const char *startSpecifier,
8376                                       unsigned specifierLen) override;
8377 
8378   void handleInvalidMaskType(StringRef MaskType) override;
8379 
8380   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8381                              const char *startSpecifier,
8382                              unsigned specifierLen) override;
8383   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8384                        const char *StartSpecifier,
8385                        unsigned SpecifierLen,
8386                        const Expr *E);
8387 
8388   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8389                     const char *startSpecifier, unsigned specifierLen);
8390   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8391                            const analyze_printf::OptionalAmount &Amt,
8392                            unsigned type,
8393                            const char *startSpecifier, unsigned specifierLen);
8394   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8395                   const analyze_printf::OptionalFlag &flag,
8396                   const char *startSpecifier, unsigned specifierLen);
8397   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8398                          const analyze_printf::OptionalFlag &ignoredFlag,
8399                          const analyze_printf::OptionalFlag &flag,
8400                          const char *startSpecifier, unsigned specifierLen);
8401   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8402                            const Expr *E);
8403 
8404   void HandleEmptyObjCModifierFlag(const char *startFlag,
8405                                    unsigned flagLen) override;
8406 
8407   void HandleInvalidObjCModifierFlag(const char *startFlag,
8408                                             unsigned flagLen) override;
8409 
8410   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8411                                            const char *flagsEnd,
8412                                            const char *conversionPosition)
8413                                              override;
8414 };
8415 
8416 } // namespace
8417 
8418 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8419                                       const analyze_printf::PrintfSpecifier &FS,
8420                                       const char *startSpecifier,
8421                                       unsigned specifierLen) {
8422   const analyze_printf::PrintfConversionSpecifier &CS =
8423     FS.getConversionSpecifier();
8424 
8425   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8426                                           getLocationOfByte(CS.getStart()),
8427                                           startSpecifier, specifierLen,
8428                                           CS.getStart(), CS.getLength());
8429 }
8430 
8431 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8432   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8433 }
8434 
8435 bool CheckPrintfHandler::HandleAmount(
8436                                const analyze_format_string::OptionalAmount &Amt,
8437                                unsigned k, const char *startSpecifier,
8438                                unsigned specifierLen) {
8439   if (Amt.hasDataArgument()) {
8440     if (!HasVAListArg) {
8441       unsigned argIndex = Amt.getArgIndex();
8442       if (argIndex >= NumDataArgs) {
8443         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8444                                << k,
8445                              getLocationOfByte(Amt.getStart()),
8446                              /*IsStringLocation*/true,
8447                              getSpecifierRange(startSpecifier, specifierLen));
8448         // Don't do any more checking.  We will just emit
8449         // spurious errors.
8450         return false;
8451       }
8452 
8453       // Type check the data argument.  It should be an 'int'.
8454       // Although not in conformance with C99, we also allow the argument to be
8455       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8456       // doesn't emit a warning for that case.
8457       CoveredArgs.set(argIndex);
8458       const Expr *Arg = getDataArg(argIndex);
8459       if (!Arg)
8460         return false;
8461 
8462       QualType T = Arg->getType();
8463 
8464       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8465       assert(AT.isValid());
8466 
8467       if (!AT.matchesType(S.Context, T)) {
8468         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8469                                << k << AT.getRepresentativeTypeName(S.Context)
8470                                << T << Arg->getSourceRange(),
8471                              getLocationOfByte(Amt.getStart()),
8472                              /*IsStringLocation*/true,
8473                              getSpecifierRange(startSpecifier, specifierLen));
8474         // Don't do any more checking.  We will just emit
8475         // spurious errors.
8476         return false;
8477       }
8478     }
8479   }
8480   return true;
8481 }
8482 
8483 void CheckPrintfHandler::HandleInvalidAmount(
8484                                       const analyze_printf::PrintfSpecifier &FS,
8485                                       const analyze_printf::OptionalAmount &Amt,
8486                                       unsigned type,
8487                                       const char *startSpecifier,
8488                                       unsigned specifierLen) {
8489   const analyze_printf::PrintfConversionSpecifier &CS =
8490     FS.getConversionSpecifier();
8491 
8492   FixItHint fixit =
8493     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8494       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8495                                  Amt.getConstantLength()))
8496       : FixItHint();
8497 
8498   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8499                          << type << CS.toString(),
8500                        getLocationOfByte(Amt.getStart()),
8501                        /*IsStringLocation*/true,
8502                        getSpecifierRange(startSpecifier, specifierLen),
8503                        fixit);
8504 }
8505 
8506 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8507                                     const analyze_printf::OptionalFlag &flag,
8508                                     const char *startSpecifier,
8509                                     unsigned specifierLen) {
8510   // Warn about pointless flag with a fixit removal.
8511   const analyze_printf::PrintfConversionSpecifier &CS =
8512     FS.getConversionSpecifier();
8513   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8514                          << flag.toString() << CS.toString(),
8515                        getLocationOfByte(flag.getPosition()),
8516                        /*IsStringLocation*/true,
8517                        getSpecifierRange(startSpecifier, specifierLen),
8518                        FixItHint::CreateRemoval(
8519                          getSpecifierRange(flag.getPosition(), 1)));
8520 }
8521 
8522 void CheckPrintfHandler::HandleIgnoredFlag(
8523                                 const analyze_printf::PrintfSpecifier &FS,
8524                                 const analyze_printf::OptionalFlag &ignoredFlag,
8525                                 const analyze_printf::OptionalFlag &flag,
8526                                 const char *startSpecifier,
8527                                 unsigned specifierLen) {
8528   // Warn about ignored flag with a fixit removal.
8529   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8530                          << ignoredFlag.toString() << flag.toString(),
8531                        getLocationOfByte(ignoredFlag.getPosition()),
8532                        /*IsStringLocation*/true,
8533                        getSpecifierRange(startSpecifier, specifierLen),
8534                        FixItHint::CreateRemoval(
8535                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8536 }
8537 
8538 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8539                                                      unsigned flagLen) {
8540   // Warn about an empty flag.
8541   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8542                        getLocationOfByte(startFlag),
8543                        /*IsStringLocation*/true,
8544                        getSpecifierRange(startFlag, flagLen));
8545 }
8546 
8547 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8548                                                        unsigned flagLen) {
8549   // Warn about an invalid flag.
8550   auto Range = getSpecifierRange(startFlag, flagLen);
8551   StringRef flag(startFlag, flagLen);
8552   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8553                       getLocationOfByte(startFlag),
8554                       /*IsStringLocation*/true,
8555                       Range, FixItHint::CreateRemoval(Range));
8556 }
8557 
8558 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8559     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8560     // Warn about using '[...]' without a '@' conversion.
8561     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8562     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8563     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8564                          getLocationOfByte(conversionPosition),
8565                          /*IsStringLocation*/true,
8566                          Range, FixItHint::CreateRemoval(Range));
8567 }
8568 
8569 // Determines if the specified is a C++ class or struct containing
8570 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8571 // "c_str()").
8572 template<typename MemberKind>
8573 static llvm::SmallPtrSet<MemberKind*, 1>
8574 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8575   const RecordType *RT = Ty->getAs<RecordType>();
8576   llvm::SmallPtrSet<MemberKind*, 1> Results;
8577 
8578   if (!RT)
8579     return Results;
8580   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8581   if (!RD || !RD->getDefinition())
8582     return Results;
8583 
8584   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8585                  Sema::LookupMemberName);
8586   R.suppressDiagnostics();
8587 
8588   // We just need to include all members of the right kind turned up by the
8589   // filter, at this point.
8590   if (S.LookupQualifiedName(R, RT->getDecl()))
8591     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8592       NamedDecl *decl = (*I)->getUnderlyingDecl();
8593       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8594         Results.insert(FK);
8595     }
8596   return Results;
8597 }
8598 
8599 /// Check if we could call '.c_str()' on an object.
8600 ///
8601 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8602 /// allow the call, or if it would be ambiguous).
8603 bool Sema::hasCStrMethod(const Expr *E) {
8604   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8605 
8606   MethodSet Results =
8607       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8608   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8609        MI != ME; ++MI)
8610     if ((*MI)->getMinRequiredArguments() == 0)
8611       return true;
8612   return false;
8613 }
8614 
8615 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8616 // better diagnostic if so. AT is assumed to be valid.
8617 // Returns true when a c_str() conversion method is found.
8618 bool CheckPrintfHandler::checkForCStrMembers(
8619     const analyze_printf::ArgType &AT, const Expr *E) {
8620   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8621 
8622   MethodSet Results =
8623       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8624 
8625   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8626        MI != ME; ++MI) {
8627     const CXXMethodDecl *Method = *MI;
8628     if (Method->getMinRequiredArguments() == 0 &&
8629         AT.matchesType(S.Context, Method->getReturnType())) {
8630       // FIXME: Suggest parens if the expression needs them.
8631       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8632       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8633           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8634       return true;
8635     }
8636   }
8637 
8638   return false;
8639 }
8640 
8641 bool
8642 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8643                                             &FS,
8644                                           const char *startSpecifier,
8645                                           unsigned specifierLen) {
8646   using namespace analyze_format_string;
8647   using namespace analyze_printf;
8648 
8649   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8650 
8651   if (FS.consumesDataArgument()) {
8652     if (atFirstArg) {
8653         atFirstArg = false;
8654         usesPositionalArgs = FS.usesPositionalArg();
8655     }
8656     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8657       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8658                                         startSpecifier, specifierLen);
8659       return false;
8660     }
8661   }
8662 
8663   // First check if the field width, precision, and conversion specifier
8664   // have matching data arguments.
8665   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8666                     startSpecifier, specifierLen)) {
8667     return false;
8668   }
8669 
8670   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8671                     startSpecifier, specifierLen)) {
8672     return false;
8673   }
8674 
8675   if (!CS.consumesDataArgument()) {
8676     // FIXME: Technically specifying a precision or field width here
8677     // makes no sense.  Worth issuing a warning at some point.
8678     return true;
8679   }
8680 
8681   // Consume the argument.
8682   unsigned argIndex = FS.getArgIndex();
8683   if (argIndex < NumDataArgs) {
8684     // The check to see if the argIndex is valid will come later.
8685     // We set the bit here because we may exit early from this
8686     // function if we encounter some other error.
8687     CoveredArgs.set(argIndex);
8688   }
8689 
8690   // FreeBSD kernel extensions.
8691   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8692       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8693     // We need at least two arguments.
8694     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8695       return false;
8696 
8697     // Claim the second argument.
8698     CoveredArgs.set(argIndex + 1);
8699 
8700     // Type check the first argument (int for %b, pointer for %D)
8701     const Expr *Ex = getDataArg(argIndex);
8702     const analyze_printf::ArgType &AT =
8703       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8704         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8705     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8706       EmitFormatDiagnostic(
8707           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8708               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8709               << false << Ex->getSourceRange(),
8710           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8711           getSpecifierRange(startSpecifier, specifierLen));
8712 
8713     // Type check the second argument (char * for both %b and %D)
8714     Ex = getDataArg(argIndex + 1);
8715     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8716     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8717       EmitFormatDiagnostic(
8718           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8719               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8720               << false << Ex->getSourceRange(),
8721           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8722           getSpecifierRange(startSpecifier, specifierLen));
8723 
8724      return true;
8725   }
8726 
8727   // Check for using an Objective-C specific conversion specifier
8728   // in a non-ObjC literal.
8729   if (!allowsObjCArg() && CS.isObjCArg()) {
8730     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8731                                                   specifierLen);
8732   }
8733 
8734   // %P can only be used with os_log.
8735   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8736     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8737                                                   specifierLen);
8738   }
8739 
8740   // %n is not allowed with os_log.
8741   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8742     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8743                          getLocationOfByte(CS.getStart()),
8744                          /*IsStringLocation*/ false,
8745                          getSpecifierRange(startSpecifier, specifierLen));
8746 
8747     return true;
8748   }
8749 
8750   // Only scalars are allowed for os_trace.
8751   if (FSType == Sema::FST_OSTrace &&
8752       (CS.getKind() == ConversionSpecifier::PArg ||
8753        CS.getKind() == ConversionSpecifier::sArg ||
8754        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8755     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8756                                                   specifierLen);
8757   }
8758 
8759   // Check for use of public/private annotation outside of os_log().
8760   if (FSType != Sema::FST_OSLog) {
8761     if (FS.isPublic().isSet()) {
8762       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8763                                << "public",
8764                            getLocationOfByte(FS.isPublic().getPosition()),
8765                            /*IsStringLocation*/ false,
8766                            getSpecifierRange(startSpecifier, specifierLen));
8767     }
8768     if (FS.isPrivate().isSet()) {
8769       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8770                                << "private",
8771                            getLocationOfByte(FS.isPrivate().getPosition()),
8772                            /*IsStringLocation*/ false,
8773                            getSpecifierRange(startSpecifier, specifierLen));
8774     }
8775   }
8776 
8777   // Check for invalid use of field width
8778   if (!FS.hasValidFieldWidth()) {
8779     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8780         startSpecifier, specifierLen);
8781   }
8782 
8783   // Check for invalid use of precision
8784   if (!FS.hasValidPrecision()) {
8785     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8786         startSpecifier, specifierLen);
8787   }
8788 
8789   // Precision is mandatory for %P specifier.
8790   if (CS.getKind() == ConversionSpecifier::PArg &&
8791       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8792     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8793                          getLocationOfByte(startSpecifier),
8794                          /*IsStringLocation*/ false,
8795                          getSpecifierRange(startSpecifier, specifierLen));
8796   }
8797 
8798   // Check each flag does not conflict with any other component.
8799   if (!FS.hasValidThousandsGroupingPrefix())
8800     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8801   if (!FS.hasValidLeadingZeros())
8802     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8803   if (!FS.hasValidPlusPrefix())
8804     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8805   if (!FS.hasValidSpacePrefix())
8806     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8807   if (!FS.hasValidAlternativeForm())
8808     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8809   if (!FS.hasValidLeftJustified())
8810     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8811 
8812   // Check that flags are not ignored by another flag
8813   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8814     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8815         startSpecifier, specifierLen);
8816   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8817     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8818             startSpecifier, specifierLen);
8819 
8820   // Check the length modifier is valid with the given conversion specifier.
8821   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8822                                  S.getLangOpts()))
8823     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8824                                 diag::warn_format_nonsensical_length);
8825   else if (!FS.hasStandardLengthModifier())
8826     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8827   else if (!FS.hasStandardLengthConversionCombination())
8828     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8829                                 diag::warn_format_non_standard_conversion_spec);
8830 
8831   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8832     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8833 
8834   // The remaining checks depend on the data arguments.
8835   if (HasVAListArg)
8836     return true;
8837 
8838   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8839     return false;
8840 
8841   const Expr *Arg = getDataArg(argIndex);
8842   if (!Arg)
8843     return true;
8844 
8845   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8846 }
8847 
8848 static bool requiresParensToAddCast(const Expr *E) {
8849   // FIXME: We should have a general way to reason about operator
8850   // precedence and whether parens are actually needed here.
8851   // Take care of a few common cases where they aren't.
8852   const Expr *Inside = E->IgnoreImpCasts();
8853   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8854     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8855 
8856   switch (Inside->getStmtClass()) {
8857   case Stmt::ArraySubscriptExprClass:
8858   case Stmt::CallExprClass:
8859   case Stmt::CharacterLiteralClass:
8860   case Stmt::CXXBoolLiteralExprClass:
8861   case Stmt::DeclRefExprClass:
8862   case Stmt::FloatingLiteralClass:
8863   case Stmt::IntegerLiteralClass:
8864   case Stmt::MemberExprClass:
8865   case Stmt::ObjCArrayLiteralClass:
8866   case Stmt::ObjCBoolLiteralExprClass:
8867   case Stmt::ObjCBoxedExprClass:
8868   case Stmt::ObjCDictionaryLiteralClass:
8869   case Stmt::ObjCEncodeExprClass:
8870   case Stmt::ObjCIvarRefExprClass:
8871   case Stmt::ObjCMessageExprClass:
8872   case Stmt::ObjCPropertyRefExprClass:
8873   case Stmt::ObjCStringLiteralClass:
8874   case Stmt::ObjCSubscriptRefExprClass:
8875   case Stmt::ParenExprClass:
8876   case Stmt::StringLiteralClass:
8877   case Stmt::UnaryOperatorClass:
8878     return false;
8879   default:
8880     return true;
8881   }
8882 }
8883 
8884 static std::pair<QualType, StringRef>
8885 shouldNotPrintDirectly(const ASTContext &Context,
8886                        QualType IntendedTy,
8887                        const Expr *E) {
8888   // Use a 'while' to peel off layers of typedefs.
8889   QualType TyTy = IntendedTy;
8890   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8891     StringRef Name = UserTy->getDecl()->getName();
8892     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8893       .Case("CFIndex", Context.getNSIntegerType())
8894       .Case("NSInteger", Context.getNSIntegerType())
8895       .Case("NSUInteger", Context.getNSUIntegerType())
8896       .Case("SInt32", Context.IntTy)
8897       .Case("UInt32", Context.UnsignedIntTy)
8898       .Default(QualType());
8899 
8900     if (!CastTy.isNull())
8901       return std::make_pair(CastTy, Name);
8902 
8903     TyTy = UserTy->desugar();
8904   }
8905 
8906   // Strip parens if necessary.
8907   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8908     return shouldNotPrintDirectly(Context,
8909                                   PE->getSubExpr()->getType(),
8910                                   PE->getSubExpr());
8911 
8912   // If this is a conditional expression, then its result type is constructed
8913   // via usual arithmetic conversions and thus there might be no necessary
8914   // typedef sugar there.  Recurse to operands to check for NSInteger &
8915   // Co. usage condition.
8916   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8917     QualType TrueTy, FalseTy;
8918     StringRef TrueName, FalseName;
8919 
8920     std::tie(TrueTy, TrueName) =
8921       shouldNotPrintDirectly(Context,
8922                              CO->getTrueExpr()->getType(),
8923                              CO->getTrueExpr());
8924     std::tie(FalseTy, FalseName) =
8925       shouldNotPrintDirectly(Context,
8926                              CO->getFalseExpr()->getType(),
8927                              CO->getFalseExpr());
8928 
8929     if (TrueTy == FalseTy)
8930       return std::make_pair(TrueTy, TrueName);
8931     else if (TrueTy.isNull())
8932       return std::make_pair(FalseTy, FalseName);
8933     else if (FalseTy.isNull())
8934       return std::make_pair(TrueTy, TrueName);
8935   }
8936 
8937   return std::make_pair(QualType(), StringRef());
8938 }
8939 
8940 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8941 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8942 /// type do not count.
8943 static bool
8944 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8945   QualType From = ICE->getSubExpr()->getType();
8946   QualType To = ICE->getType();
8947   // It's an integer promotion if the destination type is the promoted
8948   // source type.
8949   if (ICE->getCastKind() == CK_IntegralCast &&
8950       From->isPromotableIntegerType() &&
8951       S.Context.getPromotedIntegerType(From) == To)
8952     return true;
8953   // Look through vector types, since we do default argument promotion for
8954   // those in OpenCL.
8955   if (const auto *VecTy = From->getAs<ExtVectorType>())
8956     From = VecTy->getElementType();
8957   if (const auto *VecTy = To->getAs<ExtVectorType>())
8958     To = VecTy->getElementType();
8959   // It's a floating promotion if the source type is a lower rank.
8960   return ICE->getCastKind() == CK_FloatingCast &&
8961          S.Context.getFloatingTypeOrder(From, To) < 0;
8962 }
8963 
8964 bool
8965 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8966                                     const char *StartSpecifier,
8967                                     unsigned SpecifierLen,
8968                                     const Expr *E) {
8969   using namespace analyze_format_string;
8970   using namespace analyze_printf;
8971 
8972   // Now type check the data expression that matches the
8973   // format specifier.
8974   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8975   if (!AT.isValid())
8976     return true;
8977 
8978   QualType ExprTy = E->getType();
8979   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8980     ExprTy = TET->getUnderlyingExpr()->getType();
8981   }
8982 
8983   // Diagnose attempts to print a boolean value as a character. Unlike other
8984   // -Wformat diagnostics, this is fine from a type perspective, but it still
8985   // doesn't make sense.
8986   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8987       E->isKnownToHaveBooleanValue()) {
8988     const CharSourceRange &CSR =
8989         getSpecifierRange(StartSpecifier, SpecifierLen);
8990     SmallString<4> FSString;
8991     llvm::raw_svector_ostream os(FSString);
8992     FS.toString(os);
8993     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8994                              << FSString,
8995                          E->getExprLoc(), false, CSR);
8996     return true;
8997   }
8998 
8999   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9000   if (Match == analyze_printf::ArgType::Match)
9001     return true;
9002 
9003   // Look through argument promotions for our error message's reported type.
9004   // This includes the integral and floating promotions, but excludes array
9005   // and function pointer decay (seeing that an argument intended to be a
9006   // string has type 'char [6]' is probably more confusing than 'char *') and
9007   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9008   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9009     if (isArithmeticArgumentPromotion(S, ICE)) {
9010       E = ICE->getSubExpr();
9011       ExprTy = E->getType();
9012 
9013       // Check if we didn't match because of an implicit cast from a 'char'
9014       // or 'short' to an 'int'.  This is done because printf is a varargs
9015       // function.
9016       if (ICE->getType() == S.Context.IntTy ||
9017           ICE->getType() == S.Context.UnsignedIntTy) {
9018         // All further checking is done on the subexpression
9019         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9020             AT.matchesType(S.Context, ExprTy);
9021         if (ImplicitMatch == analyze_printf::ArgType::Match)
9022           return true;
9023         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9024             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9025           Match = ImplicitMatch;
9026       }
9027     }
9028   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9029     // Special case for 'a', which has type 'int' in C.
9030     // Note, however, that we do /not/ want to treat multibyte constants like
9031     // 'MooV' as characters! This form is deprecated but still exists. In
9032     // addition, don't treat expressions as of type 'char' if one byte length
9033     // modifier is provided.
9034     if (ExprTy == S.Context.IntTy &&
9035         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9036       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9037         ExprTy = S.Context.CharTy;
9038   }
9039 
9040   // Look through enums to their underlying type.
9041   bool IsEnum = false;
9042   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9043     ExprTy = EnumTy->getDecl()->getIntegerType();
9044     IsEnum = true;
9045   }
9046 
9047   // %C in an Objective-C context prints a unichar, not a wchar_t.
9048   // If the argument is an integer of some kind, believe the %C and suggest
9049   // a cast instead of changing the conversion specifier.
9050   QualType IntendedTy = ExprTy;
9051   if (isObjCContext() &&
9052       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9053     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9054         !ExprTy->isCharType()) {
9055       // 'unichar' is defined as a typedef of unsigned short, but we should
9056       // prefer using the typedef if it is visible.
9057       IntendedTy = S.Context.UnsignedShortTy;
9058 
9059       // While we are here, check if the value is an IntegerLiteral that happens
9060       // to be within the valid range.
9061       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9062         const llvm::APInt &V = IL->getValue();
9063         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9064           return true;
9065       }
9066 
9067       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9068                           Sema::LookupOrdinaryName);
9069       if (S.LookupName(Result, S.getCurScope())) {
9070         NamedDecl *ND = Result.getFoundDecl();
9071         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9072           if (TD->getUnderlyingType() == IntendedTy)
9073             IntendedTy = S.Context.getTypedefType(TD);
9074       }
9075     }
9076   }
9077 
9078   // Special-case some of Darwin's platform-independence types by suggesting
9079   // casts to primitive types that are known to be large enough.
9080   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9081   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9082     QualType CastTy;
9083     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9084     if (!CastTy.isNull()) {
9085       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9086       // (long in ASTContext). Only complain to pedants.
9087       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9088           (AT.isSizeT() || AT.isPtrdiffT()) &&
9089           AT.matchesType(S.Context, CastTy))
9090         Match = ArgType::NoMatchPedantic;
9091       IntendedTy = CastTy;
9092       ShouldNotPrintDirectly = true;
9093     }
9094   }
9095 
9096   // We may be able to offer a FixItHint if it is a supported type.
9097   PrintfSpecifier fixedFS = FS;
9098   bool Success =
9099       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9100 
9101   if (Success) {
9102     // Get the fix string from the fixed format specifier
9103     SmallString<16> buf;
9104     llvm::raw_svector_ostream os(buf);
9105     fixedFS.toString(os);
9106 
9107     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9108 
9109     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9110       unsigned Diag;
9111       switch (Match) {
9112       case ArgType::Match: llvm_unreachable("expected non-matching");
9113       case ArgType::NoMatchPedantic:
9114         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9115         break;
9116       case ArgType::NoMatchTypeConfusion:
9117         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9118         break;
9119       case ArgType::NoMatch:
9120         Diag = diag::warn_format_conversion_argument_type_mismatch;
9121         break;
9122       }
9123 
9124       // In this case, the specifier is wrong and should be changed to match
9125       // the argument.
9126       EmitFormatDiagnostic(S.PDiag(Diag)
9127                                << AT.getRepresentativeTypeName(S.Context)
9128                                << IntendedTy << IsEnum << E->getSourceRange(),
9129                            E->getBeginLoc(),
9130                            /*IsStringLocation*/ false, SpecRange,
9131                            FixItHint::CreateReplacement(SpecRange, os.str()));
9132     } else {
9133       // The canonical type for formatting this value is different from the
9134       // actual type of the expression. (This occurs, for example, with Darwin's
9135       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9136       // should be printed as 'long' for 64-bit compatibility.)
9137       // Rather than emitting a normal format/argument mismatch, we want to
9138       // add a cast to the recommended type (and correct the format string
9139       // if necessary).
9140       SmallString<16> CastBuf;
9141       llvm::raw_svector_ostream CastFix(CastBuf);
9142       CastFix << "(";
9143       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9144       CastFix << ")";
9145 
9146       SmallVector<FixItHint,4> Hints;
9147       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9148         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9149 
9150       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9151         // If there's already a cast present, just replace it.
9152         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9153         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9154 
9155       } else if (!requiresParensToAddCast(E)) {
9156         // If the expression has high enough precedence,
9157         // just write the C-style cast.
9158         Hints.push_back(
9159             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9160       } else {
9161         // Otherwise, add parens around the expression as well as the cast.
9162         CastFix << "(";
9163         Hints.push_back(
9164             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9165 
9166         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9167         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9168       }
9169 
9170       if (ShouldNotPrintDirectly) {
9171         // The expression has a type that should not be printed directly.
9172         // We extract the name from the typedef because we don't want to show
9173         // the underlying type in the diagnostic.
9174         StringRef Name;
9175         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9176           Name = TypedefTy->getDecl()->getName();
9177         else
9178           Name = CastTyName;
9179         unsigned Diag = Match == ArgType::NoMatchPedantic
9180                             ? diag::warn_format_argument_needs_cast_pedantic
9181                             : diag::warn_format_argument_needs_cast;
9182         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9183                                            << E->getSourceRange(),
9184                              E->getBeginLoc(), /*IsStringLocation=*/false,
9185                              SpecRange, Hints);
9186       } else {
9187         // In this case, the expression could be printed using a different
9188         // specifier, but we've decided that the specifier is probably correct
9189         // and we should cast instead. Just use the normal warning message.
9190         EmitFormatDiagnostic(
9191             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9192                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9193                 << E->getSourceRange(),
9194             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9195       }
9196     }
9197   } else {
9198     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9199                                                    SpecifierLen);
9200     // Since the warning for passing non-POD types to variadic functions
9201     // was deferred until now, we emit a warning for non-POD
9202     // arguments here.
9203     switch (S.isValidVarArgType(ExprTy)) {
9204     case Sema::VAK_Valid:
9205     case Sema::VAK_ValidInCXX11: {
9206       unsigned Diag;
9207       switch (Match) {
9208       case ArgType::Match: llvm_unreachable("expected non-matching");
9209       case ArgType::NoMatchPedantic:
9210         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9211         break;
9212       case ArgType::NoMatchTypeConfusion:
9213         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9214         break;
9215       case ArgType::NoMatch:
9216         Diag = diag::warn_format_conversion_argument_type_mismatch;
9217         break;
9218       }
9219 
9220       EmitFormatDiagnostic(
9221           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9222                         << IsEnum << CSR << E->getSourceRange(),
9223           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9224       break;
9225     }
9226     case Sema::VAK_Undefined:
9227     case Sema::VAK_MSVCUndefined:
9228       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9229                                << S.getLangOpts().CPlusPlus11 << ExprTy
9230                                << CallType
9231                                << AT.getRepresentativeTypeName(S.Context) << CSR
9232                                << E->getSourceRange(),
9233                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9234       checkForCStrMembers(AT, E);
9235       break;
9236 
9237     case Sema::VAK_Invalid:
9238       if (ExprTy->isObjCObjectType())
9239         EmitFormatDiagnostic(
9240             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9241                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9242                 << AT.getRepresentativeTypeName(S.Context) << CSR
9243                 << E->getSourceRange(),
9244             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9245       else
9246         // FIXME: If this is an initializer list, suggest removing the braces
9247         // or inserting a cast to the target type.
9248         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9249             << isa<InitListExpr>(E) << ExprTy << CallType
9250             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9251       break;
9252     }
9253 
9254     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9255            "format string specifier index out of range");
9256     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9257   }
9258 
9259   return true;
9260 }
9261 
9262 //===--- CHECK: Scanf format string checking ------------------------------===//
9263 
9264 namespace {
9265 
9266 class CheckScanfHandler : public CheckFormatHandler {
9267 public:
9268   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9269                     const Expr *origFormatExpr, Sema::FormatStringType type,
9270                     unsigned firstDataArg, unsigned numDataArgs,
9271                     const char *beg, bool hasVAListArg,
9272                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9273                     bool inFunctionCall, Sema::VariadicCallType CallType,
9274                     llvm::SmallBitVector &CheckedVarArgs,
9275                     UncoveredArgHandler &UncoveredArg)
9276       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9277                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9278                            inFunctionCall, CallType, CheckedVarArgs,
9279                            UncoveredArg) {}
9280 
9281   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9282                             const char *startSpecifier,
9283                             unsigned specifierLen) override;
9284 
9285   bool HandleInvalidScanfConversionSpecifier(
9286           const analyze_scanf::ScanfSpecifier &FS,
9287           const char *startSpecifier,
9288           unsigned specifierLen) override;
9289 
9290   void HandleIncompleteScanList(const char *start, const char *end) override;
9291 };
9292 
9293 } // namespace
9294 
9295 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9296                                                  const char *end) {
9297   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9298                        getLocationOfByte(end), /*IsStringLocation*/true,
9299                        getSpecifierRange(start, end - start));
9300 }
9301 
9302 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9303                                         const analyze_scanf::ScanfSpecifier &FS,
9304                                         const char *startSpecifier,
9305                                         unsigned specifierLen) {
9306   const analyze_scanf::ScanfConversionSpecifier &CS =
9307     FS.getConversionSpecifier();
9308 
9309   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9310                                           getLocationOfByte(CS.getStart()),
9311                                           startSpecifier, specifierLen,
9312                                           CS.getStart(), CS.getLength());
9313 }
9314 
9315 bool CheckScanfHandler::HandleScanfSpecifier(
9316                                        const analyze_scanf::ScanfSpecifier &FS,
9317                                        const char *startSpecifier,
9318                                        unsigned specifierLen) {
9319   using namespace analyze_scanf;
9320   using namespace analyze_format_string;
9321 
9322   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9323 
9324   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9325   // be used to decide if we are using positional arguments consistently.
9326   if (FS.consumesDataArgument()) {
9327     if (atFirstArg) {
9328       atFirstArg = false;
9329       usesPositionalArgs = FS.usesPositionalArg();
9330     }
9331     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9332       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9333                                         startSpecifier, specifierLen);
9334       return false;
9335     }
9336   }
9337 
9338   // Check if the field with is non-zero.
9339   const OptionalAmount &Amt = FS.getFieldWidth();
9340   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9341     if (Amt.getConstantAmount() == 0) {
9342       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9343                                                    Amt.getConstantLength());
9344       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9345                            getLocationOfByte(Amt.getStart()),
9346                            /*IsStringLocation*/true, R,
9347                            FixItHint::CreateRemoval(R));
9348     }
9349   }
9350 
9351   if (!FS.consumesDataArgument()) {
9352     // FIXME: Technically specifying a precision or field width here
9353     // makes no sense.  Worth issuing a warning at some point.
9354     return true;
9355   }
9356 
9357   // Consume the argument.
9358   unsigned argIndex = FS.getArgIndex();
9359   if (argIndex < NumDataArgs) {
9360       // The check to see if the argIndex is valid will come later.
9361       // We set the bit here because we may exit early from this
9362       // function if we encounter some other error.
9363     CoveredArgs.set(argIndex);
9364   }
9365 
9366   // Check the length modifier is valid with the given conversion specifier.
9367   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9368                                  S.getLangOpts()))
9369     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9370                                 diag::warn_format_nonsensical_length);
9371   else if (!FS.hasStandardLengthModifier())
9372     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9373   else if (!FS.hasStandardLengthConversionCombination())
9374     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9375                                 diag::warn_format_non_standard_conversion_spec);
9376 
9377   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9378     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9379 
9380   // The remaining checks depend on the data arguments.
9381   if (HasVAListArg)
9382     return true;
9383 
9384   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9385     return false;
9386 
9387   // Check that the argument type matches the format specifier.
9388   const Expr *Ex = getDataArg(argIndex);
9389   if (!Ex)
9390     return true;
9391 
9392   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9393 
9394   if (!AT.isValid()) {
9395     return true;
9396   }
9397 
9398   analyze_format_string::ArgType::MatchKind Match =
9399       AT.matchesType(S.Context, Ex->getType());
9400   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9401   if (Match == analyze_format_string::ArgType::Match)
9402     return true;
9403 
9404   ScanfSpecifier fixedFS = FS;
9405   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9406                                  S.getLangOpts(), S.Context);
9407 
9408   unsigned Diag =
9409       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9410                : diag::warn_format_conversion_argument_type_mismatch;
9411 
9412   if (Success) {
9413     // Get the fix string from the fixed format specifier.
9414     SmallString<128> buf;
9415     llvm::raw_svector_ostream os(buf);
9416     fixedFS.toString(os);
9417 
9418     EmitFormatDiagnostic(
9419         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9420                       << Ex->getType() << false << Ex->getSourceRange(),
9421         Ex->getBeginLoc(),
9422         /*IsStringLocation*/ false,
9423         getSpecifierRange(startSpecifier, specifierLen),
9424         FixItHint::CreateReplacement(
9425             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9426   } else {
9427     EmitFormatDiagnostic(S.PDiag(Diag)
9428                              << AT.getRepresentativeTypeName(S.Context)
9429                              << Ex->getType() << false << Ex->getSourceRange(),
9430                          Ex->getBeginLoc(),
9431                          /*IsStringLocation*/ false,
9432                          getSpecifierRange(startSpecifier, specifierLen));
9433   }
9434 
9435   return true;
9436 }
9437 
9438 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9439                               const Expr *OrigFormatExpr,
9440                               ArrayRef<const Expr *> Args,
9441                               bool HasVAListArg, unsigned format_idx,
9442                               unsigned firstDataArg,
9443                               Sema::FormatStringType Type,
9444                               bool inFunctionCall,
9445                               Sema::VariadicCallType CallType,
9446                               llvm::SmallBitVector &CheckedVarArgs,
9447                               UncoveredArgHandler &UncoveredArg,
9448                               bool IgnoreStringsWithoutSpecifiers) {
9449   // CHECK: is the format string a wide literal?
9450   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9451     CheckFormatHandler::EmitFormatDiagnostic(
9452         S, inFunctionCall, Args[format_idx],
9453         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9454         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9455     return;
9456   }
9457 
9458   // Str - The format string.  NOTE: this is NOT null-terminated!
9459   StringRef StrRef = FExpr->getString();
9460   const char *Str = StrRef.data();
9461   // Account for cases where the string literal is truncated in a declaration.
9462   const ConstantArrayType *T =
9463     S.Context.getAsConstantArrayType(FExpr->getType());
9464   assert(T && "String literal not of constant array type!");
9465   size_t TypeSize = T->getSize().getZExtValue();
9466   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9467   const unsigned numDataArgs = Args.size() - firstDataArg;
9468 
9469   if (IgnoreStringsWithoutSpecifiers &&
9470       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9471           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9472     return;
9473 
9474   // Emit a warning if the string literal is truncated and does not contain an
9475   // embedded null character.
9476   if (TypeSize <= StrRef.size() &&
9477       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9478     CheckFormatHandler::EmitFormatDiagnostic(
9479         S, inFunctionCall, Args[format_idx],
9480         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9481         FExpr->getBeginLoc(),
9482         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9483     return;
9484   }
9485 
9486   // CHECK: empty format string?
9487   if (StrLen == 0 && numDataArgs > 0) {
9488     CheckFormatHandler::EmitFormatDiagnostic(
9489         S, inFunctionCall, Args[format_idx],
9490         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9491         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9492     return;
9493   }
9494 
9495   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9496       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9497       Type == Sema::FST_OSTrace) {
9498     CheckPrintfHandler H(
9499         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9500         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9501         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9502         CheckedVarArgs, UncoveredArg);
9503 
9504     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9505                                                   S.getLangOpts(),
9506                                                   S.Context.getTargetInfo(),
9507                                             Type == Sema::FST_FreeBSDKPrintf))
9508       H.DoneProcessing();
9509   } else if (Type == Sema::FST_Scanf) {
9510     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9511                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9512                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9513 
9514     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9515                                                  S.getLangOpts(),
9516                                                  S.Context.getTargetInfo()))
9517       H.DoneProcessing();
9518   } // TODO: handle other formats
9519 }
9520 
9521 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9522   // Str - The format string.  NOTE: this is NOT null-terminated!
9523   StringRef StrRef = FExpr->getString();
9524   const char *Str = StrRef.data();
9525   // Account for cases where the string literal is truncated in a declaration.
9526   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9527   assert(T && "String literal not of constant array type!");
9528   size_t TypeSize = T->getSize().getZExtValue();
9529   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9530   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9531                                                          getLangOpts(),
9532                                                          Context.getTargetInfo());
9533 }
9534 
9535 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9536 
9537 // Returns the related absolute value function that is larger, of 0 if one
9538 // does not exist.
9539 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9540   switch (AbsFunction) {
9541   default:
9542     return 0;
9543 
9544   case Builtin::BI__builtin_abs:
9545     return Builtin::BI__builtin_labs;
9546   case Builtin::BI__builtin_labs:
9547     return Builtin::BI__builtin_llabs;
9548   case Builtin::BI__builtin_llabs:
9549     return 0;
9550 
9551   case Builtin::BI__builtin_fabsf:
9552     return Builtin::BI__builtin_fabs;
9553   case Builtin::BI__builtin_fabs:
9554     return Builtin::BI__builtin_fabsl;
9555   case Builtin::BI__builtin_fabsl:
9556     return 0;
9557 
9558   case Builtin::BI__builtin_cabsf:
9559     return Builtin::BI__builtin_cabs;
9560   case Builtin::BI__builtin_cabs:
9561     return Builtin::BI__builtin_cabsl;
9562   case Builtin::BI__builtin_cabsl:
9563     return 0;
9564 
9565   case Builtin::BIabs:
9566     return Builtin::BIlabs;
9567   case Builtin::BIlabs:
9568     return Builtin::BIllabs;
9569   case Builtin::BIllabs:
9570     return 0;
9571 
9572   case Builtin::BIfabsf:
9573     return Builtin::BIfabs;
9574   case Builtin::BIfabs:
9575     return Builtin::BIfabsl;
9576   case Builtin::BIfabsl:
9577     return 0;
9578 
9579   case Builtin::BIcabsf:
9580    return Builtin::BIcabs;
9581   case Builtin::BIcabs:
9582     return Builtin::BIcabsl;
9583   case Builtin::BIcabsl:
9584     return 0;
9585   }
9586 }
9587 
9588 // Returns the argument type of the absolute value function.
9589 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9590                                              unsigned AbsType) {
9591   if (AbsType == 0)
9592     return QualType();
9593 
9594   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9595   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9596   if (Error != ASTContext::GE_None)
9597     return QualType();
9598 
9599   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9600   if (!FT)
9601     return QualType();
9602 
9603   if (FT->getNumParams() != 1)
9604     return QualType();
9605 
9606   return FT->getParamType(0);
9607 }
9608 
9609 // Returns the best absolute value function, or zero, based on type and
9610 // current absolute value function.
9611 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9612                                    unsigned AbsFunctionKind) {
9613   unsigned BestKind = 0;
9614   uint64_t ArgSize = Context.getTypeSize(ArgType);
9615   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9616        Kind = getLargerAbsoluteValueFunction(Kind)) {
9617     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9618     if (Context.getTypeSize(ParamType) >= ArgSize) {
9619       if (BestKind == 0)
9620         BestKind = Kind;
9621       else if (Context.hasSameType(ParamType, ArgType)) {
9622         BestKind = Kind;
9623         break;
9624       }
9625     }
9626   }
9627   return BestKind;
9628 }
9629 
9630 enum AbsoluteValueKind {
9631   AVK_Integer,
9632   AVK_Floating,
9633   AVK_Complex
9634 };
9635 
9636 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9637   if (T->isIntegralOrEnumerationType())
9638     return AVK_Integer;
9639   if (T->isRealFloatingType())
9640     return AVK_Floating;
9641   if (T->isAnyComplexType())
9642     return AVK_Complex;
9643 
9644   llvm_unreachable("Type not integer, floating, or complex");
9645 }
9646 
9647 // Changes the absolute value function to a different type.  Preserves whether
9648 // the function is a builtin.
9649 static unsigned changeAbsFunction(unsigned AbsKind,
9650                                   AbsoluteValueKind ValueKind) {
9651   switch (ValueKind) {
9652   case AVK_Integer:
9653     switch (AbsKind) {
9654     default:
9655       return 0;
9656     case Builtin::BI__builtin_fabsf:
9657     case Builtin::BI__builtin_fabs:
9658     case Builtin::BI__builtin_fabsl:
9659     case Builtin::BI__builtin_cabsf:
9660     case Builtin::BI__builtin_cabs:
9661     case Builtin::BI__builtin_cabsl:
9662       return Builtin::BI__builtin_abs;
9663     case Builtin::BIfabsf:
9664     case Builtin::BIfabs:
9665     case Builtin::BIfabsl:
9666     case Builtin::BIcabsf:
9667     case Builtin::BIcabs:
9668     case Builtin::BIcabsl:
9669       return Builtin::BIabs;
9670     }
9671   case AVK_Floating:
9672     switch (AbsKind) {
9673     default:
9674       return 0;
9675     case Builtin::BI__builtin_abs:
9676     case Builtin::BI__builtin_labs:
9677     case Builtin::BI__builtin_llabs:
9678     case Builtin::BI__builtin_cabsf:
9679     case Builtin::BI__builtin_cabs:
9680     case Builtin::BI__builtin_cabsl:
9681       return Builtin::BI__builtin_fabsf;
9682     case Builtin::BIabs:
9683     case Builtin::BIlabs:
9684     case Builtin::BIllabs:
9685     case Builtin::BIcabsf:
9686     case Builtin::BIcabs:
9687     case Builtin::BIcabsl:
9688       return Builtin::BIfabsf;
9689     }
9690   case AVK_Complex:
9691     switch (AbsKind) {
9692     default:
9693       return 0;
9694     case Builtin::BI__builtin_abs:
9695     case Builtin::BI__builtin_labs:
9696     case Builtin::BI__builtin_llabs:
9697     case Builtin::BI__builtin_fabsf:
9698     case Builtin::BI__builtin_fabs:
9699     case Builtin::BI__builtin_fabsl:
9700       return Builtin::BI__builtin_cabsf;
9701     case Builtin::BIabs:
9702     case Builtin::BIlabs:
9703     case Builtin::BIllabs:
9704     case Builtin::BIfabsf:
9705     case Builtin::BIfabs:
9706     case Builtin::BIfabsl:
9707       return Builtin::BIcabsf;
9708     }
9709   }
9710   llvm_unreachable("Unable to convert function");
9711 }
9712 
9713 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9714   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9715   if (!FnInfo)
9716     return 0;
9717 
9718   switch (FDecl->getBuiltinID()) {
9719   default:
9720     return 0;
9721   case Builtin::BI__builtin_abs:
9722   case Builtin::BI__builtin_fabs:
9723   case Builtin::BI__builtin_fabsf:
9724   case Builtin::BI__builtin_fabsl:
9725   case Builtin::BI__builtin_labs:
9726   case Builtin::BI__builtin_llabs:
9727   case Builtin::BI__builtin_cabs:
9728   case Builtin::BI__builtin_cabsf:
9729   case Builtin::BI__builtin_cabsl:
9730   case Builtin::BIabs:
9731   case Builtin::BIlabs:
9732   case Builtin::BIllabs:
9733   case Builtin::BIfabs:
9734   case Builtin::BIfabsf:
9735   case Builtin::BIfabsl:
9736   case Builtin::BIcabs:
9737   case Builtin::BIcabsf:
9738   case Builtin::BIcabsl:
9739     return FDecl->getBuiltinID();
9740   }
9741   llvm_unreachable("Unknown Builtin type");
9742 }
9743 
9744 // If the replacement is valid, emit a note with replacement function.
9745 // Additionally, suggest including the proper header if not already included.
9746 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9747                             unsigned AbsKind, QualType ArgType) {
9748   bool EmitHeaderHint = true;
9749   const char *HeaderName = nullptr;
9750   const char *FunctionName = nullptr;
9751   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9752     FunctionName = "std::abs";
9753     if (ArgType->isIntegralOrEnumerationType()) {
9754       HeaderName = "cstdlib";
9755     } else if (ArgType->isRealFloatingType()) {
9756       HeaderName = "cmath";
9757     } else {
9758       llvm_unreachable("Invalid Type");
9759     }
9760 
9761     // Lookup all std::abs
9762     if (NamespaceDecl *Std = S.getStdNamespace()) {
9763       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9764       R.suppressDiagnostics();
9765       S.LookupQualifiedName(R, Std);
9766 
9767       for (const auto *I : R) {
9768         const FunctionDecl *FDecl = nullptr;
9769         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9770           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9771         } else {
9772           FDecl = dyn_cast<FunctionDecl>(I);
9773         }
9774         if (!FDecl)
9775           continue;
9776 
9777         // Found std::abs(), check that they are the right ones.
9778         if (FDecl->getNumParams() != 1)
9779           continue;
9780 
9781         // Check that the parameter type can handle the argument.
9782         QualType ParamType = FDecl->getParamDecl(0)->getType();
9783         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9784             S.Context.getTypeSize(ArgType) <=
9785                 S.Context.getTypeSize(ParamType)) {
9786           // Found a function, don't need the header hint.
9787           EmitHeaderHint = false;
9788           break;
9789         }
9790       }
9791     }
9792   } else {
9793     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9794     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9795 
9796     if (HeaderName) {
9797       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9798       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9799       R.suppressDiagnostics();
9800       S.LookupName(R, S.getCurScope());
9801 
9802       if (R.isSingleResult()) {
9803         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9804         if (FD && FD->getBuiltinID() == AbsKind) {
9805           EmitHeaderHint = false;
9806         } else {
9807           return;
9808         }
9809       } else if (!R.empty()) {
9810         return;
9811       }
9812     }
9813   }
9814 
9815   S.Diag(Loc, diag::note_replace_abs_function)
9816       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9817 
9818   if (!HeaderName)
9819     return;
9820 
9821   if (!EmitHeaderHint)
9822     return;
9823 
9824   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9825                                                     << FunctionName;
9826 }
9827 
9828 template <std::size_t StrLen>
9829 static bool IsStdFunction(const FunctionDecl *FDecl,
9830                           const char (&Str)[StrLen]) {
9831   if (!FDecl)
9832     return false;
9833   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9834     return false;
9835   if (!FDecl->isInStdNamespace())
9836     return false;
9837 
9838   return true;
9839 }
9840 
9841 // Warn when using the wrong abs() function.
9842 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9843                                       const FunctionDecl *FDecl) {
9844   if (Call->getNumArgs() != 1)
9845     return;
9846 
9847   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9848   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9849   if (AbsKind == 0 && !IsStdAbs)
9850     return;
9851 
9852   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9853   QualType ParamType = Call->getArg(0)->getType();
9854 
9855   // Unsigned types cannot be negative.  Suggest removing the absolute value
9856   // function call.
9857   if (ArgType->isUnsignedIntegerType()) {
9858     const char *FunctionName =
9859         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9860     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9861     Diag(Call->getExprLoc(), diag::note_remove_abs)
9862         << FunctionName
9863         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9864     return;
9865   }
9866 
9867   // Taking the absolute value of a pointer is very suspicious, they probably
9868   // wanted to index into an array, dereference a pointer, call a function, etc.
9869   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9870     unsigned DiagType = 0;
9871     if (ArgType->isFunctionType())
9872       DiagType = 1;
9873     else if (ArgType->isArrayType())
9874       DiagType = 2;
9875 
9876     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9877     return;
9878   }
9879 
9880   // std::abs has overloads which prevent most of the absolute value problems
9881   // from occurring.
9882   if (IsStdAbs)
9883     return;
9884 
9885   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9886   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9887 
9888   // The argument and parameter are the same kind.  Check if they are the right
9889   // size.
9890   if (ArgValueKind == ParamValueKind) {
9891     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9892       return;
9893 
9894     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9895     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9896         << FDecl << ArgType << ParamType;
9897 
9898     if (NewAbsKind == 0)
9899       return;
9900 
9901     emitReplacement(*this, Call->getExprLoc(),
9902                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9903     return;
9904   }
9905 
9906   // ArgValueKind != ParamValueKind
9907   // The wrong type of absolute value function was used.  Attempt to find the
9908   // proper one.
9909   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9910   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9911   if (NewAbsKind == 0)
9912     return;
9913 
9914   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9915       << FDecl << ParamValueKind << ArgValueKind;
9916 
9917   emitReplacement(*this, Call->getExprLoc(),
9918                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9919 }
9920 
9921 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9922 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9923                                 const FunctionDecl *FDecl) {
9924   if (!Call || !FDecl) return;
9925 
9926   // Ignore template specializations and macros.
9927   if (inTemplateInstantiation()) return;
9928   if (Call->getExprLoc().isMacroID()) return;
9929 
9930   // Only care about the one template argument, two function parameter std::max
9931   if (Call->getNumArgs() != 2) return;
9932   if (!IsStdFunction(FDecl, "max")) return;
9933   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9934   if (!ArgList) return;
9935   if (ArgList->size() != 1) return;
9936 
9937   // Check that template type argument is unsigned integer.
9938   const auto& TA = ArgList->get(0);
9939   if (TA.getKind() != TemplateArgument::Type) return;
9940   QualType ArgType = TA.getAsType();
9941   if (!ArgType->isUnsignedIntegerType()) return;
9942 
9943   // See if either argument is a literal zero.
9944   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9945     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9946     if (!MTE) return false;
9947     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9948     if (!Num) return false;
9949     if (Num->getValue() != 0) return false;
9950     return true;
9951   };
9952 
9953   const Expr *FirstArg = Call->getArg(0);
9954   const Expr *SecondArg = Call->getArg(1);
9955   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9956   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9957 
9958   // Only warn when exactly one argument is zero.
9959   if (IsFirstArgZero == IsSecondArgZero) return;
9960 
9961   SourceRange FirstRange = FirstArg->getSourceRange();
9962   SourceRange SecondRange = SecondArg->getSourceRange();
9963 
9964   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9965 
9966   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9967       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9968 
9969   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9970   SourceRange RemovalRange;
9971   if (IsFirstArgZero) {
9972     RemovalRange = SourceRange(FirstRange.getBegin(),
9973                                SecondRange.getBegin().getLocWithOffset(-1));
9974   } else {
9975     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9976                                SecondRange.getEnd());
9977   }
9978 
9979   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9980         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9981         << FixItHint::CreateRemoval(RemovalRange);
9982 }
9983 
9984 //===--- CHECK: Standard memory functions ---------------------------------===//
9985 
9986 /// Takes the expression passed to the size_t parameter of functions
9987 /// such as memcmp, strncat, etc and warns if it's a comparison.
9988 ///
9989 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9990 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9991                                            IdentifierInfo *FnName,
9992                                            SourceLocation FnLoc,
9993                                            SourceLocation RParenLoc) {
9994   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9995   if (!Size)
9996     return false;
9997 
9998   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9999   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10000     return false;
10001 
10002   SourceRange SizeRange = Size->getSourceRange();
10003   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10004       << SizeRange << FnName;
10005   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10006       << FnName
10007       << FixItHint::CreateInsertion(
10008              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10009       << FixItHint::CreateRemoval(RParenLoc);
10010   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10011       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10012       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10013                                     ")");
10014 
10015   return true;
10016 }
10017 
10018 /// Determine whether the given type is or contains a dynamic class type
10019 /// (e.g., whether it has a vtable).
10020 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10021                                                      bool &IsContained) {
10022   // Look through array types while ignoring qualifiers.
10023   const Type *Ty = T->getBaseElementTypeUnsafe();
10024   IsContained = false;
10025 
10026   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10027   RD = RD ? RD->getDefinition() : nullptr;
10028   if (!RD || RD->isInvalidDecl())
10029     return nullptr;
10030 
10031   if (RD->isDynamicClass())
10032     return RD;
10033 
10034   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10035   // It's impossible for a class to transitively contain itself by value, so
10036   // infinite recursion is impossible.
10037   for (auto *FD : RD->fields()) {
10038     bool SubContained;
10039     if (const CXXRecordDecl *ContainedRD =
10040             getContainedDynamicClass(FD->getType(), SubContained)) {
10041       IsContained = true;
10042       return ContainedRD;
10043     }
10044   }
10045 
10046   return nullptr;
10047 }
10048 
10049 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10050   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10051     if (Unary->getKind() == UETT_SizeOf)
10052       return Unary;
10053   return nullptr;
10054 }
10055 
10056 /// If E is a sizeof expression, returns its argument expression,
10057 /// otherwise returns NULL.
10058 static const Expr *getSizeOfExprArg(const Expr *E) {
10059   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10060     if (!SizeOf->isArgumentType())
10061       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10062   return nullptr;
10063 }
10064 
10065 /// If E is a sizeof expression, returns its argument type.
10066 static QualType getSizeOfArgType(const Expr *E) {
10067   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10068     return SizeOf->getTypeOfArgument();
10069   return QualType();
10070 }
10071 
10072 namespace {
10073 
10074 struct SearchNonTrivialToInitializeField
10075     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10076   using Super =
10077       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10078 
10079   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10080 
10081   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10082                      SourceLocation SL) {
10083     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10084       asDerived().visitArray(PDIK, AT, SL);
10085       return;
10086     }
10087 
10088     Super::visitWithKind(PDIK, FT, SL);
10089   }
10090 
10091   void visitARCStrong(QualType FT, SourceLocation SL) {
10092     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10093   }
10094   void visitARCWeak(QualType FT, SourceLocation SL) {
10095     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10096   }
10097   void visitStruct(QualType FT, SourceLocation SL) {
10098     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10099       visit(FD->getType(), FD->getLocation());
10100   }
10101   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10102                   const ArrayType *AT, SourceLocation SL) {
10103     visit(getContext().getBaseElementType(AT), SL);
10104   }
10105   void visitTrivial(QualType FT, SourceLocation SL) {}
10106 
10107   static void diag(QualType RT, const Expr *E, Sema &S) {
10108     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10109   }
10110 
10111   ASTContext &getContext() { return S.getASTContext(); }
10112 
10113   const Expr *E;
10114   Sema &S;
10115 };
10116 
10117 struct SearchNonTrivialToCopyField
10118     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10119   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10120 
10121   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10122 
10123   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10124                      SourceLocation SL) {
10125     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10126       asDerived().visitArray(PCK, AT, SL);
10127       return;
10128     }
10129 
10130     Super::visitWithKind(PCK, FT, SL);
10131   }
10132 
10133   void visitARCStrong(QualType FT, SourceLocation SL) {
10134     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10135   }
10136   void visitARCWeak(QualType FT, SourceLocation SL) {
10137     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10138   }
10139   void visitStruct(QualType FT, SourceLocation SL) {
10140     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10141       visit(FD->getType(), FD->getLocation());
10142   }
10143   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10144                   SourceLocation SL) {
10145     visit(getContext().getBaseElementType(AT), SL);
10146   }
10147   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10148                 SourceLocation SL) {}
10149   void visitTrivial(QualType FT, SourceLocation SL) {}
10150   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10151 
10152   static void diag(QualType RT, const Expr *E, Sema &S) {
10153     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10154   }
10155 
10156   ASTContext &getContext() { return S.getASTContext(); }
10157 
10158   const Expr *E;
10159   Sema &S;
10160 };
10161 
10162 }
10163 
10164 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10165 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10166   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10167 
10168   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10169     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10170       return false;
10171 
10172     return doesExprLikelyComputeSize(BO->getLHS()) ||
10173            doesExprLikelyComputeSize(BO->getRHS());
10174   }
10175 
10176   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10177 }
10178 
10179 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10180 ///
10181 /// \code
10182 ///   #define MACRO 0
10183 ///   foo(MACRO);
10184 ///   foo(0);
10185 /// \endcode
10186 ///
10187 /// This should return true for the first call to foo, but not for the second
10188 /// (regardless of whether foo is a macro or function).
10189 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10190                                         SourceLocation CallLoc,
10191                                         SourceLocation ArgLoc) {
10192   if (!CallLoc.isMacroID())
10193     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10194 
10195   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10196          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10197 }
10198 
10199 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10200 /// last two arguments transposed.
10201 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10202   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10203     return;
10204 
10205   const Expr *SizeArg =
10206     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10207 
10208   auto isLiteralZero = [](const Expr *E) {
10209     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10210   };
10211 
10212   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10213   SourceLocation CallLoc = Call->getRParenLoc();
10214   SourceManager &SM = S.getSourceManager();
10215   if (isLiteralZero(SizeArg) &&
10216       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10217 
10218     SourceLocation DiagLoc = SizeArg->getExprLoc();
10219 
10220     // Some platforms #define bzero to __builtin_memset. See if this is the
10221     // case, and if so, emit a better diagnostic.
10222     if (BId == Builtin::BIbzero ||
10223         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10224                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10225       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10226       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10227     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10228       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10229       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10230     }
10231     return;
10232   }
10233 
10234   // If the second argument to a memset is a sizeof expression and the third
10235   // isn't, this is also likely an error. This should catch
10236   // 'memset(buf, sizeof(buf), 0xff)'.
10237   if (BId == Builtin::BImemset &&
10238       doesExprLikelyComputeSize(Call->getArg(1)) &&
10239       !doesExprLikelyComputeSize(Call->getArg(2))) {
10240     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10241     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10242     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10243     return;
10244   }
10245 }
10246 
10247 /// Check for dangerous or invalid arguments to memset().
10248 ///
10249 /// This issues warnings on known problematic, dangerous or unspecified
10250 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10251 /// function calls.
10252 ///
10253 /// \param Call The call expression to diagnose.
10254 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10255                                    unsigned BId,
10256                                    IdentifierInfo *FnName) {
10257   assert(BId != 0);
10258 
10259   // It is possible to have a non-standard definition of memset.  Validate
10260   // we have enough arguments, and if not, abort further checking.
10261   unsigned ExpectedNumArgs =
10262       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10263   if (Call->getNumArgs() < ExpectedNumArgs)
10264     return;
10265 
10266   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10267                       BId == Builtin::BIstrndup ? 1 : 2);
10268   unsigned LenArg =
10269       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10270   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10271 
10272   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10273                                      Call->getBeginLoc(), Call->getRParenLoc()))
10274     return;
10275 
10276   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10277   CheckMemaccessSize(*this, BId, Call);
10278 
10279   // We have special checking when the length is a sizeof expression.
10280   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10281   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10282   llvm::FoldingSetNodeID SizeOfArgID;
10283 
10284   // Although widely used, 'bzero' is not a standard function. Be more strict
10285   // with the argument types before allowing diagnostics and only allow the
10286   // form bzero(ptr, sizeof(...)).
10287   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10288   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10289     return;
10290 
10291   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10292     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10293     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10294 
10295     QualType DestTy = Dest->getType();
10296     QualType PointeeTy;
10297     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10298       PointeeTy = DestPtrTy->getPointeeType();
10299 
10300       // Never warn about void type pointers. This can be used to suppress
10301       // false positives.
10302       if (PointeeTy->isVoidType())
10303         continue;
10304 
10305       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10306       // actually comparing the expressions for equality. Because computing the
10307       // expression IDs can be expensive, we only do this if the diagnostic is
10308       // enabled.
10309       if (SizeOfArg &&
10310           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10311                            SizeOfArg->getExprLoc())) {
10312         // We only compute IDs for expressions if the warning is enabled, and
10313         // cache the sizeof arg's ID.
10314         if (SizeOfArgID == llvm::FoldingSetNodeID())
10315           SizeOfArg->Profile(SizeOfArgID, Context, true);
10316         llvm::FoldingSetNodeID DestID;
10317         Dest->Profile(DestID, Context, true);
10318         if (DestID == SizeOfArgID) {
10319           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10320           //       over sizeof(src) as well.
10321           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10322           StringRef ReadableName = FnName->getName();
10323 
10324           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10325             if (UnaryOp->getOpcode() == UO_AddrOf)
10326               ActionIdx = 1; // If its an address-of operator, just remove it.
10327           if (!PointeeTy->isIncompleteType() &&
10328               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10329             ActionIdx = 2; // If the pointee's size is sizeof(char),
10330                            // suggest an explicit length.
10331 
10332           // If the function is defined as a builtin macro, do not show macro
10333           // expansion.
10334           SourceLocation SL = SizeOfArg->getExprLoc();
10335           SourceRange DSR = Dest->getSourceRange();
10336           SourceRange SSR = SizeOfArg->getSourceRange();
10337           SourceManager &SM = getSourceManager();
10338 
10339           if (SM.isMacroArgExpansion(SL)) {
10340             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10341             SL = SM.getSpellingLoc(SL);
10342             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10343                              SM.getSpellingLoc(DSR.getEnd()));
10344             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10345                              SM.getSpellingLoc(SSR.getEnd()));
10346           }
10347 
10348           DiagRuntimeBehavior(SL, SizeOfArg,
10349                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10350                                 << ReadableName
10351                                 << PointeeTy
10352                                 << DestTy
10353                                 << DSR
10354                                 << SSR);
10355           DiagRuntimeBehavior(SL, SizeOfArg,
10356                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10357                                 << ActionIdx
10358                                 << SSR);
10359 
10360           break;
10361         }
10362       }
10363 
10364       // Also check for cases where the sizeof argument is the exact same
10365       // type as the memory argument, and where it points to a user-defined
10366       // record type.
10367       if (SizeOfArgTy != QualType()) {
10368         if (PointeeTy->isRecordType() &&
10369             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10370           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10371                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10372                                 << FnName << SizeOfArgTy << ArgIdx
10373                                 << PointeeTy << Dest->getSourceRange()
10374                                 << LenExpr->getSourceRange());
10375           break;
10376         }
10377       }
10378     } else if (DestTy->isArrayType()) {
10379       PointeeTy = DestTy;
10380     }
10381 
10382     if (PointeeTy == QualType())
10383       continue;
10384 
10385     // Always complain about dynamic classes.
10386     bool IsContained;
10387     if (const CXXRecordDecl *ContainedRD =
10388             getContainedDynamicClass(PointeeTy, IsContained)) {
10389 
10390       unsigned OperationType = 0;
10391       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10392       // "overwritten" if we're warning about the destination for any call
10393       // but memcmp; otherwise a verb appropriate to the call.
10394       if (ArgIdx != 0 || IsCmp) {
10395         if (BId == Builtin::BImemcpy)
10396           OperationType = 1;
10397         else if(BId == Builtin::BImemmove)
10398           OperationType = 2;
10399         else if (IsCmp)
10400           OperationType = 3;
10401       }
10402 
10403       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10404                           PDiag(diag::warn_dyn_class_memaccess)
10405                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10406                               << IsContained << ContainedRD << OperationType
10407                               << Call->getCallee()->getSourceRange());
10408     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10409              BId != Builtin::BImemset)
10410       DiagRuntimeBehavior(
10411         Dest->getExprLoc(), Dest,
10412         PDiag(diag::warn_arc_object_memaccess)
10413           << ArgIdx << FnName << PointeeTy
10414           << Call->getCallee()->getSourceRange());
10415     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10416       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10417           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10418         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10419                             PDiag(diag::warn_cstruct_memaccess)
10420                                 << ArgIdx << FnName << PointeeTy << 0);
10421         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10422       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10423                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10424         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10425                             PDiag(diag::warn_cstruct_memaccess)
10426                                 << ArgIdx << FnName << PointeeTy << 1);
10427         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10428       } else {
10429         continue;
10430       }
10431     } else
10432       continue;
10433 
10434     DiagRuntimeBehavior(
10435       Dest->getExprLoc(), Dest,
10436       PDiag(diag::note_bad_memaccess_silence)
10437         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10438     break;
10439   }
10440 }
10441 
10442 // A little helper routine: ignore addition and subtraction of integer literals.
10443 // This intentionally does not ignore all integer constant expressions because
10444 // we don't want to remove sizeof().
10445 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10446   Ex = Ex->IgnoreParenCasts();
10447 
10448   while (true) {
10449     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10450     if (!BO || !BO->isAdditiveOp())
10451       break;
10452 
10453     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10454     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10455 
10456     if (isa<IntegerLiteral>(RHS))
10457       Ex = LHS;
10458     else if (isa<IntegerLiteral>(LHS))
10459       Ex = RHS;
10460     else
10461       break;
10462   }
10463 
10464   return Ex;
10465 }
10466 
10467 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10468                                                       ASTContext &Context) {
10469   // Only handle constant-sized or VLAs, but not flexible members.
10470   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10471     // Only issue the FIXIT for arrays of size > 1.
10472     if (CAT->getSize().getSExtValue() <= 1)
10473       return false;
10474   } else if (!Ty->isVariableArrayType()) {
10475     return false;
10476   }
10477   return true;
10478 }
10479 
10480 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10481 // be the size of the source, instead of the destination.
10482 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10483                                     IdentifierInfo *FnName) {
10484 
10485   // Don't crash if the user has the wrong number of arguments
10486   unsigned NumArgs = Call->getNumArgs();
10487   if ((NumArgs != 3) && (NumArgs != 4))
10488     return;
10489 
10490   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10491   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10492   const Expr *CompareWithSrc = nullptr;
10493 
10494   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10495                                      Call->getBeginLoc(), Call->getRParenLoc()))
10496     return;
10497 
10498   // Look for 'strlcpy(dst, x, sizeof(x))'
10499   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10500     CompareWithSrc = Ex;
10501   else {
10502     // Look for 'strlcpy(dst, x, strlen(x))'
10503     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10504       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10505           SizeCall->getNumArgs() == 1)
10506         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10507     }
10508   }
10509 
10510   if (!CompareWithSrc)
10511     return;
10512 
10513   // Determine if the argument to sizeof/strlen is equal to the source
10514   // argument.  In principle there's all kinds of things you could do
10515   // here, for instance creating an == expression and evaluating it with
10516   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10517   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10518   if (!SrcArgDRE)
10519     return;
10520 
10521   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10522   if (!CompareWithSrcDRE ||
10523       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10524     return;
10525 
10526   const Expr *OriginalSizeArg = Call->getArg(2);
10527   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10528       << OriginalSizeArg->getSourceRange() << FnName;
10529 
10530   // Output a FIXIT hint if the destination is an array (rather than a
10531   // pointer to an array).  This could be enhanced to handle some
10532   // pointers if we know the actual size, like if DstArg is 'array+2'
10533   // we could say 'sizeof(array)-2'.
10534   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10535   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10536     return;
10537 
10538   SmallString<128> sizeString;
10539   llvm::raw_svector_ostream OS(sizeString);
10540   OS << "sizeof(";
10541   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10542   OS << ")";
10543 
10544   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10545       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10546                                       OS.str());
10547 }
10548 
10549 /// Check if two expressions refer to the same declaration.
10550 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10551   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10552     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10553       return D1->getDecl() == D2->getDecl();
10554   return false;
10555 }
10556 
10557 static const Expr *getStrlenExprArg(const Expr *E) {
10558   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10559     const FunctionDecl *FD = CE->getDirectCallee();
10560     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10561       return nullptr;
10562     return CE->getArg(0)->IgnoreParenCasts();
10563   }
10564   return nullptr;
10565 }
10566 
10567 // Warn on anti-patterns as the 'size' argument to strncat.
10568 // The correct size argument should look like following:
10569 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10570 void Sema::CheckStrncatArguments(const CallExpr *CE,
10571                                  IdentifierInfo *FnName) {
10572   // Don't crash if the user has the wrong number of arguments.
10573   if (CE->getNumArgs() < 3)
10574     return;
10575   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10576   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10577   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10578 
10579   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10580                                      CE->getRParenLoc()))
10581     return;
10582 
10583   // Identify common expressions, which are wrongly used as the size argument
10584   // to strncat and may lead to buffer overflows.
10585   unsigned PatternType = 0;
10586   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10587     // - sizeof(dst)
10588     if (referToTheSameDecl(SizeOfArg, DstArg))
10589       PatternType = 1;
10590     // - sizeof(src)
10591     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10592       PatternType = 2;
10593   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10594     if (BE->getOpcode() == BO_Sub) {
10595       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10596       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10597       // - sizeof(dst) - strlen(dst)
10598       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10599           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10600         PatternType = 1;
10601       // - sizeof(src) - (anything)
10602       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10603         PatternType = 2;
10604     }
10605   }
10606 
10607   if (PatternType == 0)
10608     return;
10609 
10610   // Generate the diagnostic.
10611   SourceLocation SL = LenArg->getBeginLoc();
10612   SourceRange SR = LenArg->getSourceRange();
10613   SourceManager &SM = getSourceManager();
10614 
10615   // If the function is defined as a builtin macro, do not show macro expansion.
10616   if (SM.isMacroArgExpansion(SL)) {
10617     SL = SM.getSpellingLoc(SL);
10618     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10619                      SM.getSpellingLoc(SR.getEnd()));
10620   }
10621 
10622   // Check if the destination is an array (rather than a pointer to an array).
10623   QualType DstTy = DstArg->getType();
10624   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10625                                                                     Context);
10626   if (!isKnownSizeArray) {
10627     if (PatternType == 1)
10628       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10629     else
10630       Diag(SL, diag::warn_strncat_src_size) << SR;
10631     return;
10632   }
10633 
10634   if (PatternType == 1)
10635     Diag(SL, diag::warn_strncat_large_size) << SR;
10636   else
10637     Diag(SL, diag::warn_strncat_src_size) << SR;
10638 
10639   SmallString<128> sizeString;
10640   llvm::raw_svector_ostream OS(sizeString);
10641   OS << "sizeof(";
10642   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10643   OS << ") - ";
10644   OS << "strlen(";
10645   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10646   OS << ") - 1";
10647 
10648   Diag(SL, diag::note_strncat_wrong_size)
10649     << FixItHint::CreateReplacement(SR, OS.str());
10650 }
10651 
10652 namespace {
10653 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10654                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10655   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10656     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10657         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10658     return;
10659   }
10660 }
10661 
10662 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10663                                  const UnaryOperator *UnaryExpr) {
10664   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10665     const Decl *D = Lvalue->getDecl();
10666     if (isa<VarDecl, FunctionDecl>(D))
10667       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10668   }
10669 
10670   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10671     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10672                                       Lvalue->getMemberDecl());
10673 }
10674 
10675 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10676                             const UnaryOperator *UnaryExpr) {
10677   const auto *Lambda = dyn_cast<LambdaExpr>(
10678       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10679   if (!Lambda)
10680     return;
10681 
10682   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10683       << CalleeName << 2 /*object: lambda expression*/;
10684 }
10685 
10686 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10687                                   const DeclRefExpr *Lvalue) {
10688   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10689   if (Var == nullptr)
10690     return;
10691 
10692   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10693       << CalleeName << 0 /*object: */ << Var;
10694 }
10695 
10696 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10697                             const CastExpr *Cast) {
10698   SmallString<128> SizeString;
10699   llvm::raw_svector_ostream OS(SizeString);
10700 
10701   clang::CastKind Kind = Cast->getCastKind();
10702   if (Kind == clang::CK_BitCast &&
10703       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10704     return;
10705   if (Kind == clang::CK_IntegralToPointer &&
10706       !isa<IntegerLiteral>(
10707           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10708     return;
10709 
10710   switch (Cast->getCastKind()) {
10711   case clang::CK_BitCast:
10712   case clang::CK_IntegralToPointer:
10713   case clang::CK_FunctionToPointerDecay:
10714     OS << '\'';
10715     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10716     OS << '\'';
10717     break;
10718   default:
10719     return;
10720   }
10721 
10722   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10723       << CalleeName << 0 /*object: */ << OS.str();
10724 }
10725 } // namespace
10726 
10727 /// Alerts the user that they are attempting to free a non-malloc'd object.
10728 void Sema::CheckFreeArguments(const CallExpr *E) {
10729   const std::string CalleeName =
10730       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10731 
10732   { // Prefer something that doesn't involve a cast to make things simpler.
10733     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10734     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10735       switch (UnaryExpr->getOpcode()) {
10736       case UnaryOperator::Opcode::UO_AddrOf:
10737         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10738       case UnaryOperator::Opcode::UO_Plus:
10739         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10740       default:
10741         break;
10742       }
10743 
10744     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10745       if (Lvalue->getType()->isArrayType())
10746         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10747 
10748     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10749       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10750           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10751       return;
10752     }
10753 
10754     if (isa<BlockExpr>(Arg)) {
10755       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10756           << CalleeName << 1 /*object: block*/;
10757       return;
10758     }
10759   }
10760   // Maybe the cast was important, check after the other cases.
10761   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10762     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10763 }
10764 
10765 void
10766 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10767                          SourceLocation ReturnLoc,
10768                          bool isObjCMethod,
10769                          const AttrVec *Attrs,
10770                          const FunctionDecl *FD) {
10771   // Check if the return value is null but should not be.
10772   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10773        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10774       CheckNonNullExpr(*this, RetValExp))
10775     Diag(ReturnLoc, diag::warn_null_ret)
10776       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10777 
10778   // C++11 [basic.stc.dynamic.allocation]p4:
10779   //   If an allocation function declared with a non-throwing
10780   //   exception-specification fails to allocate storage, it shall return
10781   //   a null pointer. Any other allocation function that fails to allocate
10782   //   storage shall indicate failure only by throwing an exception [...]
10783   if (FD) {
10784     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10785     if (Op == OO_New || Op == OO_Array_New) {
10786       const FunctionProtoType *Proto
10787         = FD->getType()->castAs<FunctionProtoType>();
10788       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10789           CheckNonNullExpr(*this, RetValExp))
10790         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10791           << FD << getLangOpts().CPlusPlus11;
10792     }
10793   }
10794 
10795   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10796   // here prevent the user from using a PPC MMA type as trailing return type.
10797   if (Context.getTargetInfo().getTriple().isPPC64())
10798     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10799 }
10800 
10801 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10802 
10803 /// Check for comparisons of floating point operands using != and ==.
10804 /// Issue a warning if these are no self-comparisons, as they are not likely
10805 /// to do what the programmer intended.
10806 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10807   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10808   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10809 
10810   // Special case: check for x == x (which is OK).
10811   // Do not emit warnings for such cases.
10812   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10813     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10814       if (DRL->getDecl() == DRR->getDecl())
10815         return;
10816 
10817   // Special case: check for comparisons against literals that can be exactly
10818   //  represented by APFloat.  In such cases, do not emit a warning.  This
10819   //  is a heuristic: often comparison against such literals are used to
10820   //  detect if a value in a variable has not changed.  This clearly can
10821   //  lead to false negatives.
10822   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10823     if (FLL->isExact())
10824       return;
10825   } else
10826     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10827       if (FLR->isExact())
10828         return;
10829 
10830   // Check for comparisons with builtin types.
10831   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10832     if (CL->getBuiltinCallee())
10833       return;
10834 
10835   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10836     if (CR->getBuiltinCallee())
10837       return;
10838 
10839   // Emit the diagnostic.
10840   Diag(Loc, diag::warn_floatingpoint_eq)
10841     << LHS->getSourceRange() << RHS->getSourceRange();
10842 }
10843 
10844 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10845 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10846 
10847 namespace {
10848 
10849 /// Structure recording the 'active' range of an integer-valued
10850 /// expression.
10851 struct IntRange {
10852   /// The number of bits active in the int. Note that this includes exactly one
10853   /// sign bit if !NonNegative.
10854   unsigned Width;
10855 
10856   /// True if the int is known not to have negative values. If so, all leading
10857   /// bits before Width are known zero, otherwise they are known to be the
10858   /// same as the MSB within Width.
10859   bool NonNegative;
10860 
10861   IntRange(unsigned Width, bool NonNegative)
10862       : Width(Width), NonNegative(NonNegative) {}
10863 
10864   /// Number of bits excluding the sign bit.
10865   unsigned valueBits() const {
10866     return NonNegative ? Width : Width - 1;
10867   }
10868 
10869   /// Returns the range of the bool type.
10870   static IntRange forBoolType() {
10871     return IntRange(1, true);
10872   }
10873 
10874   /// Returns the range of an opaque value of the given integral type.
10875   static IntRange forValueOfType(ASTContext &C, QualType T) {
10876     return forValueOfCanonicalType(C,
10877                           T->getCanonicalTypeInternal().getTypePtr());
10878   }
10879 
10880   /// Returns the range of an opaque value of a canonical integral type.
10881   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10882     assert(T->isCanonicalUnqualified());
10883 
10884     if (const VectorType *VT = dyn_cast<VectorType>(T))
10885       T = VT->getElementType().getTypePtr();
10886     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10887       T = CT->getElementType().getTypePtr();
10888     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10889       T = AT->getValueType().getTypePtr();
10890 
10891     if (!C.getLangOpts().CPlusPlus) {
10892       // For enum types in C code, use the underlying datatype.
10893       if (const EnumType *ET = dyn_cast<EnumType>(T))
10894         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10895     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10896       // For enum types in C++, use the known bit width of the enumerators.
10897       EnumDecl *Enum = ET->getDecl();
10898       // In C++11, enums can have a fixed underlying type. Use this type to
10899       // compute the range.
10900       if (Enum->isFixed()) {
10901         return IntRange(C.getIntWidth(QualType(T, 0)),
10902                         !ET->isSignedIntegerOrEnumerationType());
10903       }
10904 
10905       unsigned NumPositive = Enum->getNumPositiveBits();
10906       unsigned NumNegative = Enum->getNumNegativeBits();
10907 
10908       if (NumNegative == 0)
10909         return IntRange(NumPositive, true/*NonNegative*/);
10910       else
10911         return IntRange(std::max(NumPositive + 1, NumNegative),
10912                         false/*NonNegative*/);
10913     }
10914 
10915     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10916       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10917 
10918     const BuiltinType *BT = cast<BuiltinType>(T);
10919     assert(BT->isInteger());
10920 
10921     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10922   }
10923 
10924   /// Returns the "target" range of a canonical integral type, i.e.
10925   /// the range of values expressible in the type.
10926   ///
10927   /// This matches forValueOfCanonicalType except that enums have the
10928   /// full range of their type, not the range of their enumerators.
10929   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10930     assert(T->isCanonicalUnqualified());
10931 
10932     if (const VectorType *VT = dyn_cast<VectorType>(T))
10933       T = VT->getElementType().getTypePtr();
10934     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10935       T = CT->getElementType().getTypePtr();
10936     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10937       T = AT->getValueType().getTypePtr();
10938     if (const EnumType *ET = dyn_cast<EnumType>(T))
10939       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10940 
10941     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10942       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10943 
10944     const BuiltinType *BT = cast<BuiltinType>(T);
10945     assert(BT->isInteger());
10946 
10947     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10948   }
10949 
10950   /// Returns the supremum of two ranges: i.e. their conservative merge.
10951   static IntRange join(IntRange L, IntRange R) {
10952     bool Unsigned = L.NonNegative && R.NonNegative;
10953     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10954                     L.NonNegative && R.NonNegative);
10955   }
10956 
10957   /// Return the range of a bitwise-AND of the two ranges.
10958   static IntRange bit_and(IntRange L, IntRange R) {
10959     unsigned Bits = std::max(L.Width, R.Width);
10960     bool NonNegative = false;
10961     if (L.NonNegative) {
10962       Bits = std::min(Bits, L.Width);
10963       NonNegative = true;
10964     }
10965     if (R.NonNegative) {
10966       Bits = std::min(Bits, R.Width);
10967       NonNegative = true;
10968     }
10969     return IntRange(Bits, NonNegative);
10970   }
10971 
10972   /// Return the range of a sum of the two ranges.
10973   static IntRange sum(IntRange L, IntRange R) {
10974     bool Unsigned = L.NonNegative && R.NonNegative;
10975     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10976                     Unsigned);
10977   }
10978 
10979   /// Return the range of a difference of the two ranges.
10980   static IntRange difference(IntRange L, IntRange R) {
10981     // We need a 1-bit-wider range if:
10982     //   1) LHS can be negative: least value can be reduced.
10983     //   2) RHS can be negative: greatest value can be increased.
10984     bool CanWiden = !L.NonNegative || !R.NonNegative;
10985     bool Unsigned = L.NonNegative && R.Width == 0;
10986     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10987                         !Unsigned,
10988                     Unsigned);
10989   }
10990 
10991   /// Return the range of a product of the two ranges.
10992   static IntRange product(IntRange L, IntRange R) {
10993     // If both LHS and RHS can be negative, we can form
10994     //   -2^L * -2^R = 2^(L + R)
10995     // which requires L + R + 1 value bits to represent.
10996     bool CanWiden = !L.NonNegative && !R.NonNegative;
10997     bool Unsigned = L.NonNegative && R.NonNegative;
10998     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10999                     Unsigned);
11000   }
11001 
11002   /// Return the range of a remainder operation between the two ranges.
11003   static IntRange rem(IntRange L, IntRange R) {
11004     // The result of a remainder can't be larger than the result of
11005     // either side. The sign of the result is the sign of the LHS.
11006     bool Unsigned = L.NonNegative;
11007     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11008                     Unsigned);
11009   }
11010 };
11011 
11012 } // namespace
11013 
11014 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11015                               unsigned MaxWidth) {
11016   if (value.isSigned() && value.isNegative())
11017     return IntRange(value.getMinSignedBits(), false);
11018 
11019   if (value.getBitWidth() > MaxWidth)
11020     value = value.trunc(MaxWidth);
11021 
11022   // isNonNegative() just checks the sign bit without considering
11023   // signedness.
11024   return IntRange(value.getActiveBits(), true);
11025 }
11026 
11027 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11028                               unsigned MaxWidth) {
11029   if (result.isInt())
11030     return GetValueRange(C, result.getInt(), MaxWidth);
11031 
11032   if (result.isVector()) {
11033     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11034     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11035       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11036       R = IntRange::join(R, El);
11037     }
11038     return R;
11039   }
11040 
11041   if (result.isComplexInt()) {
11042     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11043     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11044     return IntRange::join(R, I);
11045   }
11046 
11047   // This can happen with lossless casts to intptr_t of "based" lvalues.
11048   // Assume it might use arbitrary bits.
11049   // FIXME: The only reason we need to pass the type in here is to get
11050   // the sign right on this one case.  It would be nice if APValue
11051   // preserved this.
11052   assert(result.isLValue() || result.isAddrLabelDiff());
11053   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11054 }
11055 
11056 static QualType GetExprType(const Expr *E) {
11057   QualType Ty = E->getType();
11058   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11059     Ty = AtomicRHS->getValueType();
11060   return Ty;
11061 }
11062 
11063 /// Pseudo-evaluate the given integer expression, estimating the
11064 /// range of values it might take.
11065 ///
11066 /// \param MaxWidth The width to which the value will be truncated.
11067 /// \param Approximate If \c true, return a likely range for the result: in
11068 ///        particular, assume that aritmetic on narrower types doesn't leave
11069 ///        those types. If \c false, return a range including all possible
11070 ///        result values.
11071 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11072                              bool InConstantContext, bool Approximate) {
11073   E = E->IgnoreParens();
11074 
11075   // Try a full evaluation first.
11076   Expr::EvalResult result;
11077   if (E->EvaluateAsRValue(result, C, InConstantContext))
11078     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11079 
11080   // I think we only want to look through implicit casts here; if the
11081   // user has an explicit widening cast, we should treat the value as
11082   // being of the new, wider type.
11083   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11084     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11085       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11086                           Approximate);
11087 
11088     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11089 
11090     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11091                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11092 
11093     // Assume that non-integer casts can span the full range of the type.
11094     if (!isIntegerCast)
11095       return OutputTypeRange;
11096 
11097     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11098                                      std::min(MaxWidth, OutputTypeRange.Width),
11099                                      InConstantContext, Approximate);
11100 
11101     // Bail out if the subexpr's range is as wide as the cast type.
11102     if (SubRange.Width >= OutputTypeRange.Width)
11103       return OutputTypeRange;
11104 
11105     // Otherwise, we take the smaller width, and we're non-negative if
11106     // either the output type or the subexpr is.
11107     return IntRange(SubRange.Width,
11108                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11109   }
11110 
11111   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11112     // If we can fold the condition, just take that operand.
11113     bool CondResult;
11114     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11115       return GetExprRange(C,
11116                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11117                           MaxWidth, InConstantContext, Approximate);
11118 
11119     // Otherwise, conservatively merge.
11120     // GetExprRange requires an integer expression, but a throw expression
11121     // results in a void type.
11122     Expr *E = CO->getTrueExpr();
11123     IntRange L = E->getType()->isVoidType()
11124                      ? IntRange{0, true}
11125                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11126     E = CO->getFalseExpr();
11127     IntRange R = E->getType()->isVoidType()
11128                      ? IntRange{0, true}
11129                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11130     return IntRange::join(L, R);
11131   }
11132 
11133   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11134     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11135 
11136     switch (BO->getOpcode()) {
11137     case BO_Cmp:
11138       llvm_unreachable("builtin <=> should have class type");
11139 
11140     // Boolean-valued operations are single-bit and positive.
11141     case BO_LAnd:
11142     case BO_LOr:
11143     case BO_LT:
11144     case BO_GT:
11145     case BO_LE:
11146     case BO_GE:
11147     case BO_EQ:
11148     case BO_NE:
11149       return IntRange::forBoolType();
11150 
11151     // The type of the assignments is the type of the LHS, so the RHS
11152     // is not necessarily the same type.
11153     case BO_MulAssign:
11154     case BO_DivAssign:
11155     case BO_RemAssign:
11156     case BO_AddAssign:
11157     case BO_SubAssign:
11158     case BO_XorAssign:
11159     case BO_OrAssign:
11160       // TODO: bitfields?
11161       return IntRange::forValueOfType(C, GetExprType(E));
11162 
11163     // Simple assignments just pass through the RHS, which will have
11164     // been coerced to the LHS type.
11165     case BO_Assign:
11166       // TODO: bitfields?
11167       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11168                           Approximate);
11169 
11170     // Operations with opaque sources are black-listed.
11171     case BO_PtrMemD:
11172     case BO_PtrMemI:
11173       return IntRange::forValueOfType(C, GetExprType(E));
11174 
11175     // Bitwise-and uses the *infinum* of the two source ranges.
11176     case BO_And:
11177     case BO_AndAssign:
11178       Combine = IntRange::bit_and;
11179       break;
11180 
11181     // Left shift gets black-listed based on a judgement call.
11182     case BO_Shl:
11183       // ...except that we want to treat '1 << (blah)' as logically
11184       // positive.  It's an important idiom.
11185       if (IntegerLiteral *I
11186             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11187         if (I->getValue() == 1) {
11188           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11189           return IntRange(R.Width, /*NonNegative*/ true);
11190         }
11191       }
11192       LLVM_FALLTHROUGH;
11193 
11194     case BO_ShlAssign:
11195       return IntRange::forValueOfType(C, GetExprType(E));
11196 
11197     // Right shift by a constant can narrow its left argument.
11198     case BO_Shr:
11199     case BO_ShrAssign: {
11200       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11201                                 Approximate);
11202 
11203       // If the shift amount is a positive constant, drop the width by
11204       // that much.
11205       if (Optional<llvm::APSInt> shift =
11206               BO->getRHS()->getIntegerConstantExpr(C)) {
11207         if (shift->isNonNegative()) {
11208           unsigned zext = shift->getZExtValue();
11209           if (zext >= L.Width)
11210             L.Width = (L.NonNegative ? 0 : 1);
11211           else
11212             L.Width -= zext;
11213         }
11214       }
11215 
11216       return L;
11217     }
11218 
11219     // Comma acts as its right operand.
11220     case BO_Comma:
11221       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11222                           Approximate);
11223 
11224     case BO_Add:
11225       if (!Approximate)
11226         Combine = IntRange::sum;
11227       break;
11228 
11229     case BO_Sub:
11230       if (BO->getLHS()->getType()->isPointerType())
11231         return IntRange::forValueOfType(C, GetExprType(E));
11232       if (!Approximate)
11233         Combine = IntRange::difference;
11234       break;
11235 
11236     case BO_Mul:
11237       if (!Approximate)
11238         Combine = IntRange::product;
11239       break;
11240 
11241     // The width of a division result is mostly determined by the size
11242     // of the LHS.
11243     case BO_Div: {
11244       // Don't 'pre-truncate' the operands.
11245       unsigned opWidth = C.getIntWidth(GetExprType(E));
11246       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11247                                 Approximate);
11248 
11249       // If the divisor is constant, use that.
11250       if (Optional<llvm::APSInt> divisor =
11251               BO->getRHS()->getIntegerConstantExpr(C)) {
11252         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11253         if (log2 >= L.Width)
11254           L.Width = (L.NonNegative ? 0 : 1);
11255         else
11256           L.Width = std::min(L.Width - log2, MaxWidth);
11257         return L;
11258       }
11259 
11260       // Otherwise, just use the LHS's width.
11261       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11262       // could be -1.
11263       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11264                                 Approximate);
11265       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11266     }
11267 
11268     case BO_Rem:
11269       Combine = IntRange::rem;
11270       break;
11271 
11272     // The default behavior is okay for these.
11273     case BO_Xor:
11274     case BO_Or:
11275       break;
11276     }
11277 
11278     // Combine the two ranges, but limit the result to the type in which we
11279     // performed the computation.
11280     QualType T = GetExprType(E);
11281     unsigned opWidth = C.getIntWidth(T);
11282     IntRange L =
11283         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11284     IntRange R =
11285         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11286     IntRange C = Combine(L, R);
11287     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11288     C.Width = std::min(C.Width, MaxWidth);
11289     return C;
11290   }
11291 
11292   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11293     switch (UO->getOpcode()) {
11294     // Boolean-valued operations are white-listed.
11295     case UO_LNot:
11296       return IntRange::forBoolType();
11297 
11298     // Operations with opaque sources are black-listed.
11299     case UO_Deref:
11300     case UO_AddrOf: // should be impossible
11301       return IntRange::forValueOfType(C, GetExprType(E));
11302 
11303     default:
11304       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11305                           Approximate);
11306     }
11307   }
11308 
11309   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11310     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11311                         Approximate);
11312 
11313   if (const auto *BitField = E->getSourceBitField())
11314     return IntRange(BitField->getBitWidthValue(C),
11315                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11316 
11317   return IntRange::forValueOfType(C, GetExprType(E));
11318 }
11319 
11320 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11321                              bool InConstantContext, bool Approximate) {
11322   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11323                       Approximate);
11324 }
11325 
11326 /// Checks whether the given value, which currently has the given
11327 /// source semantics, has the same value when coerced through the
11328 /// target semantics.
11329 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11330                                  const llvm::fltSemantics &Src,
11331                                  const llvm::fltSemantics &Tgt) {
11332   llvm::APFloat truncated = value;
11333 
11334   bool ignored;
11335   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11336   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11337 
11338   return truncated.bitwiseIsEqual(value);
11339 }
11340 
11341 /// Checks whether the given value, which currently has the given
11342 /// source semantics, has the same value when coerced through the
11343 /// target semantics.
11344 ///
11345 /// The value might be a vector of floats (or a complex number).
11346 static bool IsSameFloatAfterCast(const APValue &value,
11347                                  const llvm::fltSemantics &Src,
11348                                  const llvm::fltSemantics &Tgt) {
11349   if (value.isFloat())
11350     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11351 
11352   if (value.isVector()) {
11353     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11354       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11355         return false;
11356     return true;
11357   }
11358 
11359   assert(value.isComplexFloat());
11360   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11361           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11362 }
11363 
11364 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11365                                        bool IsListInit = false);
11366 
11367 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11368   // Suppress cases where we are comparing against an enum constant.
11369   if (const DeclRefExpr *DR =
11370       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11371     if (isa<EnumConstantDecl>(DR->getDecl()))
11372       return true;
11373 
11374   // Suppress cases where the value is expanded from a macro, unless that macro
11375   // is how a language represents a boolean literal. This is the case in both C
11376   // and Objective-C.
11377   SourceLocation BeginLoc = E->getBeginLoc();
11378   if (BeginLoc.isMacroID()) {
11379     StringRef MacroName = Lexer::getImmediateMacroName(
11380         BeginLoc, S.getSourceManager(), S.getLangOpts());
11381     return MacroName != "YES" && MacroName != "NO" &&
11382            MacroName != "true" && MacroName != "false";
11383   }
11384 
11385   return false;
11386 }
11387 
11388 static bool isKnownToHaveUnsignedValue(Expr *E) {
11389   return E->getType()->isIntegerType() &&
11390          (!E->getType()->isSignedIntegerType() ||
11391           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11392 }
11393 
11394 namespace {
11395 /// The promoted range of values of a type. In general this has the
11396 /// following structure:
11397 ///
11398 ///     |-----------| . . . |-----------|
11399 ///     ^           ^       ^           ^
11400 ///    Min       HoleMin  HoleMax      Max
11401 ///
11402 /// ... where there is only a hole if a signed type is promoted to unsigned
11403 /// (in which case Min and Max are the smallest and largest representable
11404 /// values).
11405 struct PromotedRange {
11406   // Min, or HoleMax if there is a hole.
11407   llvm::APSInt PromotedMin;
11408   // Max, or HoleMin if there is a hole.
11409   llvm::APSInt PromotedMax;
11410 
11411   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11412     if (R.Width == 0)
11413       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11414     else if (R.Width >= BitWidth && !Unsigned) {
11415       // Promotion made the type *narrower*. This happens when promoting
11416       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11417       // Treat all values of 'signed int' as being in range for now.
11418       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11419       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11420     } else {
11421       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11422                         .extOrTrunc(BitWidth);
11423       PromotedMin.setIsUnsigned(Unsigned);
11424 
11425       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11426                         .extOrTrunc(BitWidth);
11427       PromotedMax.setIsUnsigned(Unsigned);
11428     }
11429   }
11430 
11431   // Determine whether this range is contiguous (has no hole).
11432   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11433 
11434   // Where a constant value is within the range.
11435   enum ComparisonResult {
11436     LT = 0x1,
11437     LE = 0x2,
11438     GT = 0x4,
11439     GE = 0x8,
11440     EQ = 0x10,
11441     NE = 0x20,
11442     InRangeFlag = 0x40,
11443 
11444     Less = LE | LT | NE,
11445     Min = LE | InRangeFlag,
11446     InRange = InRangeFlag,
11447     Max = GE | InRangeFlag,
11448     Greater = GE | GT | NE,
11449 
11450     OnlyValue = LE | GE | EQ | InRangeFlag,
11451     InHole = NE
11452   };
11453 
11454   ComparisonResult compare(const llvm::APSInt &Value) const {
11455     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11456            Value.isUnsigned() == PromotedMin.isUnsigned());
11457     if (!isContiguous()) {
11458       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11459       if (Value.isMinValue()) return Min;
11460       if (Value.isMaxValue()) return Max;
11461       if (Value >= PromotedMin) return InRange;
11462       if (Value <= PromotedMax) return InRange;
11463       return InHole;
11464     }
11465 
11466     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11467     case -1: return Less;
11468     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11469     case 1:
11470       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11471       case -1: return InRange;
11472       case 0: return Max;
11473       case 1: return Greater;
11474       }
11475     }
11476 
11477     llvm_unreachable("impossible compare result");
11478   }
11479 
11480   static llvm::Optional<StringRef>
11481   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11482     if (Op == BO_Cmp) {
11483       ComparisonResult LTFlag = LT, GTFlag = GT;
11484       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11485 
11486       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11487       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11488       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11489       return llvm::None;
11490     }
11491 
11492     ComparisonResult TrueFlag, FalseFlag;
11493     if (Op == BO_EQ) {
11494       TrueFlag = EQ;
11495       FalseFlag = NE;
11496     } else if (Op == BO_NE) {
11497       TrueFlag = NE;
11498       FalseFlag = EQ;
11499     } else {
11500       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11501         TrueFlag = LT;
11502         FalseFlag = GE;
11503       } else {
11504         TrueFlag = GT;
11505         FalseFlag = LE;
11506       }
11507       if (Op == BO_GE || Op == BO_LE)
11508         std::swap(TrueFlag, FalseFlag);
11509     }
11510     if (R & TrueFlag)
11511       return StringRef("true");
11512     if (R & FalseFlag)
11513       return StringRef("false");
11514     return llvm::None;
11515   }
11516 };
11517 }
11518 
11519 static bool HasEnumType(Expr *E) {
11520   // Strip off implicit integral promotions.
11521   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11522     if (ICE->getCastKind() != CK_IntegralCast &&
11523         ICE->getCastKind() != CK_NoOp)
11524       break;
11525     E = ICE->getSubExpr();
11526   }
11527 
11528   return E->getType()->isEnumeralType();
11529 }
11530 
11531 static int classifyConstantValue(Expr *Constant) {
11532   // The values of this enumeration are used in the diagnostics
11533   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11534   enum ConstantValueKind {
11535     Miscellaneous = 0,
11536     LiteralTrue,
11537     LiteralFalse
11538   };
11539   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11540     return BL->getValue() ? ConstantValueKind::LiteralTrue
11541                           : ConstantValueKind::LiteralFalse;
11542   return ConstantValueKind::Miscellaneous;
11543 }
11544 
11545 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11546                                         Expr *Constant, Expr *Other,
11547                                         const llvm::APSInt &Value,
11548                                         bool RhsConstant) {
11549   if (S.inTemplateInstantiation())
11550     return false;
11551 
11552   Expr *OriginalOther = Other;
11553 
11554   Constant = Constant->IgnoreParenImpCasts();
11555   Other = Other->IgnoreParenImpCasts();
11556 
11557   // Suppress warnings on tautological comparisons between values of the same
11558   // enumeration type. There are only two ways we could warn on this:
11559   //  - If the constant is outside the range of representable values of
11560   //    the enumeration. In such a case, we should warn about the cast
11561   //    to enumeration type, not about the comparison.
11562   //  - If the constant is the maximum / minimum in-range value. For an
11563   //    enumeratin type, such comparisons can be meaningful and useful.
11564   if (Constant->getType()->isEnumeralType() &&
11565       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11566     return false;
11567 
11568   IntRange OtherValueRange = GetExprRange(
11569       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11570 
11571   QualType OtherT = Other->getType();
11572   if (const auto *AT = OtherT->getAs<AtomicType>())
11573     OtherT = AT->getValueType();
11574   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11575 
11576   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11577   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11578   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11579                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11580                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11581 
11582   // Whether we're treating Other as being a bool because of the form of
11583   // expression despite it having another type (typically 'int' in C).
11584   bool OtherIsBooleanDespiteType =
11585       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11586   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11587     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11588 
11589   // Check if all values in the range of possible values of this expression
11590   // lead to the same comparison outcome.
11591   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11592                                         Value.isUnsigned());
11593   auto Cmp = OtherPromotedValueRange.compare(Value);
11594   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11595   if (!Result)
11596     return false;
11597 
11598   // Also consider the range determined by the type alone. This allows us to
11599   // classify the warning under the proper diagnostic group.
11600   bool TautologicalTypeCompare = false;
11601   {
11602     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11603                                          Value.isUnsigned());
11604     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11605     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11606                                                        RhsConstant)) {
11607       TautologicalTypeCompare = true;
11608       Cmp = TypeCmp;
11609       Result = TypeResult;
11610     }
11611   }
11612 
11613   // Don't warn if the non-constant operand actually always evaluates to the
11614   // same value.
11615   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11616     return false;
11617 
11618   // Suppress the diagnostic for an in-range comparison if the constant comes
11619   // from a macro or enumerator. We don't want to diagnose
11620   //
11621   //   some_long_value <= INT_MAX
11622   //
11623   // when sizeof(int) == sizeof(long).
11624   bool InRange = Cmp & PromotedRange::InRangeFlag;
11625   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11626     return false;
11627 
11628   // A comparison of an unsigned bit-field against 0 is really a type problem,
11629   // even though at the type level the bit-field might promote to 'signed int'.
11630   if (Other->refersToBitField() && InRange && Value == 0 &&
11631       Other->getType()->isUnsignedIntegerOrEnumerationType())
11632     TautologicalTypeCompare = true;
11633 
11634   // If this is a comparison to an enum constant, include that
11635   // constant in the diagnostic.
11636   const EnumConstantDecl *ED = nullptr;
11637   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11638     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11639 
11640   // Should be enough for uint128 (39 decimal digits)
11641   SmallString<64> PrettySourceValue;
11642   llvm::raw_svector_ostream OS(PrettySourceValue);
11643   if (ED) {
11644     OS << '\'' << *ED << "' (" << Value << ")";
11645   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11646                Constant->IgnoreParenImpCasts())) {
11647     OS << (BL->getValue() ? "YES" : "NO");
11648   } else {
11649     OS << Value;
11650   }
11651 
11652   if (!TautologicalTypeCompare) {
11653     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11654         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11655         << E->getOpcodeStr() << OS.str() << *Result
11656         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11657     return true;
11658   }
11659 
11660   if (IsObjCSignedCharBool) {
11661     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11662                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11663                               << OS.str() << *Result);
11664     return true;
11665   }
11666 
11667   // FIXME: We use a somewhat different formatting for the in-range cases and
11668   // cases involving boolean values for historical reasons. We should pick a
11669   // consistent way of presenting these diagnostics.
11670   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11671 
11672     S.DiagRuntimeBehavior(
11673         E->getOperatorLoc(), E,
11674         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11675                          : diag::warn_tautological_bool_compare)
11676             << OS.str() << classifyConstantValue(Constant) << OtherT
11677             << OtherIsBooleanDespiteType << *Result
11678             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11679   } else {
11680     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11681     unsigned Diag =
11682         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11683             ? (HasEnumType(OriginalOther)
11684                    ? diag::warn_unsigned_enum_always_true_comparison
11685                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11686                               : diag::warn_unsigned_always_true_comparison)
11687             : diag::warn_tautological_constant_compare;
11688 
11689     S.Diag(E->getOperatorLoc(), Diag)
11690         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11691         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11692   }
11693 
11694   return true;
11695 }
11696 
11697 /// Analyze the operands of the given comparison.  Implements the
11698 /// fallback case from AnalyzeComparison.
11699 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11700   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11701   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11702 }
11703 
11704 /// Implements -Wsign-compare.
11705 ///
11706 /// \param E the binary operator to check for warnings
11707 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11708   // The type the comparison is being performed in.
11709   QualType T = E->getLHS()->getType();
11710 
11711   // Only analyze comparison operators where both sides have been converted to
11712   // the same type.
11713   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11714     return AnalyzeImpConvsInComparison(S, E);
11715 
11716   // Don't analyze value-dependent comparisons directly.
11717   if (E->isValueDependent())
11718     return AnalyzeImpConvsInComparison(S, E);
11719 
11720   Expr *LHS = E->getLHS();
11721   Expr *RHS = E->getRHS();
11722 
11723   if (T->isIntegralType(S.Context)) {
11724     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11725     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11726 
11727     // We don't care about expressions whose result is a constant.
11728     if (RHSValue && LHSValue)
11729       return AnalyzeImpConvsInComparison(S, E);
11730 
11731     // We only care about expressions where just one side is literal
11732     if ((bool)RHSValue ^ (bool)LHSValue) {
11733       // Is the constant on the RHS or LHS?
11734       const bool RhsConstant = (bool)RHSValue;
11735       Expr *Const = RhsConstant ? RHS : LHS;
11736       Expr *Other = RhsConstant ? LHS : RHS;
11737       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11738 
11739       // Check whether an integer constant comparison results in a value
11740       // of 'true' or 'false'.
11741       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11742         return AnalyzeImpConvsInComparison(S, E);
11743     }
11744   }
11745 
11746   if (!T->hasUnsignedIntegerRepresentation()) {
11747     // We don't do anything special if this isn't an unsigned integral
11748     // comparison:  we're only interested in integral comparisons, and
11749     // signed comparisons only happen in cases we don't care to warn about.
11750     return AnalyzeImpConvsInComparison(S, E);
11751   }
11752 
11753   LHS = LHS->IgnoreParenImpCasts();
11754   RHS = RHS->IgnoreParenImpCasts();
11755 
11756   if (!S.getLangOpts().CPlusPlus) {
11757     // Avoid warning about comparison of integers with different signs when
11758     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11759     // the type of `E`.
11760     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11761       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11762     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11763       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11764   }
11765 
11766   // Check to see if one of the (unmodified) operands is of different
11767   // signedness.
11768   Expr *signedOperand, *unsignedOperand;
11769   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11770     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11771            "unsigned comparison between two signed integer expressions?");
11772     signedOperand = LHS;
11773     unsignedOperand = RHS;
11774   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11775     signedOperand = RHS;
11776     unsignedOperand = LHS;
11777   } else {
11778     return AnalyzeImpConvsInComparison(S, E);
11779   }
11780 
11781   // Otherwise, calculate the effective range of the signed operand.
11782   IntRange signedRange = GetExprRange(
11783       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11784 
11785   // Go ahead and analyze implicit conversions in the operands.  Note
11786   // that we skip the implicit conversions on both sides.
11787   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11788   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11789 
11790   // If the signed range is non-negative, -Wsign-compare won't fire.
11791   if (signedRange.NonNegative)
11792     return;
11793 
11794   // For (in)equality comparisons, if the unsigned operand is a
11795   // constant which cannot collide with a overflowed signed operand,
11796   // then reinterpreting the signed operand as unsigned will not
11797   // change the result of the comparison.
11798   if (E->isEqualityOp()) {
11799     unsigned comparisonWidth = S.Context.getIntWidth(T);
11800     IntRange unsignedRange =
11801         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11802                      /*Approximate*/ true);
11803 
11804     // We should never be unable to prove that the unsigned operand is
11805     // non-negative.
11806     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11807 
11808     if (unsignedRange.Width < comparisonWidth)
11809       return;
11810   }
11811 
11812   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11813                         S.PDiag(diag::warn_mixed_sign_comparison)
11814                             << LHS->getType() << RHS->getType()
11815                             << LHS->getSourceRange() << RHS->getSourceRange());
11816 }
11817 
11818 /// Analyzes an attempt to assign the given value to a bitfield.
11819 ///
11820 /// Returns true if there was something fishy about the attempt.
11821 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11822                                       SourceLocation InitLoc) {
11823   assert(Bitfield->isBitField());
11824   if (Bitfield->isInvalidDecl())
11825     return false;
11826 
11827   // White-list bool bitfields.
11828   QualType BitfieldType = Bitfield->getType();
11829   if (BitfieldType->isBooleanType())
11830      return false;
11831 
11832   if (BitfieldType->isEnumeralType()) {
11833     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11834     // If the underlying enum type was not explicitly specified as an unsigned
11835     // type and the enum contain only positive values, MSVC++ will cause an
11836     // inconsistency by storing this as a signed type.
11837     if (S.getLangOpts().CPlusPlus11 &&
11838         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11839         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11840         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11841       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11842           << BitfieldEnumDecl;
11843     }
11844   }
11845 
11846   if (Bitfield->getType()->isBooleanType())
11847     return false;
11848 
11849   // Ignore value- or type-dependent expressions.
11850   if (Bitfield->getBitWidth()->isValueDependent() ||
11851       Bitfield->getBitWidth()->isTypeDependent() ||
11852       Init->isValueDependent() ||
11853       Init->isTypeDependent())
11854     return false;
11855 
11856   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11857   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11858 
11859   Expr::EvalResult Result;
11860   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11861                                    Expr::SE_AllowSideEffects)) {
11862     // The RHS is not constant.  If the RHS has an enum type, make sure the
11863     // bitfield is wide enough to hold all the values of the enum without
11864     // truncation.
11865     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11866       EnumDecl *ED = EnumTy->getDecl();
11867       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11868 
11869       // Enum types are implicitly signed on Windows, so check if there are any
11870       // negative enumerators to see if the enum was intended to be signed or
11871       // not.
11872       bool SignedEnum = ED->getNumNegativeBits() > 0;
11873 
11874       // Check for surprising sign changes when assigning enum values to a
11875       // bitfield of different signedness.  If the bitfield is signed and we
11876       // have exactly the right number of bits to store this unsigned enum,
11877       // suggest changing the enum to an unsigned type. This typically happens
11878       // on Windows where unfixed enums always use an underlying type of 'int'.
11879       unsigned DiagID = 0;
11880       if (SignedEnum && !SignedBitfield) {
11881         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11882       } else if (SignedBitfield && !SignedEnum &&
11883                  ED->getNumPositiveBits() == FieldWidth) {
11884         DiagID = diag::warn_signed_bitfield_enum_conversion;
11885       }
11886 
11887       if (DiagID) {
11888         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11889         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11890         SourceRange TypeRange =
11891             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11892         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11893             << SignedEnum << TypeRange;
11894       }
11895 
11896       // Compute the required bitwidth. If the enum has negative values, we need
11897       // one more bit than the normal number of positive bits to represent the
11898       // sign bit.
11899       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11900                                                   ED->getNumNegativeBits())
11901                                        : ED->getNumPositiveBits();
11902 
11903       // Check the bitwidth.
11904       if (BitsNeeded > FieldWidth) {
11905         Expr *WidthExpr = Bitfield->getBitWidth();
11906         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11907             << Bitfield << ED;
11908         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11909             << BitsNeeded << ED << WidthExpr->getSourceRange();
11910       }
11911     }
11912 
11913     return false;
11914   }
11915 
11916   llvm::APSInt Value = Result.Val.getInt();
11917 
11918   unsigned OriginalWidth = Value.getBitWidth();
11919 
11920   if (!Value.isSigned() || Value.isNegative())
11921     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11922       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11923         OriginalWidth = Value.getMinSignedBits();
11924 
11925   if (OriginalWidth <= FieldWidth)
11926     return false;
11927 
11928   // Compute the value which the bitfield will contain.
11929   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11930   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11931 
11932   // Check whether the stored value is equal to the original value.
11933   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11934   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11935     return false;
11936 
11937   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11938   // therefore don't strictly fit into a signed bitfield of width 1.
11939   if (FieldWidth == 1 && Value == 1)
11940     return false;
11941 
11942   std::string PrettyValue = toString(Value, 10);
11943   std::string PrettyTrunc = toString(TruncatedValue, 10);
11944 
11945   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11946     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11947     << Init->getSourceRange();
11948 
11949   return true;
11950 }
11951 
11952 /// Analyze the given simple or compound assignment for warning-worthy
11953 /// operations.
11954 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11955   // Just recurse on the LHS.
11956   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11957 
11958   // We want to recurse on the RHS as normal unless we're assigning to
11959   // a bitfield.
11960   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11961     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11962                                   E->getOperatorLoc())) {
11963       // Recurse, ignoring any implicit conversions on the RHS.
11964       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11965                                         E->getOperatorLoc());
11966     }
11967   }
11968 
11969   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11970 
11971   // Diagnose implicitly sequentially-consistent atomic assignment.
11972   if (E->getLHS()->getType()->isAtomicType())
11973     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11974 }
11975 
11976 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11977 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11978                             SourceLocation CContext, unsigned diag,
11979                             bool pruneControlFlow = false) {
11980   if (pruneControlFlow) {
11981     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11982                           S.PDiag(diag)
11983                               << SourceType << T << E->getSourceRange()
11984                               << SourceRange(CContext));
11985     return;
11986   }
11987   S.Diag(E->getExprLoc(), diag)
11988     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11989 }
11990 
11991 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11992 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11993                             SourceLocation CContext,
11994                             unsigned diag, bool pruneControlFlow = false) {
11995   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11996 }
11997 
11998 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11999   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12000       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12001 }
12002 
12003 static void adornObjCBoolConversionDiagWithTernaryFixit(
12004     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12005   Expr *Ignored = SourceExpr->IgnoreImplicit();
12006   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12007     Ignored = OVE->getSourceExpr();
12008   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12009                      isa<BinaryOperator>(Ignored) ||
12010                      isa<CXXOperatorCallExpr>(Ignored);
12011   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12012   if (NeedsParens)
12013     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12014             << FixItHint::CreateInsertion(EndLoc, ")");
12015   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12016 }
12017 
12018 /// Diagnose an implicit cast from a floating point value to an integer value.
12019 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12020                                     SourceLocation CContext) {
12021   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12022   const bool PruneWarnings = S.inTemplateInstantiation();
12023 
12024   Expr *InnerE = E->IgnoreParenImpCasts();
12025   // We also want to warn on, e.g., "int i = -1.234"
12026   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12027     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12028       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12029 
12030   const bool IsLiteral =
12031       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12032 
12033   llvm::APFloat Value(0.0);
12034   bool IsConstant =
12035     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12036   if (!IsConstant) {
12037     if (isObjCSignedCharBool(S, T)) {
12038       return adornObjCBoolConversionDiagWithTernaryFixit(
12039           S, E,
12040           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12041               << E->getType());
12042     }
12043 
12044     return DiagnoseImpCast(S, E, T, CContext,
12045                            diag::warn_impcast_float_integer, PruneWarnings);
12046   }
12047 
12048   bool isExact = false;
12049 
12050   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12051                             T->hasUnsignedIntegerRepresentation());
12052   llvm::APFloat::opStatus Result = Value.convertToInteger(
12053       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12054 
12055   // FIXME: Force the precision of the source value down so we don't print
12056   // digits which are usually useless (we don't really care here if we
12057   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12058   // would automatically print the shortest representation, but it's a bit
12059   // tricky to implement.
12060   SmallString<16> PrettySourceValue;
12061   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12062   precision = (precision * 59 + 195) / 196;
12063   Value.toString(PrettySourceValue, precision);
12064 
12065   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12066     return adornObjCBoolConversionDiagWithTernaryFixit(
12067         S, E,
12068         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12069             << PrettySourceValue);
12070   }
12071 
12072   if (Result == llvm::APFloat::opOK && isExact) {
12073     if (IsLiteral) return;
12074     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12075                            PruneWarnings);
12076   }
12077 
12078   // Conversion of a floating-point value to a non-bool integer where the
12079   // integral part cannot be represented by the integer type is undefined.
12080   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12081     return DiagnoseImpCast(
12082         S, E, T, CContext,
12083         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12084                   : diag::warn_impcast_float_to_integer_out_of_range,
12085         PruneWarnings);
12086 
12087   unsigned DiagID = 0;
12088   if (IsLiteral) {
12089     // Warn on floating point literal to integer.
12090     DiagID = diag::warn_impcast_literal_float_to_integer;
12091   } else if (IntegerValue == 0) {
12092     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12093       return DiagnoseImpCast(S, E, T, CContext,
12094                              diag::warn_impcast_float_integer, PruneWarnings);
12095     }
12096     // Warn on non-zero to zero conversion.
12097     DiagID = diag::warn_impcast_float_to_integer_zero;
12098   } else {
12099     if (IntegerValue.isUnsigned()) {
12100       if (!IntegerValue.isMaxValue()) {
12101         return DiagnoseImpCast(S, E, T, CContext,
12102                                diag::warn_impcast_float_integer, PruneWarnings);
12103       }
12104     } else {  // IntegerValue.isSigned()
12105       if (!IntegerValue.isMaxSignedValue() &&
12106           !IntegerValue.isMinSignedValue()) {
12107         return DiagnoseImpCast(S, E, T, CContext,
12108                                diag::warn_impcast_float_integer, PruneWarnings);
12109       }
12110     }
12111     // Warn on evaluatable floating point expression to integer conversion.
12112     DiagID = diag::warn_impcast_float_to_integer;
12113   }
12114 
12115   SmallString<16> PrettyTargetValue;
12116   if (IsBool)
12117     PrettyTargetValue = Value.isZero() ? "false" : "true";
12118   else
12119     IntegerValue.toString(PrettyTargetValue);
12120 
12121   if (PruneWarnings) {
12122     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12123                           S.PDiag(DiagID)
12124                               << E->getType() << T.getUnqualifiedType()
12125                               << PrettySourceValue << PrettyTargetValue
12126                               << E->getSourceRange() << SourceRange(CContext));
12127   } else {
12128     S.Diag(E->getExprLoc(), DiagID)
12129         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12130         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12131   }
12132 }
12133 
12134 /// Analyze the given compound assignment for the possible losing of
12135 /// floating-point precision.
12136 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12137   assert(isa<CompoundAssignOperator>(E) &&
12138          "Must be compound assignment operation");
12139   // Recurse on the LHS and RHS in here
12140   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12141   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12142 
12143   if (E->getLHS()->getType()->isAtomicType())
12144     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12145 
12146   // Now check the outermost expression
12147   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12148   const auto *RBT = cast<CompoundAssignOperator>(E)
12149                         ->getComputationResultType()
12150                         ->getAs<BuiltinType>();
12151 
12152   // The below checks assume source is floating point.
12153   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12154 
12155   // If source is floating point but target is an integer.
12156   if (ResultBT->isInteger())
12157     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12158                            E->getExprLoc(), diag::warn_impcast_float_integer);
12159 
12160   if (!ResultBT->isFloatingPoint())
12161     return;
12162 
12163   // If both source and target are floating points, warn about losing precision.
12164   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12165       QualType(ResultBT, 0), QualType(RBT, 0));
12166   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12167     // warn about dropping FP rank.
12168     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12169                     diag::warn_impcast_float_result_precision);
12170 }
12171 
12172 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12173                                       IntRange Range) {
12174   if (!Range.Width) return "0";
12175 
12176   llvm::APSInt ValueInRange = Value;
12177   ValueInRange.setIsSigned(!Range.NonNegative);
12178   ValueInRange = ValueInRange.trunc(Range.Width);
12179   return toString(ValueInRange, 10);
12180 }
12181 
12182 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12183   if (!isa<ImplicitCastExpr>(Ex))
12184     return false;
12185 
12186   Expr *InnerE = Ex->IgnoreParenImpCasts();
12187   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12188   const Type *Source =
12189     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12190   if (Target->isDependentType())
12191     return false;
12192 
12193   const BuiltinType *FloatCandidateBT =
12194     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12195   const Type *BoolCandidateType = ToBool ? Target : Source;
12196 
12197   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12198           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12199 }
12200 
12201 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12202                                              SourceLocation CC) {
12203   unsigned NumArgs = TheCall->getNumArgs();
12204   for (unsigned i = 0; i < NumArgs; ++i) {
12205     Expr *CurrA = TheCall->getArg(i);
12206     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12207       continue;
12208 
12209     bool IsSwapped = ((i > 0) &&
12210         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12211     IsSwapped |= ((i < (NumArgs - 1)) &&
12212         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12213     if (IsSwapped) {
12214       // Warn on this floating-point to bool conversion.
12215       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12216                       CurrA->getType(), CC,
12217                       diag::warn_impcast_floating_point_to_bool);
12218     }
12219   }
12220 }
12221 
12222 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12223                                    SourceLocation CC) {
12224   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12225                         E->getExprLoc()))
12226     return;
12227 
12228   // Don't warn on functions which have return type nullptr_t.
12229   if (isa<CallExpr>(E))
12230     return;
12231 
12232   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12233   const Expr::NullPointerConstantKind NullKind =
12234       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12235   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12236     return;
12237 
12238   // Return if target type is a safe conversion.
12239   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12240       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12241     return;
12242 
12243   SourceLocation Loc = E->getSourceRange().getBegin();
12244 
12245   // Venture through the macro stacks to get to the source of macro arguments.
12246   // The new location is a better location than the complete location that was
12247   // passed in.
12248   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12249   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12250 
12251   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12252   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12253     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12254         Loc, S.SourceMgr, S.getLangOpts());
12255     if (MacroName == "NULL")
12256       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12257   }
12258 
12259   // Only warn if the null and context location are in the same macro expansion.
12260   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12261     return;
12262 
12263   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12264       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12265       << FixItHint::CreateReplacement(Loc,
12266                                       S.getFixItZeroLiteralForType(T, Loc));
12267 }
12268 
12269 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12270                                   ObjCArrayLiteral *ArrayLiteral);
12271 
12272 static void
12273 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12274                            ObjCDictionaryLiteral *DictionaryLiteral);
12275 
12276 /// Check a single element within a collection literal against the
12277 /// target element type.
12278 static void checkObjCCollectionLiteralElement(Sema &S,
12279                                               QualType TargetElementType,
12280                                               Expr *Element,
12281                                               unsigned ElementKind) {
12282   // Skip a bitcast to 'id' or qualified 'id'.
12283   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12284     if (ICE->getCastKind() == CK_BitCast &&
12285         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12286       Element = ICE->getSubExpr();
12287   }
12288 
12289   QualType ElementType = Element->getType();
12290   ExprResult ElementResult(Element);
12291   if (ElementType->getAs<ObjCObjectPointerType>() &&
12292       S.CheckSingleAssignmentConstraints(TargetElementType,
12293                                          ElementResult,
12294                                          false, false)
12295         != Sema::Compatible) {
12296     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12297         << ElementType << ElementKind << TargetElementType
12298         << Element->getSourceRange();
12299   }
12300 
12301   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12302     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12303   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12304     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12305 }
12306 
12307 /// Check an Objective-C array literal being converted to the given
12308 /// target type.
12309 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12310                                   ObjCArrayLiteral *ArrayLiteral) {
12311   if (!S.NSArrayDecl)
12312     return;
12313 
12314   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12315   if (!TargetObjCPtr)
12316     return;
12317 
12318   if (TargetObjCPtr->isUnspecialized() ||
12319       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12320         != S.NSArrayDecl->getCanonicalDecl())
12321     return;
12322 
12323   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12324   if (TypeArgs.size() != 1)
12325     return;
12326 
12327   QualType TargetElementType = TypeArgs[0];
12328   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12329     checkObjCCollectionLiteralElement(S, TargetElementType,
12330                                       ArrayLiteral->getElement(I),
12331                                       0);
12332   }
12333 }
12334 
12335 /// Check an Objective-C dictionary literal being converted to the given
12336 /// target type.
12337 static void
12338 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12339                            ObjCDictionaryLiteral *DictionaryLiteral) {
12340   if (!S.NSDictionaryDecl)
12341     return;
12342 
12343   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12344   if (!TargetObjCPtr)
12345     return;
12346 
12347   if (TargetObjCPtr->isUnspecialized() ||
12348       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12349         != S.NSDictionaryDecl->getCanonicalDecl())
12350     return;
12351 
12352   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12353   if (TypeArgs.size() != 2)
12354     return;
12355 
12356   QualType TargetKeyType = TypeArgs[0];
12357   QualType TargetObjectType = TypeArgs[1];
12358   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12359     auto Element = DictionaryLiteral->getKeyValueElement(I);
12360     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12361     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12362   }
12363 }
12364 
12365 // Helper function to filter out cases for constant width constant conversion.
12366 // Don't warn on char array initialization or for non-decimal values.
12367 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12368                                           SourceLocation CC) {
12369   // If initializing from a constant, and the constant starts with '0',
12370   // then it is a binary, octal, or hexadecimal.  Allow these constants
12371   // to fill all the bits, even if there is a sign change.
12372   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12373     const char FirstLiteralCharacter =
12374         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12375     if (FirstLiteralCharacter == '0')
12376       return false;
12377   }
12378 
12379   // If the CC location points to a '{', and the type is char, then assume
12380   // assume it is an array initialization.
12381   if (CC.isValid() && T->isCharType()) {
12382     const char FirstContextCharacter =
12383         S.getSourceManager().getCharacterData(CC)[0];
12384     if (FirstContextCharacter == '{')
12385       return false;
12386   }
12387 
12388   return true;
12389 }
12390 
12391 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12392   const auto *IL = dyn_cast<IntegerLiteral>(E);
12393   if (!IL) {
12394     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12395       if (UO->getOpcode() == UO_Minus)
12396         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12397     }
12398   }
12399 
12400   return IL;
12401 }
12402 
12403 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12404   E = E->IgnoreParenImpCasts();
12405   SourceLocation ExprLoc = E->getExprLoc();
12406 
12407   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12408     BinaryOperator::Opcode Opc = BO->getOpcode();
12409     Expr::EvalResult Result;
12410     // Do not diagnose unsigned shifts.
12411     if (Opc == BO_Shl) {
12412       const auto *LHS = getIntegerLiteral(BO->getLHS());
12413       const auto *RHS = getIntegerLiteral(BO->getRHS());
12414       if (LHS && LHS->getValue() == 0)
12415         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12416       else if (!E->isValueDependent() && LHS && RHS &&
12417                RHS->getValue().isNonNegative() &&
12418                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12419         S.Diag(ExprLoc, diag::warn_left_shift_always)
12420             << (Result.Val.getInt() != 0);
12421       else if (E->getType()->isSignedIntegerType())
12422         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12423     }
12424   }
12425 
12426   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12427     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12428     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12429     if (!LHS || !RHS)
12430       return;
12431     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12432         (RHS->getValue() == 0 || RHS->getValue() == 1))
12433       // Do not diagnose common idioms.
12434       return;
12435     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12436       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12437   }
12438 }
12439 
12440 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12441                                     SourceLocation CC,
12442                                     bool *ICContext = nullptr,
12443                                     bool IsListInit = false) {
12444   if (E->isTypeDependent() || E->isValueDependent()) return;
12445 
12446   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12447   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12448   if (Source == Target) return;
12449   if (Target->isDependentType()) return;
12450 
12451   // If the conversion context location is invalid don't complain. We also
12452   // don't want to emit a warning if the issue occurs from the expansion of
12453   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12454   // delay this check as long as possible. Once we detect we are in that
12455   // scenario, we just return.
12456   if (CC.isInvalid())
12457     return;
12458 
12459   if (Source->isAtomicType())
12460     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12461 
12462   // Diagnose implicit casts to bool.
12463   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12464     if (isa<StringLiteral>(E))
12465       // Warn on string literal to bool.  Checks for string literals in logical
12466       // and expressions, for instance, assert(0 && "error here"), are
12467       // prevented by a check in AnalyzeImplicitConversions().
12468       return DiagnoseImpCast(S, E, T, CC,
12469                              diag::warn_impcast_string_literal_to_bool);
12470     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12471         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12472       // This covers the literal expressions that evaluate to Objective-C
12473       // objects.
12474       return DiagnoseImpCast(S, E, T, CC,
12475                              diag::warn_impcast_objective_c_literal_to_bool);
12476     }
12477     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12478       // Warn on pointer to bool conversion that is always true.
12479       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12480                                      SourceRange(CC));
12481     }
12482   }
12483 
12484   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12485   // is a typedef for signed char (macOS), then that constant value has to be 1
12486   // or 0.
12487   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12488     Expr::EvalResult Result;
12489     if (E->EvaluateAsInt(Result, S.getASTContext(),
12490                          Expr::SE_AllowSideEffects)) {
12491       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12492         adornObjCBoolConversionDiagWithTernaryFixit(
12493             S, E,
12494             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12495                 << toString(Result.Val.getInt(), 10));
12496       }
12497       return;
12498     }
12499   }
12500 
12501   // Check implicit casts from Objective-C collection literals to specialized
12502   // collection types, e.g., NSArray<NSString *> *.
12503   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12504     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12505   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12506     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12507 
12508   // Strip vector types.
12509   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12510     if (Target->isVLSTBuiltinType()) {
12511       auto SourceVectorKind = SourceVT->getVectorKind();
12512       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12513           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12514           (SourceVectorKind == VectorType::GenericVector &&
12515            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12516         return;
12517     }
12518 
12519     if (!isa<VectorType>(Target)) {
12520       if (S.SourceMgr.isInSystemMacro(CC))
12521         return;
12522       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12523     }
12524 
12525     // If the vector cast is cast between two vectors of the same size, it is
12526     // a bitcast, not a conversion.
12527     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12528       return;
12529 
12530     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12531     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12532   }
12533   if (auto VecTy = dyn_cast<VectorType>(Target))
12534     Target = VecTy->getElementType().getTypePtr();
12535 
12536   // Strip complex types.
12537   if (isa<ComplexType>(Source)) {
12538     if (!isa<ComplexType>(Target)) {
12539       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12540         return;
12541 
12542       return DiagnoseImpCast(S, E, T, CC,
12543                              S.getLangOpts().CPlusPlus
12544                                  ? diag::err_impcast_complex_scalar
12545                                  : diag::warn_impcast_complex_scalar);
12546     }
12547 
12548     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12549     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12550   }
12551 
12552   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12553   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12554 
12555   // If the source is floating point...
12556   if (SourceBT && SourceBT->isFloatingPoint()) {
12557     // ...and the target is floating point...
12558     if (TargetBT && TargetBT->isFloatingPoint()) {
12559       // ...then warn if we're dropping FP rank.
12560 
12561       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12562           QualType(SourceBT, 0), QualType(TargetBT, 0));
12563       if (Order > 0) {
12564         // Don't warn about float constants that are precisely
12565         // representable in the target type.
12566         Expr::EvalResult result;
12567         if (E->EvaluateAsRValue(result, S.Context)) {
12568           // Value might be a float, a float vector, or a float complex.
12569           if (IsSameFloatAfterCast(result.Val,
12570                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12571                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12572             return;
12573         }
12574 
12575         if (S.SourceMgr.isInSystemMacro(CC))
12576           return;
12577 
12578         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12579       }
12580       // ... or possibly if we're increasing rank, too
12581       else if (Order < 0) {
12582         if (S.SourceMgr.isInSystemMacro(CC))
12583           return;
12584 
12585         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12586       }
12587       return;
12588     }
12589 
12590     // If the target is integral, always warn.
12591     if (TargetBT && TargetBT->isInteger()) {
12592       if (S.SourceMgr.isInSystemMacro(CC))
12593         return;
12594 
12595       DiagnoseFloatingImpCast(S, E, T, CC);
12596     }
12597 
12598     // Detect the case where a call result is converted from floating-point to
12599     // to bool, and the final argument to the call is converted from bool, to
12600     // discover this typo:
12601     //
12602     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12603     //
12604     // FIXME: This is an incredibly special case; is there some more general
12605     // way to detect this class of misplaced-parentheses bug?
12606     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12607       // Check last argument of function call to see if it is an
12608       // implicit cast from a type matching the type the result
12609       // is being cast to.
12610       CallExpr *CEx = cast<CallExpr>(E);
12611       if (unsigned NumArgs = CEx->getNumArgs()) {
12612         Expr *LastA = CEx->getArg(NumArgs - 1);
12613         Expr *InnerE = LastA->IgnoreParenImpCasts();
12614         if (isa<ImplicitCastExpr>(LastA) &&
12615             InnerE->getType()->isBooleanType()) {
12616           // Warn on this floating-point to bool conversion
12617           DiagnoseImpCast(S, E, T, CC,
12618                           diag::warn_impcast_floating_point_to_bool);
12619         }
12620       }
12621     }
12622     return;
12623   }
12624 
12625   // Valid casts involving fixed point types should be accounted for here.
12626   if (Source->isFixedPointType()) {
12627     if (Target->isUnsaturatedFixedPointType()) {
12628       Expr::EvalResult Result;
12629       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12630                                   S.isConstantEvaluated())) {
12631         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12632         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12633         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12634         if (Value > MaxVal || Value < MinVal) {
12635           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12636                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12637                                     << Value.toString() << T
12638                                     << E->getSourceRange()
12639                                     << clang::SourceRange(CC));
12640           return;
12641         }
12642       }
12643     } else if (Target->isIntegerType()) {
12644       Expr::EvalResult Result;
12645       if (!S.isConstantEvaluated() &&
12646           E->EvaluateAsFixedPoint(Result, S.Context,
12647                                   Expr::SE_AllowSideEffects)) {
12648         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12649 
12650         bool Overflowed;
12651         llvm::APSInt IntResult = FXResult.convertToInt(
12652             S.Context.getIntWidth(T),
12653             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12654 
12655         if (Overflowed) {
12656           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12657                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12658                                     << FXResult.toString() << T
12659                                     << E->getSourceRange()
12660                                     << clang::SourceRange(CC));
12661           return;
12662         }
12663       }
12664     }
12665   } else if (Target->isUnsaturatedFixedPointType()) {
12666     if (Source->isIntegerType()) {
12667       Expr::EvalResult Result;
12668       if (!S.isConstantEvaluated() &&
12669           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12670         llvm::APSInt Value = Result.Val.getInt();
12671 
12672         bool Overflowed;
12673         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12674             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12675 
12676         if (Overflowed) {
12677           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12678                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12679                                     << toString(Value, /*Radix=*/10) << T
12680                                     << E->getSourceRange()
12681                                     << clang::SourceRange(CC));
12682           return;
12683         }
12684       }
12685     }
12686   }
12687 
12688   // If we are casting an integer type to a floating point type without
12689   // initialization-list syntax, we might lose accuracy if the floating
12690   // point type has a narrower significand than the integer type.
12691   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12692       TargetBT->isFloatingType() && !IsListInit) {
12693     // Determine the number of precision bits in the source integer type.
12694     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12695                                         /*Approximate*/ true);
12696     unsigned int SourcePrecision = SourceRange.Width;
12697 
12698     // Determine the number of precision bits in the
12699     // target floating point type.
12700     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12701         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12702 
12703     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12704         SourcePrecision > TargetPrecision) {
12705 
12706       if (Optional<llvm::APSInt> SourceInt =
12707               E->getIntegerConstantExpr(S.Context)) {
12708         // If the source integer is a constant, convert it to the target
12709         // floating point type. Issue a warning if the value changes
12710         // during the whole conversion.
12711         llvm::APFloat TargetFloatValue(
12712             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12713         llvm::APFloat::opStatus ConversionStatus =
12714             TargetFloatValue.convertFromAPInt(
12715                 *SourceInt, SourceBT->isSignedInteger(),
12716                 llvm::APFloat::rmNearestTiesToEven);
12717 
12718         if (ConversionStatus != llvm::APFloat::opOK) {
12719           SmallString<32> PrettySourceValue;
12720           SourceInt->toString(PrettySourceValue, 10);
12721           SmallString<32> PrettyTargetValue;
12722           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12723 
12724           S.DiagRuntimeBehavior(
12725               E->getExprLoc(), E,
12726               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12727                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12728                   << E->getSourceRange() << clang::SourceRange(CC));
12729         }
12730       } else {
12731         // Otherwise, the implicit conversion may lose precision.
12732         DiagnoseImpCast(S, E, T, CC,
12733                         diag::warn_impcast_integer_float_precision);
12734       }
12735     }
12736   }
12737 
12738   DiagnoseNullConversion(S, E, T, CC);
12739 
12740   S.DiscardMisalignedMemberAddress(Target, E);
12741 
12742   if (Target->isBooleanType())
12743     DiagnoseIntInBoolContext(S, E);
12744 
12745   if (!Source->isIntegerType() || !Target->isIntegerType())
12746     return;
12747 
12748   // TODO: remove this early return once the false positives for constant->bool
12749   // in templates, macros, etc, are reduced or removed.
12750   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12751     return;
12752 
12753   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12754       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12755     return adornObjCBoolConversionDiagWithTernaryFixit(
12756         S, E,
12757         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12758             << E->getType());
12759   }
12760 
12761   IntRange SourceTypeRange =
12762       IntRange::forTargetOfCanonicalType(S.Context, Source);
12763   IntRange LikelySourceRange =
12764       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12765   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12766 
12767   if (LikelySourceRange.Width > TargetRange.Width) {
12768     // If the source is a constant, use a default-on diagnostic.
12769     // TODO: this should happen for bitfield stores, too.
12770     Expr::EvalResult Result;
12771     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12772                          S.isConstantEvaluated())) {
12773       llvm::APSInt Value(32);
12774       Value = Result.Val.getInt();
12775 
12776       if (S.SourceMgr.isInSystemMacro(CC))
12777         return;
12778 
12779       std::string PrettySourceValue = toString(Value, 10);
12780       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12781 
12782       S.DiagRuntimeBehavior(
12783           E->getExprLoc(), E,
12784           S.PDiag(diag::warn_impcast_integer_precision_constant)
12785               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12786               << E->getSourceRange() << SourceRange(CC));
12787       return;
12788     }
12789 
12790     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12791     if (S.SourceMgr.isInSystemMacro(CC))
12792       return;
12793 
12794     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12795       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12796                              /* pruneControlFlow */ true);
12797     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12798   }
12799 
12800   if (TargetRange.Width > SourceTypeRange.Width) {
12801     if (auto *UO = dyn_cast<UnaryOperator>(E))
12802       if (UO->getOpcode() == UO_Minus)
12803         if (Source->isUnsignedIntegerType()) {
12804           if (Target->isUnsignedIntegerType())
12805             return DiagnoseImpCast(S, E, T, CC,
12806                                    diag::warn_impcast_high_order_zero_bits);
12807           if (Target->isSignedIntegerType())
12808             return DiagnoseImpCast(S, E, T, CC,
12809                                    diag::warn_impcast_nonnegative_result);
12810         }
12811   }
12812 
12813   if (TargetRange.Width == LikelySourceRange.Width &&
12814       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12815       Source->isSignedIntegerType()) {
12816     // Warn when doing a signed to signed conversion, warn if the positive
12817     // source value is exactly the width of the target type, which will
12818     // cause a negative value to be stored.
12819 
12820     Expr::EvalResult Result;
12821     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12822         !S.SourceMgr.isInSystemMacro(CC)) {
12823       llvm::APSInt Value = Result.Val.getInt();
12824       if (isSameWidthConstantConversion(S, E, T, CC)) {
12825         std::string PrettySourceValue = toString(Value, 10);
12826         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12827 
12828         S.DiagRuntimeBehavior(
12829             E->getExprLoc(), E,
12830             S.PDiag(diag::warn_impcast_integer_precision_constant)
12831                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12832                 << E->getSourceRange() << SourceRange(CC));
12833         return;
12834       }
12835     }
12836 
12837     // Fall through for non-constants to give a sign conversion warning.
12838   }
12839 
12840   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12841       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12842        LikelySourceRange.Width == TargetRange.Width)) {
12843     if (S.SourceMgr.isInSystemMacro(CC))
12844       return;
12845 
12846     unsigned DiagID = diag::warn_impcast_integer_sign;
12847 
12848     // Traditionally, gcc has warned about this under -Wsign-compare.
12849     // We also want to warn about it in -Wconversion.
12850     // So if -Wconversion is off, use a completely identical diagnostic
12851     // in the sign-compare group.
12852     // The conditional-checking code will
12853     if (ICContext) {
12854       DiagID = diag::warn_impcast_integer_sign_conditional;
12855       *ICContext = true;
12856     }
12857 
12858     return DiagnoseImpCast(S, E, T, CC, DiagID);
12859   }
12860 
12861   // Diagnose conversions between different enumeration types.
12862   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12863   // type, to give us better diagnostics.
12864   QualType SourceType = E->getType();
12865   if (!S.getLangOpts().CPlusPlus) {
12866     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12867       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12868         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12869         SourceType = S.Context.getTypeDeclType(Enum);
12870         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12871       }
12872   }
12873 
12874   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12875     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12876       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12877           TargetEnum->getDecl()->hasNameForLinkage() &&
12878           SourceEnum != TargetEnum) {
12879         if (S.SourceMgr.isInSystemMacro(CC))
12880           return;
12881 
12882         return DiagnoseImpCast(S, E, SourceType, T, CC,
12883                                diag::warn_impcast_different_enum_types);
12884       }
12885 }
12886 
12887 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12888                                      SourceLocation CC, QualType T);
12889 
12890 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12891                                     SourceLocation CC, bool &ICContext) {
12892   E = E->IgnoreParenImpCasts();
12893 
12894   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12895     return CheckConditionalOperator(S, CO, CC, T);
12896 
12897   AnalyzeImplicitConversions(S, E, CC);
12898   if (E->getType() != T)
12899     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12900 }
12901 
12902 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12903                                      SourceLocation CC, QualType T) {
12904   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12905 
12906   Expr *TrueExpr = E->getTrueExpr();
12907   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12908     TrueExpr = BCO->getCommon();
12909 
12910   bool Suspicious = false;
12911   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12912   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12913 
12914   if (T->isBooleanType())
12915     DiagnoseIntInBoolContext(S, E);
12916 
12917   // If -Wconversion would have warned about either of the candidates
12918   // for a signedness conversion to the context type...
12919   if (!Suspicious) return;
12920 
12921   // ...but it's currently ignored...
12922   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12923     return;
12924 
12925   // ...then check whether it would have warned about either of the
12926   // candidates for a signedness conversion to the condition type.
12927   if (E->getType() == T) return;
12928 
12929   Suspicious = false;
12930   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12931                           E->getType(), CC, &Suspicious);
12932   if (!Suspicious)
12933     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12934                             E->getType(), CC, &Suspicious);
12935 }
12936 
12937 /// Check conversion of given expression to boolean.
12938 /// Input argument E is a logical expression.
12939 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12940   if (S.getLangOpts().Bool)
12941     return;
12942   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12943     return;
12944   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12945 }
12946 
12947 namespace {
12948 struct AnalyzeImplicitConversionsWorkItem {
12949   Expr *E;
12950   SourceLocation CC;
12951   bool IsListInit;
12952 };
12953 }
12954 
12955 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12956 /// that should be visited are added to WorkList.
12957 static void AnalyzeImplicitConversions(
12958     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12959     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12960   Expr *OrigE = Item.E;
12961   SourceLocation CC = Item.CC;
12962 
12963   QualType T = OrigE->getType();
12964   Expr *E = OrigE->IgnoreParenImpCasts();
12965 
12966   // Propagate whether we are in a C++ list initialization expression.
12967   // If so, we do not issue warnings for implicit int-float conversion
12968   // precision loss, because C++11 narrowing already handles it.
12969   bool IsListInit = Item.IsListInit ||
12970                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12971 
12972   if (E->isTypeDependent() || E->isValueDependent())
12973     return;
12974 
12975   Expr *SourceExpr = E;
12976   // Examine, but don't traverse into the source expression of an
12977   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12978   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12979   // evaluate it in the context of checking the specific conversion to T though.
12980   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12981     if (auto *Src = OVE->getSourceExpr())
12982       SourceExpr = Src;
12983 
12984   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12985     if (UO->getOpcode() == UO_Not &&
12986         UO->getSubExpr()->isKnownToHaveBooleanValue())
12987       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12988           << OrigE->getSourceRange() << T->isBooleanType()
12989           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12990 
12991   // For conditional operators, we analyze the arguments as if they
12992   // were being fed directly into the output.
12993   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12994     CheckConditionalOperator(S, CO, CC, T);
12995     return;
12996   }
12997 
12998   // Check implicit argument conversions for function calls.
12999   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13000     CheckImplicitArgumentConversions(S, Call, CC);
13001 
13002   // Go ahead and check any implicit conversions we might have skipped.
13003   // The non-canonical typecheck is just an optimization;
13004   // CheckImplicitConversion will filter out dead implicit conversions.
13005   if (SourceExpr->getType() != T)
13006     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13007 
13008   // Now continue drilling into this expression.
13009 
13010   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13011     // The bound subexpressions in a PseudoObjectExpr are not reachable
13012     // as transitive children.
13013     // FIXME: Use a more uniform representation for this.
13014     for (auto *SE : POE->semantics())
13015       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13016         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13017   }
13018 
13019   // Skip past explicit casts.
13020   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13021     E = CE->getSubExpr()->IgnoreParenImpCasts();
13022     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13023       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13024     WorkList.push_back({E, CC, IsListInit});
13025     return;
13026   }
13027 
13028   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13029     // Do a somewhat different check with comparison operators.
13030     if (BO->isComparisonOp())
13031       return AnalyzeComparison(S, BO);
13032 
13033     // And with simple assignments.
13034     if (BO->getOpcode() == BO_Assign)
13035       return AnalyzeAssignment(S, BO);
13036     // And with compound assignments.
13037     if (BO->isAssignmentOp())
13038       return AnalyzeCompoundAssignment(S, BO);
13039   }
13040 
13041   // These break the otherwise-useful invariant below.  Fortunately,
13042   // we don't really need to recurse into them, because any internal
13043   // expressions should have been analyzed already when they were
13044   // built into statements.
13045   if (isa<StmtExpr>(E)) return;
13046 
13047   // Don't descend into unevaluated contexts.
13048   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13049 
13050   // Now just recurse over the expression's children.
13051   CC = E->getExprLoc();
13052   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13053   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13054   for (Stmt *SubStmt : E->children()) {
13055     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13056     if (!ChildExpr)
13057       continue;
13058 
13059     if (IsLogicalAndOperator &&
13060         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13061       // Ignore checking string literals that are in logical and operators.
13062       // This is a common pattern for asserts.
13063       continue;
13064     WorkList.push_back({ChildExpr, CC, IsListInit});
13065   }
13066 
13067   if (BO && BO->isLogicalOp()) {
13068     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13069     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13070       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13071 
13072     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13073     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13074       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13075   }
13076 
13077   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13078     if (U->getOpcode() == UO_LNot) {
13079       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13080     } else if (U->getOpcode() != UO_AddrOf) {
13081       if (U->getSubExpr()->getType()->isAtomicType())
13082         S.Diag(U->getSubExpr()->getBeginLoc(),
13083                diag::warn_atomic_implicit_seq_cst);
13084     }
13085   }
13086 }
13087 
13088 /// AnalyzeImplicitConversions - Find and report any interesting
13089 /// implicit conversions in the given expression.  There are a couple
13090 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13091 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13092                                        bool IsListInit/*= false*/) {
13093   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13094   WorkList.push_back({OrigE, CC, IsListInit});
13095   while (!WorkList.empty())
13096     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13097 }
13098 
13099 /// Diagnose integer type and any valid implicit conversion to it.
13100 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13101   // Taking into account implicit conversions,
13102   // allow any integer.
13103   if (!E->getType()->isIntegerType()) {
13104     S.Diag(E->getBeginLoc(),
13105            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13106     return true;
13107   }
13108   // Potentially emit standard warnings for implicit conversions if enabled
13109   // using -Wconversion.
13110   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13111   return false;
13112 }
13113 
13114 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13115 // Returns true when emitting a warning about taking the address of a reference.
13116 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13117                               const PartialDiagnostic &PD) {
13118   E = E->IgnoreParenImpCasts();
13119 
13120   const FunctionDecl *FD = nullptr;
13121 
13122   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13123     if (!DRE->getDecl()->getType()->isReferenceType())
13124       return false;
13125   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13126     if (!M->getMemberDecl()->getType()->isReferenceType())
13127       return false;
13128   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13129     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13130       return false;
13131     FD = Call->getDirectCallee();
13132   } else {
13133     return false;
13134   }
13135 
13136   SemaRef.Diag(E->getExprLoc(), PD);
13137 
13138   // If possible, point to location of function.
13139   if (FD) {
13140     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13141   }
13142 
13143   return true;
13144 }
13145 
13146 // Returns true if the SourceLocation is expanded from any macro body.
13147 // Returns false if the SourceLocation is invalid, is from not in a macro
13148 // expansion, or is from expanded from a top-level macro argument.
13149 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13150   if (Loc.isInvalid())
13151     return false;
13152 
13153   while (Loc.isMacroID()) {
13154     if (SM.isMacroBodyExpansion(Loc))
13155       return true;
13156     Loc = SM.getImmediateMacroCallerLoc(Loc);
13157   }
13158 
13159   return false;
13160 }
13161 
13162 /// Diagnose pointers that are always non-null.
13163 /// \param E the expression containing the pointer
13164 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13165 /// compared to a null pointer
13166 /// \param IsEqual True when the comparison is equal to a null pointer
13167 /// \param Range Extra SourceRange to highlight in the diagnostic
13168 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13169                                         Expr::NullPointerConstantKind NullKind,
13170                                         bool IsEqual, SourceRange Range) {
13171   if (!E)
13172     return;
13173 
13174   // Don't warn inside macros.
13175   if (E->getExprLoc().isMacroID()) {
13176     const SourceManager &SM = getSourceManager();
13177     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13178         IsInAnyMacroBody(SM, Range.getBegin()))
13179       return;
13180   }
13181   E = E->IgnoreImpCasts();
13182 
13183   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13184 
13185   if (isa<CXXThisExpr>(E)) {
13186     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13187                                 : diag::warn_this_bool_conversion;
13188     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13189     return;
13190   }
13191 
13192   bool IsAddressOf = false;
13193 
13194   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13195     if (UO->getOpcode() != UO_AddrOf)
13196       return;
13197     IsAddressOf = true;
13198     E = UO->getSubExpr();
13199   }
13200 
13201   if (IsAddressOf) {
13202     unsigned DiagID = IsCompare
13203                           ? diag::warn_address_of_reference_null_compare
13204                           : diag::warn_address_of_reference_bool_conversion;
13205     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13206                                          << IsEqual;
13207     if (CheckForReference(*this, E, PD)) {
13208       return;
13209     }
13210   }
13211 
13212   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13213     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13214     std::string Str;
13215     llvm::raw_string_ostream S(Str);
13216     E->printPretty(S, nullptr, getPrintingPolicy());
13217     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13218                                 : diag::warn_cast_nonnull_to_bool;
13219     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13220       << E->getSourceRange() << Range << IsEqual;
13221     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13222   };
13223 
13224   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13225   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13226     if (auto *Callee = Call->getDirectCallee()) {
13227       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13228         ComplainAboutNonnullParamOrCall(A);
13229         return;
13230       }
13231     }
13232   }
13233 
13234   // Expect to find a single Decl.  Skip anything more complicated.
13235   ValueDecl *D = nullptr;
13236   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13237     D = R->getDecl();
13238   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13239     D = M->getMemberDecl();
13240   }
13241 
13242   // Weak Decls can be null.
13243   if (!D || D->isWeak())
13244     return;
13245 
13246   // Check for parameter decl with nonnull attribute
13247   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13248     if (getCurFunction() &&
13249         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13250       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13251         ComplainAboutNonnullParamOrCall(A);
13252         return;
13253       }
13254 
13255       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13256         // Skip function template not specialized yet.
13257         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13258           return;
13259         auto ParamIter = llvm::find(FD->parameters(), PV);
13260         assert(ParamIter != FD->param_end());
13261         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13262 
13263         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13264           if (!NonNull->args_size()) {
13265               ComplainAboutNonnullParamOrCall(NonNull);
13266               return;
13267           }
13268 
13269           for (const ParamIdx &ArgNo : NonNull->args()) {
13270             if (ArgNo.getASTIndex() == ParamNo) {
13271               ComplainAboutNonnullParamOrCall(NonNull);
13272               return;
13273             }
13274           }
13275         }
13276       }
13277     }
13278   }
13279 
13280   QualType T = D->getType();
13281   const bool IsArray = T->isArrayType();
13282   const bool IsFunction = T->isFunctionType();
13283 
13284   // Address of function is used to silence the function warning.
13285   if (IsAddressOf && IsFunction) {
13286     return;
13287   }
13288 
13289   // Found nothing.
13290   if (!IsAddressOf && !IsFunction && !IsArray)
13291     return;
13292 
13293   // Pretty print the expression for the diagnostic.
13294   std::string Str;
13295   llvm::raw_string_ostream S(Str);
13296   E->printPretty(S, nullptr, getPrintingPolicy());
13297 
13298   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13299                               : diag::warn_impcast_pointer_to_bool;
13300   enum {
13301     AddressOf,
13302     FunctionPointer,
13303     ArrayPointer
13304   } DiagType;
13305   if (IsAddressOf)
13306     DiagType = AddressOf;
13307   else if (IsFunction)
13308     DiagType = FunctionPointer;
13309   else if (IsArray)
13310     DiagType = ArrayPointer;
13311   else
13312     llvm_unreachable("Could not determine diagnostic.");
13313   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13314                                 << Range << IsEqual;
13315 
13316   if (!IsFunction)
13317     return;
13318 
13319   // Suggest '&' to silence the function warning.
13320   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13321       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13322 
13323   // Check to see if '()' fixit should be emitted.
13324   QualType ReturnType;
13325   UnresolvedSet<4> NonTemplateOverloads;
13326   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13327   if (ReturnType.isNull())
13328     return;
13329 
13330   if (IsCompare) {
13331     // There are two cases here.  If there is null constant, the only suggest
13332     // for a pointer return type.  If the null is 0, then suggest if the return
13333     // type is a pointer or an integer type.
13334     if (!ReturnType->isPointerType()) {
13335       if (NullKind == Expr::NPCK_ZeroExpression ||
13336           NullKind == Expr::NPCK_ZeroLiteral) {
13337         if (!ReturnType->isIntegerType())
13338           return;
13339       } else {
13340         return;
13341       }
13342     }
13343   } else { // !IsCompare
13344     // For function to bool, only suggest if the function pointer has bool
13345     // return type.
13346     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13347       return;
13348   }
13349   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13350       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13351 }
13352 
13353 /// Diagnoses "dangerous" implicit conversions within the given
13354 /// expression (which is a full expression).  Implements -Wconversion
13355 /// and -Wsign-compare.
13356 ///
13357 /// \param CC the "context" location of the implicit conversion, i.e.
13358 ///   the most location of the syntactic entity requiring the implicit
13359 ///   conversion
13360 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13361   // Don't diagnose in unevaluated contexts.
13362   if (isUnevaluatedContext())
13363     return;
13364 
13365   // Don't diagnose for value- or type-dependent expressions.
13366   if (E->isTypeDependent() || E->isValueDependent())
13367     return;
13368 
13369   // Check for array bounds violations in cases where the check isn't triggered
13370   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13371   // ArraySubscriptExpr is on the RHS of a variable initialization.
13372   CheckArrayAccess(E);
13373 
13374   // This is not the right CC for (e.g.) a variable initialization.
13375   AnalyzeImplicitConversions(*this, E, CC);
13376 }
13377 
13378 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13379 /// Input argument E is a logical expression.
13380 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13381   ::CheckBoolLikeConversion(*this, E, CC);
13382 }
13383 
13384 /// Diagnose when expression is an integer constant expression and its evaluation
13385 /// results in integer overflow
13386 void Sema::CheckForIntOverflow (Expr *E) {
13387   // Use a work list to deal with nested struct initializers.
13388   SmallVector<Expr *, 2> Exprs(1, E);
13389 
13390   do {
13391     Expr *OriginalE = Exprs.pop_back_val();
13392     Expr *E = OriginalE->IgnoreParenCasts();
13393 
13394     if (isa<BinaryOperator>(E)) {
13395       E->EvaluateForOverflow(Context);
13396       continue;
13397     }
13398 
13399     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13400       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13401     else if (isa<ObjCBoxedExpr>(OriginalE))
13402       E->EvaluateForOverflow(Context);
13403     else if (auto Call = dyn_cast<CallExpr>(E))
13404       Exprs.append(Call->arg_begin(), Call->arg_end());
13405     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13406       Exprs.append(Message->arg_begin(), Message->arg_end());
13407   } while (!Exprs.empty());
13408 }
13409 
13410 namespace {
13411 
13412 /// Visitor for expressions which looks for unsequenced operations on the
13413 /// same object.
13414 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13415   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13416 
13417   /// A tree of sequenced regions within an expression. Two regions are
13418   /// unsequenced if one is an ancestor or a descendent of the other. When we
13419   /// finish processing an expression with sequencing, such as a comma
13420   /// expression, we fold its tree nodes into its parent, since they are
13421   /// unsequenced with respect to nodes we will visit later.
13422   class SequenceTree {
13423     struct Value {
13424       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13425       unsigned Parent : 31;
13426       unsigned Merged : 1;
13427     };
13428     SmallVector<Value, 8> Values;
13429 
13430   public:
13431     /// A region within an expression which may be sequenced with respect
13432     /// to some other region.
13433     class Seq {
13434       friend class SequenceTree;
13435 
13436       unsigned Index;
13437 
13438       explicit Seq(unsigned N) : Index(N) {}
13439 
13440     public:
13441       Seq() : Index(0) {}
13442     };
13443 
13444     SequenceTree() { Values.push_back(Value(0)); }
13445     Seq root() const { return Seq(0); }
13446 
13447     /// Create a new sequence of operations, which is an unsequenced
13448     /// subset of \p Parent. This sequence of operations is sequenced with
13449     /// respect to other children of \p Parent.
13450     Seq allocate(Seq Parent) {
13451       Values.push_back(Value(Parent.Index));
13452       return Seq(Values.size() - 1);
13453     }
13454 
13455     /// Merge a sequence of operations into its parent.
13456     void merge(Seq S) {
13457       Values[S.Index].Merged = true;
13458     }
13459 
13460     /// Determine whether two operations are unsequenced. This operation
13461     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13462     /// should have been merged into its parent as appropriate.
13463     bool isUnsequenced(Seq Cur, Seq Old) {
13464       unsigned C = representative(Cur.Index);
13465       unsigned Target = representative(Old.Index);
13466       while (C >= Target) {
13467         if (C == Target)
13468           return true;
13469         C = Values[C].Parent;
13470       }
13471       return false;
13472     }
13473 
13474   private:
13475     /// Pick a representative for a sequence.
13476     unsigned representative(unsigned K) {
13477       if (Values[K].Merged)
13478         // Perform path compression as we go.
13479         return Values[K].Parent = representative(Values[K].Parent);
13480       return K;
13481     }
13482   };
13483 
13484   /// An object for which we can track unsequenced uses.
13485   using Object = const NamedDecl *;
13486 
13487   /// Different flavors of object usage which we track. We only track the
13488   /// least-sequenced usage of each kind.
13489   enum UsageKind {
13490     /// A read of an object. Multiple unsequenced reads are OK.
13491     UK_Use,
13492 
13493     /// A modification of an object which is sequenced before the value
13494     /// computation of the expression, such as ++n in C++.
13495     UK_ModAsValue,
13496 
13497     /// A modification of an object which is not sequenced before the value
13498     /// computation of the expression, such as n++.
13499     UK_ModAsSideEffect,
13500 
13501     UK_Count = UK_ModAsSideEffect + 1
13502   };
13503 
13504   /// Bundle together a sequencing region and the expression corresponding
13505   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13506   struct Usage {
13507     const Expr *UsageExpr;
13508     SequenceTree::Seq Seq;
13509 
13510     Usage() : UsageExpr(nullptr), Seq() {}
13511   };
13512 
13513   struct UsageInfo {
13514     Usage Uses[UK_Count];
13515 
13516     /// Have we issued a diagnostic for this object already?
13517     bool Diagnosed;
13518 
13519     UsageInfo() : Uses(), Diagnosed(false) {}
13520   };
13521   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13522 
13523   Sema &SemaRef;
13524 
13525   /// Sequenced regions within the expression.
13526   SequenceTree Tree;
13527 
13528   /// Declaration modifications and references which we have seen.
13529   UsageInfoMap UsageMap;
13530 
13531   /// The region we are currently within.
13532   SequenceTree::Seq Region;
13533 
13534   /// Filled in with declarations which were modified as a side-effect
13535   /// (that is, post-increment operations).
13536   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13537 
13538   /// Expressions to check later. We defer checking these to reduce
13539   /// stack usage.
13540   SmallVectorImpl<const Expr *> &WorkList;
13541 
13542   /// RAII object wrapping the visitation of a sequenced subexpression of an
13543   /// expression. At the end of this process, the side-effects of the evaluation
13544   /// become sequenced with respect to the value computation of the result, so
13545   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13546   /// UK_ModAsValue.
13547   struct SequencedSubexpression {
13548     SequencedSubexpression(SequenceChecker &Self)
13549       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13550       Self.ModAsSideEffect = &ModAsSideEffect;
13551     }
13552 
13553     ~SequencedSubexpression() {
13554       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13555         // Add a new usage with usage kind UK_ModAsValue, and then restore
13556         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13557         // the previous one was empty).
13558         UsageInfo &UI = Self.UsageMap[M.first];
13559         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13560         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13561         SideEffectUsage = M.second;
13562       }
13563       Self.ModAsSideEffect = OldModAsSideEffect;
13564     }
13565 
13566     SequenceChecker &Self;
13567     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13568     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13569   };
13570 
13571   /// RAII object wrapping the visitation of a subexpression which we might
13572   /// choose to evaluate as a constant. If any subexpression is evaluated and
13573   /// found to be non-constant, this allows us to suppress the evaluation of
13574   /// the outer expression.
13575   class EvaluationTracker {
13576   public:
13577     EvaluationTracker(SequenceChecker &Self)
13578         : Self(Self), Prev(Self.EvalTracker) {
13579       Self.EvalTracker = this;
13580     }
13581 
13582     ~EvaluationTracker() {
13583       Self.EvalTracker = Prev;
13584       if (Prev)
13585         Prev->EvalOK &= EvalOK;
13586     }
13587 
13588     bool evaluate(const Expr *E, bool &Result) {
13589       if (!EvalOK || E->isValueDependent())
13590         return false;
13591       EvalOK = E->EvaluateAsBooleanCondition(
13592           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13593       return EvalOK;
13594     }
13595 
13596   private:
13597     SequenceChecker &Self;
13598     EvaluationTracker *Prev;
13599     bool EvalOK = true;
13600   } *EvalTracker = nullptr;
13601 
13602   /// Find the object which is produced by the specified expression,
13603   /// if any.
13604   Object getObject(const Expr *E, bool Mod) const {
13605     E = E->IgnoreParenCasts();
13606     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13607       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13608         return getObject(UO->getSubExpr(), Mod);
13609     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13610       if (BO->getOpcode() == BO_Comma)
13611         return getObject(BO->getRHS(), Mod);
13612       if (Mod && BO->isAssignmentOp())
13613         return getObject(BO->getLHS(), Mod);
13614     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13615       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13616       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13617         return ME->getMemberDecl();
13618     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13619       // FIXME: If this is a reference, map through to its value.
13620       return DRE->getDecl();
13621     return nullptr;
13622   }
13623 
13624   /// Note that an object \p O was modified or used by an expression
13625   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13626   /// the object \p O as obtained via the \p UsageMap.
13627   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13628     // Get the old usage for the given object and usage kind.
13629     Usage &U = UI.Uses[UK];
13630     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13631       // If we have a modification as side effect and are in a sequenced
13632       // subexpression, save the old Usage so that we can restore it later
13633       // in SequencedSubexpression::~SequencedSubexpression.
13634       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13635         ModAsSideEffect->push_back(std::make_pair(O, U));
13636       // Then record the new usage with the current sequencing region.
13637       U.UsageExpr = UsageExpr;
13638       U.Seq = Region;
13639     }
13640   }
13641 
13642   /// Check whether a modification or use of an object \p O in an expression
13643   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13644   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13645   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13646   /// usage and false we are checking for a mod-use unsequenced usage.
13647   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13648                   UsageKind OtherKind, bool IsModMod) {
13649     if (UI.Diagnosed)
13650       return;
13651 
13652     const Usage &U = UI.Uses[OtherKind];
13653     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13654       return;
13655 
13656     const Expr *Mod = U.UsageExpr;
13657     const Expr *ModOrUse = UsageExpr;
13658     if (OtherKind == UK_Use)
13659       std::swap(Mod, ModOrUse);
13660 
13661     SemaRef.DiagRuntimeBehavior(
13662         Mod->getExprLoc(), {Mod, ModOrUse},
13663         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13664                                : diag::warn_unsequenced_mod_use)
13665             << O << SourceRange(ModOrUse->getExprLoc()));
13666     UI.Diagnosed = true;
13667   }
13668 
13669   // A note on note{Pre, Post}{Use, Mod}:
13670   //
13671   // (It helps to follow the algorithm with an expression such as
13672   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13673   //  operations before C++17 and both are well-defined in C++17).
13674   //
13675   // When visiting a node which uses/modify an object we first call notePreUse
13676   // or notePreMod before visiting its sub-expression(s). At this point the
13677   // children of the current node have not yet been visited and so the eventual
13678   // uses/modifications resulting from the children of the current node have not
13679   // been recorded yet.
13680   //
13681   // We then visit the children of the current node. After that notePostUse or
13682   // notePostMod is called. These will 1) detect an unsequenced modification
13683   // as side effect (as in "k++ + k") and 2) add a new usage with the
13684   // appropriate usage kind.
13685   //
13686   // We also have to be careful that some operation sequences modification as
13687   // side effect as well (for example: || or ,). To account for this we wrap
13688   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13689   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13690   // which record usages which are modifications as side effect, and then
13691   // downgrade them (or more accurately restore the previous usage which was a
13692   // modification as side effect) when exiting the scope of the sequenced
13693   // subexpression.
13694 
13695   void notePreUse(Object O, const Expr *UseExpr) {
13696     UsageInfo &UI = UsageMap[O];
13697     // Uses conflict with other modifications.
13698     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13699   }
13700 
13701   void notePostUse(Object O, const Expr *UseExpr) {
13702     UsageInfo &UI = UsageMap[O];
13703     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13704                /*IsModMod=*/false);
13705     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13706   }
13707 
13708   void notePreMod(Object O, const Expr *ModExpr) {
13709     UsageInfo &UI = UsageMap[O];
13710     // Modifications conflict with other modifications and with uses.
13711     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13712     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13713   }
13714 
13715   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13716     UsageInfo &UI = UsageMap[O];
13717     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13718                /*IsModMod=*/true);
13719     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13720   }
13721 
13722 public:
13723   SequenceChecker(Sema &S, const Expr *E,
13724                   SmallVectorImpl<const Expr *> &WorkList)
13725       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13726     Visit(E);
13727     // Silence a -Wunused-private-field since WorkList is now unused.
13728     // TODO: Evaluate if it can be used, and if not remove it.
13729     (void)this->WorkList;
13730   }
13731 
13732   void VisitStmt(const Stmt *S) {
13733     // Skip all statements which aren't expressions for now.
13734   }
13735 
13736   void VisitExpr(const Expr *E) {
13737     // By default, just recurse to evaluated subexpressions.
13738     Base::VisitStmt(E);
13739   }
13740 
13741   void VisitCastExpr(const CastExpr *E) {
13742     Object O = Object();
13743     if (E->getCastKind() == CK_LValueToRValue)
13744       O = getObject(E->getSubExpr(), false);
13745 
13746     if (O)
13747       notePreUse(O, E);
13748     VisitExpr(E);
13749     if (O)
13750       notePostUse(O, E);
13751   }
13752 
13753   void VisitSequencedExpressions(const Expr *SequencedBefore,
13754                                  const Expr *SequencedAfter) {
13755     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13756     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13757     SequenceTree::Seq OldRegion = Region;
13758 
13759     {
13760       SequencedSubexpression SeqBefore(*this);
13761       Region = BeforeRegion;
13762       Visit(SequencedBefore);
13763     }
13764 
13765     Region = AfterRegion;
13766     Visit(SequencedAfter);
13767 
13768     Region = OldRegion;
13769 
13770     Tree.merge(BeforeRegion);
13771     Tree.merge(AfterRegion);
13772   }
13773 
13774   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13775     // C++17 [expr.sub]p1:
13776     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13777     //   expression E1 is sequenced before the expression E2.
13778     if (SemaRef.getLangOpts().CPlusPlus17)
13779       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13780     else {
13781       Visit(ASE->getLHS());
13782       Visit(ASE->getRHS());
13783     }
13784   }
13785 
13786   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13787   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13788   void VisitBinPtrMem(const BinaryOperator *BO) {
13789     // C++17 [expr.mptr.oper]p4:
13790     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13791     //  the expression E1 is sequenced before the expression E2.
13792     if (SemaRef.getLangOpts().CPlusPlus17)
13793       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13794     else {
13795       Visit(BO->getLHS());
13796       Visit(BO->getRHS());
13797     }
13798   }
13799 
13800   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13801   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13802   void VisitBinShlShr(const BinaryOperator *BO) {
13803     // C++17 [expr.shift]p4:
13804     //  The expression E1 is sequenced before the expression E2.
13805     if (SemaRef.getLangOpts().CPlusPlus17)
13806       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13807     else {
13808       Visit(BO->getLHS());
13809       Visit(BO->getRHS());
13810     }
13811   }
13812 
13813   void VisitBinComma(const BinaryOperator *BO) {
13814     // C++11 [expr.comma]p1:
13815     //   Every value computation and side effect associated with the left
13816     //   expression is sequenced before every value computation and side
13817     //   effect associated with the right expression.
13818     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13819   }
13820 
13821   void VisitBinAssign(const BinaryOperator *BO) {
13822     SequenceTree::Seq RHSRegion;
13823     SequenceTree::Seq LHSRegion;
13824     if (SemaRef.getLangOpts().CPlusPlus17) {
13825       RHSRegion = Tree.allocate(Region);
13826       LHSRegion = Tree.allocate(Region);
13827     } else {
13828       RHSRegion = Region;
13829       LHSRegion = Region;
13830     }
13831     SequenceTree::Seq OldRegion = Region;
13832 
13833     // C++11 [expr.ass]p1:
13834     //  [...] the assignment is sequenced after the value computation
13835     //  of the right and left operands, [...]
13836     //
13837     // so check it before inspecting the operands and update the
13838     // map afterwards.
13839     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13840     if (O)
13841       notePreMod(O, BO);
13842 
13843     if (SemaRef.getLangOpts().CPlusPlus17) {
13844       // C++17 [expr.ass]p1:
13845       //  [...] The right operand is sequenced before the left operand. [...]
13846       {
13847         SequencedSubexpression SeqBefore(*this);
13848         Region = RHSRegion;
13849         Visit(BO->getRHS());
13850       }
13851 
13852       Region = LHSRegion;
13853       Visit(BO->getLHS());
13854 
13855       if (O && isa<CompoundAssignOperator>(BO))
13856         notePostUse(O, BO);
13857 
13858     } else {
13859       // C++11 does not specify any sequencing between the LHS and RHS.
13860       Region = LHSRegion;
13861       Visit(BO->getLHS());
13862 
13863       if (O && isa<CompoundAssignOperator>(BO))
13864         notePostUse(O, BO);
13865 
13866       Region = RHSRegion;
13867       Visit(BO->getRHS());
13868     }
13869 
13870     // C++11 [expr.ass]p1:
13871     //  the assignment is sequenced [...] before the value computation of the
13872     //  assignment expression.
13873     // C11 6.5.16/3 has no such rule.
13874     Region = OldRegion;
13875     if (O)
13876       notePostMod(O, BO,
13877                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13878                                                   : UK_ModAsSideEffect);
13879     if (SemaRef.getLangOpts().CPlusPlus17) {
13880       Tree.merge(RHSRegion);
13881       Tree.merge(LHSRegion);
13882     }
13883   }
13884 
13885   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13886     VisitBinAssign(CAO);
13887   }
13888 
13889   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13890   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13891   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13892     Object O = getObject(UO->getSubExpr(), true);
13893     if (!O)
13894       return VisitExpr(UO);
13895 
13896     notePreMod(O, UO);
13897     Visit(UO->getSubExpr());
13898     // C++11 [expr.pre.incr]p1:
13899     //   the expression ++x is equivalent to x+=1
13900     notePostMod(O, UO,
13901                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13902                                                 : UK_ModAsSideEffect);
13903   }
13904 
13905   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13906   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13907   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13908     Object O = getObject(UO->getSubExpr(), true);
13909     if (!O)
13910       return VisitExpr(UO);
13911 
13912     notePreMod(O, UO);
13913     Visit(UO->getSubExpr());
13914     notePostMod(O, UO, UK_ModAsSideEffect);
13915   }
13916 
13917   void VisitBinLOr(const BinaryOperator *BO) {
13918     // C++11 [expr.log.or]p2:
13919     //  If the second expression is evaluated, every value computation and
13920     //  side effect associated with the first expression is sequenced before
13921     //  every value computation and side effect associated with the
13922     //  second expression.
13923     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13924     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13925     SequenceTree::Seq OldRegion = Region;
13926 
13927     EvaluationTracker Eval(*this);
13928     {
13929       SequencedSubexpression Sequenced(*this);
13930       Region = LHSRegion;
13931       Visit(BO->getLHS());
13932     }
13933 
13934     // C++11 [expr.log.or]p1:
13935     //  [...] the second operand is not evaluated if the first operand
13936     //  evaluates to true.
13937     bool EvalResult = false;
13938     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13939     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13940     if (ShouldVisitRHS) {
13941       Region = RHSRegion;
13942       Visit(BO->getRHS());
13943     }
13944 
13945     Region = OldRegion;
13946     Tree.merge(LHSRegion);
13947     Tree.merge(RHSRegion);
13948   }
13949 
13950   void VisitBinLAnd(const BinaryOperator *BO) {
13951     // C++11 [expr.log.and]p2:
13952     //  If the second expression is evaluated, every value computation and
13953     //  side effect associated with the first expression is sequenced before
13954     //  every value computation and side effect associated with the
13955     //  second expression.
13956     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13957     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13958     SequenceTree::Seq OldRegion = Region;
13959 
13960     EvaluationTracker Eval(*this);
13961     {
13962       SequencedSubexpression Sequenced(*this);
13963       Region = LHSRegion;
13964       Visit(BO->getLHS());
13965     }
13966 
13967     // C++11 [expr.log.and]p1:
13968     //  [...] the second operand is not evaluated if the first operand is false.
13969     bool EvalResult = false;
13970     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13971     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13972     if (ShouldVisitRHS) {
13973       Region = RHSRegion;
13974       Visit(BO->getRHS());
13975     }
13976 
13977     Region = OldRegion;
13978     Tree.merge(LHSRegion);
13979     Tree.merge(RHSRegion);
13980   }
13981 
13982   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13983     // C++11 [expr.cond]p1:
13984     //  [...] Every value computation and side effect associated with the first
13985     //  expression is sequenced before every value computation and side effect
13986     //  associated with the second or third expression.
13987     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13988 
13989     // No sequencing is specified between the true and false expression.
13990     // However since exactly one of both is going to be evaluated we can
13991     // consider them to be sequenced. This is needed to avoid warning on
13992     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13993     // both the true and false expressions because we can't evaluate x.
13994     // This will still allow us to detect an expression like (pre C++17)
13995     // "(x ? y += 1 : y += 2) = y".
13996     //
13997     // We don't wrap the visitation of the true and false expression with
13998     // SequencedSubexpression because we don't want to downgrade modifications
13999     // as side effect in the true and false expressions after the visition
14000     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14001     // not warn between the two "y++", but we should warn between the "y++"
14002     // and the "y".
14003     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14004     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14005     SequenceTree::Seq OldRegion = Region;
14006 
14007     EvaluationTracker Eval(*this);
14008     {
14009       SequencedSubexpression Sequenced(*this);
14010       Region = ConditionRegion;
14011       Visit(CO->getCond());
14012     }
14013 
14014     // C++11 [expr.cond]p1:
14015     // [...] The first expression is contextually converted to bool (Clause 4).
14016     // It is evaluated and if it is true, the result of the conditional
14017     // expression is the value of the second expression, otherwise that of the
14018     // third expression. Only one of the second and third expressions is
14019     // evaluated. [...]
14020     bool EvalResult = false;
14021     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14022     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14023     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14024     if (ShouldVisitTrueExpr) {
14025       Region = TrueRegion;
14026       Visit(CO->getTrueExpr());
14027     }
14028     if (ShouldVisitFalseExpr) {
14029       Region = FalseRegion;
14030       Visit(CO->getFalseExpr());
14031     }
14032 
14033     Region = OldRegion;
14034     Tree.merge(ConditionRegion);
14035     Tree.merge(TrueRegion);
14036     Tree.merge(FalseRegion);
14037   }
14038 
14039   void VisitCallExpr(const CallExpr *CE) {
14040     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14041 
14042     if (CE->isUnevaluatedBuiltinCall(Context))
14043       return;
14044 
14045     // C++11 [intro.execution]p15:
14046     //   When calling a function [...], every value computation and side effect
14047     //   associated with any argument expression, or with the postfix expression
14048     //   designating the called function, is sequenced before execution of every
14049     //   expression or statement in the body of the function [and thus before
14050     //   the value computation of its result].
14051     SequencedSubexpression Sequenced(*this);
14052     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14053       // C++17 [expr.call]p5
14054       //   The postfix-expression is sequenced before each expression in the
14055       //   expression-list and any default argument. [...]
14056       SequenceTree::Seq CalleeRegion;
14057       SequenceTree::Seq OtherRegion;
14058       if (SemaRef.getLangOpts().CPlusPlus17) {
14059         CalleeRegion = Tree.allocate(Region);
14060         OtherRegion = Tree.allocate(Region);
14061       } else {
14062         CalleeRegion = Region;
14063         OtherRegion = Region;
14064       }
14065       SequenceTree::Seq OldRegion = Region;
14066 
14067       // Visit the callee expression first.
14068       Region = CalleeRegion;
14069       if (SemaRef.getLangOpts().CPlusPlus17) {
14070         SequencedSubexpression Sequenced(*this);
14071         Visit(CE->getCallee());
14072       } else {
14073         Visit(CE->getCallee());
14074       }
14075 
14076       // Then visit the argument expressions.
14077       Region = OtherRegion;
14078       for (const Expr *Argument : CE->arguments())
14079         Visit(Argument);
14080 
14081       Region = OldRegion;
14082       if (SemaRef.getLangOpts().CPlusPlus17) {
14083         Tree.merge(CalleeRegion);
14084         Tree.merge(OtherRegion);
14085       }
14086     });
14087   }
14088 
14089   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14090     // C++17 [over.match.oper]p2:
14091     //   [...] the operator notation is first transformed to the equivalent
14092     //   function-call notation as summarized in Table 12 (where @ denotes one
14093     //   of the operators covered in the specified subclause). However, the
14094     //   operands are sequenced in the order prescribed for the built-in
14095     //   operator (Clause 8).
14096     //
14097     // From the above only overloaded binary operators and overloaded call
14098     // operators have sequencing rules in C++17 that we need to handle
14099     // separately.
14100     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14101         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14102       return VisitCallExpr(CXXOCE);
14103 
14104     enum {
14105       NoSequencing,
14106       LHSBeforeRHS,
14107       RHSBeforeLHS,
14108       LHSBeforeRest
14109     } SequencingKind;
14110     switch (CXXOCE->getOperator()) {
14111     case OO_Equal:
14112     case OO_PlusEqual:
14113     case OO_MinusEqual:
14114     case OO_StarEqual:
14115     case OO_SlashEqual:
14116     case OO_PercentEqual:
14117     case OO_CaretEqual:
14118     case OO_AmpEqual:
14119     case OO_PipeEqual:
14120     case OO_LessLessEqual:
14121     case OO_GreaterGreaterEqual:
14122       SequencingKind = RHSBeforeLHS;
14123       break;
14124 
14125     case OO_LessLess:
14126     case OO_GreaterGreater:
14127     case OO_AmpAmp:
14128     case OO_PipePipe:
14129     case OO_Comma:
14130     case OO_ArrowStar:
14131     case OO_Subscript:
14132       SequencingKind = LHSBeforeRHS;
14133       break;
14134 
14135     case OO_Call:
14136       SequencingKind = LHSBeforeRest;
14137       break;
14138 
14139     default:
14140       SequencingKind = NoSequencing;
14141       break;
14142     }
14143 
14144     if (SequencingKind == NoSequencing)
14145       return VisitCallExpr(CXXOCE);
14146 
14147     // This is a call, so all subexpressions are sequenced before the result.
14148     SequencedSubexpression Sequenced(*this);
14149 
14150     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14151       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14152              "Should only get there with C++17 and above!");
14153       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14154              "Should only get there with an overloaded binary operator"
14155              " or an overloaded call operator!");
14156 
14157       if (SequencingKind == LHSBeforeRest) {
14158         assert(CXXOCE->getOperator() == OO_Call &&
14159                "We should only have an overloaded call operator here!");
14160 
14161         // This is very similar to VisitCallExpr, except that we only have the
14162         // C++17 case. The postfix-expression is the first argument of the
14163         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14164         // are in the following arguments.
14165         //
14166         // Note that we intentionally do not visit the callee expression since
14167         // it is just a decayed reference to a function.
14168         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14169         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14170         SequenceTree::Seq OldRegion = Region;
14171 
14172         assert(CXXOCE->getNumArgs() >= 1 &&
14173                "An overloaded call operator must have at least one argument"
14174                " for the postfix-expression!");
14175         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14176         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14177                                           CXXOCE->getNumArgs() - 1);
14178 
14179         // Visit the postfix-expression first.
14180         {
14181           Region = PostfixExprRegion;
14182           SequencedSubexpression Sequenced(*this);
14183           Visit(PostfixExpr);
14184         }
14185 
14186         // Then visit the argument expressions.
14187         Region = ArgsRegion;
14188         for (const Expr *Arg : Args)
14189           Visit(Arg);
14190 
14191         Region = OldRegion;
14192         Tree.merge(PostfixExprRegion);
14193         Tree.merge(ArgsRegion);
14194       } else {
14195         assert(CXXOCE->getNumArgs() == 2 &&
14196                "Should only have two arguments here!");
14197         assert((SequencingKind == LHSBeforeRHS ||
14198                 SequencingKind == RHSBeforeLHS) &&
14199                "Unexpected sequencing kind!");
14200 
14201         // We do not visit the callee expression since it is just a decayed
14202         // reference to a function.
14203         const Expr *E1 = CXXOCE->getArg(0);
14204         const Expr *E2 = CXXOCE->getArg(1);
14205         if (SequencingKind == RHSBeforeLHS)
14206           std::swap(E1, E2);
14207 
14208         return VisitSequencedExpressions(E1, E2);
14209       }
14210     });
14211   }
14212 
14213   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14214     // This is a call, so all subexpressions are sequenced before the result.
14215     SequencedSubexpression Sequenced(*this);
14216 
14217     if (!CCE->isListInitialization())
14218       return VisitExpr(CCE);
14219 
14220     // In C++11, list initializations are sequenced.
14221     SmallVector<SequenceTree::Seq, 32> Elts;
14222     SequenceTree::Seq Parent = Region;
14223     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14224                                               E = CCE->arg_end();
14225          I != E; ++I) {
14226       Region = Tree.allocate(Parent);
14227       Elts.push_back(Region);
14228       Visit(*I);
14229     }
14230 
14231     // Forget that the initializers are sequenced.
14232     Region = Parent;
14233     for (unsigned I = 0; I < Elts.size(); ++I)
14234       Tree.merge(Elts[I]);
14235   }
14236 
14237   void VisitInitListExpr(const InitListExpr *ILE) {
14238     if (!SemaRef.getLangOpts().CPlusPlus11)
14239       return VisitExpr(ILE);
14240 
14241     // In C++11, list initializations are sequenced.
14242     SmallVector<SequenceTree::Seq, 32> Elts;
14243     SequenceTree::Seq Parent = Region;
14244     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14245       const Expr *E = ILE->getInit(I);
14246       if (!E)
14247         continue;
14248       Region = Tree.allocate(Parent);
14249       Elts.push_back(Region);
14250       Visit(E);
14251     }
14252 
14253     // Forget that the initializers are sequenced.
14254     Region = Parent;
14255     for (unsigned I = 0; I < Elts.size(); ++I)
14256       Tree.merge(Elts[I]);
14257   }
14258 };
14259 
14260 } // namespace
14261 
14262 void Sema::CheckUnsequencedOperations(const Expr *E) {
14263   SmallVector<const Expr *, 8> WorkList;
14264   WorkList.push_back(E);
14265   while (!WorkList.empty()) {
14266     const Expr *Item = WorkList.pop_back_val();
14267     SequenceChecker(*this, Item, WorkList);
14268   }
14269 }
14270 
14271 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14272                               bool IsConstexpr) {
14273   llvm::SaveAndRestore<bool> ConstantContext(
14274       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14275   CheckImplicitConversions(E, CheckLoc);
14276   if (!E->isInstantiationDependent())
14277     CheckUnsequencedOperations(E);
14278   if (!IsConstexpr && !E->isValueDependent())
14279     CheckForIntOverflow(E);
14280   DiagnoseMisalignedMembers();
14281 }
14282 
14283 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14284                                        FieldDecl *BitField,
14285                                        Expr *Init) {
14286   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14287 }
14288 
14289 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14290                                          SourceLocation Loc) {
14291   if (!PType->isVariablyModifiedType())
14292     return;
14293   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14294     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14295     return;
14296   }
14297   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14298     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14299     return;
14300   }
14301   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14302     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14303     return;
14304   }
14305 
14306   const ArrayType *AT = S.Context.getAsArrayType(PType);
14307   if (!AT)
14308     return;
14309 
14310   if (AT->getSizeModifier() != ArrayType::Star) {
14311     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14312     return;
14313   }
14314 
14315   S.Diag(Loc, diag::err_array_star_in_function_definition);
14316 }
14317 
14318 /// CheckParmsForFunctionDef - Check that the parameters of the given
14319 /// function are appropriate for the definition of a function. This
14320 /// takes care of any checks that cannot be performed on the
14321 /// declaration itself, e.g., that the types of each of the function
14322 /// parameters are complete.
14323 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14324                                     bool CheckParameterNames) {
14325   bool HasInvalidParm = false;
14326   for (ParmVarDecl *Param : Parameters) {
14327     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14328     // function declarator that is part of a function definition of
14329     // that function shall not have incomplete type.
14330     //
14331     // This is also C++ [dcl.fct]p6.
14332     if (!Param->isInvalidDecl() &&
14333         RequireCompleteType(Param->getLocation(), Param->getType(),
14334                             diag::err_typecheck_decl_incomplete_type)) {
14335       Param->setInvalidDecl();
14336       HasInvalidParm = true;
14337     }
14338 
14339     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14340     // declaration of each parameter shall include an identifier.
14341     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14342         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14343       // Diagnose this as an extension in C17 and earlier.
14344       if (!getLangOpts().C2x)
14345         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14346     }
14347 
14348     // C99 6.7.5.3p12:
14349     //   If the function declarator is not part of a definition of that
14350     //   function, parameters may have incomplete type and may use the [*]
14351     //   notation in their sequences of declarator specifiers to specify
14352     //   variable length array types.
14353     QualType PType = Param->getOriginalType();
14354     // FIXME: This diagnostic should point the '[*]' if source-location
14355     // information is added for it.
14356     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14357 
14358     // If the parameter is a c++ class type and it has to be destructed in the
14359     // callee function, declare the destructor so that it can be called by the
14360     // callee function. Do not perform any direct access check on the dtor here.
14361     if (!Param->isInvalidDecl()) {
14362       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14363         if (!ClassDecl->isInvalidDecl() &&
14364             !ClassDecl->hasIrrelevantDestructor() &&
14365             !ClassDecl->isDependentContext() &&
14366             ClassDecl->isParamDestroyedInCallee()) {
14367           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14368           MarkFunctionReferenced(Param->getLocation(), Destructor);
14369           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14370         }
14371       }
14372     }
14373 
14374     // Parameters with the pass_object_size attribute only need to be marked
14375     // constant at function definitions. Because we lack information about
14376     // whether we're on a declaration or definition when we're instantiating the
14377     // attribute, we need to check for constness here.
14378     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14379       if (!Param->getType().isConstQualified())
14380         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14381             << Attr->getSpelling() << 1;
14382 
14383     // Check for parameter names shadowing fields from the class.
14384     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14385       // The owning context for the parameter should be the function, but we
14386       // want to see if this function's declaration context is a record.
14387       DeclContext *DC = Param->getDeclContext();
14388       if (DC && DC->isFunctionOrMethod()) {
14389         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14390           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14391                                      RD, /*DeclIsField*/ false);
14392       }
14393     }
14394   }
14395 
14396   return HasInvalidParm;
14397 }
14398 
14399 Optional<std::pair<CharUnits, CharUnits>>
14400 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14401 
14402 /// Compute the alignment and offset of the base class object given the
14403 /// derived-to-base cast expression and the alignment and offset of the derived
14404 /// class object.
14405 static std::pair<CharUnits, CharUnits>
14406 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14407                                    CharUnits BaseAlignment, CharUnits Offset,
14408                                    ASTContext &Ctx) {
14409   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14410        ++PathI) {
14411     const CXXBaseSpecifier *Base = *PathI;
14412     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14413     if (Base->isVirtual()) {
14414       // The complete object may have a lower alignment than the non-virtual
14415       // alignment of the base, in which case the base may be misaligned. Choose
14416       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14417       // conservative lower bound of the complete object alignment.
14418       CharUnits NonVirtualAlignment =
14419           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14420       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14421       Offset = CharUnits::Zero();
14422     } else {
14423       const ASTRecordLayout &RL =
14424           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14425       Offset += RL.getBaseClassOffset(BaseDecl);
14426     }
14427     DerivedType = Base->getType();
14428   }
14429 
14430   return std::make_pair(BaseAlignment, Offset);
14431 }
14432 
14433 /// Compute the alignment and offset of a binary additive operator.
14434 static Optional<std::pair<CharUnits, CharUnits>>
14435 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14436                                      bool IsSub, ASTContext &Ctx) {
14437   QualType PointeeType = PtrE->getType()->getPointeeType();
14438 
14439   if (!PointeeType->isConstantSizeType())
14440     return llvm::None;
14441 
14442   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14443 
14444   if (!P)
14445     return llvm::None;
14446 
14447   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14448   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14449     CharUnits Offset = EltSize * IdxRes->getExtValue();
14450     if (IsSub)
14451       Offset = -Offset;
14452     return std::make_pair(P->first, P->second + Offset);
14453   }
14454 
14455   // If the integer expression isn't a constant expression, compute the lower
14456   // bound of the alignment using the alignment and offset of the pointer
14457   // expression and the element size.
14458   return std::make_pair(
14459       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14460       CharUnits::Zero());
14461 }
14462 
14463 /// This helper function takes an lvalue expression and returns the alignment of
14464 /// a VarDecl and a constant offset from the VarDecl.
14465 Optional<std::pair<CharUnits, CharUnits>>
14466 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14467   E = E->IgnoreParens();
14468   switch (E->getStmtClass()) {
14469   default:
14470     break;
14471   case Stmt::CStyleCastExprClass:
14472   case Stmt::CXXStaticCastExprClass:
14473   case Stmt::ImplicitCastExprClass: {
14474     auto *CE = cast<CastExpr>(E);
14475     const Expr *From = CE->getSubExpr();
14476     switch (CE->getCastKind()) {
14477     default:
14478       break;
14479     case CK_NoOp:
14480       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14481     case CK_UncheckedDerivedToBase:
14482     case CK_DerivedToBase: {
14483       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14484       if (!P)
14485         break;
14486       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14487                                                 P->second, Ctx);
14488     }
14489     }
14490     break;
14491   }
14492   case Stmt::ArraySubscriptExprClass: {
14493     auto *ASE = cast<ArraySubscriptExpr>(E);
14494     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14495                                                 false, Ctx);
14496   }
14497   case Stmt::DeclRefExprClass: {
14498     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14499       // FIXME: If VD is captured by copy or is an escaping __block variable,
14500       // use the alignment of VD's type.
14501       if (!VD->getType()->isReferenceType())
14502         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14503       if (VD->hasInit())
14504         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14505     }
14506     break;
14507   }
14508   case Stmt::MemberExprClass: {
14509     auto *ME = cast<MemberExpr>(E);
14510     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14511     if (!FD || FD->getType()->isReferenceType() ||
14512         FD->getParent()->isInvalidDecl())
14513       break;
14514     Optional<std::pair<CharUnits, CharUnits>> P;
14515     if (ME->isArrow())
14516       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14517     else
14518       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14519     if (!P)
14520       break;
14521     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14522     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14523     return std::make_pair(P->first,
14524                           P->second + CharUnits::fromQuantity(Offset));
14525   }
14526   case Stmt::UnaryOperatorClass: {
14527     auto *UO = cast<UnaryOperator>(E);
14528     switch (UO->getOpcode()) {
14529     default:
14530       break;
14531     case UO_Deref:
14532       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14533     }
14534     break;
14535   }
14536   case Stmt::BinaryOperatorClass: {
14537     auto *BO = cast<BinaryOperator>(E);
14538     auto Opcode = BO->getOpcode();
14539     switch (Opcode) {
14540     default:
14541       break;
14542     case BO_Comma:
14543       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14544     }
14545     break;
14546   }
14547   }
14548   return llvm::None;
14549 }
14550 
14551 /// This helper function takes a pointer expression and returns the alignment of
14552 /// a VarDecl and a constant offset from the VarDecl.
14553 Optional<std::pair<CharUnits, CharUnits>>
14554 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14555   E = E->IgnoreParens();
14556   switch (E->getStmtClass()) {
14557   default:
14558     break;
14559   case Stmt::CStyleCastExprClass:
14560   case Stmt::CXXStaticCastExprClass:
14561   case Stmt::ImplicitCastExprClass: {
14562     auto *CE = cast<CastExpr>(E);
14563     const Expr *From = CE->getSubExpr();
14564     switch (CE->getCastKind()) {
14565     default:
14566       break;
14567     case CK_NoOp:
14568       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14569     case CK_ArrayToPointerDecay:
14570       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14571     case CK_UncheckedDerivedToBase:
14572     case CK_DerivedToBase: {
14573       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14574       if (!P)
14575         break;
14576       return getDerivedToBaseAlignmentAndOffset(
14577           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14578     }
14579     }
14580     break;
14581   }
14582   case Stmt::CXXThisExprClass: {
14583     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14584     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14585     return std::make_pair(Alignment, CharUnits::Zero());
14586   }
14587   case Stmt::UnaryOperatorClass: {
14588     auto *UO = cast<UnaryOperator>(E);
14589     if (UO->getOpcode() == UO_AddrOf)
14590       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14591     break;
14592   }
14593   case Stmt::BinaryOperatorClass: {
14594     auto *BO = cast<BinaryOperator>(E);
14595     auto Opcode = BO->getOpcode();
14596     switch (Opcode) {
14597     default:
14598       break;
14599     case BO_Add:
14600     case BO_Sub: {
14601       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14602       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14603         std::swap(LHS, RHS);
14604       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14605                                                   Ctx);
14606     }
14607     case BO_Comma:
14608       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14609     }
14610     break;
14611   }
14612   }
14613   return llvm::None;
14614 }
14615 
14616 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14617   // See if we can compute the alignment of a VarDecl and an offset from it.
14618   Optional<std::pair<CharUnits, CharUnits>> P =
14619       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14620 
14621   if (P)
14622     return P->first.alignmentAtOffset(P->second);
14623 
14624   // If that failed, return the type's alignment.
14625   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14626 }
14627 
14628 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14629 /// pointer cast increases the alignment requirements.
14630 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14631   // This is actually a lot of work to potentially be doing on every
14632   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14633   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14634     return;
14635 
14636   // Ignore dependent types.
14637   if (T->isDependentType() || Op->getType()->isDependentType())
14638     return;
14639 
14640   // Require that the destination be a pointer type.
14641   const PointerType *DestPtr = T->getAs<PointerType>();
14642   if (!DestPtr) return;
14643 
14644   // If the destination has alignment 1, we're done.
14645   QualType DestPointee = DestPtr->getPointeeType();
14646   if (DestPointee->isIncompleteType()) return;
14647   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14648   if (DestAlign.isOne()) return;
14649 
14650   // Require that the source be a pointer type.
14651   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14652   if (!SrcPtr) return;
14653   QualType SrcPointee = SrcPtr->getPointeeType();
14654 
14655   // Explicitly allow casts from cv void*.  We already implicitly
14656   // allowed casts to cv void*, since they have alignment 1.
14657   // Also allow casts involving incomplete types, which implicitly
14658   // includes 'void'.
14659   if (SrcPointee->isIncompleteType()) return;
14660 
14661   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14662 
14663   if (SrcAlign >= DestAlign) return;
14664 
14665   Diag(TRange.getBegin(), diag::warn_cast_align)
14666     << Op->getType() << T
14667     << static_cast<unsigned>(SrcAlign.getQuantity())
14668     << static_cast<unsigned>(DestAlign.getQuantity())
14669     << TRange << Op->getSourceRange();
14670 }
14671 
14672 /// Check whether this array fits the idiom of a size-one tail padded
14673 /// array member of a struct.
14674 ///
14675 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14676 /// commonly used to emulate flexible arrays in C89 code.
14677 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14678                                     const NamedDecl *ND) {
14679   if (Size != 1 || !ND) return false;
14680 
14681   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14682   if (!FD) return false;
14683 
14684   // Don't consider sizes resulting from macro expansions or template argument
14685   // substitution to form C89 tail-padded arrays.
14686 
14687   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14688   while (TInfo) {
14689     TypeLoc TL = TInfo->getTypeLoc();
14690     // Look through typedefs.
14691     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14692       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14693       TInfo = TDL->getTypeSourceInfo();
14694       continue;
14695     }
14696     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14697       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14698       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14699         return false;
14700     }
14701     break;
14702   }
14703 
14704   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14705   if (!RD) return false;
14706   if (RD->isUnion()) return false;
14707   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14708     if (!CRD->isStandardLayout()) return false;
14709   }
14710 
14711   // See if this is the last field decl in the record.
14712   const Decl *D = FD;
14713   while ((D = D->getNextDeclInContext()))
14714     if (isa<FieldDecl>(D))
14715       return false;
14716   return true;
14717 }
14718 
14719 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14720                             const ArraySubscriptExpr *ASE,
14721                             bool AllowOnePastEnd, bool IndexNegated) {
14722   // Already diagnosed by the constant evaluator.
14723   if (isConstantEvaluated())
14724     return;
14725 
14726   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14727   if (IndexExpr->isValueDependent())
14728     return;
14729 
14730   const Type *EffectiveType =
14731       BaseExpr->getType()->getPointeeOrArrayElementType();
14732   BaseExpr = BaseExpr->IgnoreParenCasts();
14733   const ConstantArrayType *ArrayTy =
14734       Context.getAsConstantArrayType(BaseExpr->getType());
14735 
14736   const Type *BaseType =
14737       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14738   bool IsUnboundedArray = (BaseType == nullptr);
14739   if (EffectiveType->isDependentType() ||
14740       (!IsUnboundedArray && BaseType->isDependentType()))
14741     return;
14742 
14743   Expr::EvalResult Result;
14744   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14745     return;
14746 
14747   llvm::APSInt index = Result.Val.getInt();
14748   if (IndexNegated) {
14749     index.setIsUnsigned(false);
14750     index = -index;
14751   }
14752 
14753   const NamedDecl *ND = nullptr;
14754   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14755     ND = DRE->getDecl();
14756   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14757     ND = ME->getMemberDecl();
14758 
14759   if (IsUnboundedArray) {
14760     if (index.isUnsigned() || !index.isNegative()) {
14761       const auto &ASTC = getASTContext();
14762       unsigned AddrBits =
14763           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14764               EffectiveType->getCanonicalTypeInternal()));
14765       if (index.getBitWidth() < AddrBits)
14766         index = index.zext(AddrBits);
14767       Optional<CharUnits> ElemCharUnits =
14768           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14769       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14770       // pointer) bounds-checking isn't meaningful.
14771       if (!ElemCharUnits)
14772         return;
14773       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14774       // If index has more active bits than address space, we already know
14775       // we have a bounds violation to warn about.  Otherwise, compute
14776       // address of (index + 1)th element, and warn about bounds violation
14777       // only if that address exceeds address space.
14778       if (index.getActiveBits() <= AddrBits) {
14779         bool Overflow;
14780         llvm::APInt Product(index);
14781         Product += 1;
14782         Product = Product.umul_ov(ElemBytes, Overflow);
14783         if (!Overflow && Product.getActiveBits() <= AddrBits)
14784           return;
14785       }
14786 
14787       // Need to compute max possible elements in address space, since that
14788       // is included in diag message.
14789       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14790       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14791       MaxElems += 1;
14792       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14793       MaxElems = MaxElems.udiv(ElemBytes);
14794 
14795       unsigned DiagID =
14796           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14797               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14798 
14799       // Diag message shows element size in bits and in "bytes" (platform-
14800       // dependent CharUnits)
14801       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14802                           PDiag(DiagID)
14803                               << toString(index, 10, true) << AddrBits
14804                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14805                               << toString(ElemBytes, 10, false)
14806                               << toString(MaxElems, 10, false)
14807                               << (unsigned)MaxElems.getLimitedValue(~0U)
14808                               << IndexExpr->getSourceRange());
14809 
14810       if (!ND) {
14811         // Try harder to find a NamedDecl to point at in the note.
14812         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14813           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14814         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14815           ND = DRE->getDecl();
14816         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14817           ND = ME->getMemberDecl();
14818       }
14819 
14820       if (ND)
14821         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14822                             PDiag(diag::note_array_declared_here) << ND);
14823     }
14824     return;
14825   }
14826 
14827   if (index.isUnsigned() || !index.isNegative()) {
14828     // It is possible that the type of the base expression after
14829     // IgnoreParenCasts is incomplete, even though the type of the base
14830     // expression before IgnoreParenCasts is complete (see PR39746 for an
14831     // example). In this case we have no information about whether the array
14832     // access exceeds the array bounds. However we can still diagnose an array
14833     // access which precedes the array bounds.
14834     if (BaseType->isIncompleteType())
14835       return;
14836 
14837     llvm::APInt size = ArrayTy->getSize();
14838     if (!size.isStrictlyPositive())
14839       return;
14840 
14841     if (BaseType != EffectiveType) {
14842       // Make sure we're comparing apples to apples when comparing index to size
14843       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14844       uint64_t array_typesize = Context.getTypeSize(BaseType);
14845       // Handle ptrarith_typesize being zero, such as when casting to void*
14846       if (!ptrarith_typesize) ptrarith_typesize = 1;
14847       if (ptrarith_typesize != array_typesize) {
14848         // There's a cast to a different size type involved
14849         uint64_t ratio = array_typesize / ptrarith_typesize;
14850         // TODO: Be smarter about handling cases where array_typesize is not a
14851         // multiple of ptrarith_typesize
14852         if (ptrarith_typesize * ratio == array_typesize)
14853           size *= llvm::APInt(size.getBitWidth(), ratio);
14854       }
14855     }
14856 
14857     if (size.getBitWidth() > index.getBitWidth())
14858       index = index.zext(size.getBitWidth());
14859     else if (size.getBitWidth() < index.getBitWidth())
14860       size = size.zext(index.getBitWidth());
14861 
14862     // For array subscripting the index must be less than size, but for pointer
14863     // arithmetic also allow the index (offset) to be equal to size since
14864     // computing the next address after the end of the array is legal and
14865     // commonly done e.g. in C++ iterators and range-based for loops.
14866     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14867       return;
14868 
14869     // Also don't warn for arrays of size 1 which are members of some
14870     // structure. These are often used to approximate flexible arrays in C89
14871     // code.
14872     if (IsTailPaddedMemberArray(*this, size, ND))
14873       return;
14874 
14875     // Suppress the warning if the subscript expression (as identified by the
14876     // ']' location) and the index expression are both from macro expansions
14877     // within a system header.
14878     if (ASE) {
14879       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14880           ASE->getRBracketLoc());
14881       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14882         SourceLocation IndexLoc =
14883             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14884         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14885           return;
14886       }
14887     }
14888 
14889     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14890                           : diag::warn_ptr_arith_exceeds_bounds;
14891 
14892     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14893                         PDiag(DiagID) << toString(index, 10, true)
14894                                       << toString(size, 10, true)
14895                                       << (unsigned)size.getLimitedValue(~0U)
14896                                       << IndexExpr->getSourceRange());
14897   } else {
14898     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14899     if (!ASE) {
14900       DiagID = diag::warn_ptr_arith_precedes_bounds;
14901       if (index.isNegative()) index = -index;
14902     }
14903 
14904     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14905                         PDiag(DiagID) << toString(index, 10, true)
14906                                       << IndexExpr->getSourceRange());
14907   }
14908 
14909   if (!ND) {
14910     // Try harder to find a NamedDecl to point at in the note.
14911     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14912       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14913     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14914       ND = DRE->getDecl();
14915     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14916       ND = ME->getMemberDecl();
14917   }
14918 
14919   if (ND)
14920     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14921                         PDiag(diag::note_array_declared_here) << ND);
14922 }
14923 
14924 void Sema::CheckArrayAccess(const Expr *expr) {
14925   int AllowOnePastEnd = 0;
14926   while (expr) {
14927     expr = expr->IgnoreParenImpCasts();
14928     switch (expr->getStmtClass()) {
14929       case Stmt::ArraySubscriptExprClass: {
14930         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14931         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14932                          AllowOnePastEnd > 0);
14933         expr = ASE->getBase();
14934         break;
14935       }
14936       case Stmt::MemberExprClass: {
14937         expr = cast<MemberExpr>(expr)->getBase();
14938         break;
14939       }
14940       case Stmt::OMPArraySectionExprClass: {
14941         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14942         if (ASE->getLowerBound())
14943           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14944                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14945         return;
14946       }
14947       case Stmt::UnaryOperatorClass: {
14948         // Only unwrap the * and & unary operators
14949         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14950         expr = UO->getSubExpr();
14951         switch (UO->getOpcode()) {
14952           case UO_AddrOf:
14953             AllowOnePastEnd++;
14954             break;
14955           case UO_Deref:
14956             AllowOnePastEnd--;
14957             break;
14958           default:
14959             return;
14960         }
14961         break;
14962       }
14963       case Stmt::ConditionalOperatorClass: {
14964         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14965         if (const Expr *lhs = cond->getLHS())
14966           CheckArrayAccess(lhs);
14967         if (const Expr *rhs = cond->getRHS())
14968           CheckArrayAccess(rhs);
14969         return;
14970       }
14971       case Stmt::CXXOperatorCallExprClass: {
14972         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14973         for (const auto *Arg : OCE->arguments())
14974           CheckArrayAccess(Arg);
14975         return;
14976       }
14977       default:
14978         return;
14979     }
14980   }
14981 }
14982 
14983 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14984 
14985 namespace {
14986 
14987 struct RetainCycleOwner {
14988   VarDecl *Variable = nullptr;
14989   SourceRange Range;
14990   SourceLocation Loc;
14991   bool Indirect = false;
14992 
14993   RetainCycleOwner() = default;
14994 
14995   void setLocsFrom(Expr *e) {
14996     Loc = e->getExprLoc();
14997     Range = e->getSourceRange();
14998   }
14999 };
15000 
15001 } // namespace
15002 
15003 /// Consider whether capturing the given variable can possibly lead to
15004 /// a retain cycle.
15005 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15006   // In ARC, it's captured strongly iff the variable has __strong
15007   // lifetime.  In MRR, it's captured strongly if the variable is
15008   // __block and has an appropriate type.
15009   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15010     return false;
15011 
15012   owner.Variable = var;
15013   if (ref)
15014     owner.setLocsFrom(ref);
15015   return true;
15016 }
15017 
15018 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15019   while (true) {
15020     e = e->IgnoreParens();
15021     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15022       switch (cast->getCastKind()) {
15023       case CK_BitCast:
15024       case CK_LValueBitCast:
15025       case CK_LValueToRValue:
15026       case CK_ARCReclaimReturnedObject:
15027         e = cast->getSubExpr();
15028         continue;
15029 
15030       default:
15031         return false;
15032       }
15033     }
15034 
15035     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15036       ObjCIvarDecl *ivar = ref->getDecl();
15037       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15038         return false;
15039 
15040       // Try to find a retain cycle in the base.
15041       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15042         return false;
15043 
15044       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15045       owner.Indirect = true;
15046       return true;
15047     }
15048 
15049     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15050       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15051       if (!var) return false;
15052       return considerVariable(var, ref, owner);
15053     }
15054 
15055     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15056       if (member->isArrow()) return false;
15057 
15058       // Don't count this as an indirect ownership.
15059       e = member->getBase();
15060       continue;
15061     }
15062 
15063     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15064       // Only pay attention to pseudo-objects on property references.
15065       ObjCPropertyRefExpr *pre
15066         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15067                                               ->IgnoreParens());
15068       if (!pre) return false;
15069       if (pre->isImplicitProperty()) return false;
15070       ObjCPropertyDecl *property = pre->getExplicitProperty();
15071       if (!property->isRetaining() &&
15072           !(property->getPropertyIvarDecl() &&
15073             property->getPropertyIvarDecl()->getType()
15074               .getObjCLifetime() == Qualifiers::OCL_Strong))
15075           return false;
15076 
15077       owner.Indirect = true;
15078       if (pre->isSuperReceiver()) {
15079         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15080         if (!owner.Variable)
15081           return false;
15082         owner.Loc = pre->getLocation();
15083         owner.Range = pre->getSourceRange();
15084         return true;
15085       }
15086       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15087                               ->getSourceExpr());
15088       continue;
15089     }
15090 
15091     // Array ivars?
15092 
15093     return false;
15094   }
15095 }
15096 
15097 namespace {
15098 
15099   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15100     ASTContext &Context;
15101     VarDecl *Variable;
15102     Expr *Capturer = nullptr;
15103     bool VarWillBeReased = false;
15104 
15105     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15106         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15107           Context(Context), Variable(variable) {}
15108 
15109     void VisitDeclRefExpr(DeclRefExpr *ref) {
15110       if (ref->getDecl() == Variable && !Capturer)
15111         Capturer = ref;
15112     }
15113 
15114     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15115       if (Capturer) return;
15116       Visit(ref->getBase());
15117       if (Capturer && ref->isFreeIvar())
15118         Capturer = ref;
15119     }
15120 
15121     void VisitBlockExpr(BlockExpr *block) {
15122       // Look inside nested blocks
15123       if (block->getBlockDecl()->capturesVariable(Variable))
15124         Visit(block->getBlockDecl()->getBody());
15125     }
15126 
15127     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15128       if (Capturer) return;
15129       if (OVE->getSourceExpr())
15130         Visit(OVE->getSourceExpr());
15131     }
15132 
15133     void VisitBinaryOperator(BinaryOperator *BinOp) {
15134       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15135         return;
15136       Expr *LHS = BinOp->getLHS();
15137       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15138         if (DRE->getDecl() != Variable)
15139           return;
15140         if (Expr *RHS = BinOp->getRHS()) {
15141           RHS = RHS->IgnoreParenCasts();
15142           Optional<llvm::APSInt> Value;
15143           VarWillBeReased =
15144               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15145                *Value == 0);
15146         }
15147       }
15148     }
15149   };
15150 
15151 } // namespace
15152 
15153 /// Check whether the given argument is a block which captures a
15154 /// variable.
15155 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15156   assert(owner.Variable && owner.Loc.isValid());
15157 
15158   e = e->IgnoreParenCasts();
15159 
15160   // Look through [^{...} copy] and Block_copy(^{...}).
15161   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15162     Selector Cmd = ME->getSelector();
15163     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15164       e = ME->getInstanceReceiver();
15165       if (!e)
15166         return nullptr;
15167       e = e->IgnoreParenCasts();
15168     }
15169   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15170     if (CE->getNumArgs() == 1) {
15171       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15172       if (Fn) {
15173         const IdentifierInfo *FnI = Fn->getIdentifier();
15174         if (FnI && FnI->isStr("_Block_copy")) {
15175           e = CE->getArg(0)->IgnoreParenCasts();
15176         }
15177       }
15178     }
15179   }
15180 
15181   BlockExpr *block = dyn_cast<BlockExpr>(e);
15182   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15183     return nullptr;
15184 
15185   FindCaptureVisitor visitor(S.Context, owner.Variable);
15186   visitor.Visit(block->getBlockDecl()->getBody());
15187   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15188 }
15189 
15190 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15191                                 RetainCycleOwner &owner) {
15192   assert(capturer);
15193   assert(owner.Variable && owner.Loc.isValid());
15194 
15195   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15196     << owner.Variable << capturer->getSourceRange();
15197   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15198     << owner.Indirect << owner.Range;
15199 }
15200 
15201 /// Check for a keyword selector that starts with the word 'add' or
15202 /// 'set'.
15203 static bool isSetterLikeSelector(Selector sel) {
15204   if (sel.isUnarySelector()) return false;
15205 
15206   StringRef str = sel.getNameForSlot(0);
15207   while (!str.empty() && str.front() == '_') str = str.substr(1);
15208   if (str.startswith("set"))
15209     str = str.substr(3);
15210   else if (str.startswith("add")) {
15211     // Specially allow 'addOperationWithBlock:'.
15212     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15213       return false;
15214     str = str.substr(3);
15215   }
15216   else
15217     return false;
15218 
15219   if (str.empty()) return true;
15220   return !isLowercase(str.front());
15221 }
15222 
15223 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15224                                                     ObjCMessageExpr *Message) {
15225   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15226                                                 Message->getReceiverInterface(),
15227                                                 NSAPI::ClassId_NSMutableArray);
15228   if (!IsMutableArray) {
15229     return None;
15230   }
15231 
15232   Selector Sel = Message->getSelector();
15233 
15234   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15235     S.NSAPIObj->getNSArrayMethodKind(Sel);
15236   if (!MKOpt) {
15237     return None;
15238   }
15239 
15240   NSAPI::NSArrayMethodKind MK = *MKOpt;
15241 
15242   switch (MK) {
15243     case NSAPI::NSMutableArr_addObject:
15244     case NSAPI::NSMutableArr_insertObjectAtIndex:
15245     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15246       return 0;
15247     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15248       return 1;
15249 
15250     default:
15251       return None;
15252   }
15253 
15254   return None;
15255 }
15256 
15257 static
15258 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15259                                                   ObjCMessageExpr *Message) {
15260   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15261                                             Message->getReceiverInterface(),
15262                                             NSAPI::ClassId_NSMutableDictionary);
15263   if (!IsMutableDictionary) {
15264     return None;
15265   }
15266 
15267   Selector Sel = Message->getSelector();
15268 
15269   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15270     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15271   if (!MKOpt) {
15272     return None;
15273   }
15274 
15275   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15276 
15277   switch (MK) {
15278     case NSAPI::NSMutableDict_setObjectForKey:
15279     case NSAPI::NSMutableDict_setValueForKey:
15280     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15281       return 0;
15282 
15283     default:
15284       return None;
15285   }
15286 
15287   return None;
15288 }
15289 
15290 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15291   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15292                                                 Message->getReceiverInterface(),
15293                                                 NSAPI::ClassId_NSMutableSet);
15294 
15295   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15296                                             Message->getReceiverInterface(),
15297                                             NSAPI::ClassId_NSMutableOrderedSet);
15298   if (!IsMutableSet && !IsMutableOrderedSet) {
15299     return None;
15300   }
15301 
15302   Selector Sel = Message->getSelector();
15303 
15304   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15305   if (!MKOpt) {
15306     return None;
15307   }
15308 
15309   NSAPI::NSSetMethodKind MK = *MKOpt;
15310 
15311   switch (MK) {
15312     case NSAPI::NSMutableSet_addObject:
15313     case NSAPI::NSOrderedSet_setObjectAtIndex:
15314     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15315     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15316       return 0;
15317     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15318       return 1;
15319   }
15320 
15321   return None;
15322 }
15323 
15324 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15325   if (!Message->isInstanceMessage()) {
15326     return;
15327   }
15328 
15329   Optional<int> ArgOpt;
15330 
15331   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15332       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15333       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15334     return;
15335   }
15336 
15337   int ArgIndex = *ArgOpt;
15338 
15339   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15340   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15341     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15342   }
15343 
15344   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15345     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15346       if (ArgRE->isObjCSelfExpr()) {
15347         Diag(Message->getSourceRange().getBegin(),
15348              diag::warn_objc_circular_container)
15349           << ArgRE->getDecl() << StringRef("'super'");
15350       }
15351     }
15352   } else {
15353     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15354 
15355     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15356       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15357     }
15358 
15359     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15360       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15361         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15362           ValueDecl *Decl = ReceiverRE->getDecl();
15363           Diag(Message->getSourceRange().getBegin(),
15364                diag::warn_objc_circular_container)
15365             << Decl << Decl;
15366           if (!ArgRE->isObjCSelfExpr()) {
15367             Diag(Decl->getLocation(),
15368                  diag::note_objc_circular_container_declared_here)
15369               << Decl;
15370           }
15371         }
15372       }
15373     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15374       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15375         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15376           ObjCIvarDecl *Decl = IvarRE->getDecl();
15377           Diag(Message->getSourceRange().getBegin(),
15378                diag::warn_objc_circular_container)
15379             << Decl << Decl;
15380           Diag(Decl->getLocation(),
15381                diag::note_objc_circular_container_declared_here)
15382             << Decl;
15383         }
15384       }
15385     }
15386   }
15387 }
15388 
15389 /// Check a message send to see if it's likely to cause a retain cycle.
15390 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15391   // Only check instance methods whose selector looks like a setter.
15392   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15393     return;
15394 
15395   // Try to find a variable that the receiver is strongly owned by.
15396   RetainCycleOwner owner;
15397   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15398     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15399       return;
15400   } else {
15401     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15402     owner.Variable = getCurMethodDecl()->getSelfDecl();
15403     owner.Loc = msg->getSuperLoc();
15404     owner.Range = msg->getSuperLoc();
15405   }
15406 
15407   // Check whether the receiver is captured by any of the arguments.
15408   const ObjCMethodDecl *MD = msg->getMethodDecl();
15409   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15410     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15411       // noescape blocks should not be retained by the method.
15412       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15413         continue;
15414       return diagnoseRetainCycle(*this, capturer, owner);
15415     }
15416   }
15417 }
15418 
15419 /// Check a property assign to see if it's likely to cause a retain cycle.
15420 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15421   RetainCycleOwner owner;
15422   if (!findRetainCycleOwner(*this, receiver, owner))
15423     return;
15424 
15425   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15426     diagnoseRetainCycle(*this, capturer, owner);
15427 }
15428 
15429 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15430   RetainCycleOwner Owner;
15431   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15432     return;
15433 
15434   // Because we don't have an expression for the variable, we have to set the
15435   // location explicitly here.
15436   Owner.Loc = Var->getLocation();
15437   Owner.Range = Var->getSourceRange();
15438 
15439   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15440     diagnoseRetainCycle(*this, Capturer, Owner);
15441 }
15442 
15443 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15444                                      Expr *RHS, bool isProperty) {
15445   // Check if RHS is an Objective-C object literal, which also can get
15446   // immediately zapped in a weak reference.  Note that we explicitly
15447   // allow ObjCStringLiterals, since those are designed to never really die.
15448   RHS = RHS->IgnoreParenImpCasts();
15449 
15450   // This enum needs to match with the 'select' in
15451   // warn_objc_arc_literal_assign (off-by-1).
15452   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15453   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15454     return false;
15455 
15456   S.Diag(Loc, diag::warn_arc_literal_assign)
15457     << (unsigned) Kind
15458     << (isProperty ? 0 : 1)
15459     << RHS->getSourceRange();
15460 
15461   return true;
15462 }
15463 
15464 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15465                                     Qualifiers::ObjCLifetime LT,
15466                                     Expr *RHS, bool isProperty) {
15467   // Strip off any implicit cast added to get to the one ARC-specific.
15468   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15469     if (cast->getCastKind() == CK_ARCConsumeObject) {
15470       S.Diag(Loc, diag::warn_arc_retained_assign)
15471         << (LT == Qualifiers::OCL_ExplicitNone)
15472         << (isProperty ? 0 : 1)
15473         << RHS->getSourceRange();
15474       return true;
15475     }
15476     RHS = cast->getSubExpr();
15477   }
15478 
15479   if (LT == Qualifiers::OCL_Weak &&
15480       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15481     return true;
15482 
15483   return false;
15484 }
15485 
15486 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15487                               QualType LHS, Expr *RHS) {
15488   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15489 
15490   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15491     return false;
15492 
15493   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15494     return true;
15495 
15496   return false;
15497 }
15498 
15499 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15500                               Expr *LHS, Expr *RHS) {
15501   QualType LHSType;
15502   // PropertyRef on LHS type need be directly obtained from
15503   // its declaration as it has a PseudoType.
15504   ObjCPropertyRefExpr *PRE
15505     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15506   if (PRE && !PRE->isImplicitProperty()) {
15507     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15508     if (PD)
15509       LHSType = PD->getType();
15510   }
15511 
15512   if (LHSType.isNull())
15513     LHSType = LHS->getType();
15514 
15515   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15516 
15517   if (LT == Qualifiers::OCL_Weak) {
15518     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15519       getCurFunction()->markSafeWeakUse(LHS);
15520   }
15521 
15522   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15523     return;
15524 
15525   // FIXME. Check for other life times.
15526   if (LT != Qualifiers::OCL_None)
15527     return;
15528 
15529   if (PRE) {
15530     if (PRE->isImplicitProperty())
15531       return;
15532     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15533     if (!PD)
15534       return;
15535 
15536     unsigned Attributes = PD->getPropertyAttributes();
15537     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15538       // when 'assign' attribute was not explicitly specified
15539       // by user, ignore it and rely on property type itself
15540       // for lifetime info.
15541       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15542       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15543           LHSType->isObjCRetainableType())
15544         return;
15545 
15546       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15547         if (cast->getCastKind() == CK_ARCConsumeObject) {
15548           Diag(Loc, diag::warn_arc_retained_property_assign)
15549           << RHS->getSourceRange();
15550           return;
15551         }
15552         RHS = cast->getSubExpr();
15553       }
15554     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15555       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15556         return;
15557     }
15558   }
15559 }
15560 
15561 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15562 
15563 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15564                                         SourceLocation StmtLoc,
15565                                         const NullStmt *Body) {
15566   // Do not warn if the body is a macro that expands to nothing, e.g:
15567   //
15568   // #define CALL(x)
15569   // if (condition)
15570   //   CALL(0);
15571   if (Body->hasLeadingEmptyMacro())
15572     return false;
15573 
15574   // Get line numbers of statement and body.
15575   bool StmtLineInvalid;
15576   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15577                                                       &StmtLineInvalid);
15578   if (StmtLineInvalid)
15579     return false;
15580 
15581   bool BodyLineInvalid;
15582   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15583                                                       &BodyLineInvalid);
15584   if (BodyLineInvalid)
15585     return false;
15586 
15587   // Warn if null statement and body are on the same line.
15588   if (StmtLine != BodyLine)
15589     return false;
15590 
15591   return true;
15592 }
15593 
15594 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15595                                  const Stmt *Body,
15596                                  unsigned DiagID) {
15597   // Since this is a syntactic check, don't emit diagnostic for template
15598   // instantiations, this just adds noise.
15599   if (CurrentInstantiationScope)
15600     return;
15601 
15602   // The body should be a null statement.
15603   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15604   if (!NBody)
15605     return;
15606 
15607   // Do the usual checks.
15608   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15609     return;
15610 
15611   Diag(NBody->getSemiLoc(), DiagID);
15612   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15613 }
15614 
15615 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15616                                  const Stmt *PossibleBody) {
15617   assert(!CurrentInstantiationScope); // Ensured by caller
15618 
15619   SourceLocation StmtLoc;
15620   const Stmt *Body;
15621   unsigned DiagID;
15622   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15623     StmtLoc = FS->getRParenLoc();
15624     Body = FS->getBody();
15625     DiagID = diag::warn_empty_for_body;
15626   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15627     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15628     Body = WS->getBody();
15629     DiagID = diag::warn_empty_while_body;
15630   } else
15631     return; // Neither `for' nor `while'.
15632 
15633   // The body should be a null statement.
15634   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15635   if (!NBody)
15636     return;
15637 
15638   // Skip expensive checks if diagnostic is disabled.
15639   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15640     return;
15641 
15642   // Do the usual checks.
15643   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15644     return;
15645 
15646   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15647   // noise level low, emit diagnostics only if for/while is followed by a
15648   // CompoundStmt, e.g.:
15649   //    for (int i = 0; i < n; i++);
15650   //    {
15651   //      a(i);
15652   //    }
15653   // or if for/while is followed by a statement with more indentation
15654   // than for/while itself:
15655   //    for (int i = 0; i < n; i++);
15656   //      a(i);
15657   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15658   if (!ProbableTypo) {
15659     bool BodyColInvalid;
15660     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15661         PossibleBody->getBeginLoc(), &BodyColInvalid);
15662     if (BodyColInvalid)
15663       return;
15664 
15665     bool StmtColInvalid;
15666     unsigned StmtCol =
15667         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15668     if (StmtColInvalid)
15669       return;
15670 
15671     if (BodyCol > StmtCol)
15672       ProbableTypo = true;
15673   }
15674 
15675   if (ProbableTypo) {
15676     Diag(NBody->getSemiLoc(), DiagID);
15677     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15678   }
15679 }
15680 
15681 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15682 
15683 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15684 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15685                              SourceLocation OpLoc) {
15686   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15687     return;
15688 
15689   if (inTemplateInstantiation())
15690     return;
15691 
15692   // Strip parens and casts away.
15693   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15694   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15695 
15696   // Check for a call expression
15697   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15698   if (!CE || CE->getNumArgs() != 1)
15699     return;
15700 
15701   // Check for a call to std::move
15702   if (!CE->isCallToStdMove())
15703     return;
15704 
15705   // Get argument from std::move
15706   RHSExpr = CE->getArg(0);
15707 
15708   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15709   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15710 
15711   // Two DeclRefExpr's, check that the decls are the same.
15712   if (LHSDeclRef && RHSDeclRef) {
15713     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15714       return;
15715     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15716         RHSDeclRef->getDecl()->getCanonicalDecl())
15717       return;
15718 
15719     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15720                                         << LHSExpr->getSourceRange()
15721                                         << RHSExpr->getSourceRange();
15722     return;
15723   }
15724 
15725   // Member variables require a different approach to check for self moves.
15726   // MemberExpr's are the same if every nested MemberExpr refers to the same
15727   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15728   // the base Expr's are CXXThisExpr's.
15729   const Expr *LHSBase = LHSExpr;
15730   const Expr *RHSBase = RHSExpr;
15731   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15732   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15733   if (!LHSME || !RHSME)
15734     return;
15735 
15736   while (LHSME && RHSME) {
15737     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15738         RHSME->getMemberDecl()->getCanonicalDecl())
15739       return;
15740 
15741     LHSBase = LHSME->getBase();
15742     RHSBase = RHSME->getBase();
15743     LHSME = dyn_cast<MemberExpr>(LHSBase);
15744     RHSME = dyn_cast<MemberExpr>(RHSBase);
15745   }
15746 
15747   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15748   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15749   if (LHSDeclRef && RHSDeclRef) {
15750     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15751       return;
15752     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15753         RHSDeclRef->getDecl()->getCanonicalDecl())
15754       return;
15755 
15756     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15757                                         << LHSExpr->getSourceRange()
15758                                         << RHSExpr->getSourceRange();
15759     return;
15760   }
15761 
15762   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15763     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15764                                         << LHSExpr->getSourceRange()
15765                                         << RHSExpr->getSourceRange();
15766 }
15767 
15768 //===--- Layout compatibility ----------------------------------------------//
15769 
15770 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15771 
15772 /// Check if two enumeration types are layout-compatible.
15773 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15774   // C++11 [dcl.enum] p8:
15775   // Two enumeration types are layout-compatible if they have the same
15776   // underlying type.
15777   return ED1->isComplete() && ED2->isComplete() &&
15778          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15779 }
15780 
15781 /// Check if two fields are layout-compatible.
15782 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15783                                FieldDecl *Field2) {
15784   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15785     return false;
15786 
15787   if (Field1->isBitField() != Field2->isBitField())
15788     return false;
15789 
15790   if (Field1->isBitField()) {
15791     // Make sure that the bit-fields are the same length.
15792     unsigned Bits1 = Field1->getBitWidthValue(C);
15793     unsigned Bits2 = Field2->getBitWidthValue(C);
15794 
15795     if (Bits1 != Bits2)
15796       return false;
15797   }
15798 
15799   return true;
15800 }
15801 
15802 /// Check if two standard-layout structs are layout-compatible.
15803 /// (C++11 [class.mem] p17)
15804 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15805                                      RecordDecl *RD2) {
15806   // If both records are C++ classes, check that base classes match.
15807   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15808     // If one of records is a CXXRecordDecl we are in C++ mode,
15809     // thus the other one is a CXXRecordDecl, too.
15810     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15811     // Check number of base classes.
15812     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15813       return false;
15814 
15815     // Check the base classes.
15816     for (CXXRecordDecl::base_class_const_iterator
15817                Base1 = D1CXX->bases_begin(),
15818            BaseEnd1 = D1CXX->bases_end(),
15819               Base2 = D2CXX->bases_begin();
15820          Base1 != BaseEnd1;
15821          ++Base1, ++Base2) {
15822       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15823         return false;
15824     }
15825   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15826     // If only RD2 is a C++ class, it should have zero base classes.
15827     if (D2CXX->getNumBases() > 0)
15828       return false;
15829   }
15830 
15831   // Check the fields.
15832   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15833                              Field2End = RD2->field_end(),
15834                              Field1 = RD1->field_begin(),
15835                              Field1End = RD1->field_end();
15836   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15837     if (!isLayoutCompatible(C, *Field1, *Field2))
15838       return false;
15839   }
15840   if (Field1 != Field1End || Field2 != Field2End)
15841     return false;
15842 
15843   return true;
15844 }
15845 
15846 /// Check if two standard-layout unions are layout-compatible.
15847 /// (C++11 [class.mem] p18)
15848 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15849                                     RecordDecl *RD2) {
15850   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15851   for (auto *Field2 : RD2->fields())
15852     UnmatchedFields.insert(Field2);
15853 
15854   for (auto *Field1 : RD1->fields()) {
15855     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15856         I = UnmatchedFields.begin(),
15857         E = UnmatchedFields.end();
15858 
15859     for ( ; I != E; ++I) {
15860       if (isLayoutCompatible(C, Field1, *I)) {
15861         bool Result = UnmatchedFields.erase(*I);
15862         (void) Result;
15863         assert(Result);
15864         break;
15865       }
15866     }
15867     if (I == E)
15868       return false;
15869   }
15870 
15871   return UnmatchedFields.empty();
15872 }
15873 
15874 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15875                                RecordDecl *RD2) {
15876   if (RD1->isUnion() != RD2->isUnion())
15877     return false;
15878 
15879   if (RD1->isUnion())
15880     return isLayoutCompatibleUnion(C, RD1, RD2);
15881   else
15882     return isLayoutCompatibleStruct(C, RD1, RD2);
15883 }
15884 
15885 /// Check if two types are layout-compatible in C++11 sense.
15886 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15887   if (T1.isNull() || T2.isNull())
15888     return false;
15889 
15890   // C++11 [basic.types] p11:
15891   // If two types T1 and T2 are the same type, then T1 and T2 are
15892   // layout-compatible types.
15893   if (C.hasSameType(T1, T2))
15894     return true;
15895 
15896   T1 = T1.getCanonicalType().getUnqualifiedType();
15897   T2 = T2.getCanonicalType().getUnqualifiedType();
15898 
15899   const Type::TypeClass TC1 = T1->getTypeClass();
15900   const Type::TypeClass TC2 = T2->getTypeClass();
15901 
15902   if (TC1 != TC2)
15903     return false;
15904 
15905   if (TC1 == Type::Enum) {
15906     return isLayoutCompatible(C,
15907                               cast<EnumType>(T1)->getDecl(),
15908                               cast<EnumType>(T2)->getDecl());
15909   } else if (TC1 == Type::Record) {
15910     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15911       return false;
15912 
15913     return isLayoutCompatible(C,
15914                               cast<RecordType>(T1)->getDecl(),
15915                               cast<RecordType>(T2)->getDecl());
15916   }
15917 
15918   return false;
15919 }
15920 
15921 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15922 
15923 /// Given a type tag expression find the type tag itself.
15924 ///
15925 /// \param TypeExpr Type tag expression, as it appears in user's code.
15926 ///
15927 /// \param VD Declaration of an identifier that appears in a type tag.
15928 ///
15929 /// \param MagicValue Type tag magic value.
15930 ///
15931 /// \param isConstantEvaluated wether the evalaution should be performed in
15932 
15933 /// constant context.
15934 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15935                             const ValueDecl **VD, uint64_t *MagicValue,
15936                             bool isConstantEvaluated) {
15937   while(true) {
15938     if (!TypeExpr)
15939       return false;
15940 
15941     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15942 
15943     switch (TypeExpr->getStmtClass()) {
15944     case Stmt::UnaryOperatorClass: {
15945       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15946       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15947         TypeExpr = UO->getSubExpr();
15948         continue;
15949       }
15950       return false;
15951     }
15952 
15953     case Stmt::DeclRefExprClass: {
15954       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15955       *VD = DRE->getDecl();
15956       return true;
15957     }
15958 
15959     case Stmt::IntegerLiteralClass: {
15960       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15961       llvm::APInt MagicValueAPInt = IL->getValue();
15962       if (MagicValueAPInt.getActiveBits() <= 64) {
15963         *MagicValue = MagicValueAPInt.getZExtValue();
15964         return true;
15965       } else
15966         return false;
15967     }
15968 
15969     case Stmt::BinaryConditionalOperatorClass:
15970     case Stmt::ConditionalOperatorClass: {
15971       const AbstractConditionalOperator *ACO =
15972           cast<AbstractConditionalOperator>(TypeExpr);
15973       bool Result;
15974       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15975                                                      isConstantEvaluated)) {
15976         if (Result)
15977           TypeExpr = ACO->getTrueExpr();
15978         else
15979           TypeExpr = ACO->getFalseExpr();
15980         continue;
15981       }
15982       return false;
15983     }
15984 
15985     case Stmt::BinaryOperatorClass: {
15986       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15987       if (BO->getOpcode() == BO_Comma) {
15988         TypeExpr = BO->getRHS();
15989         continue;
15990       }
15991       return false;
15992     }
15993 
15994     default:
15995       return false;
15996     }
15997   }
15998 }
15999 
16000 /// Retrieve the C type corresponding to type tag TypeExpr.
16001 ///
16002 /// \param TypeExpr Expression that specifies a type tag.
16003 ///
16004 /// \param MagicValues Registered magic values.
16005 ///
16006 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16007 ///        kind.
16008 ///
16009 /// \param TypeInfo Information about the corresponding C type.
16010 ///
16011 /// \param isConstantEvaluated wether the evalaution should be performed in
16012 /// constant context.
16013 ///
16014 /// \returns true if the corresponding C type was found.
16015 static bool GetMatchingCType(
16016     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16017     const ASTContext &Ctx,
16018     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16019         *MagicValues,
16020     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16021     bool isConstantEvaluated) {
16022   FoundWrongKind = false;
16023 
16024   // Variable declaration that has type_tag_for_datatype attribute.
16025   const ValueDecl *VD = nullptr;
16026 
16027   uint64_t MagicValue;
16028 
16029   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16030     return false;
16031 
16032   if (VD) {
16033     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16034       if (I->getArgumentKind() != ArgumentKind) {
16035         FoundWrongKind = true;
16036         return false;
16037       }
16038       TypeInfo.Type = I->getMatchingCType();
16039       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16040       TypeInfo.MustBeNull = I->getMustBeNull();
16041       return true;
16042     }
16043     return false;
16044   }
16045 
16046   if (!MagicValues)
16047     return false;
16048 
16049   llvm::DenseMap<Sema::TypeTagMagicValue,
16050                  Sema::TypeTagData>::const_iterator I =
16051       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16052   if (I == MagicValues->end())
16053     return false;
16054 
16055   TypeInfo = I->second;
16056   return true;
16057 }
16058 
16059 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16060                                       uint64_t MagicValue, QualType Type,
16061                                       bool LayoutCompatible,
16062                                       bool MustBeNull) {
16063   if (!TypeTagForDatatypeMagicValues)
16064     TypeTagForDatatypeMagicValues.reset(
16065         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16066 
16067   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16068   (*TypeTagForDatatypeMagicValues)[Magic] =
16069       TypeTagData(Type, LayoutCompatible, MustBeNull);
16070 }
16071 
16072 static bool IsSameCharType(QualType T1, QualType T2) {
16073   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16074   if (!BT1)
16075     return false;
16076 
16077   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16078   if (!BT2)
16079     return false;
16080 
16081   BuiltinType::Kind T1Kind = BT1->getKind();
16082   BuiltinType::Kind T2Kind = BT2->getKind();
16083 
16084   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16085          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16086          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16087          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16088 }
16089 
16090 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16091                                     const ArrayRef<const Expr *> ExprArgs,
16092                                     SourceLocation CallSiteLoc) {
16093   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16094   bool IsPointerAttr = Attr->getIsPointer();
16095 
16096   // Retrieve the argument representing the 'type_tag'.
16097   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16098   if (TypeTagIdxAST >= ExprArgs.size()) {
16099     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16100         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16101     return;
16102   }
16103   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16104   bool FoundWrongKind;
16105   TypeTagData TypeInfo;
16106   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16107                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16108                         TypeInfo, isConstantEvaluated())) {
16109     if (FoundWrongKind)
16110       Diag(TypeTagExpr->getExprLoc(),
16111            diag::warn_type_tag_for_datatype_wrong_kind)
16112         << TypeTagExpr->getSourceRange();
16113     return;
16114   }
16115 
16116   // Retrieve the argument representing the 'arg_idx'.
16117   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16118   if (ArgumentIdxAST >= ExprArgs.size()) {
16119     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16120         << 1 << Attr->getArgumentIdx().getSourceIndex();
16121     return;
16122   }
16123   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16124   if (IsPointerAttr) {
16125     // Skip implicit cast of pointer to `void *' (as a function argument).
16126     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16127       if (ICE->getType()->isVoidPointerType() &&
16128           ICE->getCastKind() == CK_BitCast)
16129         ArgumentExpr = ICE->getSubExpr();
16130   }
16131   QualType ArgumentType = ArgumentExpr->getType();
16132 
16133   // Passing a `void*' pointer shouldn't trigger a warning.
16134   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16135     return;
16136 
16137   if (TypeInfo.MustBeNull) {
16138     // Type tag with matching void type requires a null pointer.
16139     if (!ArgumentExpr->isNullPointerConstant(Context,
16140                                              Expr::NPC_ValueDependentIsNotNull)) {
16141       Diag(ArgumentExpr->getExprLoc(),
16142            diag::warn_type_safety_null_pointer_required)
16143           << ArgumentKind->getName()
16144           << ArgumentExpr->getSourceRange()
16145           << TypeTagExpr->getSourceRange();
16146     }
16147     return;
16148   }
16149 
16150   QualType RequiredType = TypeInfo.Type;
16151   if (IsPointerAttr)
16152     RequiredType = Context.getPointerType(RequiredType);
16153 
16154   bool mismatch = false;
16155   if (!TypeInfo.LayoutCompatible) {
16156     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16157 
16158     // C++11 [basic.fundamental] p1:
16159     // Plain char, signed char, and unsigned char are three distinct types.
16160     //
16161     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16162     // char' depending on the current char signedness mode.
16163     if (mismatch)
16164       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16165                                            RequiredType->getPointeeType())) ||
16166           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16167         mismatch = false;
16168   } else
16169     if (IsPointerAttr)
16170       mismatch = !isLayoutCompatible(Context,
16171                                      ArgumentType->getPointeeType(),
16172                                      RequiredType->getPointeeType());
16173     else
16174       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16175 
16176   if (mismatch)
16177     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16178         << ArgumentType << ArgumentKind
16179         << TypeInfo.LayoutCompatible << RequiredType
16180         << ArgumentExpr->getSourceRange()
16181         << TypeTagExpr->getSourceRange();
16182 }
16183 
16184 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16185                                          CharUnits Alignment) {
16186   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16187 }
16188 
16189 void Sema::DiagnoseMisalignedMembers() {
16190   for (MisalignedMember &m : MisalignedMembers) {
16191     const NamedDecl *ND = m.RD;
16192     if (ND->getName().empty()) {
16193       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16194         ND = TD;
16195     }
16196     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16197         << m.MD << ND << m.E->getSourceRange();
16198   }
16199   MisalignedMembers.clear();
16200 }
16201 
16202 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16203   E = E->IgnoreParens();
16204   if (!T->isPointerType() && !T->isIntegerType())
16205     return;
16206   if (isa<UnaryOperator>(E) &&
16207       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16208     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16209     if (isa<MemberExpr>(Op)) {
16210       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16211       if (MA != MisalignedMembers.end() &&
16212           (T->isIntegerType() ||
16213            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16214                                    Context.getTypeAlignInChars(
16215                                        T->getPointeeType()) <= MA->Alignment))))
16216         MisalignedMembers.erase(MA);
16217     }
16218   }
16219 }
16220 
16221 void Sema::RefersToMemberWithReducedAlignment(
16222     Expr *E,
16223     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16224         Action) {
16225   const auto *ME = dyn_cast<MemberExpr>(E);
16226   if (!ME)
16227     return;
16228 
16229   // No need to check expressions with an __unaligned-qualified type.
16230   if (E->getType().getQualifiers().hasUnaligned())
16231     return;
16232 
16233   // For a chain of MemberExpr like "a.b.c.d" this list
16234   // will keep FieldDecl's like [d, c, b].
16235   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16236   const MemberExpr *TopME = nullptr;
16237   bool AnyIsPacked = false;
16238   do {
16239     QualType BaseType = ME->getBase()->getType();
16240     if (BaseType->isDependentType())
16241       return;
16242     if (ME->isArrow())
16243       BaseType = BaseType->getPointeeType();
16244     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16245     if (RD->isInvalidDecl())
16246       return;
16247 
16248     ValueDecl *MD = ME->getMemberDecl();
16249     auto *FD = dyn_cast<FieldDecl>(MD);
16250     // We do not care about non-data members.
16251     if (!FD || FD->isInvalidDecl())
16252       return;
16253 
16254     AnyIsPacked =
16255         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16256     ReverseMemberChain.push_back(FD);
16257 
16258     TopME = ME;
16259     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16260   } while (ME);
16261   assert(TopME && "We did not compute a topmost MemberExpr!");
16262 
16263   // Not the scope of this diagnostic.
16264   if (!AnyIsPacked)
16265     return;
16266 
16267   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16268   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16269   // TODO: The innermost base of the member expression may be too complicated.
16270   // For now, just disregard these cases. This is left for future
16271   // improvement.
16272   if (!DRE && !isa<CXXThisExpr>(TopBase))
16273       return;
16274 
16275   // Alignment expected by the whole expression.
16276   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16277 
16278   // No need to do anything else with this case.
16279   if (ExpectedAlignment.isOne())
16280     return;
16281 
16282   // Synthesize offset of the whole access.
16283   CharUnits Offset;
16284   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16285        I++) {
16286     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16287   }
16288 
16289   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16290   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16291       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16292 
16293   // The base expression of the innermost MemberExpr may give
16294   // stronger guarantees than the class containing the member.
16295   if (DRE && !TopME->isArrow()) {
16296     const ValueDecl *VD = DRE->getDecl();
16297     if (!VD->getType()->isReferenceType())
16298       CompleteObjectAlignment =
16299           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16300   }
16301 
16302   // Check if the synthesized offset fulfills the alignment.
16303   if (Offset % ExpectedAlignment != 0 ||
16304       // It may fulfill the offset it but the effective alignment may still be
16305       // lower than the expected expression alignment.
16306       CompleteObjectAlignment < ExpectedAlignment) {
16307     // If this happens, we want to determine a sensible culprit of this.
16308     // Intuitively, watching the chain of member expressions from right to
16309     // left, we start with the required alignment (as required by the field
16310     // type) but some packed attribute in that chain has reduced the alignment.
16311     // It may happen that another packed structure increases it again. But if
16312     // we are here such increase has not been enough. So pointing the first
16313     // FieldDecl that either is packed or else its RecordDecl is,
16314     // seems reasonable.
16315     FieldDecl *FD = nullptr;
16316     CharUnits Alignment;
16317     for (FieldDecl *FDI : ReverseMemberChain) {
16318       if (FDI->hasAttr<PackedAttr>() ||
16319           FDI->getParent()->hasAttr<PackedAttr>()) {
16320         FD = FDI;
16321         Alignment = std::min(
16322             Context.getTypeAlignInChars(FD->getType()),
16323             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16324         break;
16325       }
16326     }
16327     assert(FD && "We did not find a packed FieldDecl!");
16328     Action(E, FD->getParent(), FD, Alignment);
16329   }
16330 }
16331 
16332 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16333   using namespace std::placeholders;
16334 
16335   RefersToMemberWithReducedAlignment(
16336       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16337                      _2, _3, _4));
16338 }
16339 
16340 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16341                                             ExprResult CallResult) {
16342   if (checkArgCount(*this, TheCall, 1))
16343     return ExprError();
16344 
16345   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16346   if (MatrixArg.isInvalid())
16347     return MatrixArg;
16348   Expr *Matrix = MatrixArg.get();
16349 
16350   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16351   if (!MType) {
16352     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16353     return ExprError();
16354   }
16355 
16356   // Create returned matrix type by swapping rows and columns of the argument
16357   // matrix type.
16358   QualType ResultType = Context.getConstantMatrixType(
16359       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16360 
16361   // Change the return type to the type of the returned matrix.
16362   TheCall->setType(ResultType);
16363 
16364   // Update call argument to use the possibly converted matrix argument.
16365   TheCall->setArg(0, Matrix);
16366   return CallResult;
16367 }
16368 
16369 // Get and verify the matrix dimensions.
16370 static llvm::Optional<unsigned>
16371 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16372   SourceLocation ErrorPos;
16373   Optional<llvm::APSInt> Value =
16374       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16375   if (!Value) {
16376     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16377         << Name;
16378     return {};
16379   }
16380   uint64_t Dim = Value->getZExtValue();
16381   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16382     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16383         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16384     return {};
16385   }
16386   return Dim;
16387 }
16388 
16389 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16390                                                   ExprResult CallResult) {
16391   if (!getLangOpts().MatrixTypes) {
16392     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16393     return ExprError();
16394   }
16395 
16396   if (checkArgCount(*this, TheCall, 4))
16397     return ExprError();
16398 
16399   unsigned PtrArgIdx = 0;
16400   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16401   Expr *RowsExpr = TheCall->getArg(1);
16402   Expr *ColumnsExpr = TheCall->getArg(2);
16403   Expr *StrideExpr = TheCall->getArg(3);
16404 
16405   bool ArgError = false;
16406 
16407   // Check pointer argument.
16408   {
16409     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16410     if (PtrConv.isInvalid())
16411       return PtrConv;
16412     PtrExpr = PtrConv.get();
16413     TheCall->setArg(0, PtrExpr);
16414     if (PtrExpr->isTypeDependent()) {
16415       TheCall->setType(Context.DependentTy);
16416       return TheCall;
16417     }
16418   }
16419 
16420   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16421   QualType ElementTy;
16422   if (!PtrTy) {
16423     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16424         << PtrArgIdx + 1;
16425     ArgError = true;
16426   } else {
16427     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16428 
16429     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16430       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16431           << PtrArgIdx + 1;
16432       ArgError = true;
16433     }
16434   }
16435 
16436   // Apply default Lvalue conversions and convert the expression to size_t.
16437   auto ApplyArgumentConversions = [this](Expr *E) {
16438     ExprResult Conv = DefaultLvalueConversion(E);
16439     if (Conv.isInvalid())
16440       return Conv;
16441 
16442     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16443   };
16444 
16445   // Apply conversion to row and column expressions.
16446   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16447   if (!RowsConv.isInvalid()) {
16448     RowsExpr = RowsConv.get();
16449     TheCall->setArg(1, RowsExpr);
16450   } else
16451     RowsExpr = nullptr;
16452 
16453   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16454   if (!ColumnsConv.isInvalid()) {
16455     ColumnsExpr = ColumnsConv.get();
16456     TheCall->setArg(2, ColumnsExpr);
16457   } else
16458     ColumnsExpr = nullptr;
16459 
16460   // If any any part of the result matrix type is still pending, just use
16461   // Context.DependentTy, until all parts are resolved.
16462   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16463       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16464     TheCall->setType(Context.DependentTy);
16465     return CallResult;
16466   }
16467 
16468   // Check row and column dimenions.
16469   llvm::Optional<unsigned> MaybeRows;
16470   if (RowsExpr)
16471     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16472 
16473   llvm::Optional<unsigned> MaybeColumns;
16474   if (ColumnsExpr)
16475     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16476 
16477   // Check stride argument.
16478   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16479   if (StrideConv.isInvalid())
16480     return ExprError();
16481   StrideExpr = StrideConv.get();
16482   TheCall->setArg(3, StrideExpr);
16483 
16484   if (MaybeRows) {
16485     if (Optional<llvm::APSInt> Value =
16486             StrideExpr->getIntegerConstantExpr(Context)) {
16487       uint64_t Stride = Value->getZExtValue();
16488       if (Stride < *MaybeRows) {
16489         Diag(StrideExpr->getBeginLoc(),
16490              diag::err_builtin_matrix_stride_too_small);
16491         ArgError = true;
16492       }
16493     }
16494   }
16495 
16496   if (ArgError || !MaybeRows || !MaybeColumns)
16497     return ExprError();
16498 
16499   TheCall->setType(
16500       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16501   return CallResult;
16502 }
16503 
16504 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16505                                                    ExprResult CallResult) {
16506   if (checkArgCount(*this, TheCall, 3))
16507     return ExprError();
16508 
16509   unsigned PtrArgIdx = 1;
16510   Expr *MatrixExpr = TheCall->getArg(0);
16511   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16512   Expr *StrideExpr = TheCall->getArg(2);
16513 
16514   bool ArgError = false;
16515 
16516   {
16517     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16518     if (MatrixConv.isInvalid())
16519       return MatrixConv;
16520     MatrixExpr = MatrixConv.get();
16521     TheCall->setArg(0, MatrixExpr);
16522   }
16523   if (MatrixExpr->isTypeDependent()) {
16524     TheCall->setType(Context.DependentTy);
16525     return TheCall;
16526   }
16527 
16528   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16529   if (!MatrixTy) {
16530     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16531     ArgError = true;
16532   }
16533 
16534   {
16535     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16536     if (PtrConv.isInvalid())
16537       return PtrConv;
16538     PtrExpr = PtrConv.get();
16539     TheCall->setArg(1, PtrExpr);
16540     if (PtrExpr->isTypeDependent()) {
16541       TheCall->setType(Context.DependentTy);
16542       return TheCall;
16543     }
16544   }
16545 
16546   // Check pointer argument.
16547   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16548   if (!PtrTy) {
16549     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16550         << PtrArgIdx + 1;
16551     ArgError = true;
16552   } else {
16553     QualType ElementTy = PtrTy->getPointeeType();
16554     if (ElementTy.isConstQualified()) {
16555       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16556       ArgError = true;
16557     }
16558     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16559     if (MatrixTy &&
16560         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16561       Diag(PtrExpr->getBeginLoc(),
16562            diag::err_builtin_matrix_pointer_arg_mismatch)
16563           << ElementTy << MatrixTy->getElementType();
16564       ArgError = true;
16565     }
16566   }
16567 
16568   // Apply default Lvalue conversions and convert the stride expression to
16569   // size_t.
16570   {
16571     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16572     if (StrideConv.isInvalid())
16573       return StrideConv;
16574 
16575     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16576     if (StrideConv.isInvalid())
16577       return StrideConv;
16578     StrideExpr = StrideConv.get();
16579     TheCall->setArg(2, StrideExpr);
16580   }
16581 
16582   // Check stride argument.
16583   if (MatrixTy) {
16584     if (Optional<llvm::APSInt> Value =
16585             StrideExpr->getIntegerConstantExpr(Context)) {
16586       uint64_t Stride = Value->getZExtValue();
16587       if (Stride < MatrixTy->getNumRows()) {
16588         Diag(StrideExpr->getBeginLoc(),
16589              diag::err_builtin_matrix_stride_too_small);
16590         ArgError = true;
16591       }
16592     }
16593   }
16594 
16595   if (ArgError)
16596     return ExprError();
16597 
16598   return CallResult;
16599 }
16600 
16601 /// \brief Enforce the bounds of a TCB
16602 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16603 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16604 /// and enforce_tcb_leaf attributes.
16605 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16606                                const FunctionDecl *Callee) {
16607   const FunctionDecl *Caller = getCurFunctionDecl();
16608 
16609   // Calls to builtins are not enforced.
16610   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16611       Callee->getBuiltinID() != 0)
16612     return;
16613 
16614   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16615   // all TCBs the callee is a part of.
16616   llvm::StringSet<> CalleeTCBs;
16617   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16618            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16619   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16620            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16621 
16622   // Go through the TCBs the caller is a part of and emit warnings if Caller
16623   // is in a TCB that the Callee is not.
16624   for_each(
16625       Caller->specific_attrs<EnforceTCBAttr>(),
16626       [&](const auto *A) {
16627         StringRef CallerTCB = A->getTCBName();
16628         if (CalleeTCBs.count(CallerTCB) == 0) {
16629           this->Diag(TheCall->getExprLoc(),
16630                      diag::warn_tcb_enforcement_violation) << Callee
16631                                                            << CallerTCB;
16632         }
16633       });
16634 }
16635