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 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
592                                                CallExpr *TheCall) {
593   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
594       isConstantEvaluated())
595     return;
596 
597   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
598   if (!BuiltinID)
599     return;
600 
601   const TargetInfo &TI = getASTContext().getTargetInfo();
602   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
603 
604   auto ComputeExplicitObjectSizeArgument =
605       [&](unsigned Index) -> Optional<llvm::APSInt> {
606     Expr::EvalResult Result;
607     Expr *SizeArg = TheCall->getArg(Index);
608     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
609       return llvm::None;
610     return Result.Val.getInt();
611   };
612 
613   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
614     // If the parameter has a pass_object_size attribute, then we should use its
615     // (potentially) more strict checking mode. Otherwise, conservatively assume
616     // type 0.
617     int BOSType = 0;
618     if (const auto *POS =
619             FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
620       BOSType = POS->getType();
621 
622     const Expr *ObjArg = TheCall->getArg(Index);
623     uint64_t Result;
624     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
625       return llvm::None;
626 
627     // Get the object size in the target's size_t width.
628     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
629   };
630 
631   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
632     Expr *ObjArg = TheCall->getArg(Index);
633     uint64_t Result;
634     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
635       return llvm::None;
636     // Add 1 for null byte.
637     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
638   };
639 
640   Optional<llvm::APSInt> SourceSize;
641   Optional<llvm::APSInt> DestinationSize;
642   unsigned DiagID = 0;
643   bool IsChkVariant = false;
644 
645   switch (BuiltinID) {
646   default:
647     return;
648   case Builtin::BI__builtin_strcpy:
649   case Builtin::BIstrcpy: {
650     DiagID = diag::warn_fortify_strlen_overflow;
651     SourceSize = ComputeStrLenArgument(1);
652     DestinationSize = ComputeSizeArgument(0);
653     break;
654   }
655 
656   case Builtin::BI__builtin___strcpy_chk: {
657     DiagID = diag::warn_fortify_strlen_overflow;
658     SourceSize = ComputeStrLenArgument(1);
659     DestinationSize = ComputeExplicitObjectSizeArgument(2);
660     IsChkVariant = true;
661     break;
662   }
663 
664   case Builtin::BIsprintf:
665   case Builtin::BI__builtin___sprintf_chk: {
666     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
667     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
668 
669     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
670 
671       if (!Format->isAscii() && !Format->isUTF8())
672         return;
673 
674       StringRef FormatStrRef = Format->getString();
675       EstimateSizeFormatHandler H(FormatStrRef);
676       const char *FormatBytes = FormatStrRef.data();
677       const ConstantArrayType *T =
678           Context.getAsConstantArrayType(Format->getType());
679       assert(T && "String literal not of constant array type!");
680       size_t TypeSize = T->getSize().getZExtValue();
681 
682       // In case there's a null byte somewhere.
683       size_t StrLen =
684           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
685       if (!analyze_format_string::ParsePrintfString(
686               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
687               Context.getTargetInfo(), false)) {
688         DiagID = diag::warn_fortify_source_format_overflow;
689         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
690                          .extOrTrunc(SizeTypeWidth);
691         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
692           DestinationSize = ComputeExplicitObjectSizeArgument(2);
693           IsChkVariant = true;
694         } else {
695           DestinationSize = ComputeSizeArgument(0);
696         }
697         break;
698       }
699     }
700     return;
701   }
702   case Builtin::BI__builtin___memcpy_chk:
703   case Builtin::BI__builtin___memmove_chk:
704   case Builtin::BI__builtin___memset_chk:
705   case Builtin::BI__builtin___strlcat_chk:
706   case Builtin::BI__builtin___strlcpy_chk:
707   case Builtin::BI__builtin___strncat_chk:
708   case Builtin::BI__builtin___strncpy_chk:
709   case Builtin::BI__builtin___stpncpy_chk:
710   case Builtin::BI__builtin___memccpy_chk:
711   case Builtin::BI__builtin___mempcpy_chk: {
712     DiagID = diag::warn_builtin_chk_overflow;
713     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
714     DestinationSize =
715         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
716     IsChkVariant = true;
717     break;
718   }
719 
720   case Builtin::BI__builtin___snprintf_chk:
721   case Builtin::BI__builtin___vsnprintf_chk: {
722     DiagID = diag::warn_builtin_chk_overflow;
723     SourceSize = ComputeExplicitObjectSizeArgument(1);
724     DestinationSize = ComputeExplicitObjectSizeArgument(3);
725     IsChkVariant = true;
726     break;
727   }
728 
729   case Builtin::BIstrncat:
730   case Builtin::BI__builtin_strncat:
731   case Builtin::BIstrncpy:
732   case Builtin::BI__builtin_strncpy:
733   case Builtin::BIstpncpy:
734   case Builtin::BI__builtin_stpncpy: {
735     // Whether these functions overflow depends on the runtime strlen of the
736     // string, not just the buffer size, so emitting the "always overflow"
737     // diagnostic isn't quite right. We should still diagnose passing a buffer
738     // size larger than the destination buffer though; this is a runtime abort
739     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
740     DiagID = diag::warn_fortify_source_size_mismatch;
741     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
742     DestinationSize = ComputeSizeArgument(0);
743     break;
744   }
745 
746   case Builtin::BImemcpy:
747   case Builtin::BI__builtin_memcpy:
748   case Builtin::BImemmove:
749   case Builtin::BI__builtin_memmove:
750   case Builtin::BImemset:
751   case Builtin::BI__builtin_memset:
752   case Builtin::BImempcpy:
753   case Builtin::BI__builtin_mempcpy: {
754     DiagID = diag::warn_fortify_source_overflow;
755     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
756     DestinationSize = ComputeSizeArgument(0);
757     break;
758   }
759   case Builtin::BIsnprintf:
760   case Builtin::BI__builtin_snprintf:
761   case Builtin::BIvsnprintf:
762   case Builtin::BI__builtin_vsnprintf: {
763     DiagID = diag::warn_fortify_source_size_mismatch;
764     SourceSize = ComputeExplicitObjectSizeArgument(1);
765     DestinationSize = ComputeSizeArgument(0);
766     break;
767   }
768   }
769 
770   if (!SourceSize || !DestinationSize ||
771       SourceSize.getValue().ule(DestinationSize.getValue()))
772     return;
773 
774   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775   // Skim off the details of whichever builtin was called to produce a better
776   // diagnostic, as it's unlikely that the user wrote the __builtin explicitly.
777   if (IsChkVariant) {
778     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780   } else if (FunctionName.startswith("__builtin_")) {
781     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782   }
783 
784   SmallString<16> DestinationStr;
785   SmallString<16> SourceStr;
786   DestinationSize->toString(DestinationStr, /*Radix=*/10);
787   SourceSize->toString(SourceStr, /*Radix=*/10);
788   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
789                       PDiag(DiagID)
790                           << FunctionName << DestinationStr << SourceStr);
791 }
792 
793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
794                                      Scope::ScopeFlags NeededScopeFlags,
795                                      unsigned DiagID) {
796   // Scopes aren't available during instantiation. Fortunately, builtin
797   // functions cannot be template args so they cannot be formed through template
798   // instantiation. Therefore checking once during the parse is sufficient.
799   if (SemaRef.inTemplateInstantiation())
800     return false;
801 
802   Scope *S = SemaRef.getCurScope();
803   while (S && !S->isSEHExceptScope())
804     S = S->getParent();
805   if (!S || !(S->getFlags() & NeededScopeFlags)) {
806     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
807     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
808         << DRE->getDecl()->getIdentifier();
809     return true;
810   }
811 
812   return false;
813 }
814 
815 static inline bool isBlockPointer(Expr *Arg) {
816   return Arg->getType()->isBlockPointerType();
817 }
818 
819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
820 /// void*, which is a requirement of device side enqueue.
821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
822   const BlockPointerType *BPT =
823       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
824   ArrayRef<QualType> Params =
825       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
826   unsigned ArgCounter = 0;
827   bool IllegalParams = false;
828   // Iterate through the block parameters until either one is found that is not
829   // a local void*, or the block is valid.
830   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
831        I != E; ++I, ++ArgCounter) {
832     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
833         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
834             LangAS::opencl_local) {
835       // Get the location of the error. If a block literal has been passed
836       // (BlockExpr) then we can point straight to the offending argument,
837       // else we just point to the variable reference.
838       SourceLocation ErrorLoc;
839       if (isa<BlockExpr>(BlockArg)) {
840         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
841         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
842       } else if (isa<DeclRefExpr>(BlockArg)) {
843         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
844       }
845       S.Diag(ErrorLoc,
846              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
847       IllegalParams = true;
848     }
849   }
850 
851   return IllegalParams;
852 }
853 
854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
855   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
856     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
857         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
858     return true;
859   }
860   return false;
861 }
862 
863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
864   if (checkArgCount(S, TheCall, 2))
865     return true;
866 
867   if (checkOpenCLSubgroupExt(S, TheCall))
868     return true;
869 
870   // First argument is an ndrange_t type.
871   Expr *NDRangeArg = TheCall->getArg(0);
872   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
873     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
874         << TheCall->getDirectCallee() << "'ndrange_t'";
875     return true;
876   }
877 
878   Expr *BlockArg = TheCall->getArg(1);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
888 /// get_kernel_work_group_size
889 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
891   if (checkArgCount(S, TheCall, 1))
892     return true;
893 
894   Expr *BlockArg = TheCall->getArg(0);
895   if (!isBlockPointer(BlockArg)) {
896     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
897         << TheCall->getDirectCallee() << "block";
898     return true;
899   }
900   return checkOpenCLBlockArgs(S, BlockArg);
901 }
902 
903 /// Diagnose integer type and any valid implicit conversion to it.
904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
905                                       const QualType &IntType);
906 
907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
908                                             unsigned Start, unsigned End) {
909   bool IllegalParams = false;
910   for (unsigned I = Start; I <= End; ++I)
911     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
912                                               S.Context.getSizeType());
913   return IllegalParams;
914 }
915 
916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
917 /// 'local void*' parameter of passed block.
918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
919                                            Expr *BlockArg,
920                                            unsigned NumNonVarArgs) {
921   const BlockPointerType *BPT =
922       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
923   unsigned NumBlockParams =
924       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
925   unsigned TotalNumArgs = TheCall->getNumArgs();
926 
927   // For each argument passed to the block, a corresponding uint needs to
928   // be passed to describe the size of the local memory.
929   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
930     S.Diag(TheCall->getBeginLoc(),
931            diag::err_opencl_enqueue_kernel_local_size_args);
932     return true;
933   }
934 
935   // Check that the sizes of the local memory are specified by integers.
936   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
937                                          TotalNumArgs - 1);
938 }
939 
940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
941 /// overload formats specified in Table 6.13.17.1.
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    void (^block)(void))
946 /// int enqueue_kernel(queue_t queue,
947 ///                    kernel_enqueue_flags_t flags,
948 ///                    const ndrange_t ndrange,
949 ///                    uint num_events_in_wait_list,
950 ///                    clk_event_t *event_wait_list,
951 ///                    clk_event_t *event_ret,
952 ///                    void (^block)(void))
953 /// int enqueue_kernel(queue_t queue,
954 ///                    kernel_enqueue_flags_t flags,
955 ///                    const ndrange_t ndrange,
956 ///                    void (^block)(local void*, ...),
957 ///                    uint size0, ...)
958 /// int enqueue_kernel(queue_t queue,
959 ///                    kernel_enqueue_flags_t flags,
960 ///                    const ndrange_t ndrange,
961 ///                    uint num_events_in_wait_list,
962 ///                    clk_event_t *event_wait_list,
963 ///                    clk_event_t *event_ret,
964 ///                    void (^block)(local void*, ...),
965 ///                    uint size0, ...)
966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
967   unsigned NumArgs = TheCall->getNumArgs();
968 
969   if (NumArgs < 4) {
970     S.Diag(TheCall->getBeginLoc(),
971            diag::err_typecheck_call_too_few_args_at_least)
972         << 0 << 4 << NumArgs;
973     return true;
974   }
975 
976   Expr *Arg0 = TheCall->getArg(0);
977   Expr *Arg1 = TheCall->getArg(1);
978   Expr *Arg2 = TheCall->getArg(2);
979   Expr *Arg3 = TheCall->getArg(3);
980 
981   // First argument always needs to be a queue_t type.
982   if (!Arg0->getType()->isQueueT()) {
983     S.Diag(TheCall->getArg(0)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
986     return true;
987   }
988 
989   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
990   if (!Arg1->getType()->isIntegerType()) {
991     S.Diag(TheCall->getArg(1)->getBeginLoc(),
992            diag::err_opencl_builtin_expected_type)
993         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
994     return true;
995   }
996 
997   // Third argument is always an ndrange_t type.
998   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
999     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1000            diag::err_opencl_builtin_expected_type)
1001         << TheCall->getDirectCallee() << "'ndrange_t'";
1002     return true;
1003   }
1004 
1005   // With four arguments, there is only one form that the function could be
1006   // called in: no events and no variable arguments.
1007   if (NumArgs == 4) {
1008     // check that the last argument is the right block type.
1009     if (!isBlockPointer(Arg3)) {
1010       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1011           << TheCall->getDirectCallee() << "block";
1012       return true;
1013     }
1014     // we have a block type, check the prototype
1015     const BlockPointerType *BPT =
1016         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1017     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1018       S.Diag(Arg3->getBeginLoc(),
1019              diag::err_opencl_enqueue_kernel_blocks_no_args);
1020       return true;
1021     }
1022     return false;
1023   }
1024   // we can have block + varargs.
1025   if (isBlockPointer(Arg3))
1026     return (checkOpenCLBlockArgs(S, Arg3) ||
1027             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1028   // last two cases with either exactly 7 args or 7 args and varargs.
1029   if (NumArgs >= 7) {
1030     // check common block argument.
1031     Expr *Arg6 = TheCall->getArg(6);
1032     if (!isBlockPointer(Arg6)) {
1033       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1034           << TheCall->getDirectCallee() << "block";
1035       return true;
1036     }
1037     if (checkOpenCLBlockArgs(S, Arg6))
1038       return true;
1039 
1040     // Forth argument has to be any integer type.
1041     if (!Arg3->getType()->isIntegerType()) {
1042       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee() << "integer";
1045       return true;
1046     }
1047     // check remaining common arguments.
1048     Expr *Arg4 = TheCall->getArg(4);
1049     Expr *Arg5 = TheCall->getArg(5);
1050 
1051     // Fifth argument is always passed as a pointer to clk_event_t.
1052     if (!Arg4->isNullPointerConstant(S.Context,
1053                                      Expr::NPC_ValueDependentIsNotNull) &&
1054         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1055       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1056              diag::err_opencl_builtin_expected_type)
1057           << TheCall->getDirectCallee()
1058           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1059       return true;
1060     }
1061 
1062     // Sixth argument is always passed as a pointer to clk_event_t.
1063     if (!Arg5->isNullPointerConstant(S.Context,
1064                                      Expr::NPC_ValueDependentIsNotNull) &&
1065         !(Arg5->getType()->isPointerType() &&
1066           Arg5->getType()->getPointeeType()->isClkEventT())) {
1067       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1068              diag::err_opencl_builtin_expected_type)
1069           << TheCall->getDirectCallee()
1070           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1071       return true;
1072     }
1073 
1074     if (NumArgs == 7)
1075       return false;
1076 
1077     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1078   }
1079 
1080   // None of the specific case has been detected, give generic error
1081   S.Diag(TheCall->getBeginLoc(),
1082          diag::err_opencl_enqueue_kernel_incorrect_args);
1083   return true;
1084 }
1085 
1086 /// Returns OpenCL access qual.
1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1088     return D->getAttr<OpenCLAccessAttr>();
1089 }
1090 
1091 /// Returns true if pipe element type is different from the pointer.
1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1093   const Expr *Arg0 = Call->getArg(0);
1094   // First argument type should always be pipe.
1095   if (!Arg0->getType()->isPipeType()) {
1096     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1097         << Call->getDirectCallee() << Arg0->getSourceRange();
1098     return true;
1099   }
1100   OpenCLAccessAttr *AccessQual =
1101       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1102   // Validates the access qualifier is compatible with the call.
1103   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1104   // read_only and write_only, and assumed to be read_only if no qualifier is
1105   // specified.
1106   switch (Call->getDirectCallee()->getBuiltinID()) {
1107   case Builtin::BIread_pipe:
1108   case Builtin::BIreserve_read_pipe:
1109   case Builtin::BIcommit_read_pipe:
1110   case Builtin::BIwork_group_reserve_read_pipe:
1111   case Builtin::BIsub_group_reserve_read_pipe:
1112   case Builtin::BIwork_group_commit_read_pipe:
1113   case Builtin::BIsub_group_commit_read_pipe:
1114     if (!(!AccessQual || AccessQual->isReadOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "read_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   case Builtin::BIwrite_pipe:
1122   case Builtin::BIreserve_write_pipe:
1123   case Builtin::BIcommit_write_pipe:
1124   case Builtin::BIwork_group_reserve_write_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126   case Builtin::BIwork_group_commit_write_pipe:
1127   case Builtin::BIsub_group_commit_write_pipe:
1128     if (!(AccessQual && AccessQual->isWriteOnly())) {
1129       S.Diag(Arg0->getBeginLoc(),
1130              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1131           << "write_only" << Arg0->getSourceRange();
1132       return true;
1133     }
1134     break;
1135   default:
1136     break;
1137   }
1138   return false;
1139 }
1140 
1141 /// Returns true if pipe element type is different from the pointer.
1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1143   const Expr *Arg0 = Call->getArg(0);
1144   const Expr *ArgIdx = Call->getArg(Idx);
1145   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1146   const QualType EltTy = PipeTy->getElementType();
1147   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1148   // The Idx argument should be a pointer and the type of the pointer and
1149   // the type of pipe element should also be the same.
1150   if (!ArgTy ||
1151       !S.Context.hasSameType(
1152           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1153     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1154         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1155         << ArgIdx->getType() << ArgIdx->getSourceRange();
1156     return true;
1157   }
1158   return false;
1159 }
1160 
1161 // Performs semantic analysis for the read/write_pipe call.
1162 // \param S Reference to the semantic analyzer.
1163 // \param Call A pointer to the builtin call.
1164 // \return True if a semantic error has been found, false otherwise.
1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1166   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1167   // functions have two forms.
1168   switch (Call->getNumArgs()) {
1169   case 2:
1170     if (checkOpenCLPipeArg(S, Call))
1171       return true;
1172     // The call with 2 arguments should be
1173     // read/write_pipe(pipe T, T*).
1174     // Check packet type T.
1175     if (checkOpenCLPipePacketType(S, Call, 1))
1176       return true;
1177     break;
1178 
1179   case 4: {
1180     if (checkOpenCLPipeArg(S, Call))
1181       return true;
1182     // The call with 4 arguments should be
1183     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1184     // Check reserve_id_t.
1185     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1186       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1187           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1188           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1189       return true;
1190     }
1191 
1192     // Check the index.
1193     const Expr *Arg2 = Call->getArg(2);
1194     if (!Arg2->getType()->isIntegerType() &&
1195         !Arg2->getType()->isUnsignedIntegerType()) {
1196       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1197           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1198           << Arg2->getType() << Arg2->getSourceRange();
1199       return true;
1200     }
1201 
1202     // Check packet type T.
1203     if (checkOpenCLPipePacketType(S, Call, 3))
1204       return true;
1205   } break;
1206   default:
1207     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1208         << Call->getDirectCallee() << Call->getSourceRange();
1209     return true;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on the {work_group_/sub_group_
1216 //        /_}reserve_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check the reserve size.
1228   if (!Call->getArg(1)->getType()->isIntegerType() &&
1229       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1230     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1231         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1232         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1233     return true;
1234   }
1235 
1236   // Since return type of reserve_read/write_pipe built-in function is
1237   // reserve_id_t, which is not defined in the builtin def file , we used int
1238   // as return type and need to override the return type of these functions.
1239   Call->setType(S.Context.OCLReserveIDTy);
1240 
1241   return false;
1242 }
1243 
1244 // Performs a semantic analysis on {work_group_/sub_group_
1245 //        /_}commit_{read/write}_pipe
1246 // \param S Reference to the semantic analyzer.
1247 // \param Call The call to the builtin function to be analyzed.
1248 // \return True if a semantic error was found, false otherwise.
1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1250   if (checkArgCount(S, Call, 2))
1251     return true;
1252 
1253   if (checkOpenCLPipeArg(S, Call))
1254     return true;
1255 
1256   // Check reserve_id_t.
1257   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1258     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1259         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1260         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 // Performs a semantic analysis on the call to built-in Pipe
1268 //        Query Functions.
1269 // \param S Reference to the semantic analyzer.
1270 // \param Call The call to the builtin function to be analyzed.
1271 // \return True if a semantic error was found, false otherwise.
1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1273   if (checkArgCount(S, Call, 1))
1274     return true;
1275 
1276   if (!Call->getArg(0)->getType()->isPipeType()) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1278         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1279     return true;
1280   }
1281 
1282   return false;
1283 }
1284 
1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1286 // Performs semantic analysis for the to_global/local/private call.
1287 // \param S Reference to the semantic analyzer.
1288 // \param BuiltinID ID of the builtin function.
1289 // \param Call A pointer to the builtin call.
1290 // \return True if a semantic error has been found, false otherwise.
1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1292                                     CallExpr *Call) {
1293   if (checkArgCount(S, Call, 1))
1294     return true;
1295 
1296   auto RT = Call->getArg(0)->getType();
1297   if (!RT->isPointerType() || RT->getPointeeType()
1298       .getAddressSpace() == LangAS::opencl_constant) {
1299     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1300         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1301     return true;
1302   }
1303 
1304   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1305     S.Diag(Call->getArg(0)->getBeginLoc(),
1306            diag::warn_opencl_generic_address_space_arg)
1307         << Call->getDirectCallee()->getNameInfo().getAsString()
1308         << Call->getArg(0)->getSourceRange();
1309   }
1310 
1311   RT = RT->getPointeeType();
1312   auto Qual = RT.getQualifiers();
1313   switch (BuiltinID) {
1314   case Builtin::BIto_global:
1315     Qual.setAddressSpace(LangAS::opencl_global);
1316     break;
1317   case Builtin::BIto_local:
1318     Qual.setAddressSpace(LangAS::opencl_local);
1319     break;
1320   case Builtin::BIto_private:
1321     Qual.setAddressSpace(LangAS::opencl_private);
1322     break;
1323   default:
1324     llvm_unreachable("Invalid builtin function");
1325   }
1326   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1327       RT.getUnqualifiedType(), Qual)));
1328 
1329   return false;
1330 }
1331 
1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1333   if (checkArgCount(S, TheCall, 1))
1334     return ExprError();
1335 
1336   // Compute __builtin_launder's parameter type from the argument.
1337   // The parameter type is:
1338   //  * The type of the argument if it's not an array or function type,
1339   //  Otherwise,
1340   //  * The decayed argument type.
1341   QualType ParamTy = [&]() {
1342     QualType ArgTy = TheCall->getArg(0)->getType();
1343     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1344       return S.Context.getPointerType(Ty->getElementType());
1345     if (ArgTy->isFunctionType()) {
1346       return S.Context.getPointerType(ArgTy);
1347     }
1348     return ArgTy;
1349   }();
1350 
1351   TheCall->setType(ParamTy);
1352 
1353   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1354     if (!ParamTy->isPointerType())
1355       return 0;
1356     if (ParamTy->isFunctionPointerType())
1357       return 1;
1358     if (ParamTy->isVoidPointerType())
1359       return 2;
1360     return llvm::Optional<unsigned>{};
1361   }();
1362   if (DiagSelect.hasValue()) {
1363     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1364         << DiagSelect.getValue() << TheCall->getSourceRange();
1365     return ExprError();
1366   }
1367 
1368   // We either have an incomplete class type, or we have a class template
1369   // whose instantiation has not been forced. Example:
1370   //
1371   //   template <class T> struct Foo { T value; };
1372   //   Foo<int> *p = nullptr;
1373   //   auto *d = __builtin_launder(p);
1374   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1375                             diag::err_incomplete_type))
1376     return ExprError();
1377 
1378   assert(ParamTy->getPointeeType()->isObjectType() &&
1379          "Unhandled non-object pointer case");
1380 
1381   InitializedEntity Entity =
1382       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1383   ExprResult Arg =
1384       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1385   if (Arg.isInvalid())
1386     return ExprError();
1387   TheCall->setArg(0, Arg.get());
1388 
1389   return TheCall;
1390 }
1391 
1392 // Emit an error and return true if the current architecture is not in the list
1393 // of supported architectures.
1394 static bool
1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1396                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1397   llvm::Triple::ArchType CurArch =
1398       S.getASTContext().getTargetInfo().getTriple().getArch();
1399   if (llvm::is_contained(SupportedArchs, CurArch))
1400     return false;
1401   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1402       << TheCall->getSourceRange();
1403   return true;
1404 }
1405 
1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1407                                  SourceLocation CallSiteLoc);
1408 
1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1410                                       CallExpr *TheCall) {
1411   switch (TI.getTriple().getArch()) {
1412   default:
1413     // Some builtins don't require additional checking, so just consider these
1414     // acceptable.
1415     return false;
1416   case llvm::Triple::arm:
1417   case llvm::Triple::armeb:
1418   case llvm::Triple::thumb:
1419   case llvm::Triple::thumbeb:
1420     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::aarch64:
1422   case llvm::Triple::aarch64_32:
1423   case llvm::Triple::aarch64_be:
1424     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::bpfeb:
1426   case llvm::Triple::bpfel:
1427     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1428   case llvm::Triple::hexagon:
1429     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1430   case llvm::Triple::mips:
1431   case llvm::Triple::mipsel:
1432   case llvm::Triple::mips64:
1433   case llvm::Triple::mips64el:
1434     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   case llvm::Triple::systemz:
1436     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1437   case llvm::Triple::x86:
1438   case llvm::Triple::x86_64:
1439     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1440   case llvm::Triple::ppc:
1441   case llvm::Triple::ppcle:
1442   case llvm::Triple::ppc64:
1443   case llvm::Triple::ppc64le:
1444     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1445   case llvm::Triple::amdgcn:
1446     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1447   case llvm::Triple::riscv32:
1448   case llvm::Triple::riscv64:
1449     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1450   }
1451 }
1452 
1453 ExprResult
1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1455                                CallExpr *TheCall) {
1456   ExprResult TheCallResult(TheCall);
1457 
1458   // Find out if any arguments are required to be integer constant expressions.
1459   unsigned ICEArguments = 0;
1460   ASTContext::GetBuiltinTypeError Error;
1461   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1462   if (Error != ASTContext::GE_None)
1463     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1464 
1465   // If any arguments are required to be ICE's, check and diagnose.
1466   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1467     // Skip arguments not required to be ICE's.
1468     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1469 
1470     llvm::APSInt Result;
1471     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1472       return true;
1473     ICEArguments &= ~(1 << ArgNo);
1474   }
1475 
1476   switch (BuiltinID) {
1477   case Builtin::BI__builtin___CFStringMakeConstantString:
1478     assert(TheCall->getNumArgs() == 1 &&
1479            "Wrong # arguments to builtin CFStringMakeConstantString");
1480     if (CheckObjCString(TheCall->getArg(0)))
1481       return ExprError();
1482     break;
1483   case Builtin::BI__builtin_ms_va_start:
1484   case Builtin::BI__builtin_stdarg_start:
1485   case Builtin::BI__builtin_va_start:
1486     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BI__va_start: {
1490     switch (Context.getTargetInfo().getTriple().getArch()) {
1491     case llvm::Triple::aarch64:
1492     case llvm::Triple::arm:
1493     case llvm::Triple::thumb:
1494       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1495         return ExprError();
1496       break;
1497     default:
1498       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1499         return ExprError();
1500       break;
1501     }
1502     break;
1503   }
1504 
1505   // The acquire, release, and no fence variants are ARM and AArch64 only.
1506   case Builtin::BI_interlockedbittestandset_acq:
1507   case Builtin::BI_interlockedbittestandset_rel:
1508   case Builtin::BI_interlockedbittestandset_nf:
1509   case Builtin::BI_interlockedbittestandreset_acq:
1510   case Builtin::BI_interlockedbittestandreset_rel:
1511   case Builtin::BI_interlockedbittestandreset_nf:
1512     if (CheckBuiltinTargetSupport(
1513             *this, BuiltinID, TheCall,
1514             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1519   case Builtin::BI_bittest64:
1520   case Builtin::BI_bittestandcomplement64:
1521   case Builtin::BI_bittestandreset64:
1522   case Builtin::BI_bittestandset64:
1523   case Builtin::BI_interlockedbittestandreset64:
1524   case Builtin::BI_interlockedbittestandset64:
1525     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1526                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1527                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1528       return ExprError();
1529     break;
1530 
1531   case Builtin::BI__builtin_isgreater:
1532   case Builtin::BI__builtin_isgreaterequal:
1533   case Builtin::BI__builtin_isless:
1534   case Builtin::BI__builtin_islessequal:
1535   case Builtin::BI__builtin_islessgreater:
1536   case Builtin::BI__builtin_isunordered:
1537     if (SemaBuiltinUnorderedCompare(TheCall))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_fpclassify:
1541     if (SemaBuiltinFPClassification(TheCall, 6))
1542       return ExprError();
1543     break;
1544   case Builtin::BI__builtin_isfinite:
1545   case Builtin::BI__builtin_isinf:
1546   case Builtin::BI__builtin_isinf_sign:
1547   case Builtin::BI__builtin_isnan:
1548   case Builtin::BI__builtin_isnormal:
1549   case Builtin::BI__builtin_signbit:
1550   case Builtin::BI__builtin_signbitf:
1551   case Builtin::BI__builtin_signbitl:
1552     if (SemaBuiltinFPClassification(TheCall, 1))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_shufflevector:
1556     return SemaBuiltinShuffleVector(TheCall);
1557     // TheCall will be freed by the smart pointer here, but that's fine, since
1558     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1559   case Builtin::BI__builtin_prefetch:
1560     if (SemaBuiltinPrefetch(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_alloca_with_align:
1564     if (SemaBuiltinAllocaWithAlign(TheCall))
1565       return ExprError();
1566     LLVM_FALLTHROUGH;
1567   case Builtin::BI__builtin_alloca:
1568     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1569         << TheCall->getDirectCallee();
1570     break;
1571   case Builtin::BI__arithmetic_fence:
1572     if (SemaBuiltinArithmeticFence(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__assume:
1576   case Builtin::BI__builtin_assume:
1577     if (SemaBuiltinAssume(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_assume_aligned:
1581     if (SemaBuiltinAssumeAligned(TheCall))
1582       return ExprError();
1583     break;
1584   case Builtin::BI__builtin_dynamic_object_size:
1585   case Builtin::BI__builtin_object_size:
1586     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1587       return ExprError();
1588     break;
1589   case Builtin::BI__builtin_longjmp:
1590     if (SemaBuiltinLongjmp(TheCall))
1591       return ExprError();
1592     break;
1593   case Builtin::BI__builtin_setjmp:
1594     if (SemaBuiltinSetjmp(TheCall))
1595       return ExprError();
1596     break;
1597   case Builtin::BI__builtin_classify_type:
1598     if (checkArgCount(*this, TheCall, 1)) return true;
1599     TheCall->setType(Context.IntTy);
1600     break;
1601   case Builtin::BI__builtin_complex:
1602     if (SemaBuiltinComplex(TheCall))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_constant_p: {
1606     if (checkArgCount(*this, TheCall, 1)) return true;
1607     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1608     if (Arg.isInvalid()) return true;
1609     TheCall->setArg(0, Arg.get());
1610     TheCall->setType(Context.IntTy);
1611     break;
1612   }
1613   case Builtin::BI__builtin_launder:
1614     return SemaBuiltinLaunder(*this, TheCall);
1615   case Builtin::BI__sync_fetch_and_add:
1616   case Builtin::BI__sync_fetch_and_add_1:
1617   case Builtin::BI__sync_fetch_and_add_2:
1618   case Builtin::BI__sync_fetch_and_add_4:
1619   case Builtin::BI__sync_fetch_and_add_8:
1620   case Builtin::BI__sync_fetch_and_add_16:
1621   case Builtin::BI__sync_fetch_and_sub:
1622   case Builtin::BI__sync_fetch_and_sub_1:
1623   case Builtin::BI__sync_fetch_and_sub_2:
1624   case Builtin::BI__sync_fetch_and_sub_4:
1625   case Builtin::BI__sync_fetch_and_sub_8:
1626   case Builtin::BI__sync_fetch_and_sub_16:
1627   case Builtin::BI__sync_fetch_and_or:
1628   case Builtin::BI__sync_fetch_and_or_1:
1629   case Builtin::BI__sync_fetch_and_or_2:
1630   case Builtin::BI__sync_fetch_and_or_4:
1631   case Builtin::BI__sync_fetch_and_or_8:
1632   case Builtin::BI__sync_fetch_and_or_16:
1633   case Builtin::BI__sync_fetch_and_and:
1634   case Builtin::BI__sync_fetch_and_and_1:
1635   case Builtin::BI__sync_fetch_and_and_2:
1636   case Builtin::BI__sync_fetch_and_and_4:
1637   case Builtin::BI__sync_fetch_and_and_8:
1638   case Builtin::BI__sync_fetch_and_and_16:
1639   case Builtin::BI__sync_fetch_and_xor:
1640   case Builtin::BI__sync_fetch_and_xor_1:
1641   case Builtin::BI__sync_fetch_and_xor_2:
1642   case Builtin::BI__sync_fetch_and_xor_4:
1643   case Builtin::BI__sync_fetch_and_xor_8:
1644   case Builtin::BI__sync_fetch_and_xor_16:
1645   case Builtin::BI__sync_fetch_and_nand:
1646   case Builtin::BI__sync_fetch_and_nand_1:
1647   case Builtin::BI__sync_fetch_and_nand_2:
1648   case Builtin::BI__sync_fetch_and_nand_4:
1649   case Builtin::BI__sync_fetch_and_nand_8:
1650   case Builtin::BI__sync_fetch_and_nand_16:
1651   case Builtin::BI__sync_add_and_fetch:
1652   case Builtin::BI__sync_add_and_fetch_1:
1653   case Builtin::BI__sync_add_and_fetch_2:
1654   case Builtin::BI__sync_add_and_fetch_4:
1655   case Builtin::BI__sync_add_and_fetch_8:
1656   case Builtin::BI__sync_add_and_fetch_16:
1657   case Builtin::BI__sync_sub_and_fetch:
1658   case Builtin::BI__sync_sub_and_fetch_1:
1659   case Builtin::BI__sync_sub_and_fetch_2:
1660   case Builtin::BI__sync_sub_and_fetch_4:
1661   case Builtin::BI__sync_sub_and_fetch_8:
1662   case Builtin::BI__sync_sub_and_fetch_16:
1663   case Builtin::BI__sync_and_and_fetch:
1664   case Builtin::BI__sync_and_and_fetch_1:
1665   case Builtin::BI__sync_and_and_fetch_2:
1666   case Builtin::BI__sync_and_and_fetch_4:
1667   case Builtin::BI__sync_and_and_fetch_8:
1668   case Builtin::BI__sync_and_and_fetch_16:
1669   case Builtin::BI__sync_or_and_fetch:
1670   case Builtin::BI__sync_or_and_fetch_1:
1671   case Builtin::BI__sync_or_and_fetch_2:
1672   case Builtin::BI__sync_or_and_fetch_4:
1673   case Builtin::BI__sync_or_and_fetch_8:
1674   case Builtin::BI__sync_or_and_fetch_16:
1675   case Builtin::BI__sync_xor_and_fetch:
1676   case Builtin::BI__sync_xor_and_fetch_1:
1677   case Builtin::BI__sync_xor_and_fetch_2:
1678   case Builtin::BI__sync_xor_and_fetch_4:
1679   case Builtin::BI__sync_xor_and_fetch_8:
1680   case Builtin::BI__sync_xor_and_fetch_16:
1681   case Builtin::BI__sync_nand_and_fetch:
1682   case Builtin::BI__sync_nand_and_fetch_1:
1683   case Builtin::BI__sync_nand_and_fetch_2:
1684   case Builtin::BI__sync_nand_and_fetch_4:
1685   case Builtin::BI__sync_nand_and_fetch_8:
1686   case Builtin::BI__sync_nand_and_fetch_16:
1687   case Builtin::BI__sync_val_compare_and_swap:
1688   case Builtin::BI__sync_val_compare_and_swap_1:
1689   case Builtin::BI__sync_val_compare_and_swap_2:
1690   case Builtin::BI__sync_val_compare_and_swap_4:
1691   case Builtin::BI__sync_val_compare_and_swap_8:
1692   case Builtin::BI__sync_val_compare_and_swap_16:
1693   case Builtin::BI__sync_bool_compare_and_swap:
1694   case Builtin::BI__sync_bool_compare_and_swap_1:
1695   case Builtin::BI__sync_bool_compare_and_swap_2:
1696   case Builtin::BI__sync_bool_compare_and_swap_4:
1697   case Builtin::BI__sync_bool_compare_and_swap_8:
1698   case Builtin::BI__sync_bool_compare_and_swap_16:
1699   case Builtin::BI__sync_lock_test_and_set:
1700   case Builtin::BI__sync_lock_test_and_set_1:
1701   case Builtin::BI__sync_lock_test_and_set_2:
1702   case Builtin::BI__sync_lock_test_and_set_4:
1703   case Builtin::BI__sync_lock_test_and_set_8:
1704   case Builtin::BI__sync_lock_test_and_set_16:
1705   case Builtin::BI__sync_lock_release:
1706   case Builtin::BI__sync_lock_release_1:
1707   case Builtin::BI__sync_lock_release_2:
1708   case Builtin::BI__sync_lock_release_4:
1709   case Builtin::BI__sync_lock_release_8:
1710   case Builtin::BI__sync_lock_release_16:
1711   case Builtin::BI__sync_swap:
1712   case Builtin::BI__sync_swap_1:
1713   case Builtin::BI__sync_swap_2:
1714   case Builtin::BI__sync_swap_4:
1715   case Builtin::BI__sync_swap_8:
1716   case Builtin::BI__sync_swap_16:
1717     return SemaBuiltinAtomicOverloaded(TheCallResult);
1718   case Builtin::BI__sync_synchronize:
1719     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1720         << TheCall->getCallee()->getSourceRange();
1721     break;
1722   case Builtin::BI__builtin_nontemporal_load:
1723   case Builtin::BI__builtin_nontemporal_store:
1724     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1725   case Builtin::BI__builtin_memcpy_inline: {
1726     clang::Expr *SizeOp = TheCall->getArg(2);
1727     // We warn about copying to or from `nullptr` pointers when `size` is
1728     // greater than 0. When `size` is value dependent we cannot evaluate its
1729     // value so we bail out.
1730     if (SizeOp->isValueDependent())
1731       break;
1732     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1733       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1734       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1735     }
1736     break;
1737   }
1738 #define BUILTIN(ID, TYPE, ATTRS)
1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1740   case Builtin::BI##ID: \
1741     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1742 #include "clang/Basic/Builtins.def"
1743   case Builtin::BI__annotation:
1744     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_annotation:
1748     if (SemaBuiltinAnnotation(*this, TheCall))
1749       return ExprError();
1750     break;
1751   case Builtin::BI__builtin_addressof:
1752     if (SemaBuiltinAddressof(*this, TheCall))
1753       return ExprError();
1754     break;
1755   case Builtin::BI__builtin_is_aligned:
1756   case Builtin::BI__builtin_align_up:
1757   case Builtin::BI__builtin_align_down:
1758     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__builtin_add_overflow:
1762   case Builtin::BI__builtin_sub_overflow:
1763   case Builtin::BI__builtin_mul_overflow:
1764     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1765       return ExprError();
1766     break;
1767   case Builtin::BI__builtin_operator_new:
1768   case Builtin::BI__builtin_operator_delete: {
1769     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1770     ExprResult Res =
1771         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1772     if (Res.isInvalid())
1773       CorrectDelayedTyposInExpr(TheCallResult.get());
1774     return Res;
1775   }
1776   case Builtin::BI__builtin_dump_struct: {
1777     // We first want to ensure we are called with 2 arguments
1778     if (checkArgCount(*this, TheCall, 2))
1779       return ExprError();
1780     // Ensure that the first argument is of type 'struct XX *'
1781     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1782     const QualType PtrArgType = PtrArg->getType();
1783     if (!PtrArgType->isPointerType() ||
1784         !PtrArgType->getPointeeType()->isRecordType()) {
1785       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1787           << "structure pointer";
1788       return ExprError();
1789     }
1790 
1791     // Ensure that the second argument is of type 'FunctionType'
1792     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1793     const QualType FnPtrArgType = FnPtrArg->getType();
1794     if (!FnPtrArgType->isPointerType()) {
1795       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1797           << FnPtrArgType << "'int (*)(const char *, ...)'";
1798       return ExprError();
1799     }
1800 
1801     const auto *FuncType =
1802         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1803 
1804     if (!FuncType) {
1805       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1806           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1807           << FnPtrArgType << "'int (*)(const char *, ...)'";
1808       return ExprError();
1809     }
1810 
1811     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1812       if (!FT->getNumParams()) {
1813         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1814             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1815             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1816         return ExprError();
1817       }
1818       QualType PT = FT->getParamType(0);
1819       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1820           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1821           !PT->getPointeeType().isConstQualified()) {
1822         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1823             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1824             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1825         return ExprError();
1826       }
1827     }
1828 
1829     TheCall->setType(Context.IntTy);
1830     break;
1831   }
1832   case Builtin::BI__builtin_expect_with_probability: {
1833     // We first want to ensure we are called with 3 arguments
1834     if (checkArgCount(*this, TheCall, 3))
1835       return ExprError();
1836     // then check probability is constant float in range [0.0, 1.0]
1837     const Expr *ProbArg = TheCall->getArg(2);
1838     SmallVector<PartialDiagnosticAt, 8> Notes;
1839     Expr::EvalResult Eval;
1840     Eval.Diag = &Notes;
1841     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1842         !Eval.Val.isFloat()) {
1843       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1844           << ProbArg->getSourceRange();
1845       for (const PartialDiagnosticAt &PDiag : Notes)
1846         Diag(PDiag.first, PDiag.second);
1847       return ExprError();
1848     }
1849     llvm::APFloat Probability = Eval.Val.getFloat();
1850     bool LoseInfo = false;
1851     Probability.convert(llvm::APFloat::IEEEdouble(),
1852                         llvm::RoundingMode::Dynamic, &LoseInfo);
1853     if (!(Probability >= llvm::APFloat(0.0) &&
1854           Probability <= llvm::APFloat(1.0))) {
1855       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1856           << ProbArg->getSourceRange();
1857       return ExprError();
1858     }
1859     break;
1860   }
1861   case Builtin::BI__builtin_preserve_access_index:
1862     if (SemaBuiltinPreserveAI(*this, TheCall))
1863       return ExprError();
1864     break;
1865   case Builtin::BI__builtin_call_with_static_chain:
1866     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__exception_code:
1870   case Builtin::BI_exception_code:
1871     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1872                                  diag::err_seh___except_block))
1873       return ExprError();
1874     break;
1875   case Builtin::BI__exception_info:
1876   case Builtin::BI_exception_info:
1877     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1878                                  diag::err_seh___except_filter))
1879       return ExprError();
1880     break;
1881   case Builtin::BI__GetExceptionInfo:
1882     if (checkArgCount(*this, TheCall, 1))
1883       return ExprError();
1884 
1885     if (CheckCXXThrowOperand(
1886             TheCall->getBeginLoc(),
1887             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1888             TheCall))
1889       return ExprError();
1890 
1891     TheCall->setType(Context.VoidPtrTy);
1892     break;
1893   // OpenCL v2.0, s6.13.16 - Pipe functions
1894   case Builtin::BIread_pipe:
1895   case Builtin::BIwrite_pipe:
1896     // Since those two functions are declared with var args, we need a semantic
1897     // check for the argument.
1898     if (SemaBuiltinRWPipe(*this, TheCall))
1899       return ExprError();
1900     break;
1901   case Builtin::BIreserve_read_pipe:
1902   case Builtin::BIreserve_write_pipe:
1903   case Builtin::BIwork_group_reserve_read_pipe:
1904   case Builtin::BIwork_group_reserve_write_pipe:
1905     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIsub_group_reserve_read_pipe:
1909   case Builtin::BIsub_group_reserve_write_pipe:
1910     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1911         SemaBuiltinReserveRWPipe(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIcommit_read_pipe:
1915   case Builtin::BIcommit_write_pipe:
1916   case Builtin::BIwork_group_commit_read_pipe:
1917   case Builtin::BIwork_group_commit_write_pipe:
1918     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1919       return ExprError();
1920     break;
1921   case Builtin::BIsub_group_commit_read_pipe:
1922   case Builtin::BIsub_group_commit_write_pipe:
1923     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1924         SemaBuiltinCommitRWPipe(*this, TheCall))
1925       return ExprError();
1926     break;
1927   case Builtin::BIget_pipe_num_packets:
1928   case Builtin::BIget_pipe_max_packets:
1929     if (SemaBuiltinPipePackets(*this, TheCall))
1930       return ExprError();
1931     break;
1932   case Builtin::BIto_global:
1933   case Builtin::BIto_local:
1934   case Builtin::BIto_private:
1935     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1936       return ExprError();
1937     break;
1938   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1939   case Builtin::BIenqueue_kernel:
1940     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1941       return ExprError();
1942     break;
1943   case Builtin::BIget_kernel_work_group_size:
1944   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1945     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1946       return ExprError();
1947     break;
1948   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1949   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1950     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1951       return ExprError();
1952     break;
1953   case Builtin::BI__builtin_os_log_format:
1954     Cleanup.setExprNeedsCleanups(true);
1955     LLVM_FALLTHROUGH;
1956   case Builtin::BI__builtin_os_log_format_buffer_size:
1957     if (SemaBuiltinOSLogFormat(TheCall))
1958       return ExprError();
1959     break;
1960   case Builtin::BI__builtin_frame_address:
1961   case Builtin::BI__builtin_return_address: {
1962     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1963       return ExprError();
1964 
1965     // -Wframe-address warning if non-zero passed to builtin
1966     // return/frame address.
1967     Expr::EvalResult Result;
1968     if (!TheCall->getArg(0)->isValueDependent() &&
1969         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1970         Result.Val.getInt() != 0)
1971       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1972           << ((BuiltinID == Builtin::BI__builtin_return_address)
1973                   ? "__builtin_return_address"
1974                   : "__builtin_frame_address")
1975           << TheCall->getSourceRange();
1976     break;
1977   }
1978 
1979   case Builtin::BI__builtin_elementwise_abs:
1980     if (SemaBuiltinElementwiseMathOneArg(TheCall))
1981       return ExprError();
1982     break;
1983   case Builtin::BI__builtin_elementwise_min:
1984   case Builtin::BI__builtin_elementwise_max:
1985     if (SemaBuiltinElementwiseMath(TheCall))
1986       return ExprError();
1987     break;
1988   case Builtin::BI__builtin_reduce_max:
1989   case Builtin::BI__builtin_reduce_min:
1990     if (SemaBuiltinReduceMath(TheCall))
1991       return ExprError();
1992     break;
1993   case Builtin::BI__builtin_matrix_transpose:
1994     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1995 
1996   case Builtin::BI__builtin_matrix_column_major_load:
1997     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1998 
1999   case Builtin::BI__builtin_matrix_column_major_store:
2000     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2001 
2002   case Builtin::BI__builtin_get_device_side_mangled_name: {
2003     auto Check = [](CallExpr *TheCall) {
2004       if (TheCall->getNumArgs() != 1)
2005         return false;
2006       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2007       if (!DRE)
2008         return false;
2009       auto *D = DRE->getDecl();
2010       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2011         return false;
2012       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2013              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2014     };
2015     if (!Check(TheCall)) {
2016       Diag(TheCall->getBeginLoc(),
2017            diag::err_hip_invalid_args_builtin_mangled_name);
2018       return ExprError();
2019     }
2020   }
2021   }
2022 
2023   // Since the target specific builtins for each arch overlap, only check those
2024   // of the arch we are compiling for.
2025   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2026     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2027       assert(Context.getAuxTargetInfo() &&
2028              "Aux Target Builtin, but not an aux target?");
2029 
2030       if (CheckTSBuiltinFunctionCall(
2031               *Context.getAuxTargetInfo(),
2032               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2033         return ExprError();
2034     } else {
2035       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2036                                      TheCall))
2037         return ExprError();
2038     }
2039   }
2040 
2041   return TheCallResult;
2042 }
2043 
2044 // Get the valid immediate range for the specified NEON type code.
2045 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2046   NeonTypeFlags Type(t);
2047   int IsQuad = ForceQuad ? true : Type.isQuad();
2048   switch (Type.getEltType()) {
2049   case NeonTypeFlags::Int8:
2050   case NeonTypeFlags::Poly8:
2051     return shift ? 7 : (8 << IsQuad) - 1;
2052   case NeonTypeFlags::Int16:
2053   case NeonTypeFlags::Poly16:
2054     return shift ? 15 : (4 << IsQuad) - 1;
2055   case NeonTypeFlags::Int32:
2056     return shift ? 31 : (2 << IsQuad) - 1;
2057   case NeonTypeFlags::Int64:
2058   case NeonTypeFlags::Poly64:
2059     return shift ? 63 : (1 << IsQuad) - 1;
2060   case NeonTypeFlags::Poly128:
2061     return shift ? 127 : (1 << IsQuad) - 1;
2062   case NeonTypeFlags::Float16:
2063     assert(!shift && "cannot shift float types!");
2064     return (4 << IsQuad) - 1;
2065   case NeonTypeFlags::Float32:
2066     assert(!shift && "cannot shift float types!");
2067     return (2 << IsQuad) - 1;
2068   case NeonTypeFlags::Float64:
2069     assert(!shift && "cannot shift float types!");
2070     return (1 << IsQuad) - 1;
2071   case NeonTypeFlags::BFloat16:
2072     assert(!shift && "cannot shift float types!");
2073     return (4 << IsQuad) - 1;
2074   }
2075   llvm_unreachable("Invalid NeonTypeFlag!");
2076 }
2077 
2078 /// getNeonEltType - Return the QualType corresponding to the elements of
2079 /// the vector type specified by the NeonTypeFlags.  This is used to check
2080 /// the pointer arguments for Neon load/store intrinsics.
2081 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2082                                bool IsPolyUnsigned, bool IsInt64Long) {
2083   switch (Flags.getEltType()) {
2084   case NeonTypeFlags::Int8:
2085     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2086   case NeonTypeFlags::Int16:
2087     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2088   case NeonTypeFlags::Int32:
2089     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2090   case NeonTypeFlags::Int64:
2091     if (IsInt64Long)
2092       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2093     else
2094       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2095                                 : Context.LongLongTy;
2096   case NeonTypeFlags::Poly8:
2097     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2098   case NeonTypeFlags::Poly16:
2099     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2100   case NeonTypeFlags::Poly64:
2101     if (IsInt64Long)
2102       return Context.UnsignedLongTy;
2103     else
2104       return Context.UnsignedLongLongTy;
2105   case NeonTypeFlags::Poly128:
2106     break;
2107   case NeonTypeFlags::Float16:
2108     return Context.HalfTy;
2109   case NeonTypeFlags::Float32:
2110     return Context.FloatTy;
2111   case NeonTypeFlags::Float64:
2112     return Context.DoubleTy;
2113   case NeonTypeFlags::BFloat16:
2114     return Context.BFloat16Ty;
2115   }
2116   llvm_unreachable("Invalid NeonTypeFlag!");
2117 }
2118 
2119 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2120   // Range check SVE intrinsics that take immediate values.
2121   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2122 
2123   switch (BuiltinID) {
2124   default:
2125     return false;
2126 #define GET_SVE_IMMEDIATE_CHECK
2127 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2128 #undef GET_SVE_IMMEDIATE_CHECK
2129   }
2130 
2131   // Perform all the immediate checks for this builtin call.
2132   bool HasError = false;
2133   for (auto &I : ImmChecks) {
2134     int ArgNum, CheckTy, ElementSizeInBits;
2135     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2136 
2137     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2138 
2139     // Function that checks whether the operand (ArgNum) is an immediate
2140     // that is one of the predefined values.
2141     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2142                                    int ErrDiag) -> bool {
2143       // We can't check the value of a dependent argument.
2144       Expr *Arg = TheCall->getArg(ArgNum);
2145       if (Arg->isTypeDependent() || Arg->isValueDependent())
2146         return false;
2147 
2148       // Check constant-ness first.
2149       llvm::APSInt Imm;
2150       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2151         return true;
2152 
2153       if (!CheckImm(Imm.getSExtValue()))
2154         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2155       return false;
2156     };
2157 
2158     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2159     case SVETypeFlags::ImmCheck0_31:
2160       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2161         HasError = true;
2162       break;
2163     case SVETypeFlags::ImmCheck0_13:
2164       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheck1_16:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheck0_7:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheckExtract:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2177                                       (2048 / ElementSizeInBits) - 1))
2178         HasError = true;
2179       break;
2180     case SVETypeFlags::ImmCheckShiftRight:
2181       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2182         HasError = true;
2183       break;
2184     case SVETypeFlags::ImmCheckShiftRightNarrow:
2185       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2186                                       ElementSizeInBits / 2))
2187         HasError = true;
2188       break;
2189     case SVETypeFlags::ImmCheckShiftLeft:
2190       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2191                                       ElementSizeInBits - 1))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheckLaneIndex:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2196                                       (128 / (1 * ElementSizeInBits)) - 1))
2197         HasError = true;
2198       break;
2199     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2200       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2201                                       (128 / (2 * ElementSizeInBits)) - 1))
2202         HasError = true;
2203       break;
2204     case SVETypeFlags::ImmCheckLaneIndexDot:
2205       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2206                                       (128 / (4 * ElementSizeInBits)) - 1))
2207         HasError = true;
2208       break;
2209     case SVETypeFlags::ImmCheckComplexRot90_270:
2210       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2211                               diag::err_rotation_argument_to_cadd))
2212         HasError = true;
2213       break;
2214     case SVETypeFlags::ImmCheckComplexRotAll90:
2215       if (CheckImmediateInSet(
2216               [](int64_t V) {
2217                 return V == 0 || V == 90 || V == 180 || V == 270;
2218               },
2219               diag::err_rotation_argument_to_cmla))
2220         HasError = true;
2221       break;
2222     case SVETypeFlags::ImmCheck0_1:
2223       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2224         HasError = true;
2225       break;
2226     case SVETypeFlags::ImmCheck0_2:
2227       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2228         HasError = true;
2229       break;
2230     case SVETypeFlags::ImmCheck0_3:
2231       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2232         HasError = true;
2233       break;
2234     }
2235   }
2236 
2237   return HasError;
2238 }
2239 
2240 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2241                                         unsigned BuiltinID, CallExpr *TheCall) {
2242   llvm::APSInt Result;
2243   uint64_t mask = 0;
2244   unsigned TV = 0;
2245   int PtrArgNum = -1;
2246   bool HasConstPtr = false;
2247   switch (BuiltinID) {
2248 #define GET_NEON_OVERLOAD_CHECK
2249 #include "clang/Basic/arm_neon.inc"
2250 #include "clang/Basic/arm_fp16.inc"
2251 #undef GET_NEON_OVERLOAD_CHECK
2252   }
2253 
2254   // For NEON intrinsics which are overloaded on vector element type, validate
2255   // the immediate which specifies which variant to emit.
2256   unsigned ImmArg = TheCall->getNumArgs()-1;
2257   if (mask) {
2258     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2259       return true;
2260 
2261     TV = Result.getLimitedValue(64);
2262     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2263       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2264              << TheCall->getArg(ImmArg)->getSourceRange();
2265   }
2266 
2267   if (PtrArgNum >= 0) {
2268     // Check that pointer arguments have the specified type.
2269     Expr *Arg = TheCall->getArg(PtrArgNum);
2270     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2271       Arg = ICE->getSubExpr();
2272     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2273     QualType RHSTy = RHS.get()->getType();
2274 
2275     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2276     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2277                           Arch == llvm::Triple::aarch64_32 ||
2278                           Arch == llvm::Triple::aarch64_be;
2279     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2280     QualType EltTy =
2281         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2282     if (HasConstPtr)
2283       EltTy = EltTy.withConst();
2284     QualType LHSTy = Context.getPointerType(EltTy);
2285     AssignConvertType ConvTy;
2286     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2287     if (RHS.isInvalid())
2288       return true;
2289     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2290                                  RHS.get(), AA_Assigning))
2291       return true;
2292   }
2293 
2294   // For NEON intrinsics which take an immediate value as part of the
2295   // instruction, range check them here.
2296   unsigned i = 0, l = 0, u = 0;
2297   switch (BuiltinID) {
2298   default:
2299     return false;
2300   #define GET_NEON_IMMEDIATE_CHECK
2301   #include "clang/Basic/arm_neon.inc"
2302   #include "clang/Basic/arm_fp16.inc"
2303   #undef GET_NEON_IMMEDIATE_CHECK
2304   }
2305 
2306   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2307 }
2308 
2309 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2310   switch (BuiltinID) {
2311   default:
2312     return false;
2313   #include "clang/Basic/arm_mve_builtin_sema.inc"
2314   }
2315 }
2316 
2317 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2318                                        CallExpr *TheCall) {
2319   bool Err = false;
2320   switch (BuiltinID) {
2321   default:
2322     return false;
2323 #include "clang/Basic/arm_cde_builtin_sema.inc"
2324   }
2325 
2326   if (Err)
2327     return true;
2328 
2329   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2330 }
2331 
2332 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2333                                         const Expr *CoprocArg, bool WantCDE) {
2334   if (isConstantEvaluated())
2335     return false;
2336 
2337   // We can't check the value of a dependent argument.
2338   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2339     return false;
2340 
2341   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2342   int64_t CoprocNo = CoprocNoAP.getExtValue();
2343   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2344 
2345   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2346   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2347 
2348   if (IsCDECoproc != WantCDE)
2349     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2350            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2351 
2352   return false;
2353 }
2354 
2355 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2356                                         unsigned MaxWidth) {
2357   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2358           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2359           BuiltinID == ARM::BI__builtin_arm_strex ||
2360           BuiltinID == ARM::BI__builtin_arm_stlex ||
2361           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2362           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2363           BuiltinID == AArch64::BI__builtin_arm_strex ||
2364           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2365          "unexpected ARM builtin");
2366   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2367                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2368                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2369                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2370 
2371   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2372 
2373   // Ensure that we have the proper number of arguments.
2374   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2375     return true;
2376 
2377   // Inspect the pointer argument of the atomic builtin.  This should always be
2378   // a pointer type, whose element is an integral scalar or pointer type.
2379   // Because it is a pointer type, we don't have to worry about any implicit
2380   // casts here.
2381   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2382   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2383   if (PointerArgRes.isInvalid())
2384     return true;
2385   PointerArg = PointerArgRes.get();
2386 
2387   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2388   if (!pointerType) {
2389     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2390         << PointerArg->getType() << PointerArg->getSourceRange();
2391     return true;
2392   }
2393 
2394   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2395   // task is to insert the appropriate casts into the AST. First work out just
2396   // what the appropriate type is.
2397   QualType ValType = pointerType->getPointeeType();
2398   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2399   if (IsLdrex)
2400     AddrType.addConst();
2401 
2402   // Issue a warning if the cast is dodgy.
2403   CastKind CastNeeded = CK_NoOp;
2404   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2405     CastNeeded = CK_BitCast;
2406     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2407         << PointerArg->getType() << Context.getPointerType(AddrType)
2408         << AA_Passing << PointerArg->getSourceRange();
2409   }
2410 
2411   // Finally, do the cast and replace the argument with the corrected version.
2412   AddrType = Context.getPointerType(AddrType);
2413   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2414   if (PointerArgRes.isInvalid())
2415     return true;
2416   PointerArg = PointerArgRes.get();
2417 
2418   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2419 
2420   // In general, we allow ints, floats and pointers to be loaded and stored.
2421   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2422       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2423     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2424         << PointerArg->getType() << PointerArg->getSourceRange();
2425     return true;
2426   }
2427 
2428   // But ARM doesn't have instructions to deal with 128-bit versions.
2429   if (Context.getTypeSize(ValType) > MaxWidth) {
2430     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2431     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2432         << PointerArg->getType() << PointerArg->getSourceRange();
2433     return true;
2434   }
2435 
2436   switch (ValType.getObjCLifetime()) {
2437   case Qualifiers::OCL_None:
2438   case Qualifiers::OCL_ExplicitNone:
2439     // okay
2440     break;
2441 
2442   case Qualifiers::OCL_Weak:
2443   case Qualifiers::OCL_Strong:
2444   case Qualifiers::OCL_Autoreleasing:
2445     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2446         << ValType << PointerArg->getSourceRange();
2447     return true;
2448   }
2449 
2450   if (IsLdrex) {
2451     TheCall->setType(ValType);
2452     return false;
2453   }
2454 
2455   // Initialize the argument to be stored.
2456   ExprResult ValArg = TheCall->getArg(0);
2457   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2458       Context, ValType, /*consume*/ false);
2459   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2460   if (ValArg.isInvalid())
2461     return true;
2462   TheCall->setArg(0, ValArg.get());
2463 
2464   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2465   // but the custom checker bypasses all default analysis.
2466   TheCall->setType(Context.IntTy);
2467   return false;
2468 }
2469 
2470 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2471                                        CallExpr *TheCall) {
2472   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2473       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2474       BuiltinID == ARM::BI__builtin_arm_strex ||
2475       BuiltinID == ARM::BI__builtin_arm_stlex) {
2476     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2477   }
2478 
2479   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2480     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2481       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2482   }
2483 
2484   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2485       BuiltinID == ARM::BI__builtin_arm_wsr64)
2486     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2487 
2488   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2489       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2490       BuiltinID == ARM::BI__builtin_arm_wsr ||
2491       BuiltinID == ARM::BI__builtin_arm_wsrp)
2492     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2493 
2494   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2495     return true;
2496   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2497     return true;
2498   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2499     return true;
2500 
2501   // For intrinsics which take an immediate value as part of the instruction,
2502   // range check them here.
2503   // FIXME: VFP Intrinsics should error if VFP not present.
2504   switch (BuiltinID) {
2505   default: return false;
2506   case ARM::BI__builtin_arm_ssat:
2507     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2508   case ARM::BI__builtin_arm_usat:
2509     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2510   case ARM::BI__builtin_arm_ssat16:
2511     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2512   case ARM::BI__builtin_arm_usat16:
2513     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2514   case ARM::BI__builtin_arm_vcvtr_f:
2515   case ARM::BI__builtin_arm_vcvtr_d:
2516     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2517   case ARM::BI__builtin_arm_dmb:
2518   case ARM::BI__builtin_arm_dsb:
2519   case ARM::BI__builtin_arm_isb:
2520   case ARM::BI__builtin_arm_dbg:
2521     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2522   case ARM::BI__builtin_arm_cdp:
2523   case ARM::BI__builtin_arm_cdp2:
2524   case ARM::BI__builtin_arm_mcr:
2525   case ARM::BI__builtin_arm_mcr2:
2526   case ARM::BI__builtin_arm_mrc:
2527   case ARM::BI__builtin_arm_mrc2:
2528   case ARM::BI__builtin_arm_mcrr:
2529   case ARM::BI__builtin_arm_mcrr2:
2530   case ARM::BI__builtin_arm_mrrc:
2531   case ARM::BI__builtin_arm_mrrc2:
2532   case ARM::BI__builtin_arm_ldc:
2533   case ARM::BI__builtin_arm_ldcl:
2534   case ARM::BI__builtin_arm_ldc2:
2535   case ARM::BI__builtin_arm_ldc2l:
2536   case ARM::BI__builtin_arm_stc:
2537   case ARM::BI__builtin_arm_stcl:
2538   case ARM::BI__builtin_arm_stc2:
2539   case ARM::BI__builtin_arm_stc2l:
2540     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2541            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2542                                         /*WantCDE*/ false);
2543   }
2544 }
2545 
2546 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2547                                            unsigned BuiltinID,
2548                                            CallExpr *TheCall) {
2549   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2550       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2551       BuiltinID == AArch64::BI__builtin_arm_strex ||
2552       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2553     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2554   }
2555 
2556   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2557     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2558       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2559       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2560       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2561   }
2562 
2563   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2564       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2565     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2566 
2567   // Memory Tagging Extensions (MTE) Intrinsics
2568   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2569       BuiltinID == AArch64::BI__builtin_arm_addg ||
2570       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2571       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2572       BuiltinID == AArch64::BI__builtin_arm_stg ||
2573       BuiltinID == AArch64::BI__builtin_arm_subp) {
2574     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2575   }
2576 
2577   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2578       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2579       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2580       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2581     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2582 
2583   // Only check the valid encoding range. Any constant in this range would be
2584   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2585   // an exception for incorrect registers. This matches MSVC behavior.
2586   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2587       BuiltinID == AArch64::BI_WriteStatusReg)
2588     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2589 
2590   if (BuiltinID == AArch64::BI__getReg)
2591     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2592 
2593   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2594     return true;
2595 
2596   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2597     return true;
2598 
2599   // For intrinsics which take an immediate value as part of the instruction,
2600   // range check them here.
2601   unsigned i = 0, l = 0, u = 0;
2602   switch (BuiltinID) {
2603   default: return false;
2604   case AArch64::BI__builtin_arm_dmb:
2605   case AArch64::BI__builtin_arm_dsb:
2606   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2607   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2608   }
2609 
2610   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2611 }
2612 
2613 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2614   if (Arg->getType()->getAsPlaceholderType())
2615     return false;
2616 
2617   // The first argument needs to be a record field access.
2618   // If it is an array element access, we delay decision
2619   // to BPF backend to check whether the access is a
2620   // field access or not.
2621   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2622           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2623           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2624 }
2625 
2626 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2627                             QualType VectorTy, QualType EltTy) {
2628   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2629   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2630     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2631         << Call->getSourceRange() << VectorEltTy << EltTy;
2632     return false;
2633   }
2634   return true;
2635 }
2636 
2637 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2638   QualType ArgType = Arg->getType();
2639   if (ArgType->getAsPlaceholderType())
2640     return false;
2641 
2642   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2643   // format:
2644   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2645   //   2. <type> var;
2646   //      __builtin_preserve_type_info(var, flag);
2647   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2648       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2649     return false;
2650 
2651   // Typedef type.
2652   if (ArgType->getAs<TypedefType>())
2653     return true;
2654 
2655   // Record type or Enum type.
2656   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2657   if (const auto *RT = Ty->getAs<RecordType>()) {
2658     if (!RT->getDecl()->getDeclName().isEmpty())
2659       return true;
2660   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2661     if (!ET->getDecl()->getDeclName().isEmpty())
2662       return true;
2663   }
2664 
2665   return false;
2666 }
2667 
2668 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2669   QualType ArgType = Arg->getType();
2670   if (ArgType->getAsPlaceholderType())
2671     return false;
2672 
2673   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2674   // format:
2675   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2676   //                                 flag);
2677   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2678   if (!UO)
2679     return false;
2680 
2681   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2682   if (!CE)
2683     return false;
2684   if (CE->getCastKind() != CK_IntegralToPointer &&
2685       CE->getCastKind() != CK_NullToPointer)
2686     return false;
2687 
2688   // The integer must be from an EnumConstantDecl.
2689   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2690   if (!DR)
2691     return false;
2692 
2693   const EnumConstantDecl *Enumerator =
2694       dyn_cast<EnumConstantDecl>(DR->getDecl());
2695   if (!Enumerator)
2696     return false;
2697 
2698   // The type must be EnumType.
2699   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2700   const auto *ET = Ty->getAs<EnumType>();
2701   if (!ET)
2702     return false;
2703 
2704   // The enum value must be supported.
2705   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2706 }
2707 
2708 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2709                                        CallExpr *TheCall) {
2710   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2711           BuiltinID == BPF::BI__builtin_btf_type_id ||
2712           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2713           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2714          "unexpected BPF builtin");
2715 
2716   if (checkArgCount(*this, TheCall, 2))
2717     return true;
2718 
2719   // The second argument needs to be a constant int
2720   Expr *Arg = TheCall->getArg(1);
2721   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2722   diag::kind kind;
2723   if (!Value) {
2724     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2725       kind = diag::err_preserve_field_info_not_const;
2726     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2727       kind = diag::err_btf_type_id_not_const;
2728     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2729       kind = diag::err_preserve_type_info_not_const;
2730     else
2731       kind = diag::err_preserve_enum_value_not_const;
2732     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2733     return true;
2734   }
2735 
2736   // The first argument
2737   Arg = TheCall->getArg(0);
2738   bool InvalidArg = false;
2739   bool ReturnUnsignedInt = true;
2740   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2741     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2742       InvalidArg = true;
2743       kind = diag::err_preserve_field_info_not_field;
2744     }
2745   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2746     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2747       InvalidArg = true;
2748       kind = diag::err_preserve_type_info_invalid;
2749     }
2750   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2751     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2752       InvalidArg = true;
2753       kind = diag::err_preserve_enum_value_invalid;
2754     }
2755     ReturnUnsignedInt = false;
2756   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2757     ReturnUnsignedInt = false;
2758   }
2759 
2760   if (InvalidArg) {
2761     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2762     return true;
2763   }
2764 
2765   if (ReturnUnsignedInt)
2766     TheCall->setType(Context.UnsignedIntTy);
2767   else
2768     TheCall->setType(Context.UnsignedLongTy);
2769   return false;
2770 }
2771 
2772 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2773   struct ArgInfo {
2774     uint8_t OpNum;
2775     bool IsSigned;
2776     uint8_t BitWidth;
2777     uint8_t Align;
2778   };
2779   struct BuiltinInfo {
2780     unsigned BuiltinID;
2781     ArgInfo Infos[2];
2782   };
2783 
2784   static BuiltinInfo Infos[] = {
2785     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2786     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2787     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2788     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2789     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2790     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2791     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2792     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2793     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2794     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2795     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2796 
2797     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2800     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2801     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2802     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2808 
2809     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2861                                                       {{ 1, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2869                                                       {{ 1, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2876                                                        { 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2878                                                        { 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2882                                                        { 3, false, 6,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2899                                                       {{ 2, false, 4,  0 },
2900                                                        { 3, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2902                                                       {{ 2, false, 4,  0 },
2903                                                        { 3, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2905                                                       {{ 2, false, 4,  0 },
2906                                                        { 3, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2908                                                       {{ 2, false, 4,  0 },
2909                                                        { 3, false, 5,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2921                                                        { 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2923                                                        { 2, false, 6,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2933                                                       {{ 1, false, 4,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2936                                                       {{ 1, false, 4,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2957                                                       {{ 3, false, 1,  0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2959     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2960     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2961     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2962                                                       {{ 3, false, 1,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2964     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2965     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2966     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2967                                                       {{ 3, false, 1,  0 }} },
2968   };
2969 
2970   // Use a dynamically initialized static to sort the table exactly once on
2971   // first run.
2972   static const bool SortOnce =
2973       (llvm::sort(Infos,
2974                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2975                    return LHS.BuiltinID < RHS.BuiltinID;
2976                  }),
2977        true);
2978   (void)SortOnce;
2979 
2980   const BuiltinInfo *F = llvm::partition_point(
2981       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2982   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2983     return false;
2984 
2985   bool Error = false;
2986 
2987   for (const ArgInfo &A : F->Infos) {
2988     // Ignore empty ArgInfo elements.
2989     if (A.BitWidth == 0)
2990       continue;
2991 
2992     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2993     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2994     if (!A.Align) {
2995       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2996     } else {
2997       unsigned M = 1 << A.Align;
2998       Min *= M;
2999       Max *= M;
3000       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3001       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3002     }
3003   }
3004   return Error;
3005 }
3006 
3007 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3008                                            CallExpr *TheCall) {
3009   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3010 }
3011 
3012 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3013                                         unsigned BuiltinID, CallExpr *TheCall) {
3014   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3015          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3016 }
3017 
3018 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3019                                CallExpr *TheCall) {
3020 
3021   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3022       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3023     if (!TI.hasFeature("dsp"))
3024       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3025   }
3026 
3027   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3028       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3029     if (!TI.hasFeature("dspr2"))
3030       return Diag(TheCall->getBeginLoc(),
3031                   diag::err_mips_builtin_requires_dspr2);
3032   }
3033 
3034   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3035       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3036     if (!TI.hasFeature("msa"))
3037       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3038   }
3039 
3040   return false;
3041 }
3042 
3043 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3044 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3045 // ordering for DSP is unspecified. MSA is ordered by the data format used
3046 // by the underlying instruction i.e., df/m, df/n and then by size.
3047 //
3048 // FIXME: The size tests here should instead be tablegen'd along with the
3049 //        definitions from include/clang/Basic/BuiltinsMips.def.
3050 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3051 //        be too.
3052 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3053   unsigned i = 0, l = 0, u = 0, m = 0;
3054   switch (BuiltinID) {
3055   default: return false;
3056   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3057   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3058   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3059   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3060   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3061   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3062   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3063   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3064   // df/m field.
3065   // These intrinsics take an unsigned 3 bit immediate.
3066   case Mips::BI__builtin_msa_bclri_b:
3067   case Mips::BI__builtin_msa_bnegi_b:
3068   case Mips::BI__builtin_msa_bseti_b:
3069   case Mips::BI__builtin_msa_sat_s_b:
3070   case Mips::BI__builtin_msa_sat_u_b:
3071   case Mips::BI__builtin_msa_slli_b:
3072   case Mips::BI__builtin_msa_srai_b:
3073   case Mips::BI__builtin_msa_srari_b:
3074   case Mips::BI__builtin_msa_srli_b:
3075   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3076   case Mips::BI__builtin_msa_binsli_b:
3077   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3078   // These intrinsics take an unsigned 4 bit immediate.
3079   case Mips::BI__builtin_msa_bclri_h:
3080   case Mips::BI__builtin_msa_bnegi_h:
3081   case Mips::BI__builtin_msa_bseti_h:
3082   case Mips::BI__builtin_msa_sat_s_h:
3083   case Mips::BI__builtin_msa_sat_u_h:
3084   case Mips::BI__builtin_msa_slli_h:
3085   case Mips::BI__builtin_msa_srai_h:
3086   case Mips::BI__builtin_msa_srari_h:
3087   case Mips::BI__builtin_msa_srli_h:
3088   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3089   case Mips::BI__builtin_msa_binsli_h:
3090   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3091   // These intrinsics take an unsigned 5 bit immediate.
3092   // The first block of intrinsics actually have an unsigned 5 bit field,
3093   // not a df/n field.
3094   case Mips::BI__builtin_msa_cfcmsa:
3095   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3096   case Mips::BI__builtin_msa_clei_u_b:
3097   case Mips::BI__builtin_msa_clei_u_h:
3098   case Mips::BI__builtin_msa_clei_u_w:
3099   case Mips::BI__builtin_msa_clei_u_d:
3100   case Mips::BI__builtin_msa_clti_u_b:
3101   case Mips::BI__builtin_msa_clti_u_h:
3102   case Mips::BI__builtin_msa_clti_u_w:
3103   case Mips::BI__builtin_msa_clti_u_d:
3104   case Mips::BI__builtin_msa_maxi_u_b:
3105   case Mips::BI__builtin_msa_maxi_u_h:
3106   case Mips::BI__builtin_msa_maxi_u_w:
3107   case Mips::BI__builtin_msa_maxi_u_d:
3108   case Mips::BI__builtin_msa_mini_u_b:
3109   case Mips::BI__builtin_msa_mini_u_h:
3110   case Mips::BI__builtin_msa_mini_u_w:
3111   case Mips::BI__builtin_msa_mini_u_d:
3112   case Mips::BI__builtin_msa_addvi_b:
3113   case Mips::BI__builtin_msa_addvi_h:
3114   case Mips::BI__builtin_msa_addvi_w:
3115   case Mips::BI__builtin_msa_addvi_d:
3116   case Mips::BI__builtin_msa_bclri_w:
3117   case Mips::BI__builtin_msa_bnegi_w:
3118   case Mips::BI__builtin_msa_bseti_w:
3119   case Mips::BI__builtin_msa_sat_s_w:
3120   case Mips::BI__builtin_msa_sat_u_w:
3121   case Mips::BI__builtin_msa_slli_w:
3122   case Mips::BI__builtin_msa_srai_w:
3123   case Mips::BI__builtin_msa_srari_w:
3124   case Mips::BI__builtin_msa_srli_w:
3125   case Mips::BI__builtin_msa_srlri_w:
3126   case Mips::BI__builtin_msa_subvi_b:
3127   case Mips::BI__builtin_msa_subvi_h:
3128   case Mips::BI__builtin_msa_subvi_w:
3129   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3130   case Mips::BI__builtin_msa_binsli_w:
3131   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3132   // These intrinsics take an unsigned 6 bit immediate.
3133   case Mips::BI__builtin_msa_bclri_d:
3134   case Mips::BI__builtin_msa_bnegi_d:
3135   case Mips::BI__builtin_msa_bseti_d:
3136   case Mips::BI__builtin_msa_sat_s_d:
3137   case Mips::BI__builtin_msa_sat_u_d:
3138   case Mips::BI__builtin_msa_slli_d:
3139   case Mips::BI__builtin_msa_srai_d:
3140   case Mips::BI__builtin_msa_srari_d:
3141   case Mips::BI__builtin_msa_srli_d:
3142   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3143   case Mips::BI__builtin_msa_binsli_d:
3144   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3145   // These intrinsics take a signed 5 bit immediate.
3146   case Mips::BI__builtin_msa_ceqi_b:
3147   case Mips::BI__builtin_msa_ceqi_h:
3148   case Mips::BI__builtin_msa_ceqi_w:
3149   case Mips::BI__builtin_msa_ceqi_d:
3150   case Mips::BI__builtin_msa_clti_s_b:
3151   case Mips::BI__builtin_msa_clti_s_h:
3152   case Mips::BI__builtin_msa_clti_s_w:
3153   case Mips::BI__builtin_msa_clti_s_d:
3154   case Mips::BI__builtin_msa_clei_s_b:
3155   case Mips::BI__builtin_msa_clei_s_h:
3156   case Mips::BI__builtin_msa_clei_s_w:
3157   case Mips::BI__builtin_msa_clei_s_d:
3158   case Mips::BI__builtin_msa_maxi_s_b:
3159   case Mips::BI__builtin_msa_maxi_s_h:
3160   case Mips::BI__builtin_msa_maxi_s_w:
3161   case Mips::BI__builtin_msa_maxi_s_d:
3162   case Mips::BI__builtin_msa_mini_s_b:
3163   case Mips::BI__builtin_msa_mini_s_h:
3164   case Mips::BI__builtin_msa_mini_s_w:
3165   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3166   // These intrinsics take an unsigned 8 bit immediate.
3167   case Mips::BI__builtin_msa_andi_b:
3168   case Mips::BI__builtin_msa_nori_b:
3169   case Mips::BI__builtin_msa_ori_b:
3170   case Mips::BI__builtin_msa_shf_b:
3171   case Mips::BI__builtin_msa_shf_h:
3172   case Mips::BI__builtin_msa_shf_w:
3173   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3174   case Mips::BI__builtin_msa_bseli_b:
3175   case Mips::BI__builtin_msa_bmnzi_b:
3176   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3177   // df/n format
3178   // These intrinsics take an unsigned 4 bit immediate.
3179   case Mips::BI__builtin_msa_copy_s_b:
3180   case Mips::BI__builtin_msa_copy_u_b:
3181   case Mips::BI__builtin_msa_insve_b:
3182   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3183   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3184   // These intrinsics take an unsigned 3 bit immediate.
3185   case Mips::BI__builtin_msa_copy_s_h:
3186   case Mips::BI__builtin_msa_copy_u_h:
3187   case Mips::BI__builtin_msa_insve_h:
3188   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3189   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3190   // These intrinsics take an unsigned 2 bit immediate.
3191   case Mips::BI__builtin_msa_copy_s_w:
3192   case Mips::BI__builtin_msa_copy_u_w:
3193   case Mips::BI__builtin_msa_insve_w:
3194   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3195   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3196   // These intrinsics take an unsigned 1 bit immediate.
3197   case Mips::BI__builtin_msa_copy_s_d:
3198   case Mips::BI__builtin_msa_copy_u_d:
3199   case Mips::BI__builtin_msa_insve_d:
3200   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3201   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3202   // Memory offsets and immediate loads.
3203   // These intrinsics take a signed 10 bit immediate.
3204   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3205   case Mips::BI__builtin_msa_ldi_h:
3206   case Mips::BI__builtin_msa_ldi_w:
3207   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3208   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3209   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3210   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3211   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3212   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3213   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3214   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3215   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3216   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3217   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3218   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3219   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3220   }
3221 
3222   if (!m)
3223     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3224 
3225   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3226          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3227 }
3228 
3229 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3230 /// advancing the pointer over the consumed characters. The decoded type is
3231 /// returned. If the decoded type represents a constant integer with a
3232 /// constraint on its value then Mask is set to that value. The type descriptors
3233 /// used in Str are specific to PPC MMA builtins and are documented in the file
3234 /// defining the PPC builtins.
3235 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3236                                         unsigned &Mask) {
3237   bool RequireICE = false;
3238   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3239   switch (*Str++) {
3240   case 'V':
3241     return Context.getVectorType(Context.UnsignedCharTy, 16,
3242                                  VectorType::VectorKind::AltiVecVector);
3243   case 'i': {
3244     char *End;
3245     unsigned size = strtoul(Str, &End, 10);
3246     assert(End != Str && "Missing constant parameter constraint");
3247     Str = End;
3248     Mask = size;
3249     return Context.IntTy;
3250   }
3251   case 'W': {
3252     char *End;
3253     unsigned size = strtoul(Str, &End, 10);
3254     assert(End != Str && "Missing PowerPC MMA type size");
3255     Str = End;
3256     QualType Type;
3257     switch (size) {
3258   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3259     case size: Type = Context.Id##Ty; break;
3260   #include "clang/Basic/PPCTypes.def"
3261     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3262     }
3263     bool CheckVectorArgs = false;
3264     while (!CheckVectorArgs) {
3265       switch (*Str++) {
3266       case '*':
3267         Type = Context.getPointerType(Type);
3268         break;
3269       case 'C':
3270         Type = Type.withConst();
3271         break;
3272       default:
3273         CheckVectorArgs = true;
3274         --Str;
3275         break;
3276       }
3277     }
3278     return Type;
3279   }
3280   default:
3281     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3282   }
3283 }
3284 
3285 static bool isPPC_64Builtin(unsigned BuiltinID) {
3286   // These builtins only work on PPC 64bit targets.
3287   switch (BuiltinID) {
3288   case PPC::BI__builtin_divde:
3289   case PPC::BI__builtin_divdeu:
3290   case PPC::BI__builtin_bpermd:
3291   case PPC::BI__builtin_ppc_ldarx:
3292   case PPC::BI__builtin_ppc_stdcx:
3293   case PPC::BI__builtin_ppc_tdw:
3294   case PPC::BI__builtin_ppc_trapd:
3295   case PPC::BI__builtin_ppc_cmpeqb:
3296   case PPC::BI__builtin_ppc_setb:
3297   case PPC::BI__builtin_ppc_mulhd:
3298   case PPC::BI__builtin_ppc_mulhdu:
3299   case PPC::BI__builtin_ppc_maddhd:
3300   case PPC::BI__builtin_ppc_maddhdu:
3301   case PPC::BI__builtin_ppc_maddld:
3302   case PPC::BI__builtin_ppc_load8r:
3303   case PPC::BI__builtin_ppc_store8r:
3304   case PPC::BI__builtin_ppc_insert_exp:
3305   case PPC::BI__builtin_ppc_extract_sig:
3306   case PPC::BI__builtin_ppc_addex:
3307   case PPC::BI__builtin_darn:
3308   case PPC::BI__builtin_darn_raw:
3309   case PPC::BI__builtin_ppc_compare_and_swaplp:
3310   case PPC::BI__builtin_ppc_fetch_and_addlp:
3311   case PPC::BI__builtin_ppc_fetch_and_andlp:
3312   case PPC::BI__builtin_ppc_fetch_and_orlp:
3313   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3314     return true;
3315   }
3316   return false;
3317 }
3318 
3319 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3320                              StringRef FeatureToCheck, unsigned DiagID,
3321                              StringRef DiagArg = "") {
3322   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3323     return false;
3324 
3325   if (DiagArg.empty())
3326     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3327   else
3328     S.Diag(TheCall->getBeginLoc(), DiagID)
3329         << DiagArg << TheCall->getSourceRange();
3330 
3331   return true;
3332 }
3333 
3334 /// Returns true if the argument consists of one contiguous run of 1s with any
3335 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3336 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3337 /// since all 1s are not contiguous.
3338 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3339   llvm::APSInt Result;
3340   // We can't check the value of a dependent argument.
3341   Expr *Arg = TheCall->getArg(ArgNum);
3342   if (Arg->isTypeDependent() || Arg->isValueDependent())
3343     return false;
3344 
3345   // Check constant-ness first.
3346   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3347     return true;
3348 
3349   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3350   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3351     return false;
3352 
3353   return Diag(TheCall->getBeginLoc(),
3354               diag::err_argument_not_contiguous_bit_field)
3355          << ArgNum << Arg->getSourceRange();
3356 }
3357 
3358 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3359                                        CallExpr *TheCall) {
3360   unsigned i = 0, l = 0, u = 0;
3361   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3362   llvm::APSInt Result;
3363 
3364   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3365     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3366            << TheCall->getSourceRange();
3367 
3368   switch (BuiltinID) {
3369   default: return false;
3370   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3371   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3372     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3373            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3374   case PPC::BI__builtin_altivec_dss:
3375     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3376   case PPC::BI__builtin_tbegin:
3377   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3378   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3379   case PPC::BI__builtin_tabortwc:
3380   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3381   case PPC::BI__builtin_tabortwci:
3382   case PPC::BI__builtin_tabortdci:
3383     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3384            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3385   case PPC::BI__builtin_altivec_dst:
3386   case PPC::BI__builtin_altivec_dstt:
3387   case PPC::BI__builtin_altivec_dstst:
3388   case PPC::BI__builtin_altivec_dststt:
3389     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3390   case PPC::BI__builtin_vsx_xxpermdi:
3391   case PPC::BI__builtin_vsx_xxsldwi:
3392     return SemaBuiltinVSX(TheCall);
3393   case PPC::BI__builtin_divwe:
3394   case PPC::BI__builtin_divweu:
3395   case PPC::BI__builtin_divde:
3396   case PPC::BI__builtin_divdeu:
3397     return SemaFeatureCheck(*this, TheCall, "extdiv",
3398                             diag::err_ppc_builtin_only_on_arch, "7");
3399   case PPC::BI__builtin_bpermd:
3400     return SemaFeatureCheck(*this, TheCall, "bpermd",
3401                             diag::err_ppc_builtin_only_on_arch, "7");
3402   case PPC::BI__builtin_unpack_vector_int128:
3403     return SemaFeatureCheck(*this, TheCall, "vsx",
3404                             diag::err_ppc_builtin_only_on_arch, "7") ||
3405            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3406   case PPC::BI__builtin_pack_vector_int128:
3407     return SemaFeatureCheck(*this, TheCall, "vsx",
3408                             diag::err_ppc_builtin_only_on_arch, "7");
3409   case PPC::BI__builtin_altivec_vgnb:
3410      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3411   case PPC::BI__builtin_altivec_vec_replace_elt:
3412   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3413     QualType VecTy = TheCall->getArg(0)->getType();
3414     QualType EltTy = TheCall->getArg(1)->getType();
3415     unsigned Width = Context.getIntWidth(EltTy);
3416     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3417            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3418   }
3419   case PPC::BI__builtin_vsx_xxeval:
3420      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3421   case PPC::BI__builtin_altivec_vsldbi:
3422      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3423   case PPC::BI__builtin_altivec_vsrdbi:
3424      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3425   case PPC::BI__builtin_vsx_xxpermx:
3426      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3427   case PPC::BI__builtin_ppc_tw:
3428   case PPC::BI__builtin_ppc_tdw:
3429     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3430   case PPC::BI__builtin_ppc_cmpeqb:
3431   case PPC::BI__builtin_ppc_setb:
3432   case PPC::BI__builtin_ppc_maddhd:
3433   case PPC::BI__builtin_ppc_maddhdu:
3434   case PPC::BI__builtin_ppc_maddld:
3435     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3436                             diag::err_ppc_builtin_only_on_arch, "9");
3437   case PPC::BI__builtin_ppc_cmprb:
3438     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3439                             diag::err_ppc_builtin_only_on_arch, "9") ||
3440            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3441   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3442   // be a constant that represents a contiguous bit field.
3443   case PPC::BI__builtin_ppc_rlwnm:
3444     return SemaValueIsRunOfOnes(TheCall, 2);
3445   case PPC::BI__builtin_ppc_rlwimi:
3446   case PPC::BI__builtin_ppc_rldimi:
3447     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3448            SemaValueIsRunOfOnes(TheCall, 3);
3449   case PPC::BI__builtin_ppc_extract_exp:
3450   case PPC::BI__builtin_ppc_extract_sig:
3451   case PPC::BI__builtin_ppc_insert_exp:
3452     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3453                             diag::err_ppc_builtin_only_on_arch, "9");
3454   case PPC::BI__builtin_ppc_addex: {
3455     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3456                          diag::err_ppc_builtin_only_on_arch, "9") ||
3457         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3458       return true;
3459     // Output warning for reserved values 1 to 3.
3460     int ArgValue =
3461         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3462     if (ArgValue != 0)
3463       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3464           << ArgValue;
3465     return false;
3466   }
3467   case PPC::BI__builtin_ppc_mtfsb0:
3468   case PPC::BI__builtin_ppc_mtfsb1:
3469     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3470   case PPC::BI__builtin_ppc_mtfsf:
3471     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3472   case PPC::BI__builtin_ppc_mtfsfi:
3473     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3474            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3475   case PPC::BI__builtin_ppc_alignx:
3476     return SemaBuiltinConstantArgPower2(TheCall, 0);
3477   case PPC::BI__builtin_ppc_rdlam:
3478     return SemaValueIsRunOfOnes(TheCall, 2);
3479   case PPC::BI__builtin_ppc_icbt:
3480   case PPC::BI__builtin_ppc_sthcx:
3481   case PPC::BI__builtin_ppc_stbcx:
3482   case PPC::BI__builtin_ppc_lharx:
3483   case PPC::BI__builtin_ppc_lbarx:
3484     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3485                             diag::err_ppc_builtin_only_on_arch, "8");
3486   case PPC::BI__builtin_vsx_ldrmb:
3487   case PPC::BI__builtin_vsx_strmb:
3488     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3489                             diag::err_ppc_builtin_only_on_arch, "8") ||
3490            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3491   case PPC::BI__builtin_altivec_vcntmbb:
3492   case PPC::BI__builtin_altivec_vcntmbh:
3493   case PPC::BI__builtin_altivec_vcntmbw:
3494   case PPC::BI__builtin_altivec_vcntmbd:
3495     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3496   case PPC::BI__builtin_darn:
3497   case PPC::BI__builtin_darn_raw:
3498   case PPC::BI__builtin_darn_32:
3499     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3500                             diag::err_ppc_builtin_only_on_arch, "9");
3501   case PPC::BI__builtin_vsx_xxgenpcvbm:
3502   case PPC::BI__builtin_vsx_xxgenpcvhm:
3503   case PPC::BI__builtin_vsx_xxgenpcvwm:
3504   case PPC::BI__builtin_vsx_xxgenpcvdm:
3505     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3506   case PPC::BI__builtin_ppc_compare_exp_uo:
3507   case PPC::BI__builtin_ppc_compare_exp_lt:
3508   case PPC::BI__builtin_ppc_compare_exp_gt:
3509   case PPC::BI__builtin_ppc_compare_exp_eq:
3510     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3511                             diag::err_ppc_builtin_only_on_arch, "9") ||
3512            SemaFeatureCheck(*this, TheCall, "vsx",
3513                             diag::err_ppc_builtin_requires_vsx);
3514   case PPC::BI__builtin_ppc_test_data_class: {
3515     // Check if the first argument of the __builtin_ppc_test_data_class call is
3516     // valid. The argument must be either a 'float' or a 'double'.
3517     QualType ArgType = TheCall->getArg(0)->getType();
3518     if (ArgType != QualType(Context.FloatTy) &&
3519         ArgType != QualType(Context.DoubleTy))
3520       return Diag(TheCall->getBeginLoc(),
3521                   diag::err_ppc_invalid_test_data_class_type);
3522     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3523                             diag::err_ppc_builtin_only_on_arch, "9") ||
3524            SemaFeatureCheck(*this, TheCall, "vsx",
3525                             diag::err_ppc_builtin_requires_vsx) ||
3526            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3527   }
3528   case PPC::BI__builtin_ppc_load8r:
3529   case PPC::BI__builtin_ppc_store8r:
3530     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3531                             diag::err_ppc_builtin_only_on_arch, "7");
3532 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3533   case PPC::BI__builtin_##Name:                                                \
3534     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3535 #include "clang/Basic/BuiltinsPPC.def"
3536   }
3537   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3538 }
3539 
3540 // Check if the given type is a non-pointer PPC MMA type. This function is used
3541 // in Sema to prevent invalid uses of restricted PPC MMA types.
3542 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3543   if (Type->isPointerType() || Type->isArrayType())
3544     return false;
3545 
3546   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3547 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3548   if (false
3549 #include "clang/Basic/PPCTypes.def"
3550      ) {
3551     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3552     return true;
3553   }
3554   return false;
3555 }
3556 
3557 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3558                                           CallExpr *TheCall) {
3559   // position of memory order and scope arguments in the builtin
3560   unsigned OrderIndex, ScopeIndex;
3561   switch (BuiltinID) {
3562   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3563   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3564   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3565   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3566     OrderIndex = 2;
3567     ScopeIndex = 3;
3568     break;
3569   case AMDGPU::BI__builtin_amdgcn_fence:
3570     OrderIndex = 0;
3571     ScopeIndex = 1;
3572     break;
3573   default:
3574     return false;
3575   }
3576 
3577   ExprResult Arg = TheCall->getArg(OrderIndex);
3578   auto ArgExpr = Arg.get();
3579   Expr::EvalResult ArgResult;
3580 
3581   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3582     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3583            << ArgExpr->getType();
3584   auto Ord = ArgResult.Val.getInt().getZExtValue();
3585 
3586   // Check validity of memory ordering as per C11 / C++11's memody model.
3587   // Only fence needs check. Atomic dec/inc allow all memory orders.
3588   if (!llvm::isValidAtomicOrderingCABI(Ord))
3589     return Diag(ArgExpr->getBeginLoc(),
3590                 diag::warn_atomic_op_has_invalid_memory_order)
3591            << ArgExpr->getSourceRange();
3592   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3593   case llvm::AtomicOrderingCABI::relaxed:
3594   case llvm::AtomicOrderingCABI::consume:
3595     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3596       return Diag(ArgExpr->getBeginLoc(),
3597                   diag::warn_atomic_op_has_invalid_memory_order)
3598              << ArgExpr->getSourceRange();
3599     break;
3600   case llvm::AtomicOrderingCABI::acquire:
3601   case llvm::AtomicOrderingCABI::release:
3602   case llvm::AtomicOrderingCABI::acq_rel:
3603   case llvm::AtomicOrderingCABI::seq_cst:
3604     break;
3605   }
3606 
3607   Arg = TheCall->getArg(ScopeIndex);
3608   ArgExpr = Arg.get();
3609   Expr::EvalResult ArgResult1;
3610   // Check that sync scope is a constant literal
3611   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3612     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3613            << ArgExpr->getType();
3614 
3615   return false;
3616 }
3617 
3618 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3619   llvm::APSInt Result;
3620 
3621   // We can't check the value of a dependent argument.
3622   Expr *Arg = TheCall->getArg(ArgNum);
3623   if (Arg->isTypeDependent() || Arg->isValueDependent())
3624     return false;
3625 
3626   // Check constant-ness first.
3627   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3628     return true;
3629 
3630   int64_t Val = Result.getSExtValue();
3631   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3632     return false;
3633 
3634   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3635          << Arg->getSourceRange();
3636 }
3637 
3638 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3639                                          unsigned BuiltinID,
3640                                          CallExpr *TheCall) {
3641   // CodeGenFunction can also detect this, but this gives a better error
3642   // message.
3643   bool FeatureMissing = false;
3644   SmallVector<StringRef> ReqFeatures;
3645   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3646   Features.split(ReqFeatures, ',');
3647 
3648   // Check if each required feature is included
3649   for (StringRef F : ReqFeatures) {
3650     if (TI.hasFeature(F))
3651       continue;
3652 
3653     // If the feature is 64bit, alter the string so it will print better in
3654     // the diagnostic.
3655     if (F == "64bit")
3656       F = "RV64";
3657 
3658     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3659     F.consume_front("experimental-");
3660     std::string FeatureStr = F.str();
3661     FeatureStr[0] = std::toupper(FeatureStr[0]);
3662 
3663     // Error message
3664     FeatureMissing = true;
3665     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3666         << TheCall->getSourceRange() << StringRef(FeatureStr);
3667   }
3668 
3669   if (FeatureMissing)
3670     return true;
3671 
3672   switch (BuiltinID) {
3673   case RISCVVector::BI__builtin_rvv_vsetvli:
3674     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3675            CheckRISCVLMUL(TheCall, 2);
3676   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3677     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3678            CheckRISCVLMUL(TheCall, 1);
3679   }
3680 
3681   return false;
3682 }
3683 
3684 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3685                                            CallExpr *TheCall) {
3686   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3687     Expr *Arg = TheCall->getArg(0);
3688     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3689       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3690         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3691                << Arg->getSourceRange();
3692   }
3693 
3694   // For intrinsics which take an immediate value as part of the instruction,
3695   // range check them here.
3696   unsigned i = 0, l = 0, u = 0;
3697   switch (BuiltinID) {
3698   default: return false;
3699   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3700   case SystemZ::BI__builtin_s390_verimb:
3701   case SystemZ::BI__builtin_s390_verimh:
3702   case SystemZ::BI__builtin_s390_verimf:
3703   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3704   case SystemZ::BI__builtin_s390_vfaeb:
3705   case SystemZ::BI__builtin_s390_vfaeh:
3706   case SystemZ::BI__builtin_s390_vfaef:
3707   case SystemZ::BI__builtin_s390_vfaebs:
3708   case SystemZ::BI__builtin_s390_vfaehs:
3709   case SystemZ::BI__builtin_s390_vfaefs:
3710   case SystemZ::BI__builtin_s390_vfaezb:
3711   case SystemZ::BI__builtin_s390_vfaezh:
3712   case SystemZ::BI__builtin_s390_vfaezf:
3713   case SystemZ::BI__builtin_s390_vfaezbs:
3714   case SystemZ::BI__builtin_s390_vfaezhs:
3715   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3716   case SystemZ::BI__builtin_s390_vfisb:
3717   case SystemZ::BI__builtin_s390_vfidb:
3718     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3719            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3720   case SystemZ::BI__builtin_s390_vftcisb:
3721   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3722   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3723   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3724   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3725   case SystemZ::BI__builtin_s390_vstrcb:
3726   case SystemZ::BI__builtin_s390_vstrch:
3727   case SystemZ::BI__builtin_s390_vstrcf:
3728   case SystemZ::BI__builtin_s390_vstrczb:
3729   case SystemZ::BI__builtin_s390_vstrczh:
3730   case SystemZ::BI__builtin_s390_vstrczf:
3731   case SystemZ::BI__builtin_s390_vstrcbs:
3732   case SystemZ::BI__builtin_s390_vstrchs:
3733   case SystemZ::BI__builtin_s390_vstrcfs:
3734   case SystemZ::BI__builtin_s390_vstrczbs:
3735   case SystemZ::BI__builtin_s390_vstrczhs:
3736   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3737   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3738   case SystemZ::BI__builtin_s390_vfminsb:
3739   case SystemZ::BI__builtin_s390_vfmaxsb:
3740   case SystemZ::BI__builtin_s390_vfmindb:
3741   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3742   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3743   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3744   case SystemZ::BI__builtin_s390_vclfnhs:
3745   case SystemZ::BI__builtin_s390_vclfnls:
3746   case SystemZ::BI__builtin_s390_vcfn:
3747   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3748   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3749   }
3750   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3751 }
3752 
3753 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3754 /// This checks that the target supports __builtin_cpu_supports and
3755 /// that the string argument is constant and valid.
3756 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3757                                    CallExpr *TheCall) {
3758   Expr *Arg = TheCall->getArg(0);
3759 
3760   // Check if the argument is a string literal.
3761   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3762     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3763            << Arg->getSourceRange();
3764 
3765   // Check the contents of the string.
3766   StringRef Feature =
3767       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3768   if (!TI.validateCpuSupports(Feature))
3769     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3770            << Arg->getSourceRange();
3771   return false;
3772 }
3773 
3774 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3775 /// This checks that the target supports __builtin_cpu_is and
3776 /// that the string argument is constant and valid.
3777 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3778   Expr *Arg = TheCall->getArg(0);
3779 
3780   // Check if the argument is a string literal.
3781   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3782     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3783            << Arg->getSourceRange();
3784 
3785   // Check the contents of the string.
3786   StringRef Feature =
3787       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3788   if (!TI.validateCpuIs(Feature))
3789     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3790            << Arg->getSourceRange();
3791   return false;
3792 }
3793 
3794 // Check if the rounding mode is legal.
3795 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3796   // Indicates if this instruction has rounding control or just SAE.
3797   bool HasRC = false;
3798 
3799   unsigned ArgNum = 0;
3800   switch (BuiltinID) {
3801   default:
3802     return false;
3803   case X86::BI__builtin_ia32_vcvttsd2si32:
3804   case X86::BI__builtin_ia32_vcvttsd2si64:
3805   case X86::BI__builtin_ia32_vcvttsd2usi32:
3806   case X86::BI__builtin_ia32_vcvttsd2usi64:
3807   case X86::BI__builtin_ia32_vcvttss2si32:
3808   case X86::BI__builtin_ia32_vcvttss2si64:
3809   case X86::BI__builtin_ia32_vcvttss2usi32:
3810   case X86::BI__builtin_ia32_vcvttss2usi64:
3811   case X86::BI__builtin_ia32_vcvttsh2si32:
3812   case X86::BI__builtin_ia32_vcvttsh2si64:
3813   case X86::BI__builtin_ia32_vcvttsh2usi32:
3814   case X86::BI__builtin_ia32_vcvttsh2usi64:
3815     ArgNum = 1;
3816     break;
3817   case X86::BI__builtin_ia32_maxpd512:
3818   case X86::BI__builtin_ia32_maxps512:
3819   case X86::BI__builtin_ia32_minpd512:
3820   case X86::BI__builtin_ia32_minps512:
3821   case X86::BI__builtin_ia32_maxph512:
3822   case X86::BI__builtin_ia32_minph512:
3823     ArgNum = 2;
3824     break;
3825   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3826   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3827   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3828   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3829   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3830   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3831   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3832   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3833   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3834   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3835   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3836   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3837   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3838   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3839   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3840   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3841   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3842   case X86::BI__builtin_ia32_exp2pd_mask:
3843   case X86::BI__builtin_ia32_exp2ps_mask:
3844   case X86::BI__builtin_ia32_getexppd512_mask:
3845   case X86::BI__builtin_ia32_getexpps512_mask:
3846   case X86::BI__builtin_ia32_getexpph512_mask:
3847   case X86::BI__builtin_ia32_rcp28pd_mask:
3848   case X86::BI__builtin_ia32_rcp28ps_mask:
3849   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3850   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3851   case X86::BI__builtin_ia32_vcomisd:
3852   case X86::BI__builtin_ia32_vcomiss:
3853   case X86::BI__builtin_ia32_vcomish:
3854   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3855     ArgNum = 3;
3856     break;
3857   case X86::BI__builtin_ia32_cmppd512_mask:
3858   case X86::BI__builtin_ia32_cmpps512_mask:
3859   case X86::BI__builtin_ia32_cmpsd_mask:
3860   case X86::BI__builtin_ia32_cmpss_mask:
3861   case X86::BI__builtin_ia32_cmpsh_mask:
3862   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3863   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3864   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3865   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3866   case X86::BI__builtin_ia32_getexpss128_round_mask:
3867   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3868   case X86::BI__builtin_ia32_getmantpd512_mask:
3869   case X86::BI__builtin_ia32_getmantps512_mask:
3870   case X86::BI__builtin_ia32_getmantph512_mask:
3871   case X86::BI__builtin_ia32_maxsd_round_mask:
3872   case X86::BI__builtin_ia32_maxss_round_mask:
3873   case X86::BI__builtin_ia32_maxsh_round_mask:
3874   case X86::BI__builtin_ia32_minsd_round_mask:
3875   case X86::BI__builtin_ia32_minss_round_mask:
3876   case X86::BI__builtin_ia32_minsh_round_mask:
3877   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3878   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3879   case X86::BI__builtin_ia32_reducepd512_mask:
3880   case X86::BI__builtin_ia32_reduceps512_mask:
3881   case X86::BI__builtin_ia32_reduceph512_mask:
3882   case X86::BI__builtin_ia32_rndscalepd_mask:
3883   case X86::BI__builtin_ia32_rndscaleps_mask:
3884   case X86::BI__builtin_ia32_rndscaleph_mask:
3885   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3886   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3887     ArgNum = 4;
3888     break;
3889   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3890   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3891   case X86::BI__builtin_ia32_fixupimmps512_mask:
3892   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3893   case X86::BI__builtin_ia32_fixupimmsd_mask:
3894   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3895   case X86::BI__builtin_ia32_fixupimmss_mask:
3896   case X86::BI__builtin_ia32_fixupimmss_maskz:
3897   case X86::BI__builtin_ia32_getmantsd_round_mask:
3898   case X86::BI__builtin_ia32_getmantss_round_mask:
3899   case X86::BI__builtin_ia32_getmantsh_round_mask:
3900   case X86::BI__builtin_ia32_rangepd512_mask:
3901   case X86::BI__builtin_ia32_rangeps512_mask:
3902   case X86::BI__builtin_ia32_rangesd128_round_mask:
3903   case X86::BI__builtin_ia32_rangess128_round_mask:
3904   case X86::BI__builtin_ia32_reducesd_mask:
3905   case X86::BI__builtin_ia32_reducess_mask:
3906   case X86::BI__builtin_ia32_reducesh_mask:
3907   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3908   case X86::BI__builtin_ia32_rndscaless_round_mask:
3909   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3910     ArgNum = 5;
3911     break;
3912   case X86::BI__builtin_ia32_vcvtsd2si64:
3913   case X86::BI__builtin_ia32_vcvtsd2si32:
3914   case X86::BI__builtin_ia32_vcvtsd2usi32:
3915   case X86::BI__builtin_ia32_vcvtsd2usi64:
3916   case X86::BI__builtin_ia32_vcvtss2si32:
3917   case X86::BI__builtin_ia32_vcvtss2si64:
3918   case X86::BI__builtin_ia32_vcvtss2usi32:
3919   case X86::BI__builtin_ia32_vcvtss2usi64:
3920   case X86::BI__builtin_ia32_vcvtsh2si32:
3921   case X86::BI__builtin_ia32_vcvtsh2si64:
3922   case X86::BI__builtin_ia32_vcvtsh2usi32:
3923   case X86::BI__builtin_ia32_vcvtsh2usi64:
3924   case X86::BI__builtin_ia32_sqrtpd512:
3925   case X86::BI__builtin_ia32_sqrtps512:
3926   case X86::BI__builtin_ia32_sqrtph512:
3927     ArgNum = 1;
3928     HasRC = true;
3929     break;
3930   case X86::BI__builtin_ia32_addph512:
3931   case X86::BI__builtin_ia32_divph512:
3932   case X86::BI__builtin_ia32_mulph512:
3933   case X86::BI__builtin_ia32_subph512:
3934   case X86::BI__builtin_ia32_addpd512:
3935   case X86::BI__builtin_ia32_addps512:
3936   case X86::BI__builtin_ia32_divpd512:
3937   case X86::BI__builtin_ia32_divps512:
3938   case X86::BI__builtin_ia32_mulpd512:
3939   case X86::BI__builtin_ia32_mulps512:
3940   case X86::BI__builtin_ia32_subpd512:
3941   case X86::BI__builtin_ia32_subps512:
3942   case X86::BI__builtin_ia32_cvtsi2sd64:
3943   case X86::BI__builtin_ia32_cvtsi2ss32:
3944   case X86::BI__builtin_ia32_cvtsi2ss64:
3945   case X86::BI__builtin_ia32_cvtusi2sd64:
3946   case X86::BI__builtin_ia32_cvtusi2ss32:
3947   case X86::BI__builtin_ia32_cvtusi2ss64:
3948   case X86::BI__builtin_ia32_vcvtusi2sh:
3949   case X86::BI__builtin_ia32_vcvtusi642sh:
3950   case X86::BI__builtin_ia32_vcvtsi2sh:
3951   case X86::BI__builtin_ia32_vcvtsi642sh:
3952     ArgNum = 2;
3953     HasRC = true;
3954     break;
3955   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3956   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3957   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
3958   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
3959   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3960   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3961   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3962   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3963   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3964   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3965   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3966   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3967   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3968   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3969   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3970   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3971   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3972   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
3973   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
3974   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
3975   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
3976   case X86::BI__builtin_ia32_vcvtph2w512_mask:
3977   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
3978   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
3979   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
3980   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
3981   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
3982   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
3983   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
3984     ArgNum = 3;
3985     HasRC = true;
3986     break;
3987   case X86::BI__builtin_ia32_addsh_round_mask:
3988   case X86::BI__builtin_ia32_addss_round_mask:
3989   case X86::BI__builtin_ia32_addsd_round_mask:
3990   case X86::BI__builtin_ia32_divsh_round_mask:
3991   case X86::BI__builtin_ia32_divss_round_mask:
3992   case X86::BI__builtin_ia32_divsd_round_mask:
3993   case X86::BI__builtin_ia32_mulsh_round_mask:
3994   case X86::BI__builtin_ia32_mulss_round_mask:
3995   case X86::BI__builtin_ia32_mulsd_round_mask:
3996   case X86::BI__builtin_ia32_subsh_round_mask:
3997   case X86::BI__builtin_ia32_subss_round_mask:
3998   case X86::BI__builtin_ia32_subsd_round_mask:
3999   case X86::BI__builtin_ia32_scalefph512_mask:
4000   case X86::BI__builtin_ia32_scalefpd512_mask:
4001   case X86::BI__builtin_ia32_scalefps512_mask:
4002   case X86::BI__builtin_ia32_scalefsd_round_mask:
4003   case X86::BI__builtin_ia32_scalefss_round_mask:
4004   case X86::BI__builtin_ia32_scalefsh_round_mask:
4005   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4006   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4007   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4008   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4009   case X86::BI__builtin_ia32_sqrtss_round_mask:
4010   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4011   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4012   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4013   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4014   case X86::BI__builtin_ia32_vfmaddss3_mask:
4015   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4016   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4017   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4018   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4019   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4020   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4021   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4022   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4023   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4024   case X86::BI__builtin_ia32_vfmaddps512_mask:
4025   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4026   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4027   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4028   case X86::BI__builtin_ia32_vfmaddph512_mask:
4029   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4030   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4031   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4032   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4033   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4034   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4035   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4036   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4037   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4038   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4039   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4040   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4041   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4042   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4043   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4044   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4045   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4046   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4047   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4048   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4049   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4050   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4051   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4052   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4053   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4054   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4055   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4056   case X86::BI__builtin_ia32_vfmulcsh_mask:
4057   case X86::BI__builtin_ia32_vfmulcph512_mask:
4058   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4059   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4060     ArgNum = 4;
4061     HasRC = true;
4062     break;
4063   }
4064 
4065   llvm::APSInt Result;
4066 
4067   // We can't check the value of a dependent argument.
4068   Expr *Arg = TheCall->getArg(ArgNum);
4069   if (Arg->isTypeDependent() || Arg->isValueDependent())
4070     return false;
4071 
4072   // Check constant-ness first.
4073   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4074     return true;
4075 
4076   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4077   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4078   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4079   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4080   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4081       Result == 8/*ROUND_NO_EXC*/ ||
4082       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4083       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4084     return false;
4085 
4086   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4087          << Arg->getSourceRange();
4088 }
4089 
4090 // Check if the gather/scatter scale is legal.
4091 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4092                                              CallExpr *TheCall) {
4093   unsigned ArgNum = 0;
4094   switch (BuiltinID) {
4095   default:
4096     return false;
4097   case X86::BI__builtin_ia32_gatherpfdpd:
4098   case X86::BI__builtin_ia32_gatherpfdps:
4099   case X86::BI__builtin_ia32_gatherpfqpd:
4100   case X86::BI__builtin_ia32_gatherpfqps:
4101   case X86::BI__builtin_ia32_scatterpfdpd:
4102   case X86::BI__builtin_ia32_scatterpfdps:
4103   case X86::BI__builtin_ia32_scatterpfqpd:
4104   case X86::BI__builtin_ia32_scatterpfqps:
4105     ArgNum = 3;
4106     break;
4107   case X86::BI__builtin_ia32_gatherd_pd:
4108   case X86::BI__builtin_ia32_gatherd_pd256:
4109   case X86::BI__builtin_ia32_gatherq_pd:
4110   case X86::BI__builtin_ia32_gatherq_pd256:
4111   case X86::BI__builtin_ia32_gatherd_ps:
4112   case X86::BI__builtin_ia32_gatherd_ps256:
4113   case X86::BI__builtin_ia32_gatherq_ps:
4114   case X86::BI__builtin_ia32_gatherq_ps256:
4115   case X86::BI__builtin_ia32_gatherd_q:
4116   case X86::BI__builtin_ia32_gatherd_q256:
4117   case X86::BI__builtin_ia32_gatherq_q:
4118   case X86::BI__builtin_ia32_gatherq_q256:
4119   case X86::BI__builtin_ia32_gatherd_d:
4120   case X86::BI__builtin_ia32_gatherd_d256:
4121   case X86::BI__builtin_ia32_gatherq_d:
4122   case X86::BI__builtin_ia32_gatherq_d256:
4123   case X86::BI__builtin_ia32_gather3div2df:
4124   case X86::BI__builtin_ia32_gather3div2di:
4125   case X86::BI__builtin_ia32_gather3div4df:
4126   case X86::BI__builtin_ia32_gather3div4di:
4127   case X86::BI__builtin_ia32_gather3div4sf:
4128   case X86::BI__builtin_ia32_gather3div4si:
4129   case X86::BI__builtin_ia32_gather3div8sf:
4130   case X86::BI__builtin_ia32_gather3div8si:
4131   case X86::BI__builtin_ia32_gather3siv2df:
4132   case X86::BI__builtin_ia32_gather3siv2di:
4133   case X86::BI__builtin_ia32_gather3siv4df:
4134   case X86::BI__builtin_ia32_gather3siv4di:
4135   case X86::BI__builtin_ia32_gather3siv4sf:
4136   case X86::BI__builtin_ia32_gather3siv4si:
4137   case X86::BI__builtin_ia32_gather3siv8sf:
4138   case X86::BI__builtin_ia32_gather3siv8si:
4139   case X86::BI__builtin_ia32_gathersiv8df:
4140   case X86::BI__builtin_ia32_gathersiv16sf:
4141   case X86::BI__builtin_ia32_gatherdiv8df:
4142   case X86::BI__builtin_ia32_gatherdiv16sf:
4143   case X86::BI__builtin_ia32_gathersiv8di:
4144   case X86::BI__builtin_ia32_gathersiv16si:
4145   case X86::BI__builtin_ia32_gatherdiv8di:
4146   case X86::BI__builtin_ia32_gatherdiv16si:
4147   case X86::BI__builtin_ia32_scatterdiv2df:
4148   case X86::BI__builtin_ia32_scatterdiv2di:
4149   case X86::BI__builtin_ia32_scatterdiv4df:
4150   case X86::BI__builtin_ia32_scatterdiv4di:
4151   case X86::BI__builtin_ia32_scatterdiv4sf:
4152   case X86::BI__builtin_ia32_scatterdiv4si:
4153   case X86::BI__builtin_ia32_scatterdiv8sf:
4154   case X86::BI__builtin_ia32_scatterdiv8si:
4155   case X86::BI__builtin_ia32_scattersiv2df:
4156   case X86::BI__builtin_ia32_scattersiv2di:
4157   case X86::BI__builtin_ia32_scattersiv4df:
4158   case X86::BI__builtin_ia32_scattersiv4di:
4159   case X86::BI__builtin_ia32_scattersiv4sf:
4160   case X86::BI__builtin_ia32_scattersiv4si:
4161   case X86::BI__builtin_ia32_scattersiv8sf:
4162   case X86::BI__builtin_ia32_scattersiv8si:
4163   case X86::BI__builtin_ia32_scattersiv8df:
4164   case X86::BI__builtin_ia32_scattersiv16sf:
4165   case X86::BI__builtin_ia32_scatterdiv8df:
4166   case X86::BI__builtin_ia32_scatterdiv16sf:
4167   case X86::BI__builtin_ia32_scattersiv8di:
4168   case X86::BI__builtin_ia32_scattersiv16si:
4169   case X86::BI__builtin_ia32_scatterdiv8di:
4170   case X86::BI__builtin_ia32_scatterdiv16si:
4171     ArgNum = 4;
4172     break;
4173   }
4174 
4175   llvm::APSInt Result;
4176 
4177   // We can't check the value of a dependent argument.
4178   Expr *Arg = TheCall->getArg(ArgNum);
4179   if (Arg->isTypeDependent() || Arg->isValueDependent())
4180     return false;
4181 
4182   // Check constant-ness first.
4183   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4184     return true;
4185 
4186   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4187     return false;
4188 
4189   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4190          << Arg->getSourceRange();
4191 }
4192 
4193 enum { TileRegLow = 0, TileRegHigh = 7 };
4194 
4195 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4196                                              ArrayRef<int> ArgNums) {
4197   for (int ArgNum : ArgNums) {
4198     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4199       return true;
4200   }
4201   return false;
4202 }
4203 
4204 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4205                                         ArrayRef<int> ArgNums) {
4206   // Because the max number of tile register is TileRegHigh + 1, so here we use
4207   // each bit to represent the usage of them in bitset.
4208   std::bitset<TileRegHigh + 1> ArgValues;
4209   for (int ArgNum : ArgNums) {
4210     Expr *Arg = TheCall->getArg(ArgNum);
4211     if (Arg->isTypeDependent() || Arg->isValueDependent())
4212       continue;
4213 
4214     llvm::APSInt Result;
4215     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4216       return true;
4217     int ArgExtValue = Result.getExtValue();
4218     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4219            "Incorrect tile register num.");
4220     if (ArgValues.test(ArgExtValue))
4221       return Diag(TheCall->getBeginLoc(),
4222                   diag::err_x86_builtin_tile_arg_duplicate)
4223              << TheCall->getArg(ArgNum)->getSourceRange();
4224     ArgValues.set(ArgExtValue);
4225   }
4226   return false;
4227 }
4228 
4229 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4230                                                 ArrayRef<int> ArgNums) {
4231   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4232          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4233 }
4234 
4235 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4236   switch (BuiltinID) {
4237   default:
4238     return false;
4239   case X86::BI__builtin_ia32_tileloadd64:
4240   case X86::BI__builtin_ia32_tileloaddt164:
4241   case X86::BI__builtin_ia32_tilestored64:
4242   case X86::BI__builtin_ia32_tilezero:
4243     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4244   case X86::BI__builtin_ia32_tdpbssd:
4245   case X86::BI__builtin_ia32_tdpbsud:
4246   case X86::BI__builtin_ia32_tdpbusd:
4247   case X86::BI__builtin_ia32_tdpbuud:
4248   case X86::BI__builtin_ia32_tdpbf16ps:
4249     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4250   }
4251 }
4252 static bool isX86_32Builtin(unsigned BuiltinID) {
4253   // These builtins only work on x86-32 targets.
4254   switch (BuiltinID) {
4255   case X86::BI__builtin_ia32_readeflags_u32:
4256   case X86::BI__builtin_ia32_writeeflags_u32:
4257     return true;
4258   }
4259 
4260   return false;
4261 }
4262 
4263 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4264                                        CallExpr *TheCall) {
4265   if (BuiltinID == X86::BI__builtin_cpu_supports)
4266     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4267 
4268   if (BuiltinID == X86::BI__builtin_cpu_is)
4269     return SemaBuiltinCpuIs(*this, TI, TheCall);
4270 
4271   // Check for 32-bit only builtins on a 64-bit target.
4272   const llvm::Triple &TT = TI.getTriple();
4273   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4274     return Diag(TheCall->getCallee()->getBeginLoc(),
4275                 diag::err_32_bit_builtin_64_bit_tgt);
4276 
4277   // If the intrinsic has rounding or SAE make sure its valid.
4278   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4279     return true;
4280 
4281   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4282   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4283     return true;
4284 
4285   // If the intrinsic has a tile arguments, make sure they are valid.
4286   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4287     return true;
4288 
4289   // For intrinsics which take an immediate value as part of the instruction,
4290   // range check them here.
4291   int i = 0, l = 0, u = 0;
4292   switch (BuiltinID) {
4293   default:
4294     return false;
4295   case X86::BI__builtin_ia32_vec_ext_v2si:
4296   case X86::BI__builtin_ia32_vec_ext_v2di:
4297   case X86::BI__builtin_ia32_vextractf128_pd256:
4298   case X86::BI__builtin_ia32_vextractf128_ps256:
4299   case X86::BI__builtin_ia32_vextractf128_si256:
4300   case X86::BI__builtin_ia32_extract128i256:
4301   case X86::BI__builtin_ia32_extractf64x4_mask:
4302   case X86::BI__builtin_ia32_extracti64x4_mask:
4303   case X86::BI__builtin_ia32_extractf32x8_mask:
4304   case X86::BI__builtin_ia32_extracti32x8_mask:
4305   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4306   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4307   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4308   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4309     i = 1; l = 0; u = 1;
4310     break;
4311   case X86::BI__builtin_ia32_vec_set_v2di:
4312   case X86::BI__builtin_ia32_vinsertf128_pd256:
4313   case X86::BI__builtin_ia32_vinsertf128_ps256:
4314   case X86::BI__builtin_ia32_vinsertf128_si256:
4315   case X86::BI__builtin_ia32_insert128i256:
4316   case X86::BI__builtin_ia32_insertf32x8:
4317   case X86::BI__builtin_ia32_inserti32x8:
4318   case X86::BI__builtin_ia32_insertf64x4:
4319   case X86::BI__builtin_ia32_inserti64x4:
4320   case X86::BI__builtin_ia32_insertf64x2_256:
4321   case X86::BI__builtin_ia32_inserti64x2_256:
4322   case X86::BI__builtin_ia32_insertf32x4_256:
4323   case X86::BI__builtin_ia32_inserti32x4_256:
4324     i = 2; l = 0; u = 1;
4325     break;
4326   case X86::BI__builtin_ia32_vpermilpd:
4327   case X86::BI__builtin_ia32_vec_ext_v4hi:
4328   case X86::BI__builtin_ia32_vec_ext_v4si:
4329   case X86::BI__builtin_ia32_vec_ext_v4sf:
4330   case X86::BI__builtin_ia32_vec_ext_v4di:
4331   case X86::BI__builtin_ia32_extractf32x4_mask:
4332   case X86::BI__builtin_ia32_extracti32x4_mask:
4333   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4334   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4335     i = 1; l = 0; u = 3;
4336     break;
4337   case X86::BI_mm_prefetch:
4338   case X86::BI__builtin_ia32_vec_ext_v8hi:
4339   case X86::BI__builtin_ia32_vec_ext_v8si:
4340     i = 1; l = 0; u = 7;
4341     break;
4342   case X86::BI__builtin_ia32_sha1rnds4:
4343   case X86::BI__builtin_ia32_blendpd:
4344   case X86::BI__builtin_ia32_shufpd:
4345   case X86::BI__builtin_ia32_vec_set_v4hi:
4346   case X86::BI__builtin_ia32_vec_set_v4si:
4347   case X86::BI__builtin_ia32_vec_set_v4di:
4348   case X86::BI__builtin_ia32_shuf_f32x4_256:
4349   case X86::BI__builtin_ia32_shuf_f64x2_256:
4350   case X86::BI__builtin_ia32_shuf_i32x4_256:
4351   case X86::BI__builtin_ia32_shuf_i64x2_256:
4352   case X86::BI__builtin_ia32_insertf64x2_512:
4353   case X86::BI__builtin_ia32_inserti64x2_512:
4354   case X86::BI__builtin_ia32_insertf32x4:
4355   case X86::BI__builtin_ia32_inserti32x4:
4356     i = 2; l = 0; u = 3;
4357     break;
4358   case X86::BI__builtin_ia32_vpermil2pd:
4359   case X86::BI__builtin_ia32_vpermil2pd256:
4360   case X86::BI__builtin_ia32_vpermil2ps:
4361   case X86::BI__builtin_ia32_vpermil2ps256:
4362     i = 3; l = 0; u = 3;
4363     break;
4364   case X86::BI__builtin_ia32_cmpb128_mask:
4365   case X86::BI__builtin_ia32_cmpw128_mask:
4366   case X86::BI__builtin_ia32_cmpd128_mask:
4367   case X86::BI__builtin_ia32_cmpq128_mask:
4368   case X86::BI__builtin_ia32_cmpb256_mask:
4369   case X86::BI__builtin_ia32_cmpw256_mask:
4370   case X86::BI__builtin_ia32_cmpd256_mask:
4371   case X86::BI__builtin_ia32_cmpq256_mask:
4372   case X86::BI__builtin_ia32_cmpb512_mask:
4373   case X86::BI__builtin_ia32_cmpw512_mask:
4374   case X86::BI__builtin_ia32_cmpd512_mask:
4375   case X86::BI__builtin_ia32_cmpq512_mask:
4376   case X86::BI__builtin_ia32_ucmpb128_mask:
4377   case X86::BI__builtin_ia32_ucmpw128_mask:
4378   case X86::BI__builtin_ia32_ucmpd128_mask:
4379   case X86::BI__builtin_ia32_ucmpq128_mask:
4380   case X86::BI__builtin_ia32_ucmpb256_mask:
4381   case X86::BI__builtin_ia32_ucmpw256_mask:
4382   case X86::BI__builtin_ia32_ucmpd256_mask:
4383   case X86::BI__builtin_ia32_ucmpq256_mask:
4384   case X86::BI__builtin_ia32_ucmpb512_mask:
4385   case X86::BI__builtin_ia32_ucmpw512_mask:
4386   case X86::BI__builtin_ia32_ucmpd512_mask:
4387   case X86::BI__builtin_ia32_ucmpq512_mask:
4388   case X86::BI__builtin_ia32_vpcomub:
4389   case X86::BI__builtin_ia32_vpcomuw:
4390   case X86::BI__builtin_ia32_vpcomud:
4391   case X86::BI__builtin_ia32_vpcomuq:
4392   case X86::BI__builtin_ia32_vpcomb:
4393   case X86::BI__builtin_ia32_vpcomw:
4394   case X86::BI__builtin_ia32_vpcomd:
4395   case X86::BI__builtin_ia32_vpcomq:
4396   case X86::BI__builtin_ia32_vec_set_v8hi:
4397   case X86::BI__builtin_ia32_vec_set_v8si:
4398     i = 2; l = 0; u = 7;
4399     break;
4400   case X86::BI__builtin_ia32_vpermilpd256:
4401   case X86::BI__builtin_ia32_roundps:
4402   case X86::BI__builtin_ia32_roundpd:
4403   case X86::BI__builtin_ia32_roundps256:
4404   case X86::BI__builtin_ia32_roundpd256:
4405   case X86::BI__builtin_ia32_getmantpd128_mask:
4406   case X86::BI__builtin_ia32_getmantpd256_mask:
4407   case X86::BI__builtin_ia32_getmantps128_mask:
4408   case X86::BI__builtin_ia32_getmantps256_mask:
4409   case X86::BI__builtin_ia32_getmantpd512_mask:
4410   case X86::BI__builtin_ia32_getmantps512_mask:
4411   case X86::BI__builtin_ia32_getmantph128_mask:
4412   case X86::BI__builtin_ia32_getmantph256_mask:
4413   case X86::BI__builtin_ia32_getmantph512_mask:
4414   case X86::BI__builtin_ia32_vec_ext_v16qi:
4415   case X86::BI__builtin_ia32_vec_ext_v16hi:
4416     i = 1; l = 0; u = 15;
4417     break;
4418   case X86::BI__builtin_ia32_pblendd128:
4419   case X86::BI__builtin_ia32_blendps:
4420   case X86::BI__builtin_ia32_blendpd256:
4421   case X86::BI__builtin_ia32_shufpd256:
4422   case X86::BI__builtin_ia32_roundss:
4423   case X86::BI__builtin_ia32_roundsd:
4424   case X86::BI__builtin_ia32_rangepd128_mask:
4425   case X86::BI__builtin_ia32_rangepd256_mask:
4426   case X86::BI__builtin_ia32_rangepd512_mask:
4427   case X86::BI__builtin_ia32_rangeps128_mask:
4428   case X86::BI__builtin_ia32_rangeps256_mask:
4429   case X86::BI__builtin_ia32_rangeps512_mask:
4430   case X86::BI__builtin_ia32_getmantsd_round_mask:
4431   case X86::BI__builtin_ia32_getmantss_round_mask:
4432   case X86::BI__builtin_ia32_getmantsh_round_mask:
4433   case X86::BI__builtin_ia32_vec_set_v16qi:
4434   case X86::BI__builtin_ia32_vec_set_v16hi:
4435     i = 2; l = 0; u = 15;
4436     break;
4437   case X86::BI__builtin_ia32_vec_ext_v32qi:
4438     i = 1; l = 0; u = 31;
4439     break;
4440   case X86::BI__builtin_ia32_cmpps:
4441   case X86::BI__builtin_ia32_cmpss:
4442   case X86::BI__builtin_ia32_cmppd:
4443   case X86::BI__builtin_ia32_cmpsd:
4444   case X86::BI__builtin_ia32_cmpps256:
4445   case X86::BI__builtin_ia32_cmppd256:
4446   case X86::BI__builtin_ia32_cmpps128_mask:
4447   case X86::BI__builtin_ia32_cmppd128_mask:
4448   case X86::BI__builtin_ia32_cmpps256_mask:
4449   case X86::BI__builtin_ia32_cmppd256_mask:
4450   case X86::BI__builtin_ia32_cmpps512_mask:
4451   case X86::BI__builtin_ia32_cmppd512_mask:
4452   case X86::BI__builtin_ia32_cmpsd_mask:
4453   case X86::BI__builtin_ia32_cmpss_mask:
4454   case X86::BI__builtin_ia32_vec_set_v32qi:
4455     i = 2; l = 0; u = 31;
4456     break;
4457   case X86::BI__builtin_ia32_permdf256:
4458   case X86::BI__builtin_ia32_permdi256:
4459   case X86::BI__builtin_ia32_permdf512:
4460   case X86::BI__builtin_ia32_permdi512:
4461   case X86::BI__builtin_ia32_vpermilps:
4462   case X86::BI__builtin_ia32_vpermilps256:
4463   case X86::BI__builtin_ia32_vpermilpd512:
4464   case X86::BI__builtin_ia32_vpermilps512:
4465   case X86::BI__builtin_ia32_pshufd:
4466   case X86::BI__builtin_ia32_pshufd256:
4467   case X86::BI__builtin_ia32_pshufd512:
4468   case X86::BI__builtin_ia32_pshufhw:
4469   case X86::BI__builtin_ia32_pshufhw256:
4470   case X86::BI__builtin_ia32_pshufhw512:
4471   case X86::BI__builtin_ia32_pshuflw:
4472   case X86::BI__builtin_ia32_pshuflw256:
4473   case X86::BI__builtin_ia32_pshuflw512:
4474   case X86::BI__builtin_ia32_vcvtps2ph:
4475   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4476   case X86::BI__builtin_ia32_vcvtps2ph256:
4477   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4478   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4479   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4480   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4481   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4482   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4483   case X86::BI__builtin_ia32_rndscaleps_mask:
4484   case X86::BI__builtin_ia32_rndscalepd_mask:
4485   case X86::BI__builtin_ia32_rndscaleph_mask:
4486   case X86::BI__builtin_ia32_reducepd128_mask:
4487   case X86::BI__builtin_ia32_reducepd256_mask:
4488   case X86::BI__builtin_ia32_reducepd512_mask:
4489   case X86::BI__builtin_ia32_reduceps128_mask:
4490   case X86::BI__builtin_ia32_reduceps256_mask:
4491   case X86::BI__builtin_ia32_reduceps512_mask:
4492   case X86::BI__builtin_ia32_reduceph128_mask:
4493   case X86::BI__builtin_ia32_reduceph256_mask:
4494   case X86::BI__builtin_ia32_reduceph512_mask:
4495   case X86::BI__builtin_ia32_prold512:
4496   case X86::BI__builtin_ia32_prolq512:
4497   case X86::BI__builtin_ia32_prold128:
4498   case X86::BI__builtin_ia32_prold256:
4499   case X86::BI__builtin_ia32_prolq128:
4500   case X86::BI__builtin_ia32_prolq256:
4501   case X86::BI__builtin_ia32_prord512:
4502   case X86::BI__builtin_ia32_prorq512:
4503   case X86::BI__builtin_ia32_prord128:
4504   case X86::BI__builtin_ia32_prord256:
4505   case X86::BI__builtin_ia32_prorq128:
4506   case X86::BI__builtin_ia32_prorq256:
4507   case X86::BI__builtin_ia32_fpclasspd128_mask:
4508   case X86::BI__builtin_ia32_fpclasspd256_mask:
4509   case X86::BI__builtin_ia32_fpclassps128_mask:
4510   case X86::BI__builtin_ia32_fpclassps256_mask:
4511   case X86::BI__builtin_ia32_fpclassps512_mask:
4512   case X86::BI__builtin_ia32_fpclasspd512_mask:
4513   case X86::BI__builtin_ia32_fpclassph128_mask:
4514   case X86::BI__builtin_ia32_fpclassph256_mask:
4515   case X86::BI__builtin_ia32_fpclassph512_mask:
4516   case X86::BI__builtin_ia32_fpclasssd_mask:
4517   case X86::BI__builtin_ia32_fpclassss_mask:
4518   case X86::BI__builtin_ia32_fpclasssh_mask:
4519   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4520   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4521   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4522   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4523   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4524   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4525   case X86::BI__builtin_ia32_kshiftliqi:
4526   case X86::BI__builtin_ia32_kshiftlihi:
4527   case X86::BI__builtin_ia32_kshiftlisi:
4528   case X86::BI__builtin_ia32_kshiftlidi:
4529   case X86::BI__builtin_ia32_kshiftriqi:
4530   case X86::BI__builtin_ia32_kshiftrihi:
4531   case X86::BI__builtin_ia32_kshiftrisi:
4532   case X86::BI__builtin_ia32_kshiftridi:
4533     i = 1; l = 0; u = 255;
4534     break;
4535   case X86::BI__builtin_ia32_vperm2f128_pd256:
4536   case X86::BI__builtin_ia32_vperm2f128_ps256:
4537   case X86::BI__builtin_ia32_vperm2f128_si256:
4538   case X86::BI__builtin_ia32_permti256:
4539   case X86::BI__builtin_ia32_pblendw128:
4540   case X86::BI__builtin_ia32_pblendw256:
4541   case X86::BI__builtin_ia32_blendps256:
4542   case X86::BI__builtin_ia32_pblendd256:
4543   case X86::BI__builtin_ia32_palignr128:
4544   case X86::BI__builtin_ia32_palignr256:
4545   case X86::BI__builtin_ia32_palignr512:
4546   case X86::BI__builtin_ia32_alignq512:
4547   case X86::BI__builtin_ia32_alignd512:
4548   case X86::BI__builtin_ia32_alignd128:
4549   case X86::BI__builtin_ia32_alignd256:
4550   case X86::BI__builtin_ia32_alignq128:
4551   case X86::BI__builtin_ia32_alignq256:
4552   case X86::BI__builtin_ia32_vcomisd:
4553   case X86::BI__builtin_ia32_vcomiss:
4554   case X86::BI__builtin_ia32_shuf_f32x4:
4555   case X86::BI__builtin_ia32_shuf_f64x2:
4556   case X86::BI__builtin_ia32_shuf_i32x4:
4557   case X86::BI__builtin_ia32_shuf_i64x2:
4558   case X86::BI__builtin_ia32_shufpd512:
4559   case X86::BI__builtin_ia32_shufps:
4560   case X86::BI__builtin_ia32_shufps256:
4561   case X86::BI__builtin_ia32_shufps512:
4562   case X86::BI__builtin_ia32_dbpsadbw128:
4563   case X86::BI__builtin_ia32_dbpsadbw256:
4564   case X86::BI__builtin_ia32_dbpsadbw512:
4565   case X86::BI__builtin_ia32_vpshldd128:
4566   case X86::BI__builtin_ia32_vpshldd256:
4567   case X86::BI__builtin_ia32_vpshldd512:
4568   case X86::BI__builtin_ia32_vpshldq128:
4569   case X86::BI__builtin_ia32_vpshldq256:
4570   case X86::BI__builtin_ia32_vpshldq512:
4571   case X86::BI__builtin_ia32_vpshldw128:
4572   case X86::BI__builtin_ia32_vpshldw256:
4573   case X86::BI__builtin_ia32_vpshldw512:
4574   case X86::BI__builtin_ia32_vpshrdd128:
4575   case X86::BI__builtin_ia32_vpshrdd256:
4576   case X86::BI__builtin_ia32_vpshrdd512:
4577   case X86::BI__builtin_ia32_vpshrdq128:
4578   case X86::BI__builtin_ia32_vpshrdq256:
4579   case X86::BI__builtin_ia32_vpshrdq512:
4580   case X86::BI__builtin_ia32_vpshrdw128:
4581   case X86::BI__builtin_ia32_vpshrdw256:
4582   case X86::BI__builtin_ia32_vpshrdw512:
4583     i = 2; l = 0; u = 255;
4584     break;
4585   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4586   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4587   case X86::BI__builtin_ia32_fixupimmps512_mask:
4588   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4589   case X86::BI__builtin_ia32_fixupimmsd_mask:
4590   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4591   case X86::BI__builtin_ia32_fixupimmss_mask:
4592   case X86::BI__builtin_ia32_fixupimmss_maskz:
4593   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4594   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4595   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4596   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4597   case X86::BI__builtin_ia32_fixupimmps128_mask:
4598   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4599   case X86::BI__builtin_ia32_fixupimmps256_mask:
4600   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4601   case X86::BI__builtin_ia32_pternlogd512_mask:
4602   case X86::BI__builtin_ia32_pternlogd512_maskz:
4603   case X86::BI__builtin_ia32_pternlogq512_mask:
4604   case X86::BI__builtin_ia32_pternlogq512_maskz:
4605   case X86::BI__builtin_ia32_pternlogd128_mask:
4606   case X86::BI__builtin_ia32_pternlogd128_maskz:
4607   case X86::BI__builtin_ia32_pternlogd256_mask:
4608   case X86::BI__builtin_ia32_pternlogd256_maskz:
4609   case X86::BI__builtin_ia32_pternlogq128_mask:
4610   case X86::BI__builtin_ia32_pternlogq128_maskz:
4611   case X86::BI__builtin_ia32_pternlogq256_mask:
4612   case X86::BI__builtin_ia32_pternlogq256_maskz:
4613     i = 3; l = 0; u = 255;
4614     break;
4615   case X86::BI__builtin_ia32_gatherpfdpd:
4616   case X86::BI__builtin_ia32_gatherpfdps:
4617   case X86::BI__builtin_ia32_gatherpfqpd:
4618   case X86::BI__builtin_ia32_gatherpfqps:
4619   case X86::BI__builtin_ia32_scatterpfdpd:
4620   case X86::BI__builtin_ia32_scatterpfdps:
4621   case X86::BI__builtin_ia32_scatterpfqpd:
4622   case X86::BI__builtin_ia32_scatterpfqps:
4623     i = 4; l = 2; u = 3;
4624     break;
4625   case X86::BI__builtin_ia32_reducesd_mask:
4626   case X86::BI__builtin_ia32_reducess_mask:
4627   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4628   case X86::BI__builtin_ia32_rndscaless_round_mask:
4629   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4630   case X86::BI__builtin_ia32_reducesh_mask:
4631     i = 4; l = 0; u = 255;
4632     break;
4633   }
4634 
4635   // Note that we don't force a hard error on the range check here, allowing
4636   // template-generated or macro-generated dead code to potentially have out-of-
4637   // range values. These need to code generate, but don't need to necessarily
4638   // make any sense. We use a warning that defaults to an error.
4639   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4640 }
4641 
4642 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4643 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4644 /// Returns true when the format fits the function and the FormatStringInfo has
4645 /// been populated.
4646 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4647                                FormatStringInfo *FSI) {
4648   FSI->HasVAListArg = Format->getFirstArg() == 0;
4649   FSI->FormatIdx = Format->getFormatIdx() - 1;
4650   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4651 
4652   // The way the format attribute works in GCC, the implicit this argument
4653   // of member functions is counted. However, it doesn't appear in our own
4654   // lists, so decrement format_idx in that case.
4655   if (IsCXXMember) {
4656     if(FSI->FormatIdx == 0)
4657       return false;
4658     --FSI->FormatIdx;
4659     if (FSI->FirstDataArg != 0)
4660       --FSI->FirstDataArg;
4661   }
4662   return true;
4663 }
4664 
4665 /// Checks if a the given expression evaluates to null.
4666 ///
4667 /// Returns true if the value evaluates to null.
4668 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4669   // If the expression has non-null type, it doesn't evaluate to null.
4670   if (auto nullability
4671         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4672     if (*nullability == NullabilityKind::NonNull)
4673       return false;
4674   }
4675 
4676   // As a special case, transparent unions initialized with zero are
4677   // considered null for the purposes of the nonnull attribute.
4678   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4679     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4680       if (const CompoundLiteralExpr *CLE =
4681           dyn_cast<CompoundLiteralExpr>(Expr))
4682         if (const InitListExpr *ILE =
4683             dyn_cast<InitListExpr>(CLE->getInitializer()))
4684           Expr = ILE->getInit(0);
4685   }
4686 
4687   bool Result;
4688   return (!Expr->isValueDependent() &&
4689           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4690           !Result);
4691 }
4692 
4693 static void CheckNonNullArgument(Sema &S,
4694                                  const Expr *ArgExpr,
4695                                  SourceLocation CallSiteLoc) {
4696   if (CheckNonNullExpr(S, ArgExpr))
4697     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4698                           S.PDiag(diag::warn_null_arg)
4699                               << ArgExpr->getSourceRange());
4700 }
4701 
4702 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4703   FormatStringInfo FSI;
4704   if ((GetFormatStringType(Format) == FST_NSString) &&
4705       getFormatStringInfo(Format, false, &FSI)) {
4706     Idx = FSI.FormatIdx;
4707     return true;
4708   }
4709   return false;
4710 }
4711 
4712 /// Diagnose use of %s directive in an NSString which is being passed
4713 /// as formatting string to formatting method.
4714 static void
4715 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4716                                         const NamedDecl *FDecl,
4717                                         Expr **Args,
4718                                         unsigned NumArgs) {
4719   unsigned Idx = 0;
4720   bool Format = false;
4721   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4722   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4723     Idx = 2;
4724     Format = true;
4725   }
4726   else
4727     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4728       if (S.GetFormatNSStringIdx(I, Idx)) {
4729         Format = true;
4730         break;
4731       }
4732     }
4733   if (!Format || NumArgs <= Idx)
4734     return;
4735   const Expr *FormatExpr = Args[Idx];
4736   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4737     FormatExpr = CSCE->getSubExpr();
4738   const StringLiteral *FormatString;
4739   if (const ObjCStringLiteral *OSL =
4740       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4741     FormatString = OSL->getString();
4742   else
4743     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4744   if (!FormatString)
4745     return;
4746   if (S.FormatStringHasSArg(FormatString)) {
4747     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4748       << "%s" << 1 << 1;
4749     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4750       << FDecl->getDeclName();
4751   }
4752 }
4753 
4754 /// Determine whether the given type has a non-null nullability annotation.
4755 static bool isNonNullType(ASTContext &ctx, QualType type) {
4756   if (auto nullability = type->getNullability(ctx))
4757     return *nullability == NullabilityKind::NonNull;
4758 
4759   return false;
4760 }
4761 
4762 static void CheckNonNullArguments(Sema &S,
4763                                   const NamedDecl *FDecl,
4764                                   const FunctionProtoType *Proto,
4765                                   ArrayRef<const Expr *> Args,
4766                                   SourceLocation CallSiteLoc) {
4767   assert((FDecl || Proto) && "Need a function declaration or prototype");
4768 
4769   // Already checked by by constant evaluator.
4770   if (S.isConstantEvaluated())
4771     return;
4772   // Check the attributes attached to the method/function itself.
4773   llvm::SmallBitVector NonNullArgs;
4774   if (FDecl) {
4775     // Handle the nonnull attribute on the function/method declaration itself.
4776     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4777       if (!NonNull->args_size()) {
4778         // Easy case: all pointer arguments are nonnull.
4779         for (const auto *Arg : Args)
4780           if (S.isValidPointerAttrType(Arg->getType()))
4781             CheckNonNullArgument(S, Arg, CallSiteLoc);
4782         return;
4783       }
4784 
4785       for (const ParamIdx &Idx : NonNull->args()) {
4786         unsigned IdxAST = Idx.getASTIndex();
4787         if (IdxAST >= Args.size())
4788           continue;
4789         if (NonNullArgs.empty())
4790           NonNullArgs.resize(Args.size());
4791         NonNullArgs.set(IdxAST);
4792       }
4793     }
4794   }
4795 
4796   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4797     // Handle the nonnull attribute on the parameters of the
4798     // function/method.
4799     ArrayRef<ParmVarDecl*> parms;
4800     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4801       parms = FD->parameters();
4802     else
4803       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4804 
4805     unsigned ParamIndex = 0;
4806     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4807          I != E; ++I, ++ParamIndex) {
4808       const ParmVarDecl *PVD = *I;
4809       if (PVD->hasAttr<NonNullAttr>() ||
4810           isNonNullType(S.Context, PVD->getType())) {
4811         if (NonNullArgs.empty())
4812           NonNullArgs.resize(Args.size());
4813 
4814         NonNullArgs.set(ParamIndex);
4815       }
4816     }
4817   } else {
4818     // If we have a non-function, non-method declaration but no
4819     // function prototype, try to dig out the function prototype.
4820     if (!Proto) {
4821       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4822         QualType type = VD->getType().getNonReferenceType();
4823         if (auto pointerType = type->getAs<PointerType>())
4824           type = pointerType->getPointeeType();
4825         else if (auto blockType = type->getAs<BlockPointerType>())
4826           type = blockType->getPointeeType();
4827         // FIXME: data member pointers?
4828 
4829         // Dig out the function prototype, if there is one.
4830         Proto = type->getAs<FunctionProtoType>();
4831       }
4832     }
4833 
4834     // Fill in non-null argument information from the nullability
4835     // information on the parameter types (if we have them).
4836     if (Proto) {
4837       unsigned Index = 0;
4838       for (auto paramType : Proto->getParamTypes()) {
4839         if (isNonNullType(S.Context, paramType)) {
4840           if (NonNullArgs.empty())
4841             NonNullArgs.resize(Args.size());
4842 
4843           NonNullArgs.set(Index);
4844         }
4845 
4846         ++Index;
4847       }
4848     }
4849   }
4850 
4851   // Check for non-null arguments.
4852   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4853        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4854     if (NonNullArgs[ArgIndex])
4855       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4856   }
4857 }
4858 
4859 /// Warn if a pointer or reference argument passed to a function points to an
4860 /// object that is less aligned than the parameter. This can happen when
4861 /// creating a typedef with a lower alignment than the original type and then
4862 /// calling functions defined in terms of the original type.
4863 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4864                              StringRef ParamName, QualType ArgTy,
4865                              QualType ParamTy) {
4866 
4867   // If a function accepts a pointer or reference type
4868   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4869     return;
4870 
4871   // If the parameter is a pointer type, get the pointee type for the
4872   // argument too. If the parameter is a reference type, don't try to get
4873   // the pointee type for the argument.
4874   if (ParamTy->isPointerType())
4875     ArgTy = ArgTy->getPointeeType();
4876 
4877   // Remove reference or pointer
4878   ParamTy = ParamTy->getPointeeType();
4879 
4880   // Find expected alignment, and the actual alignment of the passed object.
4881   // getTypeAlignInChars requires complete types
4882   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4883       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4884       ArgTy->isUndeducedType())
4885     return;
4886 
4887   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4888   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4889 
4890   // If the argument is less aligned than the parameter, there is a
4891   // potential alignment issue.
4892   if (ArgAlign < ParamAlign)
4893     Diag(Loc, diag::warn_param_mismatched_alignment)
4894         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4895         << ParamName << (FDecl != nullptr) << FDecl;
4896 }
4897 
4898 /// Handles the checks for format strings, non-POD arguments to vararg
4899 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4900 /// attributes.
4901 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4902                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4903                      bool IsMemberFunction, SourceLocation Loc,
4904                      SourceRange Range, VariadicCallType CallType) {
4905   // FIXME: We should check as much as we can in the template definition.
4906   if (CurContext->isDependentContext())
4907     return;
4908 
4909   // Printf and scanf checking.
4910   llvm::SmallBitVector CheckedVarArgs;
4911   if (FDecl) {
4912     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4913       // Only create vector if there are format attributes.
4914       CheckedVarArgs.resize(Args.size());
4915 
4916       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4917                            CheckedVarArgs);
4918     }
4919   }
4920 
4921   // Refuse POD arguments that weren't caught by the format string
4922   // checks above.
4923   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4924   if (CallType != VariadicDoesNotApply &&
4925       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4926     unsigned NumParams = Proto ? Proto->getNumParams()
4927                        : FDecl && isa<FunctionDecl>(FDecl)
4928                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4929                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4930                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4931                        : 0;
4932 
4933     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4934       // Args[ArgIdx] can be null in malformed code.
4935       if (const Expr *Arg = Args[ArgIdx]) {
4936         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4937           checkVariadicArgument(Arg, CallType);
4938       }
4939     }
4940   }
4941 
4942   if (FDecl || Proto) {
4943     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4944 
4945     // Type safety checking.
4946     if (FDecl) {
4947       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4948         CheckArgumentWithTypeTag(I, Args, Loc);
4949     }
4950   }
4951 
4952   // Check that passed arguments match the alignment of original arguments.
4953   // Try to get the missing prototype from the declaration.
4954   if (!Proto && FDecl) {
4955     const auto *FT = FDecl->getFunctionType();
4956     if (isa_and_nonnull<FunctionProtoType>(FT))
4957       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4958   }
4959   if (Proto) {
4960     // For variadic functions, we may have more args than parameters.
4961     // For some K&R functions, we may have less args than parameters.
4962     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4963     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4964       // Args[ArgIdx] can be null in malformed code.
4965       if (const Expr *Arg = Args[ArgIdx]) {
4966         if (Arg->containsErrors())
4967           continue;
4968 
4969         QualType ParamTy = Proto->getParamType(ArgIdx);
4970         QualType ArgTy = Arg->getType();
4971         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4972                           ArgTy, ParamTy);
4973       }
4974     }
4975   }
4976 
4977   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4978     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4979     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4980     if (!Arg->isValueDependent()) {
4981       Expr::EvalResult Align;
4982       if (Arg->EvaluateAsInt(Align, Context)) {
4983         const llvm::APSInt &I = Align.Val.getInt();
4984         if (!I.isPowerOf2())
4985           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4986               << Arg->getSourceRange();
4987 
4988         if (I > Sema::MaximumAlignment)
4989           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4990               << Arg->getSourceRange() << Sema::MaximumAlignment;
4991       }
4992     }
4993   }
4994 
4995   if (FD)
4996     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4997 }
4998 
4999 /// CheckConstructorCall - Check a constructor call for correctness and safety
5000 /// properties not enforced by the C type system.
5001 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5002                                 ArrayRef<const Expr *> Args,
5003                                 const FunctionProtoType *Proto,
5004                                 SourceLocation Loc) {
5005   VariadicCallType CallType =
5006       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5007 
5008   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5009   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5010                     Context.getPointerType(Ctor->getThisObjectType()));
5011 
5012   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5013             Loc, SourceRange(), CallType);
5014 }
5015 
5016 /// CheckFunctionCall - Check a direct function call for various correctness
5017 /// and safety properties not strictly enforced by the C type system.
5018 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5019                              const FunctionProtoType *Proto) {
5020   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5021                               isa<CXXMethodDecl>(FDecl);
5022   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5023                           IsMemberOperatorCall;
5024   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5025                                                   TheCall->getCallee());
5026   Expr** Args = TheCall->getArgs();
5027   unsigned NumArgs = TheCall->getNumArgs();
5028 
5029   Expr *ImplicitThis = nullptr;
5030   if (IsMemberOperatorCall) {
5031     // If this is a call to a member operator, hide the first argument
5032     // from checkCall.
5033     // FIXME: Our choice of AST representation here is less than ideal.
5034     ImplicitThis = Args[0];
5035     ++Args;
5036     --NumArgs;
5037   } else if (IsMemberFunction)
5038     ImplicitThis =
5039         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5040 
5041   if (ImplicitThis) {
5042     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5043     // used.
5044     QualType ThisType = ImplicitThis->getType();
5045     if (!ThisType->isPointerType()) {
5046       assert(!ThisType->isReferenceType());
5047       ThisType = Context.getPointerType(ThisType);
5048     }
5049 
5050     QualType ThisTypeFromDecl =
5051         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5052 
5053     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5054                       ThisTypeFromDecl);
5055   }
5056 
5057   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5058             IsMemberFunction, TheCall->getRParenLoc(),
5059             TheCall->getCallee()->getSourceRange(), CallType);
5060 
5061   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5062   // None of the checks below are needed for functions that don't have
5063   // simple names (e.g., C++ conversion functions).
5064   if (!FnInfo)
5065     return false;
5066 
5067   CheckTCBEnforcement(TheCall, FDecl);
5068 
5069   CheckAbsoluteValueFunction(TheCall, FDecl);
5070   CheckMaxUnsignedZero(TheCall, FDecl);
5071 
5072   if (getLangOpts().ObjC)
5073     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5074 
5075   unsigned CMId = FDecl->getMemoryFunctionKind();
5076 
5077   // Handle memory setting and copying functions.
5078   switch (CMId) {
5079   case 0:
5080     return false;
5081   case Builtin::BIstrlcpy: // fallthrough
5082   case Builtin::BIstrlcat:
5083     CheckStrlcpycatArguments(TheCall, FnInfo);
5084     break;
5085   case Builtin::BIstrncat:
5086     CheckStrncatArguments(TheCall, FnInfo);
5087     break;
5088   case Builtin::BIfree:
5089     CheckFreeArguments(TheCall);
5090     break;
5091   default:
5092     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5093   }
5094 
5095   return false;
5096 }
5097 
5098 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5099                                ArrayRef<const Expr *> Args) {
5100   VariadicCallType CallType =
5101       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5102 
5103   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5104             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5105             CallType);
5106 
5107   return false;
5108 }
5109 
5110 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5111                             const FunctionProtoType *Proto) {
5112   QualType Ty;
5113   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5114     Ty = V->getType().getNonReferenceType();
5115   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5116     Ty = F->getType().getNonReferenceType();
5117   else
5118     return false;
5119 
5120   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5121       !Ty->isFunctionProtoType())
5122     return false;
5123 
5124   VariadicCallType CallType;
5125   if (!Proto || !Proto->isVariadic()) {
5126     CallType = VariadicDoesNotApply;
5127   } else if (Ty->isBlockPointerType()) {
5128     CallType = VariadicBlock;
5129   } else { // Ty->isFunctionPointerType()
5130     CallType = VariadicFunction;
5131   }
5132 
5133   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5134             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5135             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5136             TheCall->getCallee()->getSourceRange(), CallType);
5137 
5138   return false;
5139 }
5140 
5141 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5142 /// such as function pointers returned from functions.
5143 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5144   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5145                                                   TheCall->getCallee());
5146   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5147             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5148             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5149             TheCall->getCallee()->getSourceRange(), CallType);
5150 
5151   return false;
5152 }
5153 
5154 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5155   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5156     return false;
5157 
5158   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5159   switch (Op) {
5160   case AtomicExpr::AO__c11_atomic_init:
5161   case AtomicExpr::AO__opencl_atomic_init:
5162     llvm_unreachable("There is no ordering argument for an init");
5163 
5164   case AtomicExpr::AO__c11_atomic_load:
5165   case AtomicExpr::AO__opencl_atomic_load:
5166   case AtomicExpr::AO__atomic_load_n:
5167   case AtomicExpr::AO__atomic_load:
5168     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5169            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5170 
5171   case AtomicExpr::AO__c11_atomic_store:
5172   case AtomicExpr::AO__opencl_atomic_store:
5173   case AtomicExpr::AO__atomic_store:
5174   case AtomicExpr::AO__atomic_store_n:
5175     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5176            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5177            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5178 
5179   default:
5180     return true;
5181   }
5182 }
5183 
5184 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5185                                          AtomicExpr::AtomicOp Op) {
5186   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5187   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5188   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5189   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5190                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5191                          Op);
5192 }
5193 
5194 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5195                                  SourceLocation RParenLoc, MultiExprArg Args,
5196                                  AtomicExpr::AtomicOp Op,
5197                                  AtomicArgumentOrder ArgOrder) {
5198   // All the non-OpenCL operations take one of the following forms.
5199   // The OpenCL operations take the __c11 forms with one extra argument for
5200   // synchronization scope.
5201   enum {
5202     // C    __c11_atomic_init(A *, C)
5203     Init,
5204 
5205     // C    __c11_atomic_load(A *, int)
5206     Load,
5207 
5208     // void __atomic_load(A *, CP, int)
5209     LoadCopy,
5210 
5211     // void __atomic_store(A *, CP, int)
5212     Copy,
5213 
5214     // C    __c11_atomic_add(A *, M, int)
5215     Arithmetic,
5216 
5217     // C    __atomic_exchange_n(A *, CP, int)
5218     Xchg,
5219 
5220     // void __atomic_exchange(A *, C *, CP, int)
5221     GNUXchg,
5222 
5223     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5224     C11CmpXchg,
5225 
5226     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5227     GNUCmpXchg
5228   } Form = Init;
5229 
5230   const unsigned NumForm = GNUCmpXchg + 1;
5231   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5232   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5233   // where:
5234   //   C is an appropriate type,
5235   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5236   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5237   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5238   //   the int parameters are for orderings.
5239 
5240   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5241       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5242       "need to update code for modified forms");
5243   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5244                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5245                         AtomicExpr::AO__atomic_load,
5246                 "need to update code for modified C11 atomics");
5247   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5248                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5249   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5250                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5251                IsOpenCL;
5252   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5253              Op == AtomicExpr::AO__atomic_store_n ||
5254              Op == AtomicExpr::AO__atomic_exchange_n ||
5255              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5256   bool IsAddSub = false;
5257 
5258   switch (Op) {
5259   case AtomicExpr::AO__c11_atomic_init:
5260   case AtomicExpr::AO__opencl_atomic_init:
5261     Form = Init;
5262     break;
5263 
5264   case AtomicExpr::AO__c11_atomic_load:
5265   case AtomicExpr::AO__opencl_atomic_load:
5266   case AtomicExpr::AO__atomic_load_n:
5267     Form = Load;
5268     break;
5269 
5270   case AtomicExpr::AO__atomic_load:
5271     Form = LoadCopy;
5272     break;
5273 
5274   case AtomicExpr::AO__c11_atomic_store:
5275   case AtomicExpr::AO__opencl_atomic_store:
5276   case AtomicExpr::AO__atomic_store:
5277   case AtomicExpr::AO__atomic_store_n:
5278     Form = Copy;
5279     break;
5280 
5281   case AtomicExpr::AO__c11_atomic_fetch_add:
5282   case AtomicExpr::AO__c11_atomic_fetch_sub:
5283   case AtomicExpr::AO__opencl_atomic_fetch_add:
5284   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5285   case AtomicExpr::AO__atomic_fetch_add:
5286   case AtomicExpr::AO__atomic_fetch_sub:
5287   case AtomicExpr::AO__atomic_add_fetch:
5288   case AtomicExpr::AO__atomic_sub_fetch:
5289     IsAddSub = true;
5290     Form = Arithmetic;
5291     break;
5292   case AtomicExpr::AO__c11_atomic_fetch_and:
5293   case AtomicExpr::AO__c11_atomic_fetch_or:
5294   case AtomicExpr::AO__c11_atomic_fetch_xor:
5295   case AtomicExpr::AO__c11_atomic_fetch_nand:
5296   case AtomicExpr::AO__opencl_atomic_fetch_and:
5297   case AtomicExpr::AO__opencl_atomic_fetch_or:
5298   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5299   case AtomicExpr::AO__atomic_fetch_and:
5300   case AtomicExpr::AO__atomic_fetch_or:
5301   case AtomicExpr::AO__atomic_fetch_xor:
5302   case AtomicExpr::AO__atomic_fetch_nand:
5303   case AtomicExpr::AO__atomic_and_fetch:
5304   case AtomicExpr::AO__atomic_or_fetch:
5305   case AtomicExpr::AO__atomic_xor_fetch:
5306   case AtomicExpr::AO__atomic_nand_fetch:
5307     Form = Arithmetic;
5308     break;
5309   case AtomicExpr::AO__c11_atomic_fetch_min:
5310   case AtomicExpr::AO__c11_atomic_fetch_max:
5311   case AtomicExpr::AO__opencl_atomic_fetch_min:
5312   case AtomicExpr::AO__opencl_atomic_fetch_max:
5313   case AtomicExpr::AO__atomic_min_fetch:
5314   case AtomicExpr::AO__atomic_max_fetch:
5315   case AtomicExpr::AO__atomic_fetch_min:
5316   case AtomicExpr::AO__atomic_fetch_max:
5317     Form = Arithmetic;
5318     break;
5319 
5320   case AtomicExpr::AO__c11_atomic_exchange:
5321   case AtomicExpr::AO__opencl_atomic_exchange:
5322   case AtomicExpr::AO__atomic_exchange_n:
5323     Form = Xchg;
5324     break;
5325 
5326   case AtomicExpr::AO__atomic_exchange:
5327     Form = GNUXchg;
5328     break;
5329 
5330   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5331   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5332   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5333   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5334     Form = C11CmpXchg;
5335     break;
5336 
5337   case AtomicExpr::AO__atomic_compare_exchange:
5338   case AtomicExpr::AO__atomic_compare_exchange_n:
5339     Form = GNUCmpXchg;
5340     break;
5341   }
5342 
5343   unsigned AdjustedNumArgs = NumArgs[Form];
5344   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5345     ++AdjustedNumArgs;
5346   // Check we have the right number of arguments.
5347   if (Args.size() < AdjustedNumArgs) {
5348     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5349         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5350         << ExprRange;
5351     return ExprError();
5352   } else if (Args.size() > AdjustedNumArgs) {
5353     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5354          diag::err_typecheck_call_too_many_args)
5355         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5356         << ExprRange;
5357     return ExprError();
5358   }
5359 
5360   // Inspect the first argument of the atomic operation.
5361   Expr *Ptr = Args[0];
5362   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5363   if (ConvertedPtr.isInvalid())
5364     return ExprError();
5365 
5366   Ptr = ConvertedPtr.get();
5367   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5368   if (!pointerType) {
5369     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5370         << Ptr->getType() << Ptr->getSourceRange();
5371     return ExprError();
5372   }
5373 
5374   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5375   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5376   QualType ValType = AtomTy; // 'C'
5377   if (IsC11) {
5378     if (!AtomTy->isAtomicType()) {
5379       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5380           << Ptr->getType() << Ptr->getSourceRange();
5381       return ExprError();
5382     }
5383     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5384         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5385       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5386           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5387           << Ptr->getSourceRange();
5388       return ExprError();
5389     }
5390     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5391   } else if (Form != Load && Form != LoadCopy) {
5392     if (ValType.isConstQualified()) {
5393       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5394           << Ptr->getType() << Ptr->getSourceRange();
5395       return ExprError();
5396     }
5397   }
5398 
5399   // For an arithmetic operation, the implied arithmetic must be well-formed.
5400   if (Form == Arithmetic) {
5401     // gcc does not enforce these rules for GNU atomics, but we do so for
5402     // sanity.
5403     auto IsAllowedValueType = [&](QualType ValType) {
5404       if (ValType->isIntegerType())
5405         return true;
5406       if (ValType->isPointerType())
5407         return true;
5408       if (!ValType->isFloatingType())
5409         return false;
5410       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5411       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5412           &Context.getTargetInfo().getLongDoubleFormat() ==
5413               &llvm::APFloat::x87DoubleExtended())
5414         return false;
5415       return true;
5416     };
5417     if (IsAddSub && !IsAllowedValueType(ValType)) {
5418       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5419           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5420       return ExprError();
5421     }
5422     if (!IsAddSub && !ValType->isIntegerType()) {
5423       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5424           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5425       return ExprError();
5426     }
5427     if (IsC11 && ValType->isPointerType() &&
5428         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5429                             diag::err_incomplete_type)) {
5430       return ExprError();
5431     }
5432   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5433     // For __atomic_*_n operations, the value type must be a scalar integral or
5434     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5435     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5436         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5437     return ExprError();
5438   }
5439 
5440   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5441       !AtomTy->isScalarType()) {
5442     // For GNU atomics, require a trivially-copyable type. This is not part of
5443     // the GNU atomics specification, but we enforce it for sanity.
5444     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5445         << Ptr->getType() << Ptr->getSourceRange();
5446     return ExprError();
5447   }
5448 
5449   switch (ValType.getObjCLifetime()) {
5450   case Qualifiers::OCL_None:
5451   case Qualifiers::OCL_ExplicitNone:
5452     // okay
5453     break;
5454 
5455   case Qualifiers::OCL_Weak:
5456   case Qualifiers::OCL_Strong:
5457   case Qualifiers::OCL_Autoreleasing:
5458     // FIXME: Can this happen? By this point, ValType should be known
5459     // to be trivially copyable.
5460     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5461         << ValType << Ptr->getSourceRange();
5462     return ExprError();
5463   }
5464 
5465   // All atomic operations have an overload which takes a pointer to a volatile
5466   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5467   // into the result or the other operands. Similarly atomic_load takes a
5468   // pointer to a const 'A'.
5469   ValType.removeLocalVolatile();
5470   ValType.removeLocalConst();
5471   QualType ResultType = ValType;
5472   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5473       Form == Init)
5474     ResultType = Context.VoidTy;
5475   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5476     ResultType = Context.BoolTy;
5477 
5478   // The type of a parameter passed 'by value'. In the GNU atomics, such
5479   // arguments are actually passed as pointers.
5480   QualType ByValType = ValType; // 'CP'
5481   bool IsPassedByAddress = false;
5482   if (!IsC11 && !IsN) {
5483     ByValType = Ptr->getType();
5484     IsPassedByAddress = true;
5485   }
5486 
5487   SmallVector<Expr *, 5> APIOrderedArgs;
5488   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5489     APIOrderedArgs.push_back(Args[0]);
5490     switch (Form) {
5491     case Init:
5492     case Load:
5493       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5494       break;
5495     case LoadCopy:
5496     case Copy:
5497     case Arithmetic:
5498     case Xchg:
5499       APIOrderedArgs.push_back(Args[2]); // Val1
5500       APIOrderedArgs.push_back(Args[1]); // Order
5501       break;
5502     case GNUXchg:
5503       APIOrderedArgs.push_back(Args[2]); // Val1
5504       APIOrderedArgs.push_back(Args[3]); // Val2
5505       APIOrderedArgs.push_back(Args[1]); // Order
5506       break;
5507     case C11CmpXchg:
5508       APIOrderedArgs.push_back(Args[2]); // Val1
5509       APIOrderedArgs.push_back(Args[4]); // Val2
5510       APIOrderedArgs.push_back(Args[1]); // Order
5511       APIOrderedArgs.push_back(Args[3]); // OrderFail
5512       break;
5513     case GNUCmpXchg:
5514       APIOrderedArgs.push_back(Args[2]); // Val1
5515       APIOrderedArgs.push_back(Args[4]); // Val2
5516       APIOrderedArgs.push_back(Args[5]); // Weak
5517       APIOrderedArgs.push_back(Args[1]); // Order
5518       APIOrderedArgs.push_back(Args[3]); // OrderFail
5519       break;
5520     }
5521   } else
5522     APIOrderedArgs.append(Args.begin(), Args.end());
5523 
5524   // The first argument's non-CV pointer type is used to deduce the type of
5525   // subsequent arguments, except for:
5526   //  - weak flag (always converted to bool)
5527   //  - memory order (always converted to int)
5528   //  - scope  (always converted to int)
5529   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5530     QualType Ty;
5531     if (i < NumVals[Form] + 1) {
5532       switch (i) {
5533       case 0:
5534         // The first argument is always a pointer. It has a fixed type.
5535         // It is always dereferenced, a nullptr is undefined.
5536         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5537         // Nothing else to do: we already know all we want about this pointer.
5538         continue;
5539       case 1:
5540         // The second argument is the non-atomic operand. For arithmetic, this
5541         // is always passed by value, and for a compare_exchange it is always
5542         // passed by address. For the rest, GNU uses by-address and C11 uses
5543         // by-value.
5544         assert(Form != Load);
5545         if (Form == Arithmetic && ValType->isPointerType())
5546           Ty = Context.getPointerDiffType();
5547         else if (Form == Init || Form == Arithmetic)
5548           Ty = ValType;
5549         else if (Form == Copy || Form == Xchg) {
5550           if (IsPassedByAddress) {
5551             // The value pointer is always dereferenced, a nullptr is undefined.
5552             CheckNonNullArgument(*this, APIOrderedArgs[i],
5553                                  ExprRange.getBegin());
5554           }
5555           Ty = ByValType;
5556         } else {
5557           Expr *ValArg = APIOrderedArgs[i];
5558           // The value pointer is always dereferenced, a nullptr is undefined.
5559           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5560           LangAS AS = LangAS::Default;
5561           // Keep address space of non-atomic pointer type.
5562           if (const PointerType *PtrTy =
5563                   ValArg->getType()->getAs<PointerType>()) {
5564             AS = PtrTy->getPointeeType().getAddressSpace();
5565           }
5566           Ty = Context.getPointerType(
5567               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5568         }
5569         break;
5570       case 2:
5571         // The third argument to compare_exchange / GNU exchange is the desired
5572         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5573         if (IsPassedByAddress)
5574           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5575         Ty = ByValType;
5576         break;
5577       case 3:
5578         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5579         Ty = Context.BoolTy;
5580         break;
5581       }
5582     } else {
5583       // The order(s) and scope are always converted to int.
5584       Ty = Context.IntTy;
5585     }
5586 
5587     InitializedEntity Entity =
5588         InitializedEntity::InitializeParameter(Context, Ty, false);
5589     ExprResult Arg = APIOrderedArgs[i];
5590     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5591     if (Arg.isInvalid())
5592       return true;
5593     APIOrderedArgs[i] = Arg.get();
5594   }
5595 
5596   // Permute the arguments into a 'consistent' order.
5597   SmallVector<Expr*, 5> SubExprs;
5598   SubExprs.push_back(Ptr);
5599   switch (Form) {
5600   case Init:
5601     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5602     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5603     break;
5604   case Load:
5605     SubExprs.push_back(APIOrderedArgs[1]); // Order
5606     break;
5607   case LoadCopy:
5608   case Copy:
5609   case Arithmetic:
5610   case Xchg:
5611     SubExprs.push_back(APIOrderedArgs[2]); // Order
5612     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5613     break;
5614   case GNUXchg:
5615     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5616     SubExprs.push_back(APIOrderedArgs[3]); // Order
5617     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5618     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5619     break;
5620   case C11CmpXchg:
5621     SubExprs.push_back(APIOrderedArgs[3]); // Order
5622     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5623     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5624     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5625     break;
5626   case GNUCmpXchg:
5627     SubExprs.push_back(APIOrderedArgs[4]); // Order
5628     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5629     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5630     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5631     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5632     break;
5633   }
5634 
5635   if (SubExprs.size() >= 2 && Form != Init) {
5636     if (Optional<llvm::APSInt> Result =
5637             SubExprs[1]->getIntegerConstantExpr(Context))
5638       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5639         Diag(SubExprs[1]->getBeginLoc(),
5640              diag::warn_atomic_op_has_invalid_memory_order)
5641             << SubExprs[1]->getSourceRange();
5642   }
5643 
5644   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5645     auto *Scope = Args[Args.size() - 1];
5646     if (Optional<llvm::APSInt> Result =
5647             Scope->getIntegerConstantExpr(Context)) {
5648       if (!ScopeModel->isValid(Result->getZExtValue()))
5649         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5650             << Scope->getSourceRange();
5651     }
5652     SubExprs.push_back(Scope);
5653   }
5654 
5655   AtomicExpr *AE = new (Context)
5656       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5657 
5658   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5659        Op == AtomicExpr::AO__c11_atomic_store ||
5660        Op == AtomicExpr::AO__opencl_atomic_load ||
5661        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5662       Context.AtomicUsesUnsupportedLibcall(AE))
5663     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5664         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5665              Op == AtomicExpr::AO__opencl_atomic_load)
5666                 ? 0
5667                 : 1);
5668 
5669   if (ValType->isExtIntType()) {
5670     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5671     return ExprError();
5672   }
5673 
5674   return AE;
5675 }
5676 
5677 /// checkBuiltinArgument - Given a call to a builtin function, perform
5678 /// normal type-checking on the given argument, updating the call in
5679 /// place.  This is useful when a builtin function requires custom
5680 /// type-checking for some of its arguments but not necessarily all of
5681 /// them.
5682 ///
5683 /// Returns true on error.
5684 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5685   FunctionDecl *Fn = E->getDirectCallee();
5686   assert(Fn && "builtin call without direct callee!");
5687 
5688   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5689   InitializedEntity Entity =
5690     InitializedEntity::InitializeParameter(S.Context, Param);
5691 
5692   ExprResult Arg = E->getArg(0);
5693   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5694   if (Arg.isInvalid())
5695     return true;
5696 
5697   E->setArg(ArgIndex, Arg.get());
5698   return false;
5699 }
5700 
5701 /// We have a call to a function like __sync_fetch_and_add, which is an
5702 /// overloaded function based on the pointer type of its first argument.
5703 /// The main BuildCallExpr routines have already promoted the types of
5704 /// arguments because all of these calls are prototyped as void(...).
5705 ///
5706 /// This function goes through and does final semantic checking for these
5707 /// builtins, as well as generating any warnings.
5708 ExprResult
5709 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5710   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5711   Expr *Callee = TheCall->getCallee();
5712   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5713   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5714 
5715   // Ensure that we have at least one argument to do type inference from.
5716   if (TheCall->getNumArgs() < 1) {
5717     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5718         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5719     return ExprError();
5720   }
5721 
5722   // Inspect the first argument of the atomic builtin.  This should always be
5723   // a pointer type, whose element is an integral scalar or pointer type.
5724   // Because it is a pointer type, we don't have to worry about any implicit
5725   // casts here.
5726   // FIXME: We don't allow floating point scalars as input.
5727   Expr *FirstArg = TheCall->getArg(0);
5728   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5729   if (FirstArgResult.isInvalid())
5730     return ExprError();
5731   FirstArg = FirstArgResult.get();
5732   TheCall->setArg(0, FirstArg);
5733 
5734   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5735   if (!pointerType) {
5736     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5737         << FirstArg->getType() << FirstArg->getSourceRange();
5738     return ExprError();
5739   }
5740 
5741   QualType ValType = pointerType->getPointeeType();
5742   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5743       !ValType->isBlockPointerType()) {
5744     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5745         << FirstArg->getType() << FirstArg->getSourceRange();
5746     return ExprError();
5747   }
5748 
5749   if (ValType.isConstQualified()) {
5750     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5751         << FirstArg->getType() << FirstArg->getSourceRange();
5752     return ExprError();
5753   }
5754 
5755   switch (ValType.getObjCLifetime()) {
5756   case Qualifiers::OCL_None:
5757   case Qualifiers::OCL_ExplicitNone:
5758     // okay
5759     break;
5760 
5761   case Qualifiers::OCL_Weak:
5762   case Qualifiers::OCL_Strong:
5763   case Qualifiers::OCL_Autoreleasing:
5764     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5765         << ValType << FirstArg->getSourceRange();
5766     return ExprError();
5767   }
5768 
5769   // Strip any qualifiers off ValType.
5770   ValType = ValType.getUnqualifiedType();
5771 
5772   // The majority of builtins return a value, but a few have special return
5773   // types, so allow them to override appropriately below.
5774   QualType ResultType = ValType;
5775 
5776   // We need to figure out which concrete builtin this maps onto.  For example,
5777   // __sync_fetch_and_add with a 2 byte object turns into
5778   // __sync_fetch_and_add_2.
5779 #define BUILTIN_ROW(x) \
5780   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5781     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5782 
5783   static const unsigned BuiltinIndices[][5] = {
5784     BUILTIN_ROW(__sync_fetch_and_add),
5785     BUILTIN_ROW(__sync_fetch_and_sub),
5786     BUILTIN_ROW(__sync_fetch_and_or),
5787     BUILTIN_ROW(__sync_fetch_and_and),
5788     BUILTIN_ROW(__sync_fetch_and_xor),
5789     BUILTIN_ROW(__sync_fetch_and_nand),
5790 
5791     BUILTIN_ROW(__sync_add_and_fetch),
5792     BUILTIN_ROW(__sync_sub_and_fetch),
5793     BUILTIN_ROW(__sync_and_and_fetch),
5794     BUILTIN_ROW(__sync_or_and_fetch),
5795     BUILTIN_ROW(__sync_xor_and_fetch),
5796     BUILTIN_ROW(__sync_nand_and_fetch),
5797 
5798     BUILTIN_ROW(__sync_val_compare_and_swap),
5799     BUILTIN_ROW(__sync_bool_compare_and_swap),
5800     BUILTIN_ROW(__sync_lock_test_and_set),
5801     BUILTIN_ROW(__sync_lock_release),
5802     BUILTIN_ROW(__sync_swap)
5803   };
5804 #undef BUILTIN_ROW
5805 
5806   // Determine the index of the size.
5807   unsigned SizeIndex;
5808   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5809   case 1: SizeIndex = 0; break;
5810   case 2: SizeIndex = 1; break;
5811   case 4: SizeIndex = 2; break;
5812   case 8: SizeIndex = 3; break;
5813   case 16: SizeIndex = 4; break;
5814   default:
5815     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5816         << FirstArg->getType() << FirstArg->getSourceRange();
5817     return ExprError();
5818   }
5819 
5820   // Each of these builtins has one pointer argument, followed by some number of
5821   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5822   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5823   // as the number of fixed args.
5824   unsigned BuiltinID = FDecl->getBuiltinID();
5825   unsigned BuiltinIndex, NumFixed = 1;
5826   bool WarnAboutSemanticsChange = false;
5827   switch (BuiltinID) {
5828   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5829   case Builtin::BI__sync_fetch_and_add:
5830   case Builtin::BI__sync_fetch_and_add_1:
5831   case Builtin::BI__sync_fetch_and_add_2:
5832   case Builtin::BI__sync_fetch_and_add_4:
5833   case Builtin::BI__sync_fetch_and_add_8:
5834   case Builtin::BI__sync_fetch_and_add_16:
5835     BuiltinIndex = 0;
5836     break;
5837 
5838   case Builtin::BI__sync_fetch_and_sub:
5839   case Builtin::BI__sync_fetch_and_sub_1:
5840   case Builtin::BI__sync_fetch_and_sub_2:
5841   case Builtin::BI__sync_fetch_and_sub_4:
5842   case Builtin::BI__sync_fetch_and_sub_8:
5843   case Builtin::BI__sync_fetch_and_sub_16:
5844     BuiltinIndex = 1;
5845     break;
5846 
5847   case Builtin::BI__sync_fetch_and_or:
5848   case Builtin::BI__sync_fetch_and_or_1:
5849   case Builtin::BI__sync_fetch_and_or_2:
5850   case Builtin::BI__sync_fetch_and_or_4:
5851   case Builtin::BI__sync_fetch_and_or_8:
5852   case Builtin::BI__sync_fetch_and_or_16:
5853     BuiltinIndex = 2;
5854     break;
5855 
5856   case Builtin::BI__sync_fetch_and_and:
5857   case Builtin::BI__sync_fetch_and_and_1:
5858   case Builtin::BI__sync_fetch_and_and_2:
5859   case Builtin::BI__sync_fetch_and_and_4:
5860   case Builtin::BI__sync_fetch_and_and_8:
5861   case Builtin::BI__sync_fetch_and_and_16:
5862     BuiltinIndex = 3;
5863     break;
5864 
5865   case Builtin::BI__sync_fetch_and_xor:
5866   case Builtin::BI__sync_fetch_and_xor_1:
5867   case Builtin::BI__sync_fetch_and_xor_2:
5868   case Builtin::BI__sync_fetch_and_xor_4:
5869   case Builtin::BI__sync_fetch_and_xor_8:
5870   case Builtin::BI__sync_fetch_and_xor_16:
5871     BuiltinIndex = 4;
5872     break;
5873 
5874   case Builtin::BI__sync_fetch_and_nand:
5875   case Builtin::BI__sync_fetch_and_nand_1:
5876   case Builtin::BI__sync_fetch_and_nand_2:
5877   case Builtin::BI__sync_fetch_and_nand_4:
5878   case Builtin::BI__sync_fetch_and_nand_8:
5879   case Builtin::BI__sync_fetch_and_nand_16:
5880     BuiltinIndex = 5;
5881     WarnAboutSemanticsChange = true;
5882     break;
5883 
5884   case Builtin::BI__sync_add_and_fetch:
5885   case Builtin::BI__sync_add_and_fetch_1:
5886   case Builtin::BI__sync_add_and_fetch_2:
5887   case Builtin::BI__sync_add_and_fetch_4:
5888   case Builtin::BI__sync_add_and_fetch_8:
5889   case Builtin::BI__sync_add_and_fetch_16:
5890     BuiltinIndex = 6;
5891     break;
5892 
5893   case Builtin::BI__sync_sub_and_fetch:
5894   case Builtin::BI__sync_sub_and_fetch_1:
5895   case Builtin::BI__sync_sub_and_fetch_2:
5896   case Builtin::BI__sync_sub_and_fetch_4:
5897   case Builtin::BI__sync_sub_and_fetch_8:
5898   case Builtin::BI__sync_sub_and_fetch_16:
5899     BuiltinIndex = 7;
5900     break;
5901 
5902   case Builtin::BI__sync_and_and_fetch:
5903   case Builtin::BI__sync_and_and_fetch_1:
5904   case Builtin::BI__sync_and_and_fetch_2:
5905   case Builtin::BI__sync_and_and_fetch_4:
5906   case Builtin::BI__sync_and_and_fetch_8:
5907   case Builtin::BI__sync_and_and_fetch_16:
5908     BuiltinIndex = 8;
5909     break;
5910 
5911   case Builtin::BI__sync_or_and_fetch:
5912   case Builtin::BI__sync_or_and_fetch_1:
5913   case Builtin::BI__sync_or_and_fetch_2:
5914   case Builtin::BI__sync_or_and_fetch_4:
5915   case Builtin::BI__sync_or_and_fetch_8:
5916   case Builtin::BI__sync_or_and_fetch_16:
5917     BuiltinIndex = 9;
5918     break;
5919 
5920   case Builtin::BI__sync_xor_and_fetch:
5921   case Builtin::BI__sync_xor_and_fetch_1:
5922   case Builtin::BI__sync_xor_and_fetch_2:
5923   case Builtin::BI__sync_xor_and_fetch_4:
5924   case Builtin::BI__sync_xor_and_fetch_8:
5925   case Builtin::BI__sync_xor_and_fetch_16:
5926     BuiltinIndex = 10;
5927     break;
5928 
5929   case Builtin::BI__sync_nand_and_fetch:
5930   case Builtin::BI__sync_nand_and_fetch_1:
5931   case Builtin::BI__sync_nand_and_fetch_2:
5932   case Builtin::BI__sync_nand_and_fetch_4:
5933   case Builtin::BI__sync_nand_and_fetch_8:
5934   case Builtin::BI__sync_nand_and_fetch_16:
5935     BuiltinIndex = 11;
5936     WarnAboutSemanticsChange = true;
5937     break;
5938 
5939   case Builtin::BI__sync_val_compare_and_swap:
5940   case Builtin::BI__sync_val_compare_and_swap_1:
5941   case Builtin::BI__sync_val_compare_and_swap_2:
5942   case Builtin::BI__sync_val_compare_and_swap_4:
5943   case Builtin::BI__sync_val_compare_and_swap_8:
5944   case Builtin::BI__sync_val_compare_and_swap_16:
5945     BuiltinIndex = 12;
5946     NumFixed = 2;
5947     break;
5948 
5949   case Builtin::BI__sync_bool_compare_and_swap:
5950   case Builtin::BI__sync_bool_compare_and_swap_1:
5951   case Builtin::BI__sync_bool_compare_and_swap_2:
5952   case Builtin::BI__sync_bool_compare_and_swap_4:
5953   case Builtin::BI__sync_bool_compare_and_swap_8:
5954   case Builtin::BI__sync_bool_compare_and_swap_16:
5955     BuiltinIndex = 13;
5956     NumFixed = 2;
5957     ResultType = Context.BoolTy;
5958     break;
5959 
5960   case Builtin::BI__sync_lock_test_and_set:
5961   case Builtin::BI__sync_lock_test_and_set_1:
5962   case Builtin::BI__sync_lock_test_and_set_2:
5963   case Builtin::BI__sync_lock_test_and_set_4:
5964   case Builtin::BI__sync_lock_test_and_set_8:
5965   case Builtin::BI__sync_lock_test_and_set_16:
5966     BuiltinIndex = 14;
5967     break;
5968 
5969   case Builtin::BI__sync_lock_release:
5970   case Builtin::BI__sync_lock_release_1:
5971   case Builtin::BI__sync_lock_release_2:
5972   case Builtin::BI__sync_lock_release_4:
5973   case Builtin::BI__sync_lock_release_8:
5974   case Builtin::BI__sync_lock_release_16:
5975     BuiltinIndex = 15;
5976     NumFixed = 0;
5977     ResultType = Context.VoidTy;
5978     break;
5979 
5980   case Builtin::BI__sync_swap:
5981   case Builtin::BI__sync_swap_1:
5982   case Builtin::BI__sync_swap_2:
5983   case Builtin::BI__sync_swap_4:
5984   case Builtin::BI__sync_swap_8:
5985   case Builtin::BI__sync_swap_16:
5986     BuiltinIndex = 16;
5987     break;
5988   }
5989 
5990   // Now that we know how many fixed arguments we expect, first check that we
5991   // have at least that many.
5992   if (TheCall->getNumArgs() < 1+NumFixed) {
5993     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5994         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5995         << Callee->getSourceRange();
5996     return ExprError();
5997   }
5998 
5999   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6000       << Callee->getSourceRange();
6001 
6002   if (WarnAboutSemanticsChange) {
6003     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6004         << Callee->getSourceRange();
6005   }
6006 
6007   // Get the decl for the concrete builtin from this, we can tell what the
6008   // concrete integer type we should convert to is.
6009   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6010   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6011   FunctionDecl *NewBuiltinDecl;
6012   if (NewBuiltinID == BuiltinID)
6013     NewBuiltinDecl = FDecl;
6014   else {
6015     // Perform builtin lookup to avoid redeclaring it.
6016     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6017     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6018     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6019     assert(Res.getFoundDecl());
6020     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6021     if (!NewBuiltinDecl)
6022       return ExprError();
6023   }
6024 
6025   // The first argument --- the pointer --- has a fixed type; we
6026   // deduce the types of the rest of the arguments accordingly.  Walk
6027   // the remaining arguments, converting them to the deduced value type.
6028   for (unsigned i = 0; i != NumFixed; ++i) {
6029     ExprResult Arg = TheCall->getArg(i+1);
6030 
6031     // GCC does an implicit conversion to the pointer or integer ValType.  This
6032     // can fail in some cases (1i -> int**), check for this error case now.
6033     // Initialize the argument.
6034     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6035                                                    ValType, /*consume*/ false);
6036     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6037     if (Arg.isInvalid())
6038       return ExprError();
6039 
6040     // Okay, we have something that *can* be converted to the right type.  Check
6041     // to see if there is a potentially weird extension going on here.  This can
6042     // happen when you do an atomic operation on something like an char* and
6043     // pass in 42.  The 42 gets converted to char.  This is even more strange
6044     // for things like 45.123 -> char, etc.
6045     // FIXME: Do this check.
6046     TheCall->setArg(i+1, Arg.get());
6047   }
6048 
6049   // Create a new DeclRefExpr to refer to the new decl.
6050   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6051       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6052       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6053       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6054 
6055   // Set the callee in the CallExpr.
6056   // FIXME: This loses syntactic information.
6057   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6058   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6059                                               CK_BuiltinFnToFnPtr);
6060   TheCall->setCallee(PromotedCall.get());
6061 
6062   // Change the result type of the call to match the original value type. This
6063   // is arbitrary, but the codegen for these builtins ins design to handle it
6064   // gracefully.
6065   TheCall->setType(ResultType);
6066 
6067   // Prohibit use of _ExtInt with atomic builtins.
6068   // The arguments would have already been converted to the first argument's
6069   // type, so only need to check the first argument.
6070   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6071   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6072     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6073     return ExprError();
6074   }
6075 
6076   return TheCallResult;
6077 }
6078 
6079 /// SemaBuiltinNontemporalOverloaded - We have a call to
6080 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6081 /// overloaded function based on the pointer type of its last argument.
6082 ///
6083 /// This function goes through and does final semantic checking for these
6084 /// builtins.
6085 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6086   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6087   DeclRefExpr *DRE =
6088       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6089   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6090   unsigned BuiltinID = FDecl->getBuiltinID();
6091   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6092           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6093          "Unexpected nontemporal load/store builtin!");
6094   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6095   unsigned numArgs = isStore ? 2 : 1;
6096 
6097   // Ensure that we have the proper number of arguments.
6098   if (checkArgCount(*this, TheCall, numArgs))
6099     return ExprError();
6100 
6101   // Inspect the last argument of the nontemporal builtin.  This should always
6102   // be a pointer type, from which we imply the type of the memory access.
6103   // Because it is a pointer type, we don't have to worry about any implicit
6104   // casts here.
6105   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6106   ExprResult PointerArgResult =
6107       DefaultFunctionArrayLvalueConversion(PointerArg);
6108 
6109   if (PointerArgResult.isInvalid())
6110     return ExprError();
6111   PointerArg = PointerArgResult.get();
6112   TheCall->setArg(numArgs - 1, PointerArg);
6113 
6114   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6115   if (!pointerType) {
6116     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6117         << PointerArg->getType() << PointerArg->getSourceRange();
6118     return ExprError();
6119   }
6120 
6121   QualType ValType = pointerType->getPointeeType();
6122 
6123   // Strip any qualifiers off ValType.
6124   ValType = ValType.getUnqualifiedType();
6125   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6126       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6127       !ValType->isVectorType()) {
6128     Diag(DRE->getBeginLoc(),
6129          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6130         << PointerArg->getType() << PointerArg->getSourceRange();
6131     return ExprError();
6132   }
6133 
6134   if (!isStore) {
6135     TheCall->setType(ValType);
6136     return TheCallResult;
6137   }
6138 
6139   ExprResult ValArg = TheCall->getArg(0);
6140   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6141       Context, ValType, /*consume*/ false);
6142   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6143   if (ValArg.isInvalid())
6144     return ExprError();
6145 
6146   TheCall->setArg(0, ValArg.get());
6147   TheCall->setType(Context.VoidTy);
6148   return TheCallResult;
6149 }
6150 
6151 /// CheckObjCString - Checks that the argument to the builtin
6152 /// CFString constructor is correct
6153 /// Note: It might also make sense to do the UTF-16 conversion here (would
6154 /// simplify the backend).
6155 bool Sema::CheckObjCString(Expr *Arg) {
6156   Arg = Arg->IgnoreParenCasts();
6157   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6158 
6159   if (!Literal || !Literal->isAscii()) {
6160     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6161         << Arg->getSourceRange();
6162     return true;
6163   }
6164 
6165   if (Literal->containsNonAsciiOrNull()) {
6166     StringRef String = Literal->getString();
6167     unsigned NumBytes = String.size();
6168     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6169     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6170     llvm::UTF16 *ToPtr = &ToBuf[0];
6171 
6172     llvm::ConversionResult Result =
6173         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6174                                  ToPtr + NumBytes, llvm::strictConversion);
6175     // Check for conversion failure.
6176     if (Result != llvm::conversionOK)
6177       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6178           << Arg->getSourceRange();
6179   }
6180   return false;
6181 }
6182 
6183 /// CheckObjCString - Checks that the format string argument to the os_log()
6184 /// and os_trace() functions is correct, and converts it to const char *.
6185 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6186   Arg = Arg->IgnoreParenCasts();
6187   auto *Literal = dyn_cast<StringLiteral>(Arg);
6188   if (!Literal) {
6189     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6190       Literal = ObjcLiteral->getString();
6191     }
6192   }
6193 
6194   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6195     return ExprError(
6196         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6197         << Arg->getSourceRange());
6198   }
6199 
6200   ExprResult Result(Literal);
6201   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6202   InitializedEntity Entity =
6203       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6204   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6205   return Result;
6206 }
6207 
6208 /// Check that the user is calling the appropriate va_start builtin for the
6209 /// target and calling convention.
6210 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6211   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6212   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6213   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6214                     TT.getArch() == llvm::Triple::aarch64_32);
6215   bool IsWindows = TT.isOSWindows();
6216   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6217   if (IsX64 || IsAArch64) {
6218     CallingConv CC = CC_C;
6219     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6220       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6221     if (IsMSVAStart) {
6222       // Don't allow this in System V ABI functions.
6223       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6224         return S.Diag(Fn->getBeginLoc(),
6225                       diag::err_ms_va_start_used_in_sysv_function);
6226     } else {
6227       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6228       // On x64 Windows, don't allow this in System V ABI functions.
6229       // (Yes, that means there's no corresponding way to support variadic
6230       // System V ABI functions on Windows.)
6231       if ((IsWindows && CC == CC_X86_64SysV) ||
6232           (!IsWindows && CC == CC_Win64))
6233         return S.Diag(Fn->getBeginLoc(),
6234                       diag::err_va_start_used_in_wrong_abi_function)
6235                << !IsWindows;
6236     }
6237     return false;
6238   }
6239 
6240   if (IsMSVAStart)
6241     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6242   return false;
6243 }
6244 
6245 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6246                                              ParmVarDecl **LastParam = nullptr) {
6247   // Determine whether the current function, block, or obj-c method is variadic
6248   // and get its parameter list.
6249   bool IsVariadic = false;
6250   ArrayRef<ParmVarDecl *> Params;
6251   DeclContext *Caller = S.CurContext;
6252   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6253     IsVariadic = Block->isVariadic();
6254     Params = Block->parameters();
6255   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6256     IsVariadic = FD->isVariadic();
6257     Params = FD->parameters();
6258   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6259     IsVariadic = MD->isVariadic();
6260     // FIXME: This isn't correct for methods (results in bogus warning).
6261     Params = MD->parameters();
6262   } else if (isa<CapturedDecl>(Caller)) {
6263     // We don't support va_start in a CapturedDecl.
6264     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6265     return true;
6266   } else {
6267     // This must be some other declcontext that parses exprs.
6268     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6269     return true;
6270   }
6271 
6272   if (!IsVariadic) {
6273     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6274     return true;
6275   }
6276 
6277   if (LastParam)
6278     *LastParam = Params.empty() ? nullptr : Params.back();
6279 
6280   return false;
6281 }
6282 
6283 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6284 /// for validity.  Emit an error and return true on failure; return false
6285 /// on success.
6286 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6287   Expr *Fn = TheCall->getCallee();
6288 
6289   if (checkVAStartABI(*this, BuiltinID, Fn))
6290     return true;
6291 
6292   if (checkArgCount(*this, TheCall, 2))
6293     return true;
6294 
6295   // Type-check the first argument normally.
6296   if (checkBuiltinArgument(*this, TheCall, 0))
6297     return true;
6298 
6299   // Check that the current function is variadic, and get its last parameter.
6300   ParmVarDecl *LastParam;
6301   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6302     return true;
6303 
6304   // Verify that the second argument to the builtin is the last argument of the
6305   // current function or method.
6306   bool SecondArgIsLastNamedArgument = false;
6307   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6308 
6309   // These are valid if SecondArgIsLastNamedArgument is false after the next
6310   // block.
6311   QualType Type;
6312   SourceLocation ParamLoc;
6313   bool IsCRegister = false;
6314 
6315   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6316     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6317       SecondArgIsLastNamedArgument = PV == LastParam;
6318 
6319       Type = PV->getType();
6320       ParamLoc = PV->getLocation();
6321       IsCRegister =
6322           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6323     }
6324   }
6325 
6326   if (!SecondArgIsLastNamedArgument)
6327     Diag(TheCall->getArg(1)->getBeginLoc(),
6328          diag::warn_second_arg_of_va_start_not_last_named_param);
6329   else if (IsCRegister || Type->isReferenceType() ||
6330            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6331              // Promotable integers are UB, but enumerations need a bit of
6332              // extra checking to see what their promotable type actually is.
6333              if (!Type->isPromotableIntegerType())
6334                return false;
6335              if (!Type->isEnumeralType())
6336                return true;
6337              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6338              return !(ED &&
6339                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6340            }()) {
6341     unsigned Reason = 0;
6342     if (Type->isReferenceType())  Reason = 1;
6343     else if (IsCRegister)         Reason = 2;
6344     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6345     Diag(ParamLoc, diag::note_parameter_type) << Type;
6346   }
6347 
6348   TheCall->setType(Context.VoidTy);
6349   return false;
6350 }
6351 
6352 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6353   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6354     const LangOptions &LO = getLangOpts();
6355 
6356     if (LO.CPlusPlus)
6357       return Arg->getType()
6358                  .getCanonicalType()
6359                  .getTypePtr()
6360                  ->getPointeeType()
6361                  .withoutLocalFastQualifiers() == Context.CharTy;
6362 
6363     // In C, allow aliasing through `char *`, this is required for AArch64 at
6364     // least.
6365     return true;
6366   };
6367 
6368   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6369   //                 const char *named_addr);
6370 
6371   Expr *Func = Call->getCallee();
6372 
6373   if (Call->getNumArgs() < 3)
6374     return Diag(Call->getEndLoc(),
6375                 diag::err_typecheck_call_too_few_args_at_least)
6376            << 0 /*function call*/ << 3 << Call->getNumArgs();
6377 
6378   // Type-check the first argument normally.
6379   if (checkBuiltinArgument(*this, Call, 0))
6380     return true;
6381 
6382   // Check that the current function is variadic.
6383   if (checkVAStartIsInVariadicFunction(*this, Func))
6384     return true;
6385 
6386   // __va_start on Windows does not validate the parameter qualifiers
6387 
6388   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6389   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6390 
6391   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6392   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6393 
6394   const QualType &ConstCharPtrTy =
6395       Context.getPointerType(Context.CharTy.withConst());
6396   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6397     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6398         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6399         << 0                                      /* qualifier difference */
6400         << 3                                      /* parameter mismatch */
6401         << 2 << Arg1->getType() << ConstCharPtrTy;
6402 
6403   const QualType SizeTy = Context.getSizeType();
6404   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6405     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6406         << Arg2->getType() << SizeTy << 1 /* different class */
6407         << 0                              /* qualifier difference */
6408         << 3                              /* parameter mismatch */
6409         << 3 << Arg2->getType() << SizeTy;
6410 
6411   return false;
6412 }
6413 
6414 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6415 /// friends.  This is declared to take (...), so we have to check everything.
6416 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6417   if (checkArgCount(*this, TheCall, 2))
6418     return true;
6419 
6420   ExprResult OrigArg0 = TheCall->getArg(0);
6421   ExprResult OrigArg1 = TheCall->getArg(1);
6422 
6423   // Do standard promotions between the two arguments, returning their common
6424   // type.
6425   QualType Res = UsualArithmeticConversions(
6426       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6427   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6428     return true;
6429 
6430   // Make sure any conversions are pushed back into the call; this is
6431   // type safe since unordered compare builtins are declared as "_Bool
6432   // foo(...)".
6433   TheCall->setArg(0, OrigArg0.get());
6434   TheCall->setArg(1, OrigArg1.get());
6435 
6436   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6437     return false;
6438 
6439   // If the common type isn't a real floating type, then the arguments were
6440   // invalid for this operation.
6441   if (Res.isNull() || !Res->isRealFloatingType())
6442     return Diag(OrigArg0.get()->getBeginLoc(),
6443                 diag::err_typecheck_call_invalid_ordered_compare)
6444            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6445            << SourceRange(OrigArg0.get()->getBeginLoc(),
6446                           OrigArg1.get()->getEndLoc());
6447 
6448   return false;
6449 }
6450 
6451 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6452 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6453 /// to check everything. We expect the last argument to be a floating point
6454 /// value.
6455 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6456   if (checkArgCount(*this, TheCall, NumArgs))
6457     return true;
6458 
6459   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6460   // on all preceding parameters just being int.  Try all of those.
6461   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6462     Expr *Arg = TheCall->getArg(i);
6463 
6464     if (Arg->isTypeDependent())
6465       return false;
6466 
6467     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6468 
6469     if (Res.isInvalid())
6470       return true;
6471     TheCall->setArg(i, Res.get());
6472   }
6473 
6474   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6475 
6476   if (OrigArg->isTypeDependent())
6477     return false;
6478 
6479   // Usual Unary Conversions will convert half to float, which we want for
6480   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6481   // type how it is, but do normal L->Rvalue conversions.
6482   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6483     OrigArg = UsualUnaryConversions(OrigArg).get();
6484   else
6485     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6486   TheCall->setArg(NumArgs - 1, OrigArg);
6487 
6488   // This operation requires a non-_Complex floating-point number.
6489   if (!OrigArg->getType()->isRealFloatingType())
6490     return Diag(OrigArg->getBeginLoc(),
6491                 diag::err_typecheck_call_invalid_unary_fp)
6492            << OrigArg->getType() << OrigArg->getSourceRange();
6493 
6494   return false;
6495 }
6496 
6497 /// Perform semantic analysis for a call to __builtin_complex.
6498 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6499   if (checkArgCount(*this, TheCall, 2))
6500     return true;
6501 
6502   bool Dependent = false;
6503   for (unsigned I = 0; I != 2; ++I) {
6504     Expr *Arg = TheCall->getArg(I);
6505     QualType T = Arg->getType();
6506     if (T->isDependentType()) {
6507       Dependent = true;
6508       continue;
6509     }
6510 
6511     // Despite supporting _Complex int, GCC requires a real floating point type
6512     // for the operands of __builtin_complex.
6513     if (!T->isRealFloatingType()) {
6514       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6515              << Arg->getType() << Arg->getSourceRange();
6516     }
6517 
6518     ExprResult Converted = DefaultLvalueConversion(Arg);
6519     if (Converted.isInvalid())
6520       return true;
6521     TheCall->setArg(I, Converted.get());
6522   }
6523 
6524   if (Dependent) {
6525     TheCall->setType(Context.DependentTy);
6526     return false;
6527   }
6528 
6529   Expr *Real = TheCall->getArg(0);
6530   Expr *Imag = TheCall->getArg(1);
6531   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6532     return Diag(Real->getBeginLoc(),
6533                 diag::err_typecheck_call_different_arg_types)
6534            << Real->getType() << Imag->getType()
6535            << Real->getSourceRange() << Imag->getSourceRange();
6536   }
6537 
6538   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6539   // don't allow this builtin to form those types either.
6540   // FIXME: Should we allow these types?
6541   if (Real->getType()->isFloat16Type())
6542     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6543            << "_Float16";
6544   if (Real->getType()->isHalfType())
6545     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6546            << "half";
6547 
6548   TheCall->setType(Context.getComplexType(Real->getType()));
6549   return false;
6550 }
6551 
6552 // Customized Sema Checking for VSX builtins that have the following signature:
6553 // vector [...] builtinName(vector [...], vector [...], const int);
6554 // Which takes the same type of vectors (any legal vector type) for the first
6555 // two arguments and takes compile time constant for the third argument.
6556 // Example builtins are :
6557 // vector double vec_xxpermdi(vector double, vector double, int);
6558 // vector short vec_xxsldwi(vector short, vector short, int);
6559 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6560   unsigned ExpectedNumArgs = 3;
6561   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6562     return true;
6563 
6564   // Check the third argument is a compile time constant
6565   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6566     return Diag(TheCall->getBeginLoc(),
6567                 diag::err_vsx_builtin_nonconstant_argument)
6568            << 3 /* argument index */ << TheCall->getDirectCallee()
6569            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6570                           TheCall->getArg(2)->getEndLoc());
6571 
6572   QualType Arg1Ty = TheCall->getArg(0)->getType();
6573   QualType Arg2Ty = TheCall->getArg(1)->getType();
6574 
6575   // Check the type of argument 1 and argument 2 are vectors.
6576   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6577   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6578       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6579     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6580            << TheCall->getDirectCallee()
6581            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6582                           TheCall->getArg(1)->getEndLoc());
6583   }
6584 
6585   // Check the first two arguments are the same type.
6586   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6587     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6588            << TheCall->getDirectCallee()
6589            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6590                           TheCall->getArg(1)->getEndLoc());
6591   }
6592 
6593   // When default clang type checking is turned off and the customized type
6594   // checking is used, the returning type of the function must be explicitly
6595   // set. Otherwise it is _Bool by default.
6596   TheCall->setType(Arg1Ty);
6597 
6598   return false;
6599 }
6600 
6601 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6602 // This is declared to take (...), so we have to check everything.
6603 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6604   if (TheCall->getNumArgs() < 2)
6605     return ExprError(Diag(TheCall->getEndLoc(),
6606                           diag::err_typecheck_call_too_few_args_at_least)
6607                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6608                      << TheCall->getSourceRange());
6609 
6610   // Determine which of the following types of shufflevector we're checking:
6611   // 1) unary, vector mask: (lhs, mask)
6612   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6613   QualType resType = TheCall->getArg(0)->getType();
6614   unsigned numElements = 0;
6615 
6616   if (!TheCall->getArg(0)->isTypeDependent() &&
6617       !TheCall->getArg(1)->isTypeDependent()) {
6618     QualType LHSType = TheCall->getArg(0)->getType();
6619     QualType RHSType = TheCall->getArg(1)->getType();
6620 
6621     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6622       return ExprError(
6623           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6624           << TheCall->getDirectCallee()
6625           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6626                          TheCall->getArg(1)->getEndLoc()));
6627 
6628     numElements = LHSType->castAs<VectorType>()->getNumElements();
6629     unsigned numResElements = TheCall->getNumArgs() - 2;
6630 
6631     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6632     // with mask.  If so, verify that RHS is an integer vector type with the
6633     // same number of elts as lhs.
6634     if (TheCall->getNumArgs() == 2) {
6635       if (!RHSType->hasIntegerRepresentation() ||
6636           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6637         return ExprError(Diag(TheCall->getBeginLoc(),
6638                               diag::err_vec_builtin_incompatible_vector)
6639                          << TheCall->getDirectCallee()
6640                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6641                                         TheCall->getArg(1)->getEndLoc()));
6642     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6643       return ExprError(Diag(TheCall->getBeginLoc(),
6644                             diag::err_vec_builtin_incompatible_vector)
6645                        << TheCall->getDirectCallee()
6646                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6647                                       TheCall->getArg(1)->getEndLoc()));
6648     } else if (numElements != numResElements) {
6649       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6650       resType = Context.getVectorType(eltType, numResElements,
6651                                       VectorType::GenericVector);
6652     }
6653   }
6654 
6655   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6656     if (TheCall->getArg(i)->isTypeDependent() ||
6657         TheCall->getArg(i)->isValueDependent())
6658       continue;
6659 
6660     Optional<llvm::APSInt> Result;
6661     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6662       return ExprError(Diag(TheCall->getBeginLoc(),
6663                             diag::err_shufflevector_nonconstant_argument)
6664                        << TheCall->getArg(i)->getSourceRange());
6665 
6666     // Allow -1 which will be translated to undef in the IR.
6667     if (Result->isSigned() && Result->isAllOnes())
6668       continue;
6669 
6670     if (Result->getActiveBits() > 64 ||
6671         Result->getZExtValue() >= numElements * 2)
6672       return ExprError(Diag(TheCall->getBeginLoc(),
6673                             diag::err_shufflevector_argument_too_large)
6674                        << TheCall->getArg(i)->getSourceRange());
6675   }
6676 
6677   SmallVector<Expr*, 32> exprs;
6678 
6679   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6680     exprs.push_back(TheCall->getArg(i));
6681     TheCall->setArg(i, nullptr);
6682   }
6683 
6684   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6685                                          TheCall->getCallee()->getBeginLoc(),
6686                                          TheCall->getRParenLoc());
6687 }
6688 
6689 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6690 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6691                                        SourceLocation BuiltinLoc,
6692                                        SourceLocation RParenLoc) {
6693   ExprValueKind VK = VK_PRValue;
6694   ExprObjectKind OK = OK_Ordinary;
6695   QualType DstTy = TInfo->getType();
6696   QualType SrcTy = E->getType();
6697 
6698   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6699     return ExprError(Diag(BuiltinLoc,
6700                           diag::err_convertvector_non_vector)
6701                      << E->getSourceRange());
6702   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6703     return ExprError(Diag(BuiltinLoc,
6704                           diag::err_convertvector_non_vector_type));
6705 
6706   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6707     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6708     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6709     if (SrcElts != DstElts)
6710       return ExprError(Diag(BuiltinLoc,
6711                             diag::err_convertvector_incompatible_vector)
6712                        << E->getSourceRange());
6713   }
6714 
6715   return new (Context)
6716       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6717 }
6718 
6719 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6720 // This is declared to take (const void*, ...) and can take two
6721 // optional constant int args.
6722 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6723   unsigned NumArgs = TheCall->getNumArgs();
6724 
6725   if (NumArgs > 3)
6726     return Diag(TheCall->getEndLoc(),
6727                 diag::err_typecheck_call_too_many_args_at_most)
6728            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6729 
6730   // Argument 0 is checked for us and the remaining arguments must be
6731   // constant integers.
6732   for (unsigned i = 1; i != NumArgs; ++i)
6733     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6734       return true;
6735 
6736   return false;
6737 }
6738 
6739 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6740 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6741   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6742     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6743            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6744   if (checkArgCount(*this, TheCall, 1))
6745     return true;
6746   Expr *Arg = TheCall->getArg(0);
6747   if (Arg->isInstantiationDependent())
6748     return false;
6749 
6750   QualType ArgTy = Arg->getType();
6751   if (!ArgTy->hasFloatingRepresentation())
6752     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6753            << ArgTy;
6754   if (Arg->isLValue()) {
6755     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6756     TheCall->setArg(0, FirstArg.get());
6757   }
6758   TheCall->setType(TheCall->getArg(0)->getType());
6759   return false;
6760 }
6761 
6762 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6763 // __assume does not evaluate its arguments, and should warn if its argument
6764 // has side effects.
6765 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6766   Expr *Arg = TheCall->getArg(0);
6767   if (Arg->isInstantiationDependent()) return false;
6768 
6769   if (Arg->HasSideEffects(Context))
6770     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6771         << Arg->getSourceRange()
6772         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6773 
6774   return false;
6775 }
6776 
6777 /// Handle __builtin_alloca_with_align. This is declared
6778 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6779 /// than 8.
6780 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6781   // The alignment must be a constant integer.
6782   Expr *Arg = TheCall->getArg(1);
6783 
6784   // We can't check the value of a dependent argument.
6785   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6786     if (const auto *UE =
6787             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6788       if (UE->getKind() == UETT_AlignOf ||
6789           UE->getKind() == UETT_PreferredAlignOf)
6790         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6791             << Arg->getSourceRange();
6792 
6793     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6794 
6795     if (!Result.isPowerOf2())
6796       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6797              << Arg->getSourceRange();
6798 
6799     if (Result < Context.getCharWidth())
6800       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6801              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6802 
6803     if (Result > std::numeric_limits<int32_t>::max())
6804       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6805              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6806   }
6807 
6808   return false;
6809 }
6810 
6811 /// Handle __builtin_assume_aligned. This is declared
6812 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6813 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6814   unsigned NumArgs = TheCall->getNumArgs();
6815 
6816   if (NumArgs > 3)
6817     return Diag(TheCall->getEndLoc(),
6818                 diag::err_typecheck_call_too_many_args_at_most)
6819            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6820 
6821   // The alignment must be a constant integer.
6822   Expr *Arg = TheCall->getArg(1);
6823 
6824   // We can't check the value of a dependent argument.
6825   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6826     llvm::APSInt Result;
6827     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6828       return true;
6829 
6830     if (!Result.isPowerOf2())
6831       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6832              << Arg->getSourceRange();
6833 
6834     if (Result > Sema::MaximumAlignment)
6835       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6836           << Arg->getSourceRange() << Sema::MaximumAlignment;
6837   }
6838 
6839   if (NumArgs > 2) {
6840     ExprResult Arg(TheCall->getArg(2));
6841     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6842       Context.getSizeType(), false);
6843     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6844     if (Arg.isInvalid()) return true;
6845     TheCall->setArg(2, Arg.get());
6846   }
6847 
6848   return false;
6849 }
6850 
6851 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6852   unsigned BuiltinID =
6853       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6854   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6855 
6856   unsigned NumArgs = TheCall->getNumArgs();
6857   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6858   if (NumArgs < NumRequiredArgs) {
6859     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6860            << 0 /* function call */ << NumRequiredArgs << NumArgs
6861            << TheCall->getSourceRange();
6862   }
6863   if (NumArgs >= NumRequiredArgs + 0x100) {
6864     return Diag(TheCall->getEndLoc(),
6865                 diag::err_typecheck_call_too_many_args_at_most)
6866            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6867            << TheCall->getSourceRange();
6868   }
6869   unsigned i = 0;
6870 
6871   // For formatting call, check buffer arg.
6872   if (!IsSizeCall) {
6873     ExprResult Arg(TheCall->getArg(i));
6874     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6875         Context, Context.VoidPtrTy, false);
6876     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6877     if (Arg.isInvalid())
6878       return true;
6879     TheCall->setArg(i, Arg.get());
6880     i++;
6881   }
6882 
6883   // Check string literal arg.
6884   unsigned FormatIdx = i;
6885   {
6886     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6887     if (Arg.isInvalid())
6888       return true;
6889     TheCall->setArg(i, Arg.get());
6890     i++;
6891   }
6892 
6893   // Make sure variadic args are scalar.
6894   unsigned FirstDataArg = i;
6895   while (i < NumArgs) {
6896     ExprResult Arg = DefaultVariadicArgumentPromotion(
6897         TheCall->getArg(i), VariadicFunction, nullptr);
6898     if (Arg.isInvalid())
6899       return true;
6900     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6901     if (ArgSize.getQuantity() >= 0x100) {
6902       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6903              << i << (int)ArgSize.getQuantity() << 0xff
6904              << TheCall->getSourceRange();
6905     }
6906     TheCall->setArg(i, Arg.get());
6907     i++;
6908   }
6909 
6910   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6911   // call to avoid duplicate diagnostics.
6912   if (!IsSizeCall) {
6913     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6914     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6915     bool Success = CheckFormatArguments(
6916         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6917         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6918         CheckedVarArgs);
6919     if (!Success)
6920       return true;
6921   }
6922 
6923   if (IsSizeCall) {
6924     TheCall->setType(Context.getSizeType());
6925   } else {
6926     TheCall->setType(Context.VoidPtrTy);
6927   }
6928   return false;
6929 }
6930 
6931 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6932 /// TheCall is a constant expression.
6933 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6934                                   llvm::APSInt &Result) {
6935   Expr *Arg = TheCall->getArg(ArgNum);
6936   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6937   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6938 
6939   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6940 
6941   Optional<llvm::APSInt> R;
6942   if (!(R = Arg->getIntegerConstantExpr(Context)))
6943     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6944            << FDecl->getDeclName() << Arg->getSourceRange();
6945   Result = *R;
6946   return false;
6947 }
6948 
6949 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6950 /// TheCall is a constant expression in the range [Low, High].
6951 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6952                                        int Low, int High, bool RangeIsError) {
6953   if (isConstantEvaluated())
6954     return false;
6955   llvm::APSInt Result;
6956 
6957   // We can't check the value of a dependent argument.
6958   Expr *Arg = TheCall->getArg(ArgNum);
6959   if (Arg->isTypeDependent() || Arg->isValueDependent())
6960     return false;
6961 
6962   // Check constant-ness first.
6963   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6964     return true;
6965 
6966   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6967     if (RangeIsError)
6968       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6969              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6970     else
6971       // Defer the warning until we know if the code will be emitted so that
6972       // dead code can ignore this.
6973       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6974                           PDiag(diag::warn_argument_invalid_range)
6975                               << toString(Result, 10) << Low << High
6976                               << Arg->getSourceRange());
6977   }
6978 
6979   return false;
6980 }
6981 
6982 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6983 /// TheCall is a constant expression is a multiple of Num..
6984 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6985                                           unsigned Num) {
6986   llvm::APSInt Result;
6987 
6988   // We can't check the value of a dependent argument.
6989   Expr *Arg = TheCall->getArg(ArgNum);
6990   if (Arg->isTypeDependent() || Arg->isValueDependent())
6991     return false;
6992 
6993   // Check constant-ness first.
6994   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6995     return true;
6996 
6997   if (Result.getSExtValue() % Num != 0)
6998     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6999            << Num << Arg->getSourceRange();
7000 
7001   return false;
7002 }
7003 
7004 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7005 /// constant expression representing a power of 2.
7006 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7007   llvm::APSInt Result;
7008 
7009   // We can't check the value of a dependent argument.
7010   Expr *Arg = TheCall->getArg(ArgNum);
7011   if (Arg->isTypeDependent() || Arg->isValueDependent())
7012     return false;
7013 
7014   // Check constant-ness first.
7015   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7016     return true;
7017 
7018   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7019   // and only if x is a power of 2.
7020   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7021     return false;
7022 
7023   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7024          << Arg->getSourceRange();
7025 }
7026 
7027 static bool IsShiftedByte(llvm::APSInt Value) {
7028   if (Value.isNegative())
7029     return false;
7030 
7031   // Check if it's a shifted byte, by shifting it down
7032   while (true) {
7033     // If the value fits in the bottom byte, the check passes.
7034     if (Value < 0x100)
7035       return true;
7036 
7037     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7038     // fails.
7039     if ((Value & 0xFF) != 0)
7040       return false;
7041 
7042     // If the bottom 8 bits are all 0, but something above that is nonzero,
7043     // then shifting the value right by 8 bits won't affect whether it's a
7044     // shifted byte or not. So do that, and go round again.
7045     Value >>= 8;
7046   }
7047 }
7048 
7049 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7050 /// a constant expression representing an arbitrary byte value shifted left by
7051 /// a multiple of 8 bits.
7052 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7053                                              unsigned ArgBits) {
7054   llvm::APSInt Result;
7055 
7056   // We can't check the value of a dependent argument.
7057   Expr *Arg = TheCall->getArg(ArgNum);
7058   if (Arg->isTypeDependent() || Arg->isValueDependent())
7059     return false;
7060 
7061   // Check constant-ness first.
7062   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7063     return true;
7064 
7065   // Truncate to the given size.
7066   Result = Result.getLoBits(ArgBits);
7067   Result.setIsUnsigned(true);
7068 
7069   if (IsShiftedByte(Result))
7070     return false;
7071 
7072   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7073          << Arg->getSourceRange();
7074 }
7075 
7076 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7077 /// TheCall is a constant expression representing either a shifted byte value,
7078 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7079 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7080 /// Arm MVE intrinsics.
7081 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7082                                                    int ArgNum,
7083                                                    unsigned ArgBits) {
7084   llvm::APSInt Result;
7085 
7086   // We can't check the value of a dependent argument.
7087   Expr *Arg = TheCall->getArg(ArgNum);
7088   if (Arg->isTypeDependent() || Arg->isValueDependent())
7089     return false;
7090 
7091   // Check constant-ness first.
7092   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7093     return true;
7094 
7095   // Truncate to the given size.
7096   Result = Result.getLoBits(ArgBits);
7097   Result.setIsUnsigned(true);
7098 
7099   // Check to see if it's in either of the required forms.
7100   if (IsShiftedByte(Result) ||
7101       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7102     return false;
7103 
7104   return Diag(TheCall->getBeginLoc(),
7105               diag::err_argument_not_shifted_byte_or_xxff)
7106          << Arg->getSourceRange();
7107 }
7108 
7109 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7110 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7111   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7112     if (checkArgCount(*this, TheCall, 2))
7113       return true;
7114     Expr *Arg0 = TheCall->getArg(0);
7115     Expr *Arg1 = TheCall->getArg(1);
7116 
7117     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7118     if (FirstArg.isInvalid())
7119       return true;
7120     QualType FirstArgType = FirstArg.get()->getType();
7121     if (!FirstArgType->isAnyPointerType())
7122       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7123                << "first" << FirstArgType << Arg0->getSourceRange();
7124     TheCall->setArg(0, FirstArg.get());
7125 
7126     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7127     if (SecArg.isInvalid())
7128       return true;
7129     QualType SecArgType = SecArg.get()->getType();
7130     if (!SecArgType->isIntegerType())
7131       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7132                << "second" << SecArgType << Arg1->getSourceRange();
7133 
7134     // Derive the return type from the pointer argument.
7135     TheCall->setType(FirstArgType);
7136     return false;
7137   }
7138 
7139   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7140     if (checkArgCount(*this, TheCall, 2))
7141       return true;
7142 
7143     Expr *Arg0 = TheCall->getArg(0);
7144     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7145     if (FirstArg.isInvalid())
7146       return true;
7147     QualType FirstArgType = FirstArg.get()->getType();
7148     if (!FirstArgType->isAnyPointerType())
7149       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7150                << "first" << FirstArgType << Arg0->getSourceRange();
7151     TheCall->setArg(0, FirstArg.get());
7152 
7153     // Derive the return type from the pointer argument.
7154     TheCall->setType(FirstArgType);
7155 
7156     // Second arg must be an constant in range [0,15]
7157     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7158   }
7159 
7160   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7161     if (checkArgCount(*this, TheCall, 2))
7162       return true;
7163     Expr *Arg0 = TheCall->getArg(0);
7164     Expr *Arg1 = TheCall->getArg(1);
7165 
7166     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7167     if (FirstArg.isInvalid())
7168       return true;
7169     QualType FirstArgType = FirstArg.get()->getType();
7170     if (!FirstArgType->isAnyPointerType())
7171       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7172                << "first" << FirstArgType << Arg0->getSourceRange();
7173 
7174     QualType SecArgType = Arg1->getType();
7175     if (!SecArgType->isIntegerType())
7176       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7177                << "second" << SecArgType << Arg1->getSourceRange();
7178     TheCall->setType(Context.IntTy);
7179     return false;
7180   }
7181 
7182   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7183       BuiltinID == AArch64::BI__builtin_arm_stg) {
7184     if (checkArgCount(*this, TheCall, 1))
7185       return true;
7186     Expr *Arg0 = TheCall->getArg(0);
7187     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7188     if (FirstArg.isInvalid())
7189       return true;
7190 
7191     QualType FirstArgType = FirstArg.get()->getType();
7192     if (!FirstArgType->isAnyPointerType())
7193       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7194                << "first" << FirstArgType << Arg0->getSourceRange();
7195     TheCall->setArg(0, FirstArg.get());
7196 
7197     // Derive the return type from the pointer argument.
7198     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7199       TheCall->setType(FirstArgType);
7200     return false;
7201   }
7202 
7203   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7204     Expr *ArgA = TheCall->getArg(0);
7205     Expr *ArgB = TheCall->getArg(1);
7206 
7207     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7208     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7209 
7210     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7211       return true;
7212 
7213     QualType ArgTypeA = ArgExprA.get()->getType();
7214     QualType ArgTypeB = ArgExprB.get()->getType();
7215 
7216     auto isNull = [&] (Expr *E) -> bool {
7217       return E->isNullPointerConstant(
7218                         Context, Expr::NPC_ValueDependentIsNotNull); };
7219 
7220     // argument should be either a pointer or null
7221     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7222       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7223         << "first" << ArgTypeA << ArgA->getSourceRange();
7224 
7225     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7226       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7227         << "second" << ArgTypeB << ArgB->getSourceRange();
7228 
7229     // Ensure Pointee types are compatible
7230     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7231         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7232       QualType pointeeA = ArgTypeA->getPointeeType();
7233       QualType pointeeB = ArgTypeB->getPointeeType();
7234       if (!Context.typesAreCompatible(
7235              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7236              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7237         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7238           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7239           << ArgB->getSourceRange();
7240       }
7241     }
7242 
7243     // at least one argument should be pointer type
7244     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7245       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7246         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7247 
7248     if (isNull(ArgA)) // adopt type of the other pointer
7249       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7250 
7251     if (isNull(ArgB))
7252       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7253 
7254     TheCall->setArg(0, ArgExprA.get());
7255     TheCall->setArg(1, ArgExprB.get());
7256     TheCall->setType(Context.LongLongTy);
7257     return false;
7258   }
7259   assert(false && "Unhandled ARM MTE intrinsic");
7260   return true;
7261 }
7262 
7263 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7264 /// TheCall is an ARM/AArch64 special register string literal.
7265 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7266                                     int ArgNum, unsigned ExpectedFieldNum,
7267                                     bool AllowName) {
7268   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7269                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7270                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7271                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7272                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7273                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7274   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7275                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7276                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7277                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7278                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7279                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7280   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7281 
7282   // We can't check the value of a dependent argument.
7283   Expr *Arg = TheCall->getArg(ArgNum);
7284   if (Arg->isTypeDependent() || Arg->isValueDependent())
7285     return false;
7286 
7287   // Check if the argument is a string literal.
7288   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7289     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7290            << Arg->getSourceRange();
7291 
7292   // Check the type of special register given.
7293   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7294   SmallVector<StringRef, 6> Fields;
7295   Reg.split(Fields, ":");
7296 
7297   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7298     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7299            << Arg->getSourceRange();
7300 
7301   // If the string is the name of a register then we cannot check that it is
7302   // valid here but if the string is of one the forms described in ACLE then we
7303   // can check that the supplied fields are integers and within the valid
7304   // ranges.
7305   if (Fields.size() > 1) {
7306     bool FiveFields = Fields.size() == 5;
7307 
7308     bool ValidString = true;
7309     if (IsARMBuiltin) {
7310       ValidString &= Fields[0].startswith_insensitive("cp") ||
7311                      Fields[0].startswith_insensitive("p");
7312       if (ValidString)
7313         Fields[0] = Fields[0].drop_front(
7314             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7315 
7316       ValidString &= Fields[2].startswith_insensitive("c");
7317       if (ValidString)
7318         Fields[2] = Fields[2].drop_front(1);
7319 
7320       if (FiveFields) {
7321         ValidString &= Fields[3].startswith_insensitive("c");
7322         if (ValidString)
7323           Fields[3] = Fields[3].drop_front(1);
7324       }
7325     }
7326 
7327     SmallVector<int, 5> Ranges;
7328     if (FiveFields)
7329       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7330     else
7331       Ranges.append({15, 7, 15});
7332 
7333     for (unsigned i=0; i<Fields.size(); ++i) {
7334       int IntField;
7335       ValidString &= !Fields[i].getAsInteger(10, IntField);
7336       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7337     }
7338 
7339     if (!ValidString)
7340       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7341              << Arg->getSourceRange();
7342   } else if (IsAArch64Builtin && Fields.size() == 1) {
7343     // If the register name is one of those that appear in the condition below
7344     // and the special register builtin being used is one of the write builtins,
7345     // then we require that the argument provided for writing to the register
7346     // is an integer constant expression. This is because it will be lowered to
7347     // an MSR (immediate) instruction, so we need to know the immediate at
7348     // compile time.
7349     if (TheCall->getNumArgs() != 2)
7350       return false;
7351 
7352     std::string RegLower = Reg.lower();
7353     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7354         RegLower != "pan" && RegLower != "uao")
7355       return false;
7356 
7357     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7358   }
7359 
7360   return false;
7361 }
7362 
7363 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7364 /// Emit an error and return true on failure; return false on success.
7365 /// TypeStr is a string containing the type descriptor of the value returned by
7366 /// the builtin and the descriptors of the expected type of the arguments.
7367 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7368                                  const char *TypeStr) {
7369 
7370   assert((TypeStr[0] != '\0') &&
7371          "Invalid types in PPC MMA builtin declaration");
7372 
7373   switch (BuiltinID) {
7374   default:
7375     // This function is called in CheckPPCBuiltinFunctionCall where the
7376     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7377     // we are isolating the pair vector memop builtins that can be used with mma
7378     // off so the default case is every builtin that requires mma and paired
7379     // vector memops.
7380     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7381                          diag::err_ppc_builtin_only_on_arch, "10") ||
7382         SemaFeatureCheck(*this, TheCall, "mma",
7383                          diag::err_ppc_builtin_only_on_arch, "10"))
7384       return true;
7385     break;
7386   case PPC::BI__builtin_vsx_lxvp:
7387   case PPC::BI__builtin_vsx_stxvp:
7388   case PPC::BI__builtin_vsx_assemble_pair:
7389   case PPC::BI__builtin_vsx_disassemble_pair:
7390     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7391                          diag::err_ppc_builtin_only_on_arch, "10"))
7392       return true;
7393     break;
7394   }
7395 
7396   unsigned Mask = 0;
7397   unsigned ArgNum = 0;
7398 
7399   // The first type in TypeStr is the type of the value returned by the
7400   // builtin. So we first read that type and change the type of TheCall.
7401   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7402   TheCall->setType(type);
7403 
7404   while (*TypeStr != '\0') {
7405     Mask = 0;
7406     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7407     if (ArgNum >= TheCall->getNumArgs()) {
7408       ArgNum++;
7409       break;
7410     }
7411 
7412     Expr *Arg = TheCall->getArg(ArgNum);
7413     QualType PassedType = Arg->getType();
7414     QualType StrippedRVType = PassedType.getCanonicalType();
7415 
7416     // Strip Restrict/Volatile qualifiers.
7417     if (StrippedRVType.isRestrictQualified() ||
7418         StrippedRVType.isVolatileQualified())
7419       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7420 
7421     // The only case where the argument type and expected type are allowed to
7422     // mismatch is if the argument type is a non-void pointer and expected type
7423     // is a void pointer.
7424     if (StrippedRVType != ExpectedType)
7425       if (!(ExpectedType->isVoidPointerType() &&
7426             StrippedRVType->isPointerType()))
7427         return Diag(Arg->getBeginLoc(),
7428                     diag::err_typecheck_convert_incompatible)
7429                << PassedType << ExpectedType << 1 << 0 << 0;
7430 
7431     // If the value of the Mask is not 0, we have a constraint in the size of
7432     // the integer argument so here we ensure the argument is a constant that
7433     // is in the valid range.
7434     if (Mask != 0 &&
7435         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7436       return true;
7437 
7438     ArgNum++;
7439   }
7440 
7441   // In case we exited early from the previous loop, there are other types to
7442   // read from TypeStr. So we need to read them all to ensure we have the right
7443   // number of arguments in TheCall and if it is not the case, to display a
7444   // better error message.
7445   while (*TypeStr != '\0') {
7446     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7447     ArgNum++;
7448   }
7449   if (checkArgCount(*this, TheCall, ArgNum))
7450     return true;
7451 
7452   return false;
7453 }
7454 
7455 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7456 /// This checks that the target supports __builtin_longjmp and
7457 /// that val is a constant 1.
7458 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7459   if (!Context.getTargetInfo().hasSjLjLowering())
7460     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7461            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7462 
7463   Expr *Arg = TheCall->getArg(1);
7464   llvm::APSInt Result;
7465 
7466   // TODO: This is less than ideal. Overload this to take a value.
7467   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7468     return true;
7469 
7470   if (Result != 1)
7471     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7472            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7473 
7474   return false;
7475 }
7476 
7477 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7478 /// This checks that the target supports __builtin_setjmp.
7479 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7480   if (!Context.getTargetInfo().hasSjLjLowering())
7481     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7482            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7483   return false;
7484 }
7485 
7486 namespace {
7487 
7488 class UncoveredArgHandler {
7489   enum { Unknown = -1, AllCovered = -2 };
7490 
7491   signed FirstUncoveredArg = Unknown;
7492   SmallVector<const Expr *, 4> DiagnosticExprs;
7493 
7494 public:
7495   UncoveredArgHandler() = default;
7496 
7497   bool hasUncoveredArg() const {
7498     return (FirstUncoveredArg >= 0);
7499   }
7500 
7501   unsigned getUncoveredArg() const {
7502     assert(hasUncoveredArg() && "no uncovered argument");
7503     return FirstUncoveredArg;
7504   }
7505 
7506   void setAllCovered() {
7507     // A string has been found with all arguments covered, so clear out
7508     // the diagnostics.
7509     DiagnosticExprs.clear();
7510     FirstUncoveredArg = AllCovered;
7511   }
7512 
7513   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7514     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7515 
7516     // Don't update if a previous string covers all arguments.
7517     if (FirstUncoveredArg == AllCovered)
7518       return;
7519 
7520     // UncoveredArgHandler tracks the highest uncovered argument index
7521     // and with it all the strings that match this index.
7522     if (NewFirstUncoveredArg == FirstUncoveredArg)
7523       DiagnosticExprs.push_back(StrExpr);
7524     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7525       DiagnosticExprs.clear();
7526       DiagnosticExprs.push_back(StrExpr);
7527       FirstUncoveredArg = NewFirstUncoveredArg;
7528     }
7529   }
7530 
7531   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7532 };
7533 
7534 enum StringLiteralCheckType {
7535   SLCT_NotALiteral,
7536   SLCT_UncheckedLiteral,
7537   SLCT_CheckedLiteral
7538 };
7539 
7540 } // namespace
7541 
7542 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7543                                      BinaryOperatorKind BinOpKind,
7544                                      bool AddendIsRight) {
7545   unsigned BitWidth = Offset.getBitWidth();
7546   unsigned AddendBitWidth = Addend.getBitWidth();
7547   // There might be negative interim results.
7548   if (Addend.isUnsigned()) {
7549     Addend = Addend.zext(++AddendBitWidth);
7550     Addend.setIsSigned(true);
7551   }
7552   // Adjust the bit width of the APSInts.
7553   if (AddendBitWidth > BitWidth) {
7554     Offset = Offset.sext(AddendBitWidth);
7555     BitWidth = AddendBitWidth;
7556   } else if (BitWidth > AddendBitWidth) {
7557     Addend = Addend.sext(BitWidth);
7558   }
7559 
7560   bool Ov = false;
7561   llvm::APSInt ResOffset = Offset;
7562   if (BinOpKind == BO_Add)
7563     ResOffset = Offset.sadd_ov(Addend, Ov);
7564   else {
7565     assert(AddendIsRight && BinOpKind == BO_Sub &&
7566            "operator must be add or sub with addend on the right");
7567     ResOffset = Offset.ssub_ov(Addend, Ov);
7568   }
7569 
7570   // We add an offset to a pointer here so we should support an offset as big as
7571   // possible.
7572   if (Ov) {
7573     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7574            "index (intermediate) result too big");
7575     Offset = Offset.sext(2 * BitWidth);
7576     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7577     return;
7578   }
7579 
7580   Offset = ResOffset;
7581 }
7582 
7583 namespace {
7584 
7585 // This is a wrapper class around StringLiteral to support offsetted string
7586 // literals as format strings. It takes the offset into account when returning
7587 // the string and its length or the source locations to display notes correctly.
7588 class FormatStringLiteral {
7589   const StringLiteral *FExpr;
7590   int64_t Offset;
7591 
7592  public:
7593   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7594       : FExpr(fexpr), Offset(Offset) {}
7595 
7596   StringRef getString() const {
7597     return FExpr->getString().drop_front(Offset);
7598   }
7599 
7600   unsigned getByteLength() const {
7601     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7602   }
7603 
7604   unsigned getLength() const { return FExpr->getLength() - Offset; }
7605   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7606 
7607   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7608 
7609   QualType getType() const { return FExpr->getType(); }
7610 
7611   bool isAscii() const { return FExpr->isAscii(); }
7612   bool isWide() const { return FExpr->isWide(); }
7613   bool isUTF8() const { return FExpr->isUTF8(); }
7614   bool isUTF16() const { return FExpr->isUTF16(); }
7615   bool isUTF32() const { return FExpr->isUTF32(); }
7616   bool isPascal() const { return FExpr->isPascal(); }
7617 
7618   SourceLocation getLocationOfByte(
7619       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7620       const TargetInfo &Target, unsigned *StartToken = nullptr,
7621       unsigned *StartTokenByteOffset = nullptr) const {
7622     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7623                                     StartToken, StartTokenByteOffset);
7624   }
7625 
7626   SourceLocation getBeginLoc() const LLVM_READONLY {
7627     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7628   }
7629 
7630   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7631 };
7632 
7633 }  // namespace
7634 
7635 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7636                               const Expr *OrigFormatExpr,
7637                               ArrayRef<const Expr *> Args,
7638                               bool HasVAListArg, unsigned format_idx,
7639                               unsigned firstDataArg,
7640                               Sema::FormatStringType Type,
7641                               bool inFunctionCall,
7642                               Sema::VariadicCallType CallType,
7643                               llvm::SmallBitVector &CheckedVarArgs,
7644                               UncoveredArgHandler &UncoveredArg,
7645                               bool IgnoreStringsWithoutSpecifiers);
7646 
7647 // Determine if an expression is a string literal or constant string.
7648 // If this function returns false on the arguments to a function expecting a
7649 // format string, we will usually need to emit a warning.
7650 // True string literals are then checked by CheckFormatString.
7651 static StringLiteralCheckType
7652 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7653                       bool HasVAListArg, unsigned format_idx,
7654                       unsigned firstDataArg, Sema::FormatStringType Type,
7655                       Sema::VariadicCallType CallType, bool InFunctionCall,
7656                       llvm::SmallBitVector &CheckedVarArgs,
7657                       UncoveredArgHandler &UncoveredArg,
7658                       llvm::APSInt Offset,
7659                       bool IgnoreStringsWithoutSpecifiers = false) {
7660   if (S.isConstantEvaluated())
7661     return SLCT_NotALiteral;
7662  tryAgain:
7663   assert(Offset.isSigned() && "invalid offset");
7664 
7665   if (E->isTypeDependent() || E->isValueDependent())
7666     return SLCT_NotALiteral;
7667 
7668   E = E->IgnoreParenCasts();
7669 
7670   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7671     // Technically -Wformat-nonliteral does not warn about this case.
7672     // The behavior of printf and friends in this case is implementation
7673     // dependent.  Ideally if the format string cannot be null then
7674     // it should have a 'nonnull' attribute in the function prototype.
7675     return SLCT_UncheckedLiteral;
7676 
7677   switch (E->getStmtClass()) {
7678   case Stmt::BinaryConditionalOperatorClass:
7679   case Stmt::ConditionalOperatorClass: {
7680     // The expression is a literal if both sub-expressions were, and it was
7681     // completely checked only if both sub-expressions were checked.
7682     const AbstractConditionalOperator *C =
7683         cast<AbstractConditionalOperator>(E);
7684 
7685     // Determine whether it is necessary to check both sub-expressions, for
7686     // example, because the condition expression is a constant that can be
7687     // evaluated at compile time.
7688     bool CheckLeft = true, CheckRight = true;
7689 
7690     bool Cond;
7691     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7692                                                  S.isConstantEvaluated())) {
7693       if (Cond)
7694         CheckRight = false;
7695       else
7696         CheckLeft = false;
7697     }
7698 
7699     // We need to maintain the offsets for the right and the left hand side
7700     // separately to check if every possible indexed expression is a valid
7701     // string literal. They might have different offsets for different string
7702     // literals in the end.
7703     StringLiteralCheckType Left;
7704     if (!CheckLeft)
7705       Left = SLCT_UncheckedLiteral;
7706     else {
7707       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7708                                    HasVAListArg, format_idx, firstDataArg,
7709                                    Type, CallType, InFunctionCall,
7710                                    CheckedVarArgs, UncoveredArg, Offset,
7711                                    IgnoreStringsWithoutSpecifiers);
7712       if (Left == SLCT_NotALiteral || !CheckRight) {
7713         return Left;
7714       }
7715     }
7716 
7717     StringLiteralCheckType Right = checkFormatStringExpr(
7718         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7719         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7720         IgnoreStringsWithoutSpecifiers);
7721 
7722     return (CheckLeft && Left < Right) ? Left : Right;
7723   }
7724 
7725   case Stmt::ImplicitCastExprClass:
7726     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7727     goto tryAgain;
7728 
7729   case Stmt::OpaqueValueExprClass:
7730     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7731       E = src;
7732       goto tryAgain;
7733     }
7734     return SLCT_NotALiteral;
7735 
7736   case Stmt::PredefinedExprClass:
7737     // While __func__, etc., are technically not string literals, they
7738     // cannot contain format specifiers and thus are not a security
7739     // liability.
7740     return SLCT_UncheckedLiteral;
7741 
7742   case Stmt::DeclRefExprClass: {
7743     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7744 
7745     // As an exception, do not flag errors for variables binding to
7746     // const string literals.
7747     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7748       bool isConstant = false;
7749       QualType T = DR->getType();
7750 
7751       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7752         isConstant = AT->getElementType().isConstant(S.Context);
7753       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7754         isConstant = T.isConstant(S.Context) &&
7755                      PT->getPointeeType().isConstant(S.Context);
7756       } else if (T->isObjCObjectPointerType()) {
7757         // In ObjC, there is usually no "const ObjectPointer" type,
7758         // so don't check if the pointee type is constant.
7759         isConstant = T.isConstant(S.Context);
7760       }
7761 
7762       if (isConstant) {
7763         if (const Expr *Init = VD->getAnyInitializer()) {
7764           // Look through initializers like const char c[] = { "foo" }
7765           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7766             if (InitList->isStringLiteralInit())
7767               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7768           }
7769           return checkFormatStringExpr(S, Init, Args,
7770                                        HasVAListArg, format_idx,
7771                                        firstDataArg, Type, CallType,
7772                                        /*InFunctionCall*/ false, CheckedVarArgs,
7773                                        UncoveredArg, Offset);
7774         }
7775       }
7776 
7777       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7778       // special check to see if the format string is a function parameter
7779       // of the function calling the printf function.  If the function
7780       // has an attribute indicating it is a printf-like function, then we
7781       // should suppress warnings concerning non-literals being used in a call
7782       // to a vprintf function.  For example:
7783       //
7784       // void
7785       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7786       //      va_list ap;
7787       //      va_start(ap, fmt);
7788       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7789       //      ...
7790       // }
7791       if (HasVAListArg) {
7792         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7793           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
7794             int PVIndex = PV->getFunctionScopeIndex() + 1;
7795             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7796               // adjust for implicit parameter
7797               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
7798                 if (MD->isInstance())
7799                   ++PVIndex;
7800               // We also check if the formats are compatible.
7801               // We can't pass a 'scanf' string to a 'printf' function.
7802               if (PVIndex == PVFormat->getFormatIdx() &&
7803                   Type == S.GetFormatStringType(PVFormat))
7804                 return SLCT_UncheckedLiteral;
7805             }
7806           }
7807         }
7808       }
7809     }
7810 
7811     return SLCT_NotALiteral;
7812   }
7813 
7814   case Stmt::CallExprClass:
7815   case Stmt::CXXMemberCallExprClass: {
7816     const CallExpr *CE = cast<CallExpr>(E);
7817     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7818       bool IsFirst = true;
7819       StringLiteralCheckType CommonResult;
7820       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7821         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7822         StringLiteralCheckType Result = checkFormatStringExpr(
7823             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7824             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7825             IgnoreStringsWithoutSpecifiers);
7826         if (IsFirst) {
7827           CommonResult = Result;
7828           IsFirst = false;
7829         }
7830       }
7831       if (!IsFirst)
7832         return CommonResult;
7833 
7834       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7835         unsigned BuiltinID = FD->getBuiltinID();
7836         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7837             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7838           const Expr *Arg = CE->getArg(0);
7839           return checkFormatStringExpr(S, Arg, Args,
7840                                        HasVAListArg, format_idx,
7841                                        firstDataArg, Type, CallType,
7842                                        InFunctionCall, CheckedVarArgs,
7843                                        UncoveredArg, Offset,
7844                                        IgnoreStringsWithoutSpecifiers);
7845         }
7846       }
7847     }
7848 
7849     return SLCT_NotALiteral;
7850   }
7851   case Stmt::ObjCMessageExprClass: {
7852     const auto *ME = cast<ObjCMessageExpr>(E);
7853     if (const auto *MD = ME->getMethodDecl()) {
7854       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7855         // As a special case heuristic, if we're using the method -[NSBundle
7856         // localizedStringForKey:value:table:], ignore any key strings that lack
7857         // format specifiers. The idea is that if the key doesn't have any
7858         // format specifiers then its probably just a key to map to the
7859         // localized strings. If it does have format specifiers though, then its
7860         // likely that the text of the key is the format string in the
7861         // programmer's language, and should be checked.
7862         const ObjCInterfaceDecl *IFace;
7863         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7864             IFace->getIdentifier()->isStr("NSBundle") &&
7865             MD->getSelector().isKeywordSelector(
7866                 {"localizedStringForKey", "value", "table"})) {
7867           IgnoreStringsWithoutSpecifiers = true;
7868         }
7869 
7870         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7871         return checkFormatStringExpr(
7872             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7873             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7874             IgnoreStringsWithoutSpecifiers);
7875       }
7876     }
7877 
7878     return SLCT_NotALiteral;
7879   }
7880   case Stmt::ObjCStringLiteralClass:
7881   case Stmt::StringLiteralClass: {
7882     const StringLiteral *StrE = nullptr;
7883 
7884     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7885       StrE = ObjCFExpr->getString();
7886     else
7887       StrE = cast<StringLiteral>(E);
7888 
7889     if (StrE) {
7890       if (Offset.isNegative() || Offset > StrE->getLength()) {
7891         // TODO: It would be better to have an explicit warning for out of
7892         // bounds literals.
7893         return SLCT_NotALiteral;
7894       }
7895       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7896       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7897                         firstDataArg, Type, InFunctionCall, CallType,
7898                         CheckedVarArgs, UncoveredArg,
7899                         IgnoreStringsWithoutSpecifiers);
7900       return SLCT_CheckedLiteral;
7901     }
7902 
7903     return SLCT_NotALiteral;
7904   }
7905   case Stmt::BinaryOperatorClass: {
7906     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7907 
7908     // A string literal + an int offset is still a string literal.
7909     if (BinOp->isAdditiveOp()) {
7910       Expr::EvalResult LResult, RResult;
7911 
7912       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7913           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7914       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7915           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7916 
7917       if (LIsInt != RIsInt) {
7918         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7919 
7920         if (LIsInt) {
7921           if (BinOpKind == BO_Add) {
7922             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7923             E = BinOp->getRHS();
7924             goto tryAgain;
7925           }
7926         } else {
7927           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7928           E = BinOp->getLHS();
7929           goto tryAgain;
7930         }
7931       }
7932     }
7933 
7934     return SLCT_NotALiteral;
7935   }
7936   case Stmt::UnaryOperatorClass: {
7937     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7938     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7939     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7940       Expr::EvalResult IndexResult;
7941       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7942                                        Expr::SE_NoSideEffects,
7943                                        S.isConstantEvaluated())) {
7944         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7945                    /*RHS is int*/ true);
7946         E = ASE->getBase();
7947         goto tryAgain;
7948       }
7949     }
7950 
7951     return SLCT_NotALiteral;
7952   }
7953 
7954   default:
7955     return SLCT_NotALiteral;
7956   }
7957 }
7958 
7959 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7960   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7961       .Case("scanf", FST_Scanf)
7962       .Cases("printf", "printf0", FST_Printf)
7963       .Cases("NSString", "CFString", FST_NSString)
7964       .Case("strftime", FST_Strftime)
7965       .Case("strfmon", FST_Strfmon)
7966       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7967       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7968       .Case("os_trace", FST_OSLog)
7969       .Case("os_log", FST_OSLog)
7970       .Default(FST_Unknown);
7971 }
7972 
7973 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7974 /// functions) for correct use of format strings.
7975 /// Returns true if a format string has been fully checked.
7976 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7977                                 ArrayRef<const Expr *> Args,
7978                                 bool IsCXXMember,
7979                                 VariadicCallType CallType,
7980                                 SourceLocation Loc, SourceRange Range,
7981                                 llvm::SmallBitVector &CheckedVarArgs) {
7982   FormatStringInfo FSI;
7983   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7984     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7985                                 FSI.FirstDataArg, GetFormatStringType(Format),
7986                                 CallType, Loc, Range, CheckedVarArgs);
7987   return false;
7988 }
7989 
7990 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7991                                 bool HasVAListArg, unsigned format_idx,
7992                                 unsigned firstDataArg, FormatStringType Type,
7993                                 VariadicCallType CallType,
7994                                 SourceLocation Loc, SourceRange Range,
7995                                 llvm::SmallBitVector &CheckedVarArgs) {
7996   // CHECK: printf/scanf-like function is called with no format string.
7997   if (format_idx >= Args.size()) {
7998     Diag(Loc, diag::warn_missing_format_string) << Range;
7999     return false;
8000   }
8001 
8002   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8003 
8004   // CHECK: format string is not a string literal.
8005   //
8006   // Dynamically generated format strings are difficult to
8007   // automatically vet at compile time.  Requiring that format strings
8008   // are string literals: (1) permits the checking of format strings by
8009   // the compiler and thereby (2) can practically remove the source of
8010   // many format string exploits.
8011 
8012   // Format string can be either ObjC string (e.g. @"%d") or
8013   // C string (e.g. "%d")
8014   // ObjC string uses the same format specifiers as C string, so we can use
8015   // the same format string checking logic for both ObjC and C strings.
8016   UncoveredArgHandler UncoveredArg;
8017   StringLiteralCheckType CT =
8018       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8019                             format_idx, firstDataArg, Type, CallType,
8020                             /*IsFunctionCall*/ true, CheckedVarArgs,
8021                             UncoveredArg,
8022                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8023 
8024   // Generate a diagnostic where an uncovered argument is detected.
8025   if (UncoveredArg.hasUncoveredArg()) {
8026     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8027     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8028     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8029   }
8030 
8031   if (CT != SLCT_NotALiteral)
8032     // Literal format string found, check done!
8033     return CT == SLCT_CheckedLiteral;
8034 
8035   // Strftime is particular as it always uses a single 'time' argument,
8036   // so it is safe to pass a non-literal string.
8037   if (Type == FST_Strftime)
8038     return false;
8039 
8040   // Do not emit diag when the string param is a macro expansion and the
8041   // format is either NSString or CFString. This is a hack to prevent
8042   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8043   // which are usually used in place of NS and CF string literals.
8044   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8045   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8046     return false;
8047 
8048   // If there are no arguments specified, warn with -Wformat-security, otherwise
8049   // warn only with -Wformat-nonliteral.
8050   if (Args.size() == firstDataArg) {
8051     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8052       << OrigFormatExpr->getSourceRange();
8053     switch (Type) {
8054     default:
8055       break;
8056     case FST_Kprintf:
8057     case FST_FreeBSDKPrintf:
8058     case FST_Printf:
8059       Diag(FormatLoc, diag::note_format_security_fixit)
8060         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8061       break;
8062     case FST_NSString:
8063       Diag(FormatLoc, diag::note_format_security_fixit)
8064         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8065       break;
8066     }
8067   } else {
8068     Diag(FormatLoc, diag::warn_format_nonliteral)
8069       << OrigFormatExpr->getSourceRange();
8070   }
8071   return false;
8072 }
8073 
8074 namespace {
8075 
8076 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8077 protected:
8078   Sema &S;
8079   const FormatStringLiteral *FExpr;
8080   const Expr *OrigFormatExpr;
8081   const Sema::FormatStringType FSType;
8082   const unsigned FirstDataArg;
8083   const unsigned NumDataArgs;
8084   const char *Beg; // Start of format string.
8085   const bool HasVAListArg;
8086   ArrayRef<const Expr *> Args;
8087   unsigned FormatIdx;
8088   llvm::SmallBitVector CoveredArgs;
8089   bool usesPositionalArgs = false;
8090   bool atFirstArg = true;
8091   bool inFunctionCall;
8092   Sema::VariadicCallType CallType;
8093   llvm::SmallBitVector &CheckedVarArgs;
8094   UncoveredArgHandler &UncoveredArg;
8095 
8096 public:
8097   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8098                      const Expr *origFormatExpr,
8099                      const Sema::FormatStringType type, unsigned firstDataArg,
8100                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8101                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8102                      bool inFunctionCall, Sema::VariadicCallType callType,
8103                      llvm::SmallBitVector &CheckedVarArgs,
8104                      UncoveredArgHandler &UncoveredArg)
8105       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8106         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8107         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8108         inFunctionCall(inFunctionCall), CallType(callType),
8109         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8110     CoveredArgs.resize(numDataArgs);
8111     CoveredArgs.reset();
8112   }
8113 
8114   void DoneProcessing();
8115 
8116   void HandleIncompleteSpecifier(const char *startSpecifier,
8117                                  unsigned specifierLen) override;
8118 
8119   void HandleInvalidLengthModifier(
8120                            const analyze_format_string::FormatSpecifier &FS,
8121                            const analyze_format_string::ConversionSpecifier &CS,
8122                            const char *startSpecifier, unsigned specifierLen,
8123                            unsigned DiagID);
8124 
8125   void HandleNonStandardLengthModifier(
8126                     const analyze_format_string::FormatSpecifier &FS,
8127                     const char *startSpecifier, unsigned specifierLen);
8128 
8129   void HandleNonStandardConversionSpecifier(
8130                     const analyze_format_string::ConversionSpecifier &CS,
8131                     const char *startSpecifier, unsigned specifierLen);
8132 
8133   void HandlePosition(const char *startPos, unsigned posLen) override;
8134 
8135   void HandleInvalidPosition(const char *startSpecifier,
8136                              unsigned specifierLen,
8137                              analyze_format_string::PositionContext p) override;
8138 
8139   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8140 
8141   void HandleNullChar(const char *nullCharacter) override;
8142 
8143   template <typename Range>
8144   static void
8145   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8146                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8147                        bool IsStringLocation, Range StringRange,
8148                        ArrayRef<FixItHint> Fixit = None);
8149 
8150 protected:
8151   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8152                                         const char *startSpec,
8153                                         unsigned specifierLen,
8154                                         const char *csStart, unsigned csLen);
8155 
8156   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8157                                          const char *startSpec,
8158                                          unsigned specifierLen);
8159 
8160   SourceRange getFormatStringRange();
8161   CharSourceRange getSpecifierRange(const char *startSpecifier,
8162                                     unsigned specifierLen);
8163   SourceLocation getLocationOfByte(const char *x);
8164 
8165   const Expr *getDataArg(unsigned i) const;
8166 
8167   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8168                     const analyze_format_string::ConversionSpecifier &CS,
8169                     const char *startSpecifier, unsigned specifierLen,
8170                     unsigned argIndex);
8171 
8172   template <typename Range>
8173   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8174                             bool IsStringLocation, Range StringRange,
8175                             ArrayRef<FixItHint> Fixit = None);
8176 };
8177 
8178 } // namespace
8179 
8180 SourceRange CheckFormatHandler::getFormatStringRange() {
8181   return OrigFormatExpr->getSourceRange();
8182 }
8183 
8184 CharSourceRange CheckFormatHandler::
8185 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8186   SourceLocation Start = getLocationOfByte(startSpecifier);
8187   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8188 
8189   // Advance the end SourceLocation by one due to half-open ranges.
8190   End = End.getLocWithOffset(1);
8191 
8192   return CharSourceRange::getCharRange(Start, End);
8193 }
8194 
8195 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8196   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8197                                   S.getLangOpts(), S.Context.getTargetInfo());
8198 }
8199 
8200 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8201                                                    unsigned specifierLen){
8202   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8203                        getLocationOfByte(startSpecifier),
8204                        /*IsStringLocation*/true,
8205                        getSpecifierRange(startSpecifier, specifierLen));
8206 }
8207 
8208 void CheckFormatHandler::HandleInvalidLengthModifier(
8209     const analyze_format_string::FormatSpecifier &FS,
8210     const analyze_format_string::ConversionSpecifier &CS,
8211     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8212   using namespace analyze_format_string;
8213 
8214   const LengthModifier &LM = FS.getLengthModifier();
8215   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8216 
8217   // See if we know how to fix this length modifier.
8218   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8219   if (FixedLM) {
8220     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8221                          getLocationOfByte(LM.getStart()),
8222                          /*IsStringLocation*/true,
8223                          getSpecifierRange(startSpecifier, specifierLen));
8224 
8225     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8226       << FixedLM->toString()
8227       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8228 
8229   } else {
8230     FixItHint Hint;
8231     if (DiagID == diag::warn_format_nonsensical_length)
8232       Hint = FixItHint::CreateRemoval(LMRange);
8233 
8234     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8235                          getLocationOfByte(LM.getStart()),
8236                          /*IsStringLocation*/true,
8237                          getSpecifierRange(startSpecifier, specifierLen),
8238                          Hint);
8239   }
8240 }
8241 
8242 void CheckFormatHandler::HandleNonStandardLengthModifier(
8243     const analyze_format_string::FormatSpecifier &FS,
8244     const char *startSpecifier, unsigned specifierLen) {
8245   using namespace analyze_format_string;
8246 
8247   const LengthModifier &LM = FS.getLengthModifier();
8248   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8249 
8250   // See if we know how to fix this length modifier.
8251   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8252   if (FixedLM) {
8253     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8254                            << LM.toString() << 0,
8255                          getLocationOfByte(LM.getStart()),
8256                          /*IsStringLocation*/true,
8257                          getSpecifierRange(startSpecifier, specifierLen));
8258 
8259     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8260       << FixedLM->toString()
8261       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8262 
8263   } else {
8264     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8265                            << LM.toString() << 0,
8266                          getLocationOfByte(LM.getStart()),
8267                          /*IsStringLocation*/true,
8268                          getSpecifierRange(startSpecifier, specifierLen));
8269   }
8270 }
8271 
8272 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8273     const analyze_format_string::ConversionSpecifier &CS,
8274     const char *startSpecifier, unsigned specifierLen) {
8275   using namespace analyze_format_string;
8276 
8277   // See if we know how to fix this conversion specifier.
8278   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8279   if (FixedCS) {
8280     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8281                           << CS.toString() << /*conversion specifier*/1,
8282                          getLocationOfByte(CS.getStart()),
8283                          /*IsStringLocation*/true,
8284                          getSpecifierRange(startSpecifier, specifierLen));
8285 
8286     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8287     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8288       << FixedCS->toString()
8289       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8290   } else {
8291     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8292                           << CS.toString() << /*conversion specifier*/1,
8293                          getLocationOfByte(CS.getStart()),
8294                          /*IsStringLocation*/true,
8295                          getSpecifierRange(startSpecifier, specifierLen));
8296   }
8297 }
8298 
8299 void CheckFormatHandler::HandlePosition(const char *startPos,
8300                                         unsigned posLen) {
8301   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8302                                getLocationOfByte(startPos),
8303                                /*IsStringLocation*/true,
8304                                getSpecifierRange(startPos, posLen));
8305 }
8306 
8307 void
8308 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8309                                      analyze_format_string::PositionContext p) {
8310   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8311                          << (unsigned) p,
8312                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8313                        getSpecifierRange(startPos, posLen));
8314 }
8315 
8316 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8317                                             unsigned posLen) {
8318   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8319                                getLocationOfByte(startPos),
8320                                /*IsStringLocation*/true,
8321                                getSpecifierRange(startPos, posLen));
8322 }
8323 
8324 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8325   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8326     // The presence of a null character is likely an error.
8327     EmitFormatDiagnostic(
8328       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8329       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8330       getFormatStringRange());
8331   }
8332 }
8333 
8334 // Note that this may return NULL if there was an error parsing or building
8335 // one of the argument expressions.
8336 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8337   return Args[FirstDataArg + i];
8338 }
8339 
8340 void CheckFormatHandler::DoneProcessing() {
8341   // Does the number of data arguments exceed the number of
8342   // format conversions in the format string?
8343   if (!HasVAListArg) {
8344       // Find any arguments that weren't covered.
8345     CoveredArgs.flip();
8346     signed notCoveredArg = CoveredArgs.find_first();
8347     if (notCoveredArg >= 0) {
8348       assert((unsigned)notCoveredArg < NumDataArgs);
8349       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8350     } else {
8351       UncoveredArg.setAllCovered();
8352     }
8353   }
8354 }
8355 
8356 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8357                                    const Expr *ArgExpr) {
8358   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8359          "Invalid state");
8360 
8361   if (!ArgExpr)
8362     return;
8363 
8364   SourceLocation Loc = ArgExpr->getBeginLoc();
8365 
8366   if (S.getSourceManager().isInSystemMacro(Loc))
8367     return;
8368 
8369   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8370   for (auto E : DiagnosticExprs)
8371     PDiag << E->getSourceRange();
8372 
8373   CheckFormatHandler::EmitFormatDiagnostic(
8374                                   S, IsFunctionCall, DiagnosticExprs[0],
8375                                   PDiag, Loc, /*IsStringLocation*/false,
8376                                   DiagnosticExprs[0]->getSourceRange());
8377 }
8378 
8379 bool
8380 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8381                                                      SourceLocation Loc,
8382                                                      const char *startSpec,
8383                                                      unsigned specifierLen,
8384                                                      const char *csStart,
8385                                                      unsigned csLen) {
8386   bool keepGoing = true;
8387   if (argIndex < NumDataArgs) {
8388     // Consider the argument coverered, even though the specifier doesn't
8389     // make sense.
8390     CoveredArgs.set(argIndex);
8391   }
8392   else {
8393     // If argIndex exceeds the number of data arguments we
8394     // don't issue a warning because that is just a cascade of warnings (and
8395     // they may have intended '%%' anyway). We don't want to continue processing
8396     // the format string after this point, however, as we will like just get
8397     // gibberish when trying to match arguments.
8398     keepGoing = false;
8399   }
8400 
8401   StringRef Specifier(csStart, csLen);
8402 
8403   // If the specifier in non-printable, it could be the first byte of a UTF-8
8404   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8405   // hex value.
8406   std::string CodePointStr;
8407   if (!llvm::sys::locale::isPrint(*csStart)) {
8408     llvm::UTF32 CodePoint;
8409     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8410     const llvm::UTF8 *E =
8411         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8412     llvm::ConversionResult Result =
8413         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8414 
8415     if (Result != llvm::conversionOK) {
8416       unsigned char FirstChar = *csStart;
8417       CodePoint = (llvm::UTF32)FirstChar;
8418     }
8419 
8420     llvm::raw_string_ostream OS(CodePointStr);
8421     if (CodePoint < 256)
8422       OS << "\\x" << llvm::format("%02x", CodePoint);
8423     else if (CodePoint <= 0xFFFF)
8424       OS << "\\u" << llvm::format("%04x", CodePoint);
8425     else
8426       OS << "\\U" << llvm::format("%08x", CodePoint);
8427     OS.flush();
8428     Specifier = CodePointStr;
8429   }
8430 
8431   EmitFormatDiagnostic(
8432       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8433       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8434 
8435   return keepGoing;
8436 }
8437 
8438 void
8439 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8440                                                       const char *startSpec,
8441                                                       unsigned specifierLen) {
8442   EmitFormatDiagnostic(
8443     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8444     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8445 }
8446 
8447 bool
8448 CheckFormatHandler::CheckNumArgs(
8449   const analyze_format_string::FormatSpecifier &FS,
8450   const analyze_format_string::ConversionSpecifier &CS,
8451   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8452 
8453   if (argIndex >= NumDataArgs) {
8454     PartialDiagnostic PDiag = FS.usesPositionalArg()
8455       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8456            << (argIndex+1) << NumDataArgs)
8457       : S.PDiag(diag::warn_printf_insufficient_data_args);
8458     EmitFormatDiagnostic(
8459       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8460       getSpecifierRange(startSpecifier, specifierLen));
8461 
8462     // Since more arguments than conversion tokens are given, by extension
8463     // all arguments are covered, so mark this as so.
8464     UncoveredArg.setAllCovered();
8465     return false;
8466   }
8467   return true;
8468 }
8469 
8470 template<typename Range>
8471 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8472                                               SourceLocation Loc,
8473                                               bool IsStringLocation,
8474                                               Range StringRange,
8475                                               ArrayRef<FixItHint> FixIt) {
8476   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8477                        Loc, IsStringLocation, StringRange, FixIt);
8478 }
8479 
8480 /// If the format string is not within the function call, emit a note
8481 /// so that the function call and string are in diagnostic messages.
8482 ///
8483 /// \param InFunctionCall if true, the format string is within the function
8484 /// call and only one diagnostic message will be produced.  Otherwise, an
8485 /// extra note will be emitted pointing to location of the format string.
8486 ///
8487 /// \param ArgumentExpr the expression that is passed as the format string
8488 /// argument in the function call.  Used for getting locations when two
8489 /// diagnostics are emitted.
8490 ///
8491 /// \param PDiag the callee should already have provided any strings for the
8492 /// diagnostic message.  This function only adds locations and fixits
8493 /// to diagnostics.
8494 ///
8495 /// \param Loc primary location for diagnostic.  If two diagnostics are
8496 /// required, one will be at Loc and a new SourceLocation will be created for
8497 /// the other one.
8498 ///
8499 /// \param IsStringLocation if true, Loc points to the format string should be
8500 /// used for the note.  Otherwise, Loc points to the argument list and will
8501 /// be used with PDiag.
8502 ///
8503 /// \param StringRange some or all of the string to highlight.  This is
8504 /// templated so it can accept either a CharSourceRange or a SourceRange.
8505 ///
8506 /// \param FixIt optional fix it hint for the format string.
8507 template <typename Range>
8508 void CheckFormatHandler::EmitFormatDiagnostic(
8509     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8510     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8511     Range StringRange, ArrayRef<FixItHint> FixIt) {
8512   if (InFunctionCall) {
8513     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8514     D << StringRange;
8515     D << FixIt;
8516   } else {
8517     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8518       << ArgumentExpr->getSourceRange();
8519 
8520     const Sema::SemaDiagnosticBuilder &Note =
8521       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8522              diag::note_format_string_defined);
8523 
8524     Note << StringRange;
8525     Note << FixIt;
8526   }
8527 }
8528 
8529 //===--- CHECK: Printf format string checking ------------------------------===//
8530 
8531 namespace {
8532 
8533 class CheckPrintfHandler : public CheckFormatHandler {
8534 public:
8535   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8536                      const Expr *origFormatExpr,
8537                      const Sema::FormatStringType type, unsigned firstDataArg,
8538                      unsigned numDataArgs, bool isObjC, const char *beg,
8539                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8540                      unsigned formatIdx, bool inFunctionCall,
8541                      Sema::VariadicCallType CallType,
8542                      llvm::SmallBitVector &CheckedVarArgs,
8543                      UncoveredArgHandler &UncoveredArg)
8544       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8545                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8546                            inFunctionCall, CallType, CheckedVarArgs,
8547                            UncoveredArg) {}
8548 
8549   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8550 
8551   /// Returns true if '%@' specifiers are allowed in the format string.
8552   bool allowsObjCArg() const {
8553     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8554            FSType == Sema::FST_OSTrace;
8555   }
8556 
8557   bool HandleInvalidPrintfConversionSpecifier(
8558                                       const analyze_printf::PrintfSpecifier &FS,
8559                                       const char *startSpecifier,
8560                                       unsigned specifierLen) override;
8561 
8562   void handleInvalidMaskType(StringRef MaskType) override;
8563 
8564   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8565                              const char *startSpecifier,
8566                              unsigned specifierLen) override;
8567   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8568                        const char *StartSpecifier,
8569                        unsigned SpecifierLen,
8570                        const Expr *E);
8571 
8572   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8573                     const char *startSpecifier, unsigned specifierLen);
8574   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8575                            const analyze_printf::OptionalAmount &Amt,
8576                            unsigned type,
8577                            const char *startSpecifier, unsigned specifierLen);
8578   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8579                   const analyze_printf::OptionalFlag &flag,
8580                   const char *startSpecifier, unsigned specifierLen);
8581   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8582                          const analyze_printf::OptionalFlag &ignoredFlag,
8583                          const analyze_printf::OptionalFlag &flag,
8584                          const char *startSpecifier, unsigned specifierLen);
8585   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8586                            const Expr *E);
8587 
8588   void HandleEmptyObjCModifierFlag(const char *startFlag,
8589                                    unsigned flagLen) override;
8590 
8591   void HandleInvalidObjCModifierFlag(const char *startFlag,
8592                                             unsigned flagLen) override;
8593 
8594   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8595                                            const char *flagsEnd,
8596                                            const char *conversionPosition)
8597                                              override;
8598 };
8599 
8600 } // namespace
8601 
8602 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8603                                       const analyze_printf::PrintfSpecifier &FS,
8604                                       const char *startSpecifier,
8605                                       unsigned specifierLen) {
8606   const analyze_printf::PrintfConversionSpecifier &CS =
8607     FS.getConversionSpecifier();
8608 
8609   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8610                                           getLocationOfByte(CS.getStart()),
8611                                           startSpecifier, specifierLen,
8612                                           CS.getStart(), CS.getLength());
8613 }
8614 
8615 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8616   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8617 }
8618 
8619 bool CheckPrintfHandler::HandleAmount(
8620                                const analyze_format_string::OptionalAmount &Amt,
8621                                unsigned k, const char *startSpecifier,
8622                                unsigned specifierLen) {
8623   if (Amt.hasDataArgument()) {
8624     if (!HasVAListArg) {
8625       unsigned argIndex = Amt.getArgIndex();
8626       if (argIndex >= NumDataArgs) {
8627         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8628                                << k,
8629                              getLocationOfByte(Amt.getStart()),
8630                              /*IsStringLocation*/true,
8631                              getSpecifierRange(startSpecifier, specifierLen));
8632         // Don't do any more checking.  We will just emit
8633         // spurious errors.
8634         return false;
8635       }
8636 
8637       // Type check the data argument.  It should be an 'int'.
8638       // Although not in conformance with C99, we also allow the argument to be
8639       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8640       // doesn't emit a warning for that case.
8641       CoveredArgs.set(argIndex);
8642       const Expr *Arg = getDataArg(argIndex);
8643       if (!Arg)
8644         return false;
8645 
8646       QualType T = Arg->getType();
8647 
8648       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8649       assert(AT.isValid());
8650 
8651       if (!AT.matchesType(S.Context, T)) {
8652         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8653                                << k << AT.getRepresentativeTypeName(S.Context)
8654                                << T << Arg->getSourceRange(),
8655                              getLocationOfByte(Amt.getStart()),
8656                              /*IsStringLocation*/true,
8657                              getSpecifierRange(startSpecifier, specifierLen));
8658         // Don't do any more checking.  We will just emit
8659         // spurious errors.
8660         return false;
8661       }
8662     }
8663   }
8664   return true;
8665 }
8666 
8667 void CheckPrintfHandler::HandleInvalidAmount(
8668                                       const analyze_printf::PrintfSpecifier &FS,
8669                                       const analyze_printf::OptionalAmount &Amt,
8670                                       unsigned type,
8671                                       const char *startSpecifier,
8672                                       unsigned specifierLen) {
8673   const analyze_printf::PrintfConversionSpecifier &CS =
8674     FS.getConversionSpecifier();
8675 
8676   FixItHint fixit =
8677     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8678       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8679                                  Amt.getConstantLength()))
8680       : FixItHint();
8681 
8682   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8683                          << type << CS.toString(),
8684                        getLocationOfByte(Amt.getStart()),
8685                        /*IsStringLocation*/true,
8686                        getSpecifierRange(startSpecifier, specifierLen),
8687                        fixit);
8688 }
8689 
8690 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8691                                     const analyze_printf::OptionalFlag &flag,
8692                                     const char *startSpecifier,
8693                                     unsigned specifierLen) {
8694   // Warn about pointless flag with a fixit removal.
8695   const analyze_printf::PrintfConversionSpecifier &CS =
8696     FS.getConversionSpecifier();
8697   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8698                          << flag.toString() << CS.toString(),
8699                        getLocationOfByte(flag.getPosition()),
8700                        /*IsStringLocation*/true,
8701                        getSpecifierRange(startSpecifier, specifierLen),
8702                        FixItHint::CreateRemoval(
8703                          getSpecifierRange(flag.getPosition(), 1)));
8704 }
8705 
8706 void CheckPrintfHandler::HandleIgnoredFlag(
8707                                 const analyze_printf::PrintfSpecifier &FS,
8708                                 const analyze_printf::OptionalFlag &ignoredFlag,
8709                                 const analyze_printf::OptionalFlag &flag,
8710                                 const char *startSpecifier,
8711                                 unsigned specifierLen) {
8712   // Warn about ignored flag with a fixit removal.
8713   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8714                          << ignoredFlag.toString() << flag.toString(),
8715                        getLocationOfByte(ignoredFlag.getPosition()),
8716                        /*IsStringLocation*/true,
8717                        getSpecifierRange(startSpecifier, specifierLen),
8718                        FixItHint::CreateRemoval(
8719                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8720 }
8721 
8722 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8723                                                      unsigned flagLen) {
8724   // Warn about an empty flag.
8725   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8726                        getLocationOfByte(startFlag),
8727                        /*IsStringLocation*/true,
8728                        getSpecifierRange(startFlag, flagLen));
8729 }
8730 
8731 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8732                                                        unsigned flagLen) {
8733   // Warn about an invalid flag.
8734   auto Range = getSpecifierRange(startFlag, flagLen);
8735   StringRef flag(startFlag, flagLen);
8736   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8737                       getLocationOfByte(startFlag),
8738                       /*IsStringLocation*/true,
8739                       Range, FixItHint::CreateRemoval(Range));
8740 }
8741 
8742 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8743     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8744     // Warn about using '[...]' without a '@' conversion.
8745     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8746     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8747     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8748                          getLocationOfByte(conversionPosition),
8749                          /*IsStringLocation*/true,
8750                          Range, FixItHint::CreateRemoval(Range));
8751 }
8752 
8753 // Determines if the specified is a C++ class or struct containing
8754 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8755 // "c_str()").
8756 template<typename MemberKind>
8757 static llvm::SmallPtrSet<MemberKind*, 1>
8758 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8759   const RecordType *RT = Ty->getAs<RecordType>();
8760   llvm::SmallPtrSet<MemberKind*, 1> Results;
8761 
8762   if (!RT)
8763     return Results;
8764   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8765   if (!RD || !RD->getDefinition())
8766     return Results;
8767 
8768   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8769                  Sema::LookupMemberName);
8770   R.suppressDiagnostics();
8771 
8772   // We just need to include all members of the right kind turned up by the
8773   // filter, at this point.
8774   if (S.LookupQualifiedName(R, RT->getDecl()))
8775     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8776       NamedDecl *decl = (*I)->getUnderlyingDecl();
8777       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8778         Results.insert(FK);
8779     }
8780   return Results;
8781 }
8782 
8783 /// Check if we could call '.c_str()' on an object.
8784 ///
8785 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8786 /// allow the call, or if it would be ambiguous).
8787 bool Sema::hasCStrMethod(const Expr *E) {
8788   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8789 
8790   MethodSet Results =
8791       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8792   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8793        MI != ME; ++MI)
8794     if ((*MI)->getMinRequiredArguments() == 0)
8795       return true;
8796   return false;
8797 }
8798 
8799 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8800 // better diagnostic if so. AT is assumed to be valid.
8801 // Returns true when a c_str() conversion method is found.
8802 bool CheckPrintfHandler::checkForCStrMembers(
8803     const analyze_printf::ArgType &AT, const Expr *E) {
8804   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8805 
8806   MethodSet Results =
8807       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8808 
8809   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8810        MI != ME; ++MI) {
8811     const CXXMethodDecl *Method = *MI;
8812     if (Method->getMinRequiredArguments() == 0 &&
8813         AT.matchesType(S.Context, Method->getReturnType())) {
8814       // FIXME: Suggest parens if the expression needs them.
8815       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8816       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8817           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8818       return true;
8819     }
8820   }
8821 
8822   return false;
8823 }
8824 
8825 bool
8826 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8827                                             &FS,
8828                                           const char *startSpecifier,
8829                                           unsigned specifierLen) {
8830   using namespace analyze_format_string;
8831   using namespace analyze_printf;
8832 
8833   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8834 
8835   if (FS.consumesDataArgument()) {
8836     if (atFirstArg) {
8837         atFirstArg = false;
8838         usesPositionalArgs = FS.usesPositionalArg();
8839     }
8840     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8841       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8842                                         startSpecifier, specifierLen);
8843       return false;
8844     }
8845   }
8846 
8847   // First check if the field width, precision, and conversion specifier
8848   // have matching data arguments.
8849   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8850                     startSpecifier, specifierLen)) {
8851     return false;
8852   }
8853 
8854   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8855                     startSpecifier, specifierLen)) {
8856     return false;
8857   }
8858 
8859   if (!CS.consumesDataArgument()) {
8860     // FIXME: Technically specifying a precision or field width here
8861     // makes no sense.  Worth issuing a warning at some point.
8862     return true;
8863   }
8864 
8865   // Consume the argument.
8866   unsigned argIndex = FS.getArgIndex();
8867   if (argIndex < NumDataArgs) {
8868     // The check to see if the argIndex is valid will come later.
8869     // We set the bit here because we may exit early from this
8870     // function if we encounter some other error.
8871     CoveredArgs.set(argIndex);
8872   }
8873 
8874   // FreeBSD kernel extensions.
8875   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8876       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8877     // We need at least two arguments.
8878     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8879       return false;
8880 
8881     // Claim the second argument.
8882     CoveredArgs.set(argIndex + 1);
8883 
8884     // Type check the first argument (int for %b, pointer for %D)
8885     const Expr *Ex = getDataArg(argIndex);
8886     const analyze_printf::ArgType &AT =
8887       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8888         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8889     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8890       EmitFormatDiagnostic(
8891           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8892               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8893               << false << Ex->getSourceRange(),
8894           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8895           getSpecifierRange(startSpecifier, specifierLen));
8896 
8897     // Type check the second argument (char * for both %b and %D)
8898     Ex = getDataArg(argIndex + 1);
8899     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8900     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8901       EmitFormatDiagnostic(
8902           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8903               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8904               << false << Ex->getSourceRange(),
8905           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8906           getSpecifierRange(startSpecifier, specifierLen));
8907 
8908      return true;
8909   }
8910 
8911   // Check for using an Objective-C specific conversion specifier
8912   // in a non-ObjC literal.
8913   if (!allowsObjCArg() && CS.isObjCArg()) {
8914     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8915                                                   specifierLen);
8916   }
8917 
8918   // %P can only be used with os_log.
8919   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8920     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8921                                                   specifierLen);
8922   }
8923 
8924   // %n is not allowed with os_log.
8925   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8926     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8927                          getLocationOfByte(CS.getStart()),
8928                          /*IsStringLocation*/ false,
8929                          getSpecifierRange(startSpecifier, specifierLen));
8930 
8931     return true;
8932   }
8933 
8934   // Only scalars are allowed for os_trace.
8935   if (FSType == Sema::FST_OSTrace &&
8936       (CS.getKind() == ConversionSpecifier::PArg ||
8937        CS.getKind() == ConversionSpecifier::sArg ||
8938        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8939     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8940                                                   specifierLen);
8941   }
8942 
8943   // Check for use of public/private annotation outside of os_log().
8944   if (FSType != Sema::FST_OSLog) {
8945     if (FS.isPublic().isSet()) {
8946       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8947                                << "public",
8948                            getLocationOfByte(FS.isPublic().getPosition()),
8949                            /*IsStringLocation*/ false,
8950                            getSpecifierRange(startSpecifier, specifierLen));
8951     }
8952     if (FS.isPrivate().isSet()) {
8953       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8954                                << "private",
8955                            getLocationOfByte(FS.isPrivate().getPosition()),
8956                            /*IsStringLocation*/ false,
8957                            getSpecifierRange(startSpecifier, specifierLen));
8958     }
8959   }
8960 
8961   // Check for invalid use of field width
8962   if (!FS.hasValidFieldWidth()) {
8963     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8964         startSpecifier, specifierLen);
8965   }
8966 
8967   // Check for invalid use of precision
8968   if (!FS.hasValidPrecision()) {
8969     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8970         startSpecifier, specifierLen);
8971   }
8972 
8973   // Precision is mandatory for %P specifier.
8974   if (CS.getKind() == ConversionSpecifier::PArg &&
8975       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8976     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8977                          getLocationOfByte(startSpecifier),
8978                          /*IsStringLocation*/ false,
8979                          getSpecifierRange(startSpecifier, specifierLen));
8980   }
8981 
8982   // Check each flag does not conflict with any other component.
8983   if (!FS.hasValidThousandsGroupingPrefix())
8984     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8985   if (!FS.hasValidLeadingZeros())
8986     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8987   if (!FS.hasValidPlusPrefix())
8988     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8989   if (!FS.hasValidSpacePrefix())
8990     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8991   if (!FS.hasValidAlternativeForm())
8992     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8993   if (!FS.hasValidLeftJustified())
8994     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8995 
8996   // Check that flags are not ignored by another flag
8997   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8998     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8999         startSpecifier, specifierLen);
9000   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9001     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9002             startSpecifier, specifierLen);
9003 
9004   // Check the length modifier is valid with the given conversion specifier.
9005   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9006                                  S.getLangOpts()))
9007     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9008                                 diag::warn_format_nonsensical_length);
9009   else if (!FS.hasStandardLengthModifier())
9010     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9011   else if (!FS.hasStandardLengthConversionCombination())
9012     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9013                                 diag::warn_format_non_standard_conversion_spec);
9014 
9015   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9016     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9017 
9018   // The remaining checks depend on the data arguments.
9019   if (HasVAListArg)
9020     return true;
9021 
9022   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9023     return false;
9024 
9025   const Expr *Arg = getDataArg(argIndex);
9026   if (!Arg)
9027     return true;
9028 
9029   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9030 }
9031 
9032 static bool requiresParensToAddCast(const Expr *E) {
9033   // FIXME: We should have a general way to reason about operator
9034   // precedence and whether parens are actually needed here.
9035   // Take care of a few common cases where they aren't.
9036   const Expr *Inside = E->IgnoreImpCasts();
9037   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9038     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9039 
9040   switch (Inside->getStmtClass()) {
9041   case Stmt::ArraySubscriptExprClass:
9042   case Stmt::CallExprClass:
9043   case Stmt::CharacterLiteralClass:
9044   case Stmt::CXXBoolLiteralExprClass:
9045   case Stmt::DeclRefExprClass:
9046   case Stmt::FloatingLiteralClass:
9047   case Stmt::IntegerLiteralClass:
9048   case Stmt::MemberExprClass:
9049   case Stmt::ObjCArrayLiteralClass:
9050   case Stmt::ObjCBoolLiteralExprClass:
9051   case Stmt::ObjCBoxedExprClass:
9052   case Stmt::ObjCDictionaryLiteralClass:
9053   case Stmt::ObjCEncodeExprClass:
9054   case Stmt::ObjCIvarRefExprClass:
9055   case Stmt::ObjCMessageExprClass:
9056   case Stmt::ObjCPropertyRefExprClass:
9057   case Stmt::ObjCStringLiteralClass:
9058   case Stmt::ObjCSubscriptRefExprClass:
9059   case Stmt::ParenExprClass:
9060   case Stmt::StringLiteralClass:
9061   case Stmt::UnaryOperatorClass:
9062     return false;
9063   default:
9064     return true;
9065   }
9066 }
9067 
9068 static std::pair<QualType, StringRef>
9069 shouldNotPrintDirectly(const ASTContext &Context,
9070                        QualType IntendedTy,
9071                        const Expr *E) {
9072   // Use a 'while' to peel off layers of typedefs.
9073   QualType TyTy = IntendedTy;
9074   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9075     StringRef Name = UserTy->getDecl()->getName();
9076     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9077       .Case("CFIndex", Context.getNSIntegerType())
9078       .Case("NSInteger", Context.getNSIntegerType())
9079       .Case("NSUInteger", Context.getNSUIntegerType())
9080       .Case("SInt32", Context.IntTy)
9081       .Case("UInt32", Context.UnsignedIntTy)
9082       .Default(QualType());
9083 
9084     if (!CastTy.isNull())
9085       return std::make_pair(CastTy, Name);
9086 
9087     TyTy = UserTy->desugar();
9088   }
9089 
9090   // Strip parens if necessary.
9091   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9092     return shouldNotPrintDirectly(Context,
9093                                   PE->getSubExpr()->getType(),
9094                                   PE->getSubExpr());
9095 
9096   // If this is a conditional expression, then its result type is constructed
9097   // via usual arithmetic conversions and thus there might be no necessary
9098   // typedef sugar there.  Recurse to operands to check for NSInteger &
9099   // Co. usage condition.
9100   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9101     QualType TrueTy, FalseTy;
9102     StringRef TrueName, FalseName;
9103 
9104     std::tie(TrueTy, TrueName) =
9105       shouldNotPrintDirectly(Context,
9106                              CO->getTrueExpr()->getType(),
9107                              CO->getTrueExpr());
9108     std::tie(FalseTy, FalseName) =
9109       shouldNotPrintDirectly(Context,
9110                              CO->getFalseExpr()->getType(),
9111                              CO->getFalseExpr());
9112 
9113     if (TrueTy == FalseTy)
9114       return std::make_pair(TrueTy, TrueName);
9115     else if (TrueTy.isNull())
9116       return std::make_pair(FalseTy, FalseName);
9117     else if (FalseTy.isNull())
9118       return std::make_pair(TrueTy, TrueName);
9119   }
9120 
9121   return std::make_pair(QualType(), StringRef());
9122 }
9123 
9124 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9125 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9126 /// type do not count.
9127 static bool
9128 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9129   QualType From = ICE->getSubExpr()->getType();
9130   QualType To = ICE->getType();
9131   // It's an integer promotion if the destination type is the promoted
9132   // source type.
9133   if (ICE->getCastKind() == CK_IntegralCast &&
9134       From->isPromotableIntegerType() &&
9135       S.Context.getPromotedIntegerType(From) == To)
9136     return true;
9137   // Look through vector types, since we do default argument promotion for
9138   // those in OpenCL.
9139   if (const auto *VecTy = From->getAs<ExtVectorType>())
9140     From = VecTy->getElementType();
9141   if (const auto *VecTy = To->getAs<ExtVectorType>())
9142     To = VecTy->getElementType();
9143   // It's a floating promotion if the source type is a lower rank.
9144   return ICE->getCastKind() == CK_FloatingCast &&
9145          S.Context.getFloatingTypeOrder(From, To) < 0;
9146 }
9147 
9148 bool
9149 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9150                                     const char *StartSpecifier,
9151                                     unsigned SpecifierLen,
9152                                     const Expr *E) {
9153   using namespace analyze_format_string;
9154   using namespace analyze_printf;
9155 
9156   // Now type check the data expression that matches the
9157   // format specifier.
9158   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9159   if (!AT.isValid())
9160     return true;
9161 
9162   QualType ExprTy = E->getType();
9163   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9164     ExprTy = TET->getUnderlyingExpr()->getType();
9165   }
9166 
9167   // Diagnose attempts to print a boolean value as a character. Unlike other
9168   // -Wformat diagnostics, this is fine from a type perspective, but it still
9169   // doesn't make sense.
9170   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9171       E->isKnownToHaveBooleanValue()) {
9172     const CharSourceRange &CSR =
9173         getSpecifierRange(StartSpecifier, SpecifierLen);
9174     SmallString<4> FSString;
9175     llvm::raw_svector_ostream os(FSString);
9176     FS.toString(os);
9177     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9178                              << FSString,
9179                          E->getExprLoc(), false, CSR);
9180     return true;
9181   }
9182 
9183   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9184   if (Match == analyze_printf::ArgType::Match)
9185     return true;
9186 
9187   // Look through argument promotions for our error message's reported type.
9188   // This includes the integral and floating promotions, but excludes array
9189   // and function pointer decay (seeing that an argument intended to be a
9190   // string has type 'char [6]' is probably more confusing than 'char *') and
9191   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9192   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9193     if (isArithmeticArgumentPromotion(S, ICE)) {
9194       E = ICE->getSubExpr();
9195       ExprTy = E->getType();
9196 
9197       // Check if we didn't match because of an implicit cast from a 'char'
9198       // or 'short' to an 'int'.  This is done because printf is a varargs
9199       // function.
9200       if (ICE->getType() == S.Context.IntTy ||
9201           ICE->getType() == S.Context.UnsignedIntTy) {
9202         // All further checking is done on the subexpression
9203         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9204             AT.matchesType(S.Context, ExprTy);
9205         if (ImplicitMatch == analyze_printf::ArgType::Match)
9206           return true;
9207         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9208             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9209           Match = ImplicitMatch;
9210       }
9211     }
9212   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9213     // Special case for 'a', which has type 'int' in C.
9214     // Note, however, that we do /not/ want to treat multibyte constants like
9215     // 'MooV' as characters! This form is deprecated but still exists. In
9216     // addition, don't treat expressions as of type 'char' if one byte length
9217     // modifier is provided.
9218     if (ExprTy == S.Context.IntTy &&
9219         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9220       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9221         ExprTy = S.Context.CharTy;
9222   }
9223 
9224   // Look through enums to their underlying type.
9225   bool IsEnum = false;
9226   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9227     ExprTy = EnumTy->getDecl()->getIntegerType();
9228     IsEnum = true;
9229   }
9230 
9231   // %C in an Objective-C context prints a unichar, not a wchar_t.
9232   // If the argument is an integer of some kind, believe the %C and suggest
9233   // a cast instead of changing the conversion specifier.
9234   QualType IntendedTy = ExprTy;
9235   if (isObjCContext() &&
9236       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9237     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9238         !ExprTy->isCharType()) {
9239       // 'unichar' is defined as a typedef of unsigned short, but we should
9240       // prefer using the typedef if it is visible.
9241       IntendedTy = S.Context.UnsignedShortTy;
9242 
9243       // While we are here, check if the value is an IntegerLiteral that happens
9244       // to be within the valid range.
9245       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9246         const llvm::APInt &V = IL->getValue();
9247         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9248           return true;
9249       }
9250 
9251       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9252                           Sema::LookupOrdinaryName);
9253       if (S.LookupName(Result, S.getCurScope())) {
9254         NamedDecl *ND = Result.getFoundDecl();
9255         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9256           if (TD->getUnderlyingType() == IntendedTy)
9257             IntendedTy = S.Context.getTypedefType(TD);
9258       }
9259     }
9260   }
9261 
9262   // Special-case some of Darwin's platform-independence types by suggesting
9263   // casts to primitive types that are known to be large enough.
9264   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9265   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9266     QualType CastTy;
9267     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9268     if (!CastTy.isNull()) {
9269       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9270       // (long in ASTContext). Only complain to pedants.
9271       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9272           (AT.isSizeT() || AT.isPtrdiffT()) &&
9273           AT.matchesType(S.Context, CastTy))
9274         Match = ArgType::NoMatchPedantic;
9275       IntendedTy = CastTy;
9276       ShouldNotPrintDirectly = true;
9277     }
9278   }
9279 
9280   // We may be able to offer a FixItHint if it is a supported type.
9281   PrintfSpecifier fixedFS = FS;
9282   bool Success =
9283       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9284 
9285   if (Success) {
9286     // Get the fix string from the fixed format specifier
9287     SmallString<16> buf;
9288     llvm::raw_svector_ostream os(buf);
9289     fixedFS.toString(os);
9290 
9291     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9292 
9293     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9294       unsigned Diag;
9295       switch (Match) {
9296       case ArgType::Match: llvm_unreachable("expected non-matching");
9297       case ArgType::NoMatchPedantic:
9298         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9299         break;
9300       case ArgType::NoMatchTypeConfusion:
9301         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9302         break;
9303       case ArgType::NoMatch:
9304         Diag = diag::warn_format_conversion_argument_type_mismatch;
9305         break;
9306       }
9307 
9308       // In this case, the specifier is wrong and should be changed to match
9309       // the argument.
9310       EmitFormatDiagnostic(S.PDiag(Diag)
9311                                << AT.getRepresentativeTypeName(S.Context)
9312                                << IntendedTy << IsEnum << E->getSourceRange(),
9313                            E->getBeginLoc(),
9314                            /*IsStringLocation*/ false, SpecRange,
9315                            FixItHint::CreateReplacement(SpecRange, os.str()));
9316     } else {
9317       // The canonical type for formatting this value is different from the
9318       // actual type of the expression. (This occurs, for example, with Darwin's
9319       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9320       // should be printed as 'long' for 64-bit compatibility.)
9321       // Rather than emitting a normal format/argument mismatch, we want to
9322       // add a cast to the recommended type (and correct the format string
9323       // if necessary).
9324       SmallString<16> CastBuf;
9325       llvm::raw_svector_ostream CastFix(CastBuf);
9326       CastFix << "(";
9327       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9328       CastFix << ")";
9329 
9330       SmallVector<FixItHint,4> Hints;
9331       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9332         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9333 
9334       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9335         // If there's already a cast present, just replace it.
9336         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9337         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9338 
9339       } else if (!requiresParensToAddCast(E)) {
9340         // If the expression has high enough precedence,
9341         // just write the C-style cast.
9342         Hints.push_back(
9343             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9344       } else {
9345         // Otherwise, add parens around the expression as well as the cast.
9346         CastFix << "(";
9347         Hints.push_back(
9348             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9349 
9350         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9351         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9352       }
9353 
9354       if (ShouldNotPrintDirectly) {
9355         // The expression has a type that should not be printed directly.
9356         // We extract the name from the typedef because we don't want to show
9357         // the underlying type in the diagnostic.
9358         StringRef Name;
9359         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9360           Name = TypedefTy->getDecl()->getName();
9361         else
9362           Name = CastTyName;
9363         unsigned Diag = Match == ArgType::NoMatchPedantic
9364                             ? diag::warn_format_argument_needs_cast_pedantic
9365                             : diag::warn_format_argument_needs_cast;
9366         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9367                                            << E->getSourceRange(),
9368                              E->getBeginLoc(), /*IsStringLocation=*/false,
9369                              SpecRange, Hints);
9370       } else {
9371         // In this case, the expression could be printed using a different
9372         // specifier, but we've decided that the specifier is probably correct
9373         // and we should cast instead. Just use the normal warning message.
9374         EmitFormatDiagnostic(
9375             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9376                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9377                 << E->getSourceRange(),
9378             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9379       }
9380     }
9381   } else {
9382     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9383                                                    SpecifierLen);
9384     // Since the warning for passing non-POD types to variadic functions
9385     // was deferred until now, we emit a warning for non-POD
9386     // arguments here.
9387     switch (S.isValidVarArgType(ExprTy)) {
9388     case Sema::VAK_Valid:
9389     case Sema::VAK_ValidInCXX11: {
9390       unsigned Diag;
9391       switch (Match) {
9392       case ArgType::Match: llvm_unreachable("expected non-matching");
9393       case ArgType::NoMatchPedantic:
9394         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9395         break;
9396       case ArgType::NoMatchTypeConfusion:
9397         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9398         break;
9399       case ArgType::NoMatch:
9400         Diag = diag::warn_format_conversion_argument_type_mismatch;
9401         break;
9402       }
9403 
9404       EmitFormatDiagnostic(
9405           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9406                         << IsEnum << CSR << E->getSourceRange(),
9407           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9408       break;
9409     }
9410     case Sema::VAK_Undefined:
9411     case Sema::VAK_MSVCUndefined:
9412       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9413                                << S.getLangOpts().CPlusPlus11 << ExprTy
9414                                << CallType
9415                                << AT.getRepresentativeTypeName(S.Context) << CSR
9416                                << E->getSourceRange(),
9417                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9418       checkForCStrMembers(AT, E);
9419       break;
9420 
9421     case Sema::VAK_Invalid:
9422       if (ExprTy->isObjCObjectType())
9423         EmitFormatDiagnostic(
9424             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9425                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9426                 << AT.getRepresentativeTypeName(S.Context) << CSR
9427                 << E->getSourceRange(),
9428             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9429       else
9430         // FIXME: If this is an initializer list, suggest removing the braces
9431         // or inserting a cast to the target type.
9432         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9433             << isa<InitListExpr>(E) << ExprTy << CallType
9434             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9435       break;
9436     }
9437 
9438     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9439            "format string specifier index out of range");
9440     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9441   }
9442 
9443   return true;
9444 }
9445 
9446 //===--- CHECK: Scanf format string checking ------------------------------===//
9447 
9448 namespace {
9449 
9450 class CheckScanfHandler : public CheckFormatHandler {
9451 public:
9452   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9453                     const Expr *origFormatExpr, Sema::FormatStringType type,
9454                     unsigned firstDataArg, unsigned numDataArgs,
9455                     const char *beg, bool hasVAListArg,
9456                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9457                     bool inFunctionCall, Sema::VariadicCallType CallType,
9458                     llvm::SmallBitVector &CheckedVarArgs,
9459                     UncoveredArgHandler &UncoveredArg)
9460       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9461                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9462                            inFunctionCall, CallType, CheckedVarArgs,
9463                            UncoveredArg) {}
9464 
9465   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9466                             const char *startSpecifier,
9467                             unsigned specifierLen) override;
9468 
9469   bool HandleInvalidScanfConversionSpecifier(
9470           const analyze_scanf::ScanfSpecifier &FS,
9471           const char *startSpecifier,
9472           unsigned specifierLen) override;
9473 
9474   void HandleIncompleteScanList(const char *start, const char *end) override;
9475 };
9476 
9477 } // namespace
9478 
9479 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9480                                                  const char *end) {
9481   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9482                        getLocationOfByte(end), /*IsStringLocation*/true,
9483                        getSpecifierRange(start, end - start));
9484 }
9485 
9486 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9487                                         const analyze_scanf::ScanfSpecifier &FS,
9488                                         const char *startSpecifier,
9489                                         unsigned specifierLen) {
9490   const analyze_scanf::ScanfConversionSpecifier &CS =
9491     FS.getConversionSpecifier();
9492 
9493   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9494                                           getLocationOfByte(CS.getStart()),
9495                                           startSpecifier, specifierLen,
9496                                           CS.getStart(), CS.getLength());
9497 }
9498 
9499 bool CheckScanfHandler::HandleScanfSpecifier(
9500                                        const analyze_scanf::ScanfSpecifier &FS,
9501                                        const char *startSpecifier,
9502                                        unsigned specifierLen) {
9503   using namespace analyze_scanf;
9504   using namespace analyze_format_string;
9505 
9506   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9507 
9508   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9509   // be used to decide if we are using positional arguments consistently.
9510   if (FS.consumesDataArgument()) {
9511     if (atFirstArg) {
9512       atFirstArg = false;
9513       usesPositionalArgs = FS.usesPositionalArg();
9514     }
9515     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9516       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9517                                         startSpecifier, specifierLen);
9518       return false;
9519     }
9520   }
9521 
9522   // Check if the field with is non-zero.
9523   const OptionalAmount &Amt = FS.getFieldWidth();
9524   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9525     if (Amt.getConstantAmount() == 0) {
9526       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9527                                                    Amt.getConstantLength());
9528       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9529                            getLocationOfByte(Amt.getStart()),
9530                            /*IsStringLocation*/true, R,
9531                            FixItHint::CreateRemoval(R));
9532     }
9533   }
9534 
9535   if (!FS.consumesDataArgument()) {
9536     // FIXME: Technically specifying a precision or field width here
9537     // makes no sense.  Worth issuing a warning at some point.
9538     return true;
9539   }
9540 
9541   // Consume the argument.
9542   unsigned argIndex = FS.getArgIndex();
9543   if (argIndex < NumDataArgs) {
9544       // The check to see if the argIndex is valid will come later.
9545       // We set the bit here because we may exit early from this
9546       // function if we encounter some other error.
9547     CoveredArgs.set(argIndex);
9548   }
9549 
9550   // Check the length modifier is valid with the given conversion specifier.
9551   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9552                                  S.getLangOpts()))
9553     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9554                                 diag::warn_format_nonsensical_length);
9555   else if (!FS.hasStandardLengthModifier())
9556     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9557   else if (!FS.hasStandardLengthConversionCombination())
9558     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9559                                 diag::warn_format_non_standard_conversion_spec);
9560 
9561   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9562     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9563 
9564   // The remaining checks depend on the data arguments.
9565   if (HasVAListArg)
9566     return true;
9567 
9568   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9569     return false;
9570 
9571   // Check that the argument type matches the format specifier.
9572   const Expr *Ex = getDataArg(argIndex);
9573   if (!Ex)
9574     return true;
9575 
9576   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9577 
9578   if (!AT.isValid()) {
9579     return true;
9580   }
9581 
9582   analyze_format_string::ArgType::MatchKind Match =
9583       AT.matchesType(S.Context, Ex->getType());
9584   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9585   if (Match == analyze_format_string::ArgType::Match)
9586     return true;
9587 
9588   ScanfSpecifier fixedFS = FS;
9589   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9590                                  S.getLangOpts(), S.Context);
9591 
9592   unsigned Diag =
9593       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9594                : diag::warn_format_conversion_argument_type_mismatch;
9595 
9596   if (Success) {
9597     // Get the fix string from the fixed format specifier.
9598     SmallString<128> buf;
9599     llvm::raw_svector_ostream os(buf);
9600     fixedFS.toString(os);
9601 
9602     EmitFormatDiagnostic(
9603         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9604                       << Ex->getType() << false << Ex->getSourceRange(),
9605         Ex->getBeginLoc(),
9606         /*IsStringLocation*/ false,
9607         getSpecifierRange(startSpecifier, specifierLen),
9608         FixItHint::CreateReplacement(
9609             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9610   } else {
9611     EmitFormatDiagnostic(S.PDiag(Diag)
9612                              << AT.getRepresentativeTypeName(S.Context)
9613                              << Ex->getType() << false << Ex->getSourceRange(),
9614                          Ex->getBeginLoc(),
9615                          /*IsStringLocation*/ false,
9616                          getSpecifierRange(startSpecifier, specifierLen));
9617   }
9618 
9619   return true;
9620 }
9621 
9622 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9623                               const Expr *OrigFormatExpr,
9624                               ArrayRef<const Expr *> Args,
9625                               bool HasVAListArg, unsigned format_idx,
9626                               unsigned firstDataArg,
9627                               Sema::FormatStringType Type,
9628                               bool inFunctionCall,
9629                               Sema::VariadicCallType CallType,
9630                               llvm::SmallBitVector &CheckedVarArgs,
9631                               UncoveredArgHandler &UncoveredArg,
9632                               bool IgnoreStringsWithoutSpecifiers) {
9633   // CHECK: is the format string a wide literal?
9634   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9635     CheckFormatHandler::EmitFormatDiagnostic(
9636         S, inFunctionCall, Args[format_idx],
9637         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9638         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9639     return;
9640   }
9641 
9642   // Str - The format string.  NOTE: this is NOT null-terminated!
9643   StringRef StrRef = FExpr->getString();
9644   const char *Str = StrRef.data();
9645   // Account for cases where the string literal is truncated in a declaration.
9646   const ConstantArrayType *T =
9647     S.Context.getAsConstantArrayType(FExpr->getType());
9648   assert(T && "String literal not of constant array type!");
9649   size_t TypeSize = T->getSize().getZExtValue();
9650   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9651   const unsigned numDataArgs = Args.size() - firstDataArg;
9652 
9653   if (IgnoreStringsWithoutSpecifiers &&
9654       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9655           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9656     return;
9657 
9658   // Emit a warning if the string literal is truncated and does not contain an
9659   // embedded null character.
9660   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9661     CheckFormatHandler::EmitFormatDiagnostic(
9662         S, inFunctionCall, Args[format_idx],
9663         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9664         FExpr->getBeginLoc(),
9665         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9666     return;
9667   }
9668 
9669   // CHECK: empty format string?
9670   if (StrLen == 0 && numDataArgs > 0) {
9671     CheckFormatHandler::EmitFormatDiagnostic(
9672         S, inFunctionCall, Args[format_idx],
9673         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9674         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9675     return;
9676   }
9677 
9678   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9679       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9680       Type == Sema::FST_OSTrace) {
9681     CheckPrintfHandler H(
9682         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9683         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9684         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9685         CheckedVarArgs, UncoveredArg);
9686 
9687     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9688                                                   S.getLangOpts(),
9689                                                   S.Context.getTargetInfo(),
9690                                             Type == Sema::FST_FreeBSDKPrintf))
9691       H.DoneProcessing();
9692   } else if (Type == Sema::FST_Scanf) {
9693     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9694                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9695                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9696 
9697     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9698                                                  S.getLangOpts(),
9699                                                  S.Context.getTargetInfo()))
9700       H.DoneProcessing();
9701   } // TODO: handle other formats
9702 }
9703 
9704 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9705   // Str - The format string.  NOTE: this is NOT null-terminated!
9706   StringRef StrRef = FExpr->getString();
9707   const char *Str = StrRef.data();
9708   // Account for cases where the string literal is truncated in a declaration.
9709   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9710   assert(T && "String literal not of constant array type!");
9711   size_t TypeSize = T->getSize().getZExtValue();
9712   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9713   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9714                                                          getLangOpts(),
9715                                                          Context.getTargetInfo());
9716 }
9717 
9718 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9719 
9720 // Returns the related absolute value function that is larger, of 0 if one
9721 // does not exist.
9722 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9723   switch (AbsFunction) {
9724   default:
9725     return 0;
9726 
9727   case Builtin::BI__builtin_abs:
9728     return Builtin::BI__builtin_labs;
9729   case Builtin::BI__builtin_labs:
9730     return Builtin::BI__builtin_llabs;
9731   case Builtin::BI__builtin_llabs:
9732     return 0;
9733 
9734   case Builtin::BI__builtin_fabsf:
9735     return Builtin::BI__builtin_fabs;
9736   case Builtin::BI__builtin_fabs:
9737     return Builtin::BI__builtin_fabsl;
9738   case Builtin::BI__builtin_fabsl:
9739     return 0;
9740 
9741   case Builtin::BI__builtin_cabsf:
9742     return Builtin::BI__builtin_cabs;
9743   case Builtin::BI__builtin_cabs:
9744     return Builtin::BI__builtin_cabsl;
9745   case Builtin::BI__builtin_cabsl:
9746     return 0;
9747 
9748   case Builtin::BIabs:
9749     return Builtin::BIlabs;
9750   case Builtin::BIlabs:
9751     return Builtin::BIllabs;
9752   case Builtin::BIllabs:
9753     return 0;
9754 
9755   case Builtin::BIfabsf:
9756     return Builtin::BIfabs;
9757   case Builtin::BIfabs:
9758     return Builtin::BIfabsl;
9759   case Builtin::BIfabsl:
9760     return 0;
9761 
9762   case Builtin::BIcabsf:
9763    return Builtin::BIcabs;
9764   case Builtin::BIcabs:
9765     return Builtin::BIcabsl;
9766   case Builtin::BIcabsl:
9767     return 0;
9768   }
9769 }
9770 
9771 // Returns the argument type of the absolute value function.
9772 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9773                                              unsigned AbsType) {
9774   if (AbsType == 0)
9775     return QualType();
9776 
9777   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9778   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9779   if (Error != ASTContext::GE_None)
9780     return QualType();
9781 
9782   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9783   if (!FT)
9784     return QualType();
9785 
9786   if (FT->getNumParams() != 1)
9787     return QualType();
9788 
9789   return FT->getParamType(0);
9790 }
9791 
9792 // Returns the best absolute value function, or zero, based on type and
9793 // current absolute value function.
9794 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9795                                    unsigned AbsFunctionKind) {
9796   unsigned BestKind = 0;
9797   uint64_t ArgSize = Context.getTypeSize(ArgType);
9798   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9799        Kind = getLargerAbsoluteValueFunction(Kind)) {
9800     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9801     if (Context.getTypeSize(ParamType) >= ArgSize) {
9802       if (BestKind == 0)
9803         BestKind = Kind;
9804       else if (Context.hasSameType(ParamType, ArgType)) {
9805         BestKind = Kind;
9806         break;
9807       }
9808     }
9809   }
9810   return BestKind;
9811 }
9812 
9813 enum AbsoluteValueKind {
9814   AVK_Integer,
9815   AVK_Floating,
9816   AVK_Complex
9817 };
9818 
9819 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9820   if (T->isIntegralOrEnumerationType())
9821     return AVK_Integer;
9822   if (T->isRealFloatingType())
9823     return AVK_Floating;
9824   if (T->isAnyComplexType())
9825     return AVK_Complex;
9826 
9827   llvm_unreachable("Type not integer, floating, or complex");
9828 }
9829 
9830 // Changes the absolute value function to a different type.  Preserves whether
9831 // the function is a builtin.
9832 static unsigned changeAbsFunction(unsigned AbsKind,
9833                                   AbsoluteValueKind ValueKind) {
9834   switch (ValueKind) {
9835   case AVK_Integer:
9836     switch (AbsKind) {
9837     default:
9838       return 0;
9839     case Builtin::BI__builtin_fabsf:
9840     case Builtin::BI__builtin_fabs:
9841     case Builtin::BI__builtin_fabsl:
9842     case Builtin::BI__builtin_cabsf:
9843     case Builtin::BI__builtin_cabs:
9844     case Builtin::BI__builtin_cabsl:
9845       return Builtin::BI__builtin_abs;
9846     case Builtin::BIfabsf:
9847     case Builtin::BIfabs:
9848     case Builtin::BIfabsl:
9849     case Builtin::BIcabsf:
9850     case Builtin::BIcabs:
9851     case Builtin::BIcabsl:
9852       return Builtin::BIabs;
9853     }
9854   case AVK_Floating:
9855     switch (AbsKind) {
9856     default:
9857       return 0;
9858     case Builtin::BI__builtin_abs:
9859     case Builtin::BI__builtin_labs:
9860     case Builtin::BI__builtin_llabs:
9861     case Builtin::BI__builtin_cabsf:
9862     case Builtin::BI__builtin_cabs:
9863     case Builtin::BI__builtin_cabsl:
9864       return Builtin::BI__builtin_fabsf;
9865     case Builtin::BIabs:
9866     case Builtin::BIlabs:
9867     case Builtin::BIllabs:
9868     case Builtin::BIcabsf:
9869     case Builtin::BIcabs:
9870     case Builtin::BIcabsl:
9871       return Builtin::BIfabsf;
9872     }
9873   case AVK_Complex:
9874     switch (AbsKind) {
9875     default:
9876       return 0;
9877     case Builtin::BI__builtin_abs:
9878     case Builtin::BI__builtin_labs:
9879     case Builtin::BI__builtin_llabs:
9880     case Builtin::BI__builtin_fabsf:
9881     case Builtin::BI__builtin_fabs:
9882     case Builtin::BI__builtin_fabsl:
9883       return Builtin::BI__builtin_cabsf;
9884     case Builtin::BIabs:
9885     case Builtin::BIlabs:
9886     case Builtin::BIllabs:
9887     case Builtin::BIfabsf:
9888     case Builtin::BIfabs:
9889     case Builtin::BIfabsl:
9890       return Builtin::BIcabsf;
9891     }
9892   }
9893   llvm_unreachable("Unable to convert function");
9894 }
9895 
9896 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9897   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9898   if (!FnInfo)
9899     return 0;
9900 
9901   switch (FDecl->getBuiltinID()) {
9902   default:
9903     return 0;
9904   case Builtin::BI__builtin_abs:
9905   case Builtin::BI__builtin_fabs:
9906   case Builtin::BI__builtin_fabsf:
9907   case Builtin::BI__builtin_fabsl:
9908   case Builtin::BI__builtin_labs:
9909   case Builtin::BI__builtin_llabs:
9910   case Builtin::BI__builtin_cabs:
9911   case Builtin::BI__builtin_cabsf:
9912   case Builtin::BI__builtin_cabsl:
9913   case Builtin::BIabs:
9914   case Builtin::BIlabs:
9915   case Builtin::BIllabs:
9916   case Builtin::BIfabs:
9917   case Builtin::BIfabsf:
9918   case Builtin::BIfabsl:
9919   case Builtin::BIcabs:
9920   case Builtin::BIcabsf:
9921   case Builtin::BIcabsl:
9922     return FDecl->getBuiltinID();
9923   }
9924   llvm_unreachable("Unknown Builtin type");
9925 }
9926 
9927 // If the replacement is valid, emit a note with replacement function.
9928 // Additionally, suggest including the proper header if not already included.
9929 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9930                             unsigned AbsKind, QualType ArgType) {
9931   bool EmitHeaderHint = true;
9932   const char *HeaderName = nullptr;
9933   const char *FunctionName = nullptr;
9934   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9935     FunctionName = "std::abs";
9936     if (ArgType->isIntegralOrEnumerationType()) {
9937       HeaderName = "cstdlib";
9938     } else if (ArgType->isRealFloatingType()) {
9939       HeaderName = "cmath";
9940     } else {
9941       llvm_unreachable("Invalid Type");
9942     }
9943 
9944     // Lookup all std::abs
9945     if (NamespaceDecl *Std = S.getStdNamespace()) {
9946       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9947       R.suppressDiagnostics();
9948       S.LookupQualifiedName(R, Std);
9949 
9950       for (const auto *I : R) {
9951         const FunctionDecl *FDecl = nullptr;
9952         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9953           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9954         } else {
9955           FDecl = dyn_cast<FunctionDecl>(I);
9956         }
9957         if (!FDecl)
9958           continue;
9959 
9960         // Found std::abs(), check that they are the right ones.
9961         if (FDecl->getNumParams() != 1)
9962           continue;
9963 
9964         // Check that the parameter type can handle the argument.
9965         QualType ParamType = FDecl->getParamDecl(0)->getType();
9966         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9967             S.Context.getTypeSize(ArgType) <=
9968                 S.Context.getTypeSize(ParamType)) {
9969           // Found a function, don't need the header hint.
9970           EmitHeaderHint = false;
9971           break;
9972         }
9973       }
9974     }
9975   } else {
9976     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9977     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9978 
9979     if (HeaderName) {
9980       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9981       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9982       R.suppressDiagnostics();
9983       S.LookupName(R, S.getCurScope());
9984 
9985       if (R.isSingleResult()) {
9986         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9987         if (FD && FD->getBuiltinID() == AbsKind) {
9988           EmitHeaderHint = false;
9989         } else {
9990           return;
9991         }
9992       } else if (!R.empty()) {
9993         return;
9994       }
9995     }
9996   }
9997 
9998   S.Diag(Loc, diag::note_replace_abs_function)
9999       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10000 
10001   if (!HeaderName)
10002     return;
10003 
10004   if (!EmitHeaderHint)
10005     return;
10006 
10007   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10008                                                     << FunctionName;
10009 }
10010 
10011 template <std::size_t StrLen>
10012 static bool IsStdFunction(const FunctionDecl *FDecl,
10013                           const char (&Str)[StrLen]) {
10014   if (!FDecl)
10015     return false;
10016   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10017     return false;
10018   if (!FDecl->isInStdNamespace())
10019     return false;
10020 
10021   return true;
10022 }
10023 
10024 // Warn when using the wrong abs() function.
10025 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10026                                       const FunctionDecl *FDecl) {
10027   if (Call->getNumArgs() != 1)
10028     return;
10029 
10030   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10031   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10032   if (AbsKind == 0 && !IsStdAbs)
10033     return;
10034 
10035   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10036   QualType ParamType = Call->getArg(0)->getType();
10037 
10038   // Unsigned types cannot be negative.  Suggest removing the absolute value
10039   // function call.
10040   if (ArgType->isUnsignedIntegerType()) {
10041     const char *FunctionName =
10042         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10043     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10044     Diag(Call->getExprLoc(), diag::note_remove_abs)
10045         << FunctionName
10046         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10047     return;
10048   }
10049 
10050   // Taking the absolute value of a pointer is very suspicious, they probably
10051   // wanted to index into an array, dereference a pointer, call a function, etc.
10052   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10053     unsigned DiagType = 0;
10054     if (ArgType->isFunctionType())
10055       DiagType = 1;
10056     else if (ArgType->isArrayType())
10057       DiagType = 2;
10058 
10059     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10060     return;
10061   }
10062 
10063   // std::abs has overloads which prevent most of the absolute value problems
10064   // from occurring.
10065   if (IsStdAbs)
10066     return;
10067 
10068   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10069   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10070 
10071   // The argument and parameter are the same kind.  Check if they are the right
10072   // size.
10073   if (ArgValueKind == ParamValueKind) {
10074     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10075       return;
10076 
10077     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10078     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10079         << FDecl << ArgType << ParamType;
10080 
10081     if (NewAbsKind == 0)
10082       return;
10083 
10084     emitReplacement(*this, Call->getExprLoc(),
10085                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10086     return;
10087   }
10088 
10089   // ArgValueKind != ParamValueKind
10090   // The wrong type of absolute value function was used.  Attempt to find the
10091   // proper one.
10092   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10093   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10094   if (NewAbsKind == 0)
10095     return;
10096 
10097   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10098       << FDecl << ParamValueKind << ArgValueKind;
10099 
10100   emitReplacement(*this, Call->getExprLoc(),
10101                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10102 }
10103 
10104 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10105 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10106                                 const FunctionDecl *FDecl) {
10107   if (!Call || !FDecl) return;
10108 
10109   // Ignore template specializations and macros.
10110   if (inTemplateInstantiation()) return;
10111   if (Call->getExprLoc().isMacroID()) return;
10112 
10113   // Only care about the one template argument, two function parameter std::max
10114   if (Call->getNumArgs() != 2) return;
10115   if (!IsStdFunction(FDecl, "max")) return;
10116   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10117   if (!ArgList) return;
10118   if (ArgList->size() != 1) return;
10119 
10120   // Check that template type argument is unsigned integer.
10121   const auto& TA = ArgList->get(0);
10122   if (TA.getKind() != TemplateArgument::Type) return;
10123   QualType ArgType = TA.getAsType();
10124   if (!ArgType->isUnsignedIntegerType()) return;
10125 
10126   // See if either argument is a literal zero.
10127   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10128     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10129     if (!MTE) return false;
10130     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10131     if (!Num) return false;
10132     if (Num->getValue() != 0) return false;
10133     return true;
10134   };
10135 
10136   const Expr *FirstArg = Call->getArg(0);
10137   const Expr *SecondArg = Call->getArg(1);
10138   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10139   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10140 
10141   // Only warn when exactly one argument is zero.
10142   if (IsFirstArgZero == IsSecondArgZero) return;
10143 
10144   SourceRange FirstRange = FirstArg->getSourceRange();
10145   SourceRange SecondRange = SecondArg->getSourceRange();
10146 
10147   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10148 
10149   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10150       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10151 
10152   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10153   SourceRange RemovalRange;
10154   if (IsFirstArgZero) {
10155     RemovalRange = SourceRange(FirstRange.getBegin(),
10156                                SecondRange.getBegin().getLocWithOffset(-1));
10157   } else {
10158     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10159                                SecondRange.getEnd());
10160   }
10161 
10162   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10163         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10164         << FixItHint::CreateRemoval(RemovalRange);
10165 }
10166 
10167 //===--- CHECK: Standard memory functions ---------------------------------===//
10168 
10169 /// Takes the expression passed to the size_t parameter of functions
10170 /// such as memcmp, strncat, etc and warns if it's a comparison.
10171 ///
10172 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10173 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10174                                            IdentifierInfo *FnName,
10175                                            SourceLocation FnLoc,
10176                                            SourceLocation RParenLoc) {
10177   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10178   if (!Size)
10179     return false;
10180 
10181   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10182   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10183     return false;
10184 
10185   SourceRange SizeRange = Size->getSourceRange();
10186   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10187       << SizeRange << FnName;
10188   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10189       << FnName
10190       << FixItHint::CreateInsertion(
10191              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10192       << FixItHint::CreateRemoval(RParenLoc);
10193   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10194       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10195       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10196                                     ")");
10197 
10198   return true;
10199 }
10200 
10201 /// Determine whether the given type is or contains a dynamic class type
10202 /// (e.g., whether it has a vtable).
10203 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10204                                                      bool &IsContained) {
10205   // Look through array types while ignoring qualifiers.
10206   const Type *Ty = T->getBaseElementTypeUnsafe();
10207   IsContained = false;
10208 
10209   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10210   RD = RD ? RD->getDefinition() : nullptr;
10211   if (!RD || RD->isInvalidDecl())
10212     return nullptr;
10213 
10214   if (RD->isDynamicClass())
10215     return RD;
10216 
10217   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10218   // It's impossible for a class to transitively contain itself by value, so
10219   // infinite recursion is impossible.
10220   for (auto *FD : RD->fields()) {
10221     bool SubContained;
10222     if (const CXXRecordDecl *ContainedRD =
10223             getContainedDynamicClass(FD->getType(), SubContained)) {
10224       IsContained = true;
10225       return ContainedRD;
10226     }
10227   }
10228 
10229   return nullptr;
10230 }
10231 
10232 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10233   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10234     if (Unary->getKind() == UETT_SizeOf)
10235       return Unary;
10236   return nullptr;
10237 }
10238 
10239 /// If E is a sizeof expression, returns its argument expression,
10240 /// otherwise returns NULL.
10241 static const Expr *getSizeOfExprArg(const Expr *E) {
10242   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10243     if (!SizeOf->isArgumentType())
10244       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10245   return nullptr;
10246 }
10247 
10248 /// If E is a sizeof expression, returns its argument type.
10249 static QualType getSizeOfArgType(const Expr *E) {
10250   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10251     return SizeOf->getTypeOfArgument();
10252   return QualType();
10253 }
10254 
10255 namespace {
10256 
10257 struct SearchNonTrivialToInitializeField
10258     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10259   using Super =
10260       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10261 
10262   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10263 
10264   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10265                      SourceLocation SL) {
10266     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10267       asDerived().visitArray(PDIK, AT, SL);
10268       return;
10269     }
10270 
10271     Super::visitWithKind(PDIK, FT, SL);
10272   }
10273 
10274   void visitARCStrong(QualType FT, SourceLocation SL) {
10275     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10276   }
10277   void visitARCWeak(QualType FT, SourceLocation SL) {
10278     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10279   }
10280   void visitStruct(QualType FT, SourceLocation SL) {
10281     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10282       visit(FD->getType(), FD->getLocation());
10283   }
10284   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10285                   const ArrayType *AT, SourceLocation SL) {
10286     visit(getContext().getBaseElementType(AT), SL);
10287   }
10288   void visitTrivial(QualType FT, SourceLocation SL) {}
10289 
10290   static void diag(QualType RT, const Expr *E, Sema &S) {
10291     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10292   }
10293 
10294   ASTContext &getContext() { return S.getASTContext(); }
10295 
10296   const Expr *E;
10297   Sema &S;
10298 };
10299 
10300 struct SearchNonTrivialToCopyField
10301     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10302   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10303 
10304   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10305 
10306   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10307                      SourceLocation SL) {
10308     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10309       asDerived().visitArray(PCK, AT, SL);
10310       return;
10311     }
10312 
10313     Super::visitWithKind(PCK, FT, SL);
10314   }
10315 
10316   void visitARCStrong(QualType FT, SourceLocation SL) {
10317     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10318   }
10319   void visitARCWeak(QualType FT, SourceLocation SL) {
10320     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10321   }
10322   void visitStruct(QualType FT, SourceLocation SL) {
10323     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10324       visit(FD->getType(), FD->getLocation());
10325   }
10326   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10327                   SourceLocation SL) {
10328     visit(getContext().getBaseElementType(AT), SL);
10329   }
10330   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10331                 SourceLocation SL) {}
10332   void visitTrivial(QualType FT, SourceLocation SL) {}
10333   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10334 
10335   static void diag(QualType RT, const Expr *E, Sema &S) {
10336     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10337   }
10338 
10339   ASTContext &getContext() { return S.getASTContext(); }
10340 
10341   const Expr *E;
10342   Sema &S;
10343 };
10344 
10345 }
10346 
10347 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10348 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10349   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10350 
10351   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10352     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10353       return false;
10354 
10355     return doesExprLikelyComputeSize(BO->getLHS()) ||
10356            doesExprLikelyComputeSize(BO->getRHS());
10357   }
10358 
10359   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10360 }
10361 
10362 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10363 ///
10364 /// \code
10365 ///   #define MACRO 0
10366 ///   foo(MACRO);
10367 ///   foo(0);
10368 /// \endcode
10369 ///
10370 /// This should return true for the first call to foo, but not for the second
10371 /// (regardless of whether foo is a macro or function).
10372 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10373                                         SourceLocation CallLoc,
10374                                         SourceLocation ArgLoc) {
10375   if (!CallLoc.isMacroID())
10376     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10377 
10378   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10379          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10380 }
10381 
10382 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10383 /// last two arguments transposed.
10384 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10385   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10386     return;
10387 
10388   const Expr *SizeArg =
10389     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10390 
10391   auto isLiteralZero = [](const Expr *E) {
10392     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10393   };
10394 
10395   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10396   SourceLocation CallLoc = Call->getRParenLoc();
10397   SourceManager &SM = S.getSourceManager();
10398   if (isLiteralZero(SizeArg) &&
10399       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10400 
10401     SourceLocation DiagLoc = SizeArg->getExprLoc();
10402 
10403     // Some platforms #define bzero to __builtin_memset. See if this is the
10404     // case, and if so, emit a better diagnostic.
10405     if (BId == Builtin::BIbzero ||
10406         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10407                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10408       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10409       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10410     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10411       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10412       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10413     }
10414     return;
10415   }
10416 
10417   // If the second argument to a memset is a sizeof expression and the third
10418   // isn't, this is also likely an error. This should catch
10419   // 'memset(buf, sizeof(buf), 0xff)'.
10420   if (BId == Builtin::BImemset &&
10421       doesExprLikelyComputeSize(Call->getArg(1)) &&
10422       !doesExprLikelyComputeSize(Call->getArg(2))) {
10423     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10424     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10425     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10426     return;
10427   }
10428 }
10429 
10430 /// Check for dangerous or invalid arguments to memset().
10431 ///
10432 /// This issues warnings on known problematic, dangerous or unspecified
10433 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10434 /// function calls.
10435 ///
10436 /// \param Call The call expression to diagnose.
10437 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10438                                    unsigned BId,
10439                                    IdentifierInfo *FnName) {
10440   assert(BId != 0);
10441 
10442   // It is possible to have a non-standard definition of memset.  Validate
10443   // we have enough arguments, and if not, abort further checking.
10444   unsigned ExpectedNumArgs =
10445       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10446   if (Call->getNumArgs() < ExpectedNumArgs)
10447     return;
10448 
10449   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10450                       BId == Builtin::BIstrndup ? 1 : 2);
10451   unsigned LenArg =
10452       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10453   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10454 
10455   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10456                                      Call->getBeginLoc(), Call->getRParenLoc()))
10457     return;
10458 
10459   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10460   CheckMemaccessSize(*this, BId, Call);
10461 
10462   // We have special checking when the length is a sizeof expression.
10463   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10464   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10465   llvm::FoldingSetNodeID SizeOfArgID;
10466 
10467   // Although widely used, 'bzero' is not a standard function. Be more strict
10468   // with the argument types before allowing diagnostics and only allow the
10469   // form bzero(ptr, sizeof(...)).
10470   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10471   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10472     return;
10473 
10474   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10475     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10476     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10477 
10478     QualType DestTy = Dest->getType();
10479     QualType PointeeTy;
10480     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10481       PointeeTy = DestPtrTy->getPointeeType();
10482 
10483       // Never warn about void type pointers. This can be used to suppress
10484       // false positives.
10485       if (PointeeTy->isVoidType())
10486         continue;
10487 
10488       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10489       // actually comparing the expressions for equality. Because computing the
10490       // expression IDs can be expensive, we only do this if the diagnostic is
10491       // enabled.
10492       if (SizeOfArg &&
10493           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10494                            SizeOfArg->getExprLoc())) {
10495         // We only compute IDs for expressions if the warning is enabled, and
10496         // cache the sizeof arg's ID.
10497         if (SizeOfArgID == llvm::FoldingSetNodeID())
10498           SizeOfArg->Profile(SizeOfArgID, Context, true);
10499         llvm::FoldingSetNodeID DestID;
10500         Dest->Profile(DestID, Context, true);
10501         if (DestID == SizeOfArgID) {
10502           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10503           //       over sizeof(src) as well.
10504           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10505           StringRef ReadableName = FnName->getName();
10506 
10507           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10508             if (UnaryOp->getOpcode() == UO_AddrOf)
10509               ActionIdx = 1; // If its an address-of operator, just remove it.
10510           if (!PointeeTy->isIncompleteType() &&
10511               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10512             ActionIdx = 2; // If the pointee's size is sizeof(char),
10513                            // suggest an explicit length.
10514 
10515           // If the function is defined as a builtin macro, do not show macro
10516           // expansion.
10517           SourceLocation SL = SizeOfArg->getExprLoc();
10518           SourceRange DSR = Dest->getSourceRange();
10519           SourceRange SSR = SizeOfArg->getSourceRange();
10520           SourceManager &SM = getSourceManager();
10521 
10522           if (SM.isMacroArgExpansion(SL)) {
10523             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10524             SL = SM.getSpellingLoc(SL);
10525             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10526                              SM.getSpellingLoc(DSR.getEnd()));
10527             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10528                              SM.getSpellingLoc(SSR.getEnd()));
10529           }
10530 
10531           DiagRuntimeBehavior(SL, SizeOfArg,
10532                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10533                                 << ReadableName
10534                                 << PointeeTy
10535                                 << DestTy
10536                                 << DSR
10537                                 << SSR);
10538           DiagRuntimeBehavior(SL, SizeOfArg,
10539                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10540                                 << ActionIdx
10541                                 << SSR);
10542 
10543           break;
10544         }
10545       }
10546 
10547       // Also check for cases where the sizeof argument is the exact same
10548       // type as the memory argument, and where it points to a user-defined
10549       // record type.
10550       if (SizeOfArgTy != QualType()) {
10551         if (PointeeTy->isRecordType() &&
10552             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10553           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10554                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10555                                 << FnName << SizeOfArgTy << ArgIdx
10556                                 << PointeeTy << Dest->getSourceRange()
10557                                 << LenExpr->getSourceRange());
10558           break;
10559         }
10560       }
10561     } else if (DestTy->isArrayType()) {
10562       PointeeTy = DestTy;
10563     }
10564 
10565     if (PointeeTy == QualType())
10566       continue;
10567 
10568     // Always complain about dynamic classes.
10569     bool IsContained;
10570     if (const CXXRecordDecl *ContainedRD =
10571             getContainedDynamicClass(PointeeTy, IsContained)) {
10572 
10573       unsigned OperationType = 0;
10574       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10575       // "overwritten" if we're warning about the destination for any call
10576       // but memcmp; otherwise a verb appropriate to the call.
10577       if (ArgIdx != 0 || IsCmp) {
10578         if (BId == Builtin::BImemcpy)
10579           OperationType = 1;
10580         else if(BId == Builtin::BImemmove)
10581           OperationType = 2;
10582         else if (IsCmp)
10583           OperationType = 3;
10584       }
10585 
10586       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10587                           PDiag(diag::warn_dyn_class_memaccess)
10588                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10589                               << IsContained << ContainedRD << OperationType
10590                               << Call->getCallee()->getSourceRange());
10591     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10592              BId != Builtin::BImemset)
10593       DiagRuntimeBehavior(
10594         Dest->getExprLoc(), Dest,
10595         PDiag(diag::warn_arc_object_memaccess)
10596           << ArgIdx << FnName << PointeeTy
10597           << Call->getCallee()->getSourceRange());
10598     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10599       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10600           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10601         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10602                             PDiag(diag::warn_cstruct_memaccess)
10603                                 << ArgIdx << FnName << PointeeTy << 0);
10604         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10605       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10606                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10607         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10608                             PDiag(diag::warn_cstruct_memaccess)
10609                                 << ArgIdx << FnName << PointeeTy << 1);
10610         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10611       } else {
10612         continue;
10613       }
10614     } else
10615       continue;
10616 
10617     DiagRuntimeBehavior(
10618       Dest->getExprLoc(), Dest,
10619       PDiag(diag::note_bad_memaccess_silence)
10620         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10621     break;
10622   }
10623 }
10624 
10625 // A little helper routine: ignore addition and subtraction of integer literals.
10626 // This intentionally does not ignore all integer constant expressions because
10627 // we don't want to remove sizeof().
10628 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10629   Ex = Ex->IgnoreParenCasts();
10630 
10631   while (true) {
10632     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10633     if (!BO || !BO->isAdditiveOp())
10634       break;
10635 
10636     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10637     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10638 
10639     if (isa<IntegerLiteral>(RHS))
10640       Ex = LHS;
10641     else if (isa<IntegerLiteral>(LHS))
10642       Ex = RHS;
10643     else
10644       break;
10645   }
10646 
10647   return Ex;
10648 }
10649 
10650 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10651                                                       ASTContext &Context) {
10652   // Only handle constant-sized or VLAs, but not flexible members.
10653   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10654     // Only issue the FIXIT for arrays of size > 1.
10655     if (CAT->getSize().getSExtValue() <= 1)
10656       return false;
10657   } else if (!Ty->isVariableArrayType()) {
10658     return false;
10659   }
10660   return true;
10661 }
10662 
10663 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10664 // be the size of the source, instead of the destination.
10665 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10666                                     IdentifierInfo *FnName) {
10667 
10668   // Don't crash if the user has the wrong number of arguments
10669   unsigned NumArgs = Call->getNumArgs();
10670   if ((NumArgs != 3) && (NumArgs != 4))
10671     return;
10672 
10673   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10674   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10675   const Expr *CompareWithSrc = nullptr;
10676 
10677   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10678                                      Call->getBeginLoc(), Call->getRParenLoc()))
10679     return;
10680 
10681   // Look for 'strlcpy(dst, x, sizeof(x))'
10682   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10683     CompareWithSrc = Ex;
10684   else {
10685     // Look for 'strlcpy(dst, x, strlen(x))'
10686     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10687       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10688           SizeCall->getNumArgs() == 1)
10689         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10690     }
10691   }
10692 
10693   if (!CompareWithSrc)
10694     return;
10695 
10696   // Determine if the argument to sizeof/strlen is equal to the source
10697   // argument.  In principle there's all kinds of things you could do
10698   // here, for instance creating an == expression and evaluating it with
10699   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10700   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10701   if (!SrcArgDRE)
10702     return;
10703 
10704   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10705   if (!CompareWithSrcDRE ||
10706       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10707     return;
10708 
10709   const Expr *OriginalSizeArg = Call->getArg(2);
10710   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10711       << OriginalSizeArg->getSourceRange() << FnName;
10712 
10713   // Output a FIXIT hint if the destination is an array (rather than a
10714   // pointer to an array).  This could be enhanced to handle some
10715   // pointers if we know the actual size, like if DstArg is 'array+2'
10716   // we could say 'sizeof(array)-2'.
10717   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10718   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10719     return;
10720 
10721   SmallString<128> sizeString;
10722   llvm::raw_svector_ostream OS(sizeString);
10723   OS << "sizeof(";
10724   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10725   OS << ")";
10726 
10727   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10728       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10729                                       OS.str());
10730 }
10731 
10732 /// Check if two expressions refer to the same declaration.
10733 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10734   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10735     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10736       return D1->getDecl() == D2->getDecl();
10737   return false;
10738 }
10739 
10740 static const Expr *getStrlenExprArg(const Expr *E) {
10741   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10742     const FunctionDecl *FD = CE->getDirectCallee();
10743     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10744       return nullptr;
10745     return CE->getArg(0)->IgnoreParenCasts();
10746   }
10747   return nullptr;
10748 }
10749 
10750 // Warn on anti-patterns as the 'size' argument to strncat.
10751 // The correct size argument should look like following:
10752 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10753 void Sema::CheckStrncatArguments(const CallExpr *CE,
10754                                  IdentifierInfo *FnName) {
10755   // Don't crash if the user has the wrong number of arguments.
10756   if (CE->getNumArgs() < 3)
10757     return;
10758   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10759   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10760   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10761 
10762   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10763                                      CE->getRParenLoc()))
10764     return;
10765 
10766   // Identify common expressions, which are wrongly used as the size argument
10767   // to strncat and may lead to buffer overflows.
10768   unsigned PatternType = 0;
10769   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10770     // - sizeof(dst)
10771     if (referToTheSameDecl(SizeOfArg, DstArg))
10772       PatternType = 1;
10773     // - sizeof(src)
10774     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10775       PatternType = 2;
10776   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10777     if (BE->getOpcode() == BO_Sub) {
10778       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10779       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10780       // - sizeof(dst) - strlen(dst)
10781       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10782           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10783         PatternType = 1;
10784       // - sizeof(src) - (anything)
10785       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10786         PatternType = 2;
10787     }
10788   }
10789 
10790   if (PatternType == 0)
10791     return;
10792 
10793   // Generate the diagnostic.
10794   SourceLocation SL = LenArg->getBeginLoc();
10795   SourceRange SR = LenArg->getSourceRange();
10796   SourceManager &SM = getSourceManager();
10797 
10798   // If the function is defined as a builtin macro, do not show macro expansion.
10799   if (SM.isMacroArgExpansion(SL)) {
10800     SL = SM.getSpellingLoc(SL);
10801     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10802                      SM.getSpellingLoc(SR.getEnd()));
10803   }
10804 
10805   // Check if the destination is an array (rather than a pointer to an array).
10806   QualType DstTy = DstArg->getType();
10807   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10808                                                                     Context);
10809   if (!isKnownSizeArray) {
10810     if (PatternType == 1)
10811       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10812     else
10813       Diag(SL, diag::warn_strncat_src_size) << SR;
10814     return;
10815   }
10816 
10817   if (PatternType == 1)
10818     Diag(SL, diag::warn_strncat_large_size) << SR;
10819   else
10820     Diag(SL, diag::warn_strncat_src_size) << SR;
10821 
10822   SmallString<128> sizeString;
10823   llvm::raw_svector_ostream OS(sizeString);
10824   OS << "sizeof(";
10825   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10826   OS << ") - ";
10827   OS << "strlen(";
10828   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10829   OS << ") - 1";
10830 
10831   Diag(SL, diag::note_strncat_wrong_size)
10832     << FixItHint::CreateReplacement(SR, OS.str());
10833 }
10834 
10835 namespace {
10836 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10837                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10838   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10839     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10840         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10841     return;
10842   }
10843 }
10844 
10845 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10846                                  const UnaryOperator *UnaryExpr) {
10847   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10848     const Decl *D = Lvalue->getDecl();
10849     if (isa<DeclaratorDecl>(D))
10850       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10851         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10852   }
10853 
10854   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10855     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10856                                       Lvalue->getMemberDecl());
10857 }
10858 
10859 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10860                             const UnaryOperator *UnaryExpr) {
10861   const auto *Lambda = dyn_cast<LambdaExpr>(
10862       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10863   if (!Lambda)
10864     return;
10865 
10866   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10867       << CalleeName << 2 /*object: lambda expression*/;
10868 }
10869 
10870 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10871                                   const DeclRefExpr *Lvalue) {
10872   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10873   if (Var == nullptr)
10874     return;
10875 
10876   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10877       << CalleeName << 0 /*object: */ << Var;
10878 }
10879 
10880 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10881                             const CastExpr *Cast) {
10882   SmallString<128> SizeString;
10883   llvm::raw_svector_ostream OS(SizeString);
10884 
10885   clang::CastKind Kind = Cast->getCastKind();
10886   if (Kind == clang::CK_BitCast &&
10887       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10888     return;
10889   if (Kind == clang::CK_IntegralToPointer &&
10890       !isa<IntegerLiteral>(
10891           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10892     return;
10893 
10894   switch (Cast->getCastKind()) {
10895   case clang::CK_BitCast:
10896   case clang::CK_IntegralToPointer:
10897   case clang::CK_FunctionToPointerDecay:
10898     OS << '\'';
10899     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10900     OS << '\'';
10901     break;
10902   default:
10903     return;
10904   }
10905 
10906   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10907       << CalleeName << 0 /*object: */ << OS.str();
10908 }
10909 } // namespace
10910 
10911 /// Alerts the user that they are attempting to free a non-malloc'd object.
10912 void Sema::CheckFreeArguments(const CallExpr *E) {
10913   const std::string CalleeName =
10914       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10915 
10916   { // Prefer something that doesn't involve a cast to make things simpler.
10917     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10918     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10919       switch (UnaryExpr->getOpcode()) {
10920       case UnaryOperator::Opcode::UO_AddrOf:
10921         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10922       case UnaryOperator::Opcode::UO_Plus:
10923         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10924       default:
10925         break;
10926       }
10927 
10928     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10929       if (Lvalue->getType()->isArrayType())
10930         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10931 
10932     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10933       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10934           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10935       return;
10936     }
10937 
10938     if (isa<BlockExpr>(Arg)) {
10939       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10940           << CalleeName << 1 /*object: block*/;
10941       return;
10942     }
10943   }
10944   // Maybe the cast was important, check after the other cases.
10945   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10946     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10947 }
10948 
10949 void
10950 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10951                          SourceLocation ReturnLoc,
10952                          bool isObjCMethod,
10953                          const AttrVec *Attrs,
10954                          const FunctionDecl *FD) {
10955   // Check if the return value is null but should not be.
10956   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10957        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10958       CheckNonNullExpr(*this, RetValExp))
10959     Diag(ReturnLoc, diag::warn_null_ret)
10960       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10961 
10962   // C++11 [basic.stc.dynamic.allocation]p4:
10963   //   If an allocation function declared with a non-throwing
10964   //   exception-specification fails to allocate storage, it shall return
10965   //   a null pointer. Any other allocation function that fails to allocate
10966   //   storage shall indicate failure only by throwing an exception [...]
10967   if (FD) {
10968     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10969     if (Op == OO_New || Op == OO_Array_New) {
10970       const FunctionProtoType *Proto
10971         = FD->getType()->castAs<FunctionProtoType>();
10972       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10973           CheckNonNullExpr(*this, RetValExp))
10974         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10975           << FD << getLangOpts().CPlusPlus11;
10976     }
10977   }
10978 
10979   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10980   // here prevent the user from using a PPC MMA type as trailing return type.
10981   if (Context.getTargetInfo().getTriple().isPPC64())
10982     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10983 }
10984 
10985 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10986 
10987 /// Check for comparisons of floating point operands using != and ==.
10988 /// Issue a warning if these are no self-comparisons, as they are not likely
10989 /// to do what the programmer intended.
10990 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10991   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10992   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10993 
10994   // Special case: check for x == x (which is OK).
10995   // Do not emit warnings for such cases.
10996   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10997     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10998       if (DRL->getDecl() == DRR->getDecl())
10999         return;
11000 
11001   // Special case: check for comparisons against literals that can be exactly
11002   //  represented by APFloat.  In such cases, do not emit a warning.  This
11003   //  is a heuristic: often comparison against such literals are used to
11004   //  detect if a value in a variable has not changed.  This clearly can
11005   //  lead to false negatives.
11006   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11007     if (FLL->isExact())
11008       return;
11009   } else
11010     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11011       if (FLR->isExact())
11012         return;
11013 
11014   // Check for comparisons with builtin types.
11015   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11016     if (CL->getBuiltinCallee())
11017       return;
11018 
11019   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11020     if (CR->getBuiltinCallee())
11021       return;
11022 
11023   // Emit the diagnostic.
11024   Diag(Loc, diag::warn_floatingpoint_eq)
11025     << LHS->getSourceRange() << RHS->getSourceRange();
11026 }
11027 
11028 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11029 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11030 
11031 namespace {
11032 
11033 /// Structure recording the 'active' range of an integer-valued
11034 /// expression.
11035 struct IntRange {
11036   /// The number of bits active in the int. Note that this includes exactly one
11037   /// sign bit if !NonNegative.
11038   unsigned Width;
11039 
11040   /// True if the int is known not to have negative values. If so, all leading
11041   /// bits before Width are known zero, otherwise they are known to be the
11042   /// same as the MSB within Width.
11043   bool NonNegative;
11044 
11045   IntRange(unsigned Width, bool NonNegative)
11046       : Width(Width), NonNegative(NonNegative) {}
11047 
11048   /// Number of bits excluding the sign bit.
11049   unsigned valueBits() const {
11050     return NonNegative ? Width : Width - 1;
11051   }
11052 
11053   /// Returns the range of the bool type.
11054   static IntRange forBoolType() {
11055     return IntRange(1, true);
11056   }
11057 
11058   /// Returns the range of an opaque value of the given integral type.
11059   static IntRange forValueOfType(ASTContext &C, QualType T) {
11060     return forValueOfCanonicalType(C,
11061                           T->getCanonicalTypeInternal().getTypePtr());
11062   }
11063 
11064   /// Returns the range of an opaque value of a canonical integral type.
11065   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11066     assert(T->isCanonicalUnqualified());
11067 
11068     if (const VectorType *VT = dyn_cast<VectorType>(T))
11069       T = VT->getElementType().getTypePtr();
11070     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11071       T = CT->getElementType().getTypePtr();
11072     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11073       T = AT->getValueType().getTypePtr();
11074 
11075     if (!C.getLangOpts().CPlusPlus) {
11076       // For enum types in C code, use the underlying datatype.
11077       if (const EnumType *ET = dyn_cast<EnumType>(T))
11078         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11079     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11080       // For enum types in C++, use the known bit width of the enumerators.
11081       EnumDecl *Enum = ET->getDecl();
11082       // In C++11, enums can have a fixed underlying type. Use this type to
11083       // compute the range.
11084       if (Enum->isFixed()) {
11085         return IntRange(C.getIntWidth(QualType(T, 0)),
11086                         !ET->isSignedIntegerOrEnumerationType());
11087       }
11088 
11089       unsigned NumPositive = Enum->getNumPositiveBits();
11090       unsigned NumNegative = Enum->getNumNegativeBits();
11091 
11092       if (NumNegative == 0)
11093         return IntRange(NumPositive, true/*NonNegative*/);
11094       else
11095         return IntRange(std::max(NumPositive + 1, NumNegative),
11096                         false/*NonNegative*/);
11097     }
11098 
11099     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11100       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11101 
11102     const BuiltinType *BT = cast<BuiltinType>(T);
11103     assert(BT->isInteger());
11104 
11105     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11106   }
11107 
11108   /// Returns the "target" range of a canonical integral type, i.e.
11109   /// the range of values expressible in the type.
11110   ///
11111   /// This matches forValueOfCanonicalType except that enums have the
11112   /// full range of their type, not the range of their enumerators.
11113   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11114     assert(T->isCanonicalUnqualified());
11115 
11116     if (const VectorType *VT = dyn_cast<VectorType>(T))
11117       T = VT->getElementType().getTypePtr();
11118     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11119       T = CT->getElementType().getTypePtr();
11120     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11121       T = AT->getValueType().getTypePtr();
11122     if (const EnumType *ET = dyn_cast<EnumType>(T))
11123       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11124 
11125     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11126       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11127 
11128     const BuiltinType *BT = cast<BuiltinType>(T);
11129     assert(BT->isInteger());
11130 
11131     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11132   }
11133 
11134   /// Returns the supremum of two ranges: i.e. their conservative merge.
11135   static IntRange join(IntRange L, IntRange R) {
11136     bool Unsigned = L.NonNegative && R.NonNegative;
11137     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11138                     L.NonNegative && R.NonNegative);
11139   }
11140 
11141   /// Return the range of a bitwise-AND of the two ranges.
11142   static IntRange bit_and(IntRange L, IntRange R) {
11143     unsigned Bits = std::max(L.Width, R.Width);
11144     bool NonNegative = false;
11145     if (L.NonNegative) {
11146       Bits = std::min(Bits, L.Width);
11147       NonNegative = true;
11148     }
11149     if (R.NonNegative) {
11150       Bits = std::min(Bits, R.Width);
11151       NonNegative = true;
11152     }
11153     return IntRange(Bits, NonNegative);
11154   }
11155 
11156   /// Return the range of a sum of the two ranges.
11157   static IntRange sum(IntRange L, IntRange R) {
11158     bool Unsigned = L.NonNegative && R.NonNegative;
11159     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11160                     Unsigned);
11161   }
11162 
11163   /// Return the range of a difference of the two ranges.
11164   static IntRange difference(IntRange L, IntRange R) {
11165     // We need a 1-bit-wider range if:
11166     //   1) LHS can be negative: least value can be reduced.
11167     //   2) RHS can be negative: greatest value can be increased.
11168     bool CanWiden = !L.NonNegative || !R.NonNegative;
11169     bool Unsigned = L.NonNegative && R.Width == 0;
11170     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11171                         !Unsigned,
11172                     Unsigned);
11173   }
11174 
11175   /// Return the range of a product of the two ranges.
11176   static IntRange product(IntRange L, IntRange R) {
11177     // If both LHS and RHS can be negative, we can form
11178     //   -2^L * -2^R = 2^(L + R)
11179     // which requires L + R + 1 value bits to represent.
11180     bool CanWiden = !L.NonNegative && !R.NonNegative;
11181     bool Unsigned = L.NonNegative && R.NonNegative;
11182     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11183                     Unsigned);
11184   }
11185 
11186   /// Return the range of a remainder operation between the two ranges.
11187   static IntRange rem(IntRange L, IntRange R) {
11188     // The result of a remainder can't be larger than the result of
11189     // either side. The sign of the result is the sign of the LHS.
11190     bool Unsigned = L.NonNegative;
11191     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11192                     Unsigned);
11193   }
11194 };
11195 
11196 } // namespace
11197 
11198 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11199                               unsigned MaxWidth) {
11200   if (value.isSigned() && value.isNegative())
11201     return IntRange(value.getMinSignedBits(), false);
11202 
11203   if (value.getBitWidth() > MaxWidth)
11204     value = value.trunc(MaxWidth);
11205 
11206   // isNonNegative() just checks the sign bit without considering
11207   // signedness.
11208   return IntRange(value.getActiveBits(), true);
11209 }
11210 
11211 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11212                               unsigned MaxWidth) {
11213   if (result.isInt())
11214     return GetValueRange(C, result.getInt(), MaxWidth);
11215 
11216   if (result.isVector()) {
11217     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11218     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11219       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11220       R = IntRange::join(R, El);
11221     }
11222     return R;
11223   }
11224 
11225   if (result.isComplexInt()) {
11226     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11227     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11228     return IntRange::join(R, I);
11229   }
11230 
11231   // This can happen with lossless casts to intptr_t of "based" lvalues.
11232   // Assume it might use arbitrary bits.
11233   // FIXME: The only reason we need to pass the type in here is to get
11234   // the sign right on this one case.  It would be nice if APValue
11235   // preserved this.
11236   assert(result.isLValue() || result.isAddrLabelDiff());
11237   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11238 }
11239 
11240 static QualType GetExprType(const Expr *E) {
11241   QualType Ty = E->getType();
11242   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11243     Ty = AtomicRHS->getValueType();
11244   return Ty;
11245 }
11246 
11247 /// Pseudo-evaluate the given integer expression, estimating the
11248 /// range of values it might take.
11249 ///
11250 /// \param MaxWidth The width to which the value will be truncated.
11251 /// \param Approximate If \c true, return a likely range for the result: in
11252 ///        particular, assume that arithmetic on narrower types doesn't leave
11253 ///        those types. If \c false, return a range including all possible
11254 ///        result values.
11255 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11256                              bool InConstantContext, bool Approximate) {
11257   E = E->IgnoreParens();
11258 
11259   // Try a full evaluation first.
11260   Expr::EvalResult result;
11261   if (E->EvaluateAsRValue(result, C, InConstantContext))
11262     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11263 
11264   // I think we only want to look through implicit casts here; if the
11265   // user has an explicit widening cast, we should treat the value as
11266   // being of the new, wider type.
11267   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11268     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11269       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11270                           Approximate);
11271 
11272     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11273 
11274     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11275                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11276 
11277     // Assume that non-integer casts can span the full range of the type.
11278     if (!isIntegerCast)
11279       return OutputTypeRange;
11280 
11281     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11282                                      std::min(MaxWidth, OutputTypeRange.Width),
11283                                      InConstantContext, Approximate);
11284 
11285     // Bail out if the subexpr's range is as wide as the cast type.
11286     if (SubRange.Width >= OutputTypeRange.Width)
11287       return OutputTypeRange;
11288 
11289     // Otherwise, we take the smaller width, and we're non-negative if
11290     // either the output type or the subexpr is.
11291     return IntRange(SubRange.Width,
11292                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11293   }
11294 
11295   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11296     // If we can fold the condition, just take that operand.
11297     bool CondResult;
11298     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11299       return GetExprRange(C,
11300                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11301                           MaxWidth, InConstantContext, Approximate);
11302 
11303     // Otherwise, conservatively merge.
11304     // GetExprRange requires an integer expression, but a throw expression
11305     // results in a void type.
11306     Expr *E = CO->getTrueExpr();
11307     IntRange L = E->getType()->isVoidType()
11308                      ? IntRange{0, true}
11309                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11310     E = CO->getFalseExpr();
11311     IntRange R = E->getType()->isVoidType()
11312                      ? IntRange{0, true}
11313                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11314     return IntRange::join(L, R);
11315   }
11316 
11317   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11318     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11319 
11320     switch (BO->getOpcode()) {
11321     case BO_Cmp:
11322       llvm_unreachable("builtin <=> should have class type");
11323 
11324     // Boolean-valued operations are single-bit and positive.
11325     case BO_LAnd:
11326     case BO_LOr:
11327     case BO_LT:
11328     case BO_GT:
11329     case BO_LE:
11330     case BO_GE:
11331     case BO_EQ:
11332     case BO_NE:
11333       return IntRange::forBoolType();
11334 
11335     // The type of the assignments is the type of the LHS, so the RHS
11336     // is not necessarily the same type.
11337     case BO_MulAssign:
11338     case BO_DivAssign:
11339     case BO_RemAssign:
11340     case BO_AddAssign:
11341     case BO_SubAssign:
11342     case BO_XorAssign:
11343     case BO_OrAssign:
11344       // TODO: bitfields?
11345       return IntRange::forValueOfType(C, GetExprType(E));
11346 
11347     // Simple assignments just pass through the RHS, which will have
11348     // been coerced to the LHS type.
11349     case BO_Assign:
11350       // TODO: bitfields?
11351       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11352                           Approximate);
11353 
11354     // Operations with opaque sources are black-listed.
11355     case BO_PtrMemD:
11356     case BO_PtrMemI:
11357       return IntRange::forValueOfType(C, GetExprType(E));
11358 
11359     // Bitwise-and uses the *infinum* of the two source ranges.
11360     case BO_And:
11361     case BO_AndAssign:
11362       Combine = IntRange::bit_and;
11363       break;
11364 
11365     // Left shift gets black-listed based on a judgement call.
11366     case BO_Shl:
11367       // ...except that we want to treat '1 << (blah)' as logically
11368       // positive.  It's an important idiom.
11369       if (IntegerLiteral *I
11370             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11371         if (I->getValue() == 1) {
11372           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11373           return IntRange(R.Width, /*NonNegative*/ true);
11374         }
11375       }
11376       LLVM_FALLTHROUGH;
11377 
11378     case BO_ShlAssign:
11379       return IntRange::forValueOfType(C, GetExprType(E));
11380 
11381     // Right shift by a constant can narrow its left argument.
11382     case BO_Shr:
11383     case BO_ShrAssign: {
11384       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11385                                 Approximate);
11386 
11387       // If the shift amount is a positive constant, drop the width by
11388       // that much.
11389       if (Optional<llvm::APSInt> shift =
11390               BO->getRHS()->getIntegerConstantExpr(C)) {
11391         if (shift->isNonNegative()) {
11392           unsigned zext = shift->getZExtValue();
11393           if (zext >= L.Width)
11394             L.Width = (L.NonNegative ? 0 : 1);
11395           else
11396             L.Width -= zext;
11397         }
11398       }
11399 
11400       return L;
11401     }
11402 
11403     // Comma acts as its right operand.
11404     case BO_Comma:
11405       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11406                           Approximate);
11407 
11408     case BO_Add:
11409       if (!Approximate)
11410         Combine = IntRange::sum;
11411       break;
11412 
11413     case BO_Sub:
11414       if (BO->getLHS()->getType()->isPointerType())
11415         return IntRange::forValueOfType(C, GetExprType(E));
11416       if (!Approximate)
11417         Combine = IntRange::difference;
11418       break;
11419 
11420     case BO_Mul:
11421       if (!Approximate)
11422         Combine = IntRange::product;
11423       break;
11424 
11425     // The width of a division result is mostly determined by the size
11426     // of the LHS.
11427     case BO_Div: {
11428       // Don't 'pre-truncate' the operands.
11429       unsigned opWidth = C.getIntWidth(GetExprType(E));
11430       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11431                                 Approximate);
11432 
11433       // If the divisor is constant, use that.
11434       if (Optional<llvm::APSInt> divisor =
11435               BO->getRHS()->getIntegerConstantExpr(C)) {
11436         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11437         if (log2 >= L.Width)
11438           L.Width = (L.NonNegative ? 0 : 1);
11439         else
11440           L.Width = std::min(L.Width - log2, MaxWidth);
11441         return L;
11442       }
11443 
11444       // Otherwise, just use the LHS's width.
11445       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11446       // could be -1.
11447       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11448                                 Approximate);
11449       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11450     }
11451 
11452     case BO_Rem:
11453       Combine = IntRange::rem;
11454       break;
11455 
11456     // The default behavior is okay for these.
11457     case BO_Xor:
11458     case BO_Or:
11459       break;
11460     }
11461 
11462     // Combine the two ranges, but limit the result to the type in which we
11463     // performed the computation.
11464     QualType T = GetExprType(E);
11465     unsigned opWidth = C.getIntWidth(T);
11466     IntRange L =
11467         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11468     IntRange R =
11469         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11470     IntRange C = Combine(L, R);
11471     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11472     C.Width = std::min(C.Width, MaxWidth);
11473     return C;
11474   }
11475 
11476   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11477     switch (UO->getOpcode()) {
11478     // Boolean-valued operations are white-listed.
11479     case UO_LNot:
11480       return IntRange::forBoolType();
11481 
11482     // Operations with opaque sources are black-listed.
11483     case UO_Deref:
11484     case UO_AddrOf: // should be impossible
11485       return IntRange::forValueOfType(C, GetExprType(E));
11486 
11487     default:
11488       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11489                           Approximate);
11490     }
11491   }
11492 
11493   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11494     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11495                         Approximate);
11496 
11497   if (const auto *BitField = E->getSourceBitField())
11498     return IntRange(BitField->getBitWidthValue(C),
11499                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11500 
11501   return IntRange::forValueOfType(C, GetExprType(E));
11502 }
11503 
11504 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11505                              bool InConstantContext, bool Approximate) {
11506   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11507                       Approximate);
11508 }
11509 
11510 /// Checks whether the given value, which currently has the given
11511 /// source semantics, has the same value when coerced through the
11512 /// target semantics.
11513 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11514                                  const llvm::fltSemantics &Src,
11515                                  const llvm::fltSemantics &Tgt) {
11516   llvm::APFloat truncated = value;
11517 
11518   bool ignored;
11519   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11520   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11521 
11522   return truncated.bitwiseIsEqual(value);
11523 }
11524 
11525 /// Checks whether the given value, which currently has the given
11526 /// source semantics, has the same value when coerced through the
11527 /// target semantics.
11528 ///
11529 /// The value might be a vector of floats (or a complex number).
11530 static bool IsSameFloatAfterCast(const APValue &value,
11531                                  const llvm::fltSemantics &Src,
11532                                  const llvm::fltSemantics &Tgt) {
11533   if (value.isFloat())
11534     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11535 
11536   if (value.isVector()) {
11537     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11538       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11539         return false;
11540     return true;
11541   }
11542 
11543   assert(value.isComplexFloat());
11544   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11545           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11546 }
11547 
11548 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11549                                        bool IsListInit = false);
11550 
11551 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11552   // Suppress cases where we are comparing against an enum constant.
11553   if (const DeclRefExpr *DR =
11554       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11555     if (isa<EnumConstantDecl>(DR->getDecl()))
11556       return true;
11557 
11558   // Suppress cases where the value is expanded from a macro, unless that macro
11559   // is how a language represents a boolean literal. This is the case in both C
11560   // and Objective-C.
11561   SourceLocation BeginLoc = E->getBeginLoc();
11562   if (BeginLoc.isMacroID()) {
11563     StringRef MacroName = Lexer::getImmediateMacroName(
11564         BeginLoc, S.getSourceManager(), S.getLangOpts());
11565     return MacroName != "YES" && MacroName != "NO" &&
11566            MacroName != "true" && MacroName != "false";
11567   }
11568 
11569   return false;
11570 }
11571 
11572 static bool isKnownToHaveUnsignedValue(Expr *E) {
11573   return E->getType()->isIntegerType() &&
11574          (!E->getType()->isSignedIntegerType() ||
11575           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11576 }
11577 
11578 namespace {
11579 /// The promoted range of values of a type. In general this has the
11580 /// following structure:
11581 ///
11582 ///     |-----------| . . . |-----------|
11583 ///     ^           ^       ^           ^
11584 ///    Min       HoleMin  HoleMax      Max
11585 ///
11586 /// ... where there is only a hole if a signed type is promoted to unsigned
11587 /// (in which case Min and Max are the smallest and largest representable
11588 /// values).
11589 struct PromotedRange {
11590   // Min, or HoleMax if there is a hole.
11591   llvm::APSInt PromotedMin;
11592   // Max, or HoleMin if there is a hole.
11593   llvm::APSInt PromotedMax;
11594 
11595   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11596     if (R.Width == 0)
11597       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11598     else if (R.Width >= BitWidth && !Unsigned) {
11599       // Promotion made the type *narrower*. This happens when promoting
11600       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11601       // Treat all values of 'signed int' as being in range for now.
11602       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11603       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11604     } else {
11605       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11606                         .extOrTrunc(BitWidth);
11607       PromotedMin.setIsUnsigned(Unsigned);
11608 
11609       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11610                         .extOrTrunc(BitWidth);
11611       PromotedMax.setIsUnsigned(Unsigned);
11612     }
11613   }
11614 
11615   // Determine whether this range is contiguous (has no hole).
11616   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11617 
11618   // Where a constant value is within the range.
11619   enum ComparisonResult {
11620     LT = 0x1,
11621     LE = 0x2,
11622     GT = 0x4,
11623     GE = 0x8,
11624     EQ = 0x10,
11625     NE = 0x20,
11626     InRangeFlag = 0x40,
11627 
11628     Less = LE | LT | NE,
11629     Min = LE | InRangeFlag,
11630     InRange = InRangeFlag,
11631     Max = GE | InRangeFlag,
11632     Greater = GE | GT | NE,
11633 
11634     OnlyValue = LE | GE | EQ | InRangeFlag,
11635     InHole = NE
11636   };
11637 
11638   ComparisonResult compare(const llvm::APSInt &Value) const {
11639     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11640            Value.isUnsigned() == PromotedMin.isUnsigned());
11641     if (!isContiguous()) {
11642       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11643       if (Value.isMinValue()) return Min;
11644       if (Value.isMaxValue()) return Max;
11645       if (Value >= PromotedMin) return InRange;
11646       if (Value <= PromotedMax) return InRange;
11647       return InHole;
11648     }
11649 
11650     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11651     case -1: return Less;
11652     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11653     case 1:
11654       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11655       case -1: return InRange;
11656       case 0: return Max;
11657       case 1: return Greater;
11658       }
11659     }
11660 
11661     llvm_unreachable("impossible compare result");
11662   }
11663 
11664   static llvm::Optional<StringRef>
11665   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11666     if (Op == BO_Cmp) {
11667       ComparisonResult LTFlag = LT, GTFlag = GT;
11668       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11669 
11670       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11671       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11672       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11673       return llvm::None;
11674     }
11675 
11676     ComparisonResult TrueFlag, FalseFlag;
11677     if (Op == BO_EQ) {
11678       TrueFlag = EQ;
11679       FalseFlag = NE;
11680     } else if (Op == BO_NE) {
11681       TrueFlag = NE;
11682       FalseFlag = EQ;
11683     } else {
11684       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11685         TrueFlag = LT;
11686         FalseFlag = GE;
11687       } else {
11688         TrueFlag = GT;
11689         FalseFlag = LE;
11690       }
11691       if (Op == BO_GE || Op == BO_LE)
11692         std::swap(TrueFlag, FalseFlag);
11693     }
11694     if (R & TrueFlag)
11695       return StringRef("true");
11696     if (R & FalseFlag)
11697       return StringRef("false");
11698     return llvm::None;
11699   }
11700 };
11701 }
11702 
11703 static bool HasEnumType(Expr *E) {
11704   // Strip off implicit integral promotions.
11705   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11706     if (ICE->getCastKind() != CK_IntegralCast &&
11707         ICE->getCastKind() != CK_NoOp)
11708       break;
11709     E = ICE->getSubExpr();
11710   }
11711 
11712   return E->getType()->isEnumeralType();
11713 }
11714 
11715 static int classifyConstantValue(Expr *Constant) {
11716   // The values of this enumeration are used in the diagnostics
11717   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11718   enum ConstantValueKind {
11719     Miscellaneous = 0,
11720     LiteralTrue,
11721     LiteralFalse
11722   };
11723   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11724     return BL->getValue() ? ConstantValueKind::LiteralTrue
11725                           : ConstantValueKind::LiteralFalse;
11726   return ConstantValueKind::Miscellaneous;
11727 }
11728 
11729 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11730                                         Expr *Constant, Expr *Other,
11731                                         const llvm::APSInt &Value,
11732                                         bool RhsConstant) {
11733   if (S.inTemplateInstantiation())
11734     return false;
11735 
11736   Expr *OriginalOther = Other;
11737 
11738   Constant = Constant->IgnoreParenImpCasts();
11739   Other = Other->IgnoreParenImpCasts();
11740 
11741   // Suppress warnings on tautological comparisons between values of the same
11742   // enumeration type. There are only two ways we could warn on this:
11743   //  - If the constant is outside the range of representable values of
11744   //    the enumeration. In such a case, we should warn about the cast
11745   //    to enumeration type, not about the comparison.
11746   //  - If the constant is the maximum / minimum in-range value. For an
11747   //    enumeratin type, such comparisons can be meaningful and useful.
11748   if (Constant->getType()->isEnumeralType() &&
11749       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11750     return false;
11751 
11752   IntRange OtherValueRange = GetExprRange(
11753       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11754 
11755   QualType OtherT = Other->getType();
11756   if (const auto *AT = OtherT->getAs<AtomicType>())
11757     OtherT = AT->getValueType();
11758   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11759 
11760   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11761   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11762   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11763                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11764                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11765 
11766   // Whether we're treating Other as being a bool because of the form of
11767   // expression despite it having another type (typically 'int' in C).
11768   bool OtherIsBooleanDespiteType =
11769       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11770   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11771     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11772 
11773   // Check if all values in the range of possible values of this expression
11774   // lead to the same comparison outcome.
11775   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11776                                         Value.isUnsigned());
11777   auto Cmp = OtherPromotedValueRange.compare(Value);
11778   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11779   if (!Result)
11780     return false;
11781 
11782   // Also consider the range determined by the type alone. This allows us to
11783   // classify the warning under the proper diagnostic group.
11784   bool TautologicalTypeCompare = false;
11785   {
11786     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11787                                          Value.isUnsigned());
11788     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11789     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11790                                                        RhsConstant)) {
11791       TautologicalTypeCompare = true;
11792       Cmp = TypeCmp;
11793       Result = TypeResult;
11794     }
11795   }
11796 
11797   // Don't warn if the non-constant operand actually always evaluates to the
11798   // same value.
11799   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11800     return false;
11801 
11802   // Suppress the diagnostic for an in-range comparison if the constant comes
11803   // from a macro or enumerator. We don't want to diagnose
11804   //
11805   //   some_long_value <= INT_MAX
11806   //
11807   // when sizeof(int) == sizeof(long).
11808   bool InRange = Cmp & PromotedRange::InRangeFlag;
11809   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11810     return false;
11811 
11812   // A comparison of an unsigned bit-field against 0 is really a type problem,
11813   // even though at the type level the bit-field might promote to 'signed int'.
11814   if (Other->refersToBitField() && InRange && Value == 0 &&
11815       Other->getType()->isUnsignedIntegerOrEnumerationType())
11816     TautologicalTypeCompare = true;
11817 
11818   // If this is a comparison to an enum constant, include that
11819   // constant in the diagnostic.
11820   const EnumConstantDecl *ED = nullptr;
11821   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11822     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11823 
11824   // Should be enough for uint128 (39 decimal digits)
11825   SmallString<64> PrettySourceValue;
11826   llvm::raw_svector_ostream OS(PrettySourceValue);
11827   if (ED) {
11828     OS << '\'' << *ED << "' (" << Value << ")";
11829   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11830                Constant->IgnoreParenImpCasts())) {
11831     OS << (BL->getValue() ? "YES" : "NO");
11832   } else {
11833     OS << Value;
11834   }
11835 
11836   if (!TautologicalTypeCompare) {
11837     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11838         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11839         << E->getOpcodeStr() << OS.str() << *Result
11840         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11841     return true;
11842   }
11843 
11844   if (IsObjCSignedCharBool) {
11845     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11846                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11847                               << OS.str() << *Result);
11848     return true;
11849   }
11850 
11851   // FIXME: We use a somewhat different formatting for the in-range cases and
11852   // cases involving boolean values for historical reasons. We should pick a
11853   // consistent way of presenting these diagnostics.
11854   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11855 
11856     S.DiagRuntimeBehavior(
11857         E->getOperatorLoc(), E,
11858         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11859                          : diag::warn_tautological_bool_compare)
11860             << OS.str() << classifyConstantValue(Constant) << OtherT
11861             << OtherIsBooleanDespiteType << *Result
11862             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11863   } else {
11864     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11865     unsigned Diag =
11866         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11867             ? (HasEnumType(OriginalOther)
11868                    ? diag::warn_unsigned_enum_always_true_comparison
11869                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11870                               : diag::warn_unsigned_always_true_comparison)
11871             : diag::warn_tautological_constant_compare;
11872 
11873     S.Diag(E->getOperatorLoc(), Diag)
11874         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11875         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11876   }
11877 
11878   return true;
11879 }
11880 
11881 /// Analyze the operands of the given comparison.  Implements the
11882 /// fallback case from AnalyzeComparison.
11883 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11884   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11885   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11886 }
11887 
11888 /// Implements -Wsign-compare.
11889 ///
11890 /// \param E the binary operator to check for warnings
11891 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11892   // The type the comparison is being performed in.
11893   QualType T = E->getLHS()->getType();
11894 
11895   // Only analyze comparison operators where both sides have been converted to
11896   // the same type.
11897   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11898     return AnalyzeImpConvsInComparison(S, E);
11899 
11900   // Don't analyze value-dependent comparisons directly.
11901   if (E->isValueDependent())
11902     return AnalyzeImpConvsInComparison(S, E);
11903 
11904   Expr *LHS = E->getLHS();
11905   Expr *RHS = E->getRHS();
11906 
11907   if (T->isIntegralType(S.Context)) {
11908     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11909     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11910 
11911     // We don't care about expressions whose result is a constant.
11912     if (RHSValue && LHSValue)
11913       return AnalyzeImpConvsInComparison(S, E);
11914 
11915     // We only care about expressions where just one side is literal
11916     if ((bool)RHSValue ^ (bool)LHSValue) {
11917       // Is the constant on the RHS or LHS?
11918       const bool RhsConstant = (bool)RHSValue;
11919       Expr *Const = RhsConstant ? RHS : LHS;
11920       Expr *Other = RhsConstant ? LHS : RHS;
11921       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11922 
11923       // Check whether an integer constant comparison results in a value
11924       // of 'true' or 'false'.
11925       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11926         return AnalyzeImpConvsInComparison(S, E);
11927     }
11928   }
11929 
11930   if (!T->hasUnsignedIntegerRepresentation()) {
11931     // We don't do anything special if this isn't an unsigned integral
11932     // comparison:  we're only interested in integral comparisons, and
11933     // signed comparisons only happen in cases we don't care to warn about.
11934     return AnalyzeImpConvsInComparison(S, E);
11935   }
11936 
11937   LHS = LHS->IgnoreParenImpCasts();
11938   RHS = RHS->IgnoreParenImpCasts();
11939 
11940   if (!S.getLangOpts().CPlusPlus) {
11941     // Avoid warning about comparison of integers with different signs when
11942     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11943     // the type of `E`.
11944     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11945       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11946     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11947       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11948   }
11949 
11950   // Check to see if one of the (unmodified) operands is of different
11951   // signedness.
11952   Expr *signedOperand, *unsignedOperand;
11953   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11954     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11955            "unsigned comparison between two signed integer expressions?");
11956     signedOperand = LHS;
11957     unsignedOperand = RHS;
11958   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11959     signedOperand = RHS;
11960     unsignedOperand = LHS;
11961   } else {
11962     return AnalyzeImpConvsInComparison(S, E);
11963   }
11964 
11965   // Otherwise, calculate the effective range of the signed operand.
11966   IntRange signedRange = GetExprRange(
11967       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11968 
11969   // Go ahead and analyze implicit conversions in the operands.  Note
11970   // that we skip the implicit conversions on both sides.
11971   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11972   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11973 
11974   // If the signed range is non-negative, -Wsign-compare won't fire.
11975   if (signedRange.NonNegative)
11976     return;
11977 
11978   // For (in)equality comparisons, if the unsigned operand is a
11979   // constant which cannot collide with a overflowed signed operand,
11980   // then reinterpreting the signed operand as unsigned will not
11981   // change the result of the comparison.
11982   if (E->isEqualityOp()) {
11983     unsigned comparisonWidth = S.Context.getIntWidth(T);
11984     IntRange unsignedRange =
11985         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11986                      /*Approximate*/ true);
11987 
11988     // We should never be unable to prove that the unsigned operand is
11989     // non-negative.
11990     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11991 
11992     if (unsignedRange.Width < comparisonWidth)
11993       return;
11994   }
11995 
11996   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11997                         S.PDiag(diag::warn_mixed_sign_comparison)
11998                             << LHS->getType() << RHS->getType()
11999                             << LHS->getSourceRange() << RHS->getSourceRange());
12000 }
12001 
12002 /// Analyzes an attempt to assign the given value to a bitfield.
12003 ///
12004 /// Returns true if there was something fishy about the attempt.
12005 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12006                                       SourceLocation InitLoc) {
12007   assert(Bitfield->isBitField());
12008   if (Bitfield->isInvalidDecl())
12009     return false;
12010 
12011   // White-list bool bitfields.
12012   QualType BitfieldType = Bitfield->getType();
12013   if (BitfieldType->isBooleanType())
12014      return false;
12015 
12016   if (BitfieldType->isEnumeralType()) {
12017     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12018     // If the underlying enum type was not explicitly specified as an unsigned
12019     // type and the enum contain only positive values, MSVC++ will cause an
12020     // inconsistency by storing this as a signed type.
12021     if (S.getLangOpts().CPlusPlus11 &&
12022         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12023         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12024         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12025       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12026           << BitfieldEnumDecl;
12027     }
12028   }
12029 
12030   if (Bitfield->getType()->isBooleanType())
12031     return false;
12032 
12033   // Ignore value- or type-dependent expressions.
12034   if (Bitfield->getBitWidth()->isValueDependent() ||
12035       Bitfield->getBitWidth()->isTypeDependent() ||
12036       Init->isValueDependent() ||
12037       Init->isTypeDependent())
12038     return false;
12039 
12040   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12041   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12042 
12043   Expr::EvalResult Result;
12044   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12045                                    Expr::SE_AllowSideEffects)) {
12046     // The RHS is not constant.  If the RHS has an enum type, make sure the
12047     // bitfield is wide enough to hold all the values of the enum without
12048     // truncation.
12049     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12050       EnumDecl *ED = EnumTy->getDecl();
12051       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12052 
12053       // Enum types are implicitly signed on Windows, so check if there are any
12054       // negative enumerators to see if the enum was intended to be signed or
12055       // not.
12056       bool SignedEnum = ED->getNumNegativeBits() > 0;
12057 
12058       // Check for surprising sign changes when assigning enum values to a
12059       // bitfield of different signedness.  If the bitfield is signed and we
12060       // have exactly the right number of bits to store this unsigned enum,
12061       // suggest changing the enum to an unsigned type. This typically happens
12062       // on Windows where unfixed enums always use an underlying type of 'int'.
12063       unsigned DiagID = 0;
12064       if (SignedEnum && !SignedBitfield) {
12065         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12066       } else if (SignedBitfield && !SignedEnum &&
12067                  ED->getNumPositiveBits() == FieldWidth) {
12068         DiagID = diag::warn_signed_bitfield_enum_conversion;
12069       }
12070 
12071       if (DiagID) {
12072         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12073         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12074         SourceRange TypeRange =
12075             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12076         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12077             << SignedEnum << TypeRange;
12078       }
12079 
12080       // Compute the required bitwidth. If the enum has negative values, we need
12081       // one more bit than the normal number of positive bits to represent the
12082       // sign bit.
12083       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12084                                                   ED->getNumNegativeBits())
12085                                        : ED->getNumPositiveBits();
12086 
12087       // Check the bitwidth.
12088       if (BitsNeeded > FieldWidth) {
12089         Expr *WidthExpr = Bitfield->getBitWidth();
12090         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12091             << Bitfield << ED;
12092         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12093             << BitsNeeded << ED << WidthExpr->getSourceRange();
12094       }
12095     }
12096 
12097     return false;
12098   }
12099 
12100   llvm::APSInt Value = Result.Val.getInt();
12101 
12102   unsigned OriginalWidth = Value.getBitWidth();
12103 
12104   if (!Value.isSigned() || Value.isNegative())
12105     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12106       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12107         OriginalWidth = Value.getMinSignedBits();
12108 
12109   if (OriginalWidth <= FieldWidth)
12110     return false;
12111 
12112   // Compute the value which the bitfield will contain.
12113   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12114   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12115 
12116   // Check whether the stored value is equal to the original value.
12117   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12118   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12119     return false;
12120 
12121   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12122   // therefore don't strictly fit into a signed bitfield of width 1.
12123   if (FieldWidth == 1 && Value == 1)
12124     return false;
12125 
12126   std::string PrettyValue = toString(Value, 10);
12127   std::string PrettyTrunc = toString(TruncatedValue, 10);
12128 
12129   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12130     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12131     << Init->getSourceRange();
12132 
12133   return true;
12134 }
12135 
12136 /// Analyze the given simple or compound assignment for warning-worthy
12137 /// operations.
12138 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12139   // Just recurse on the LHS.
12140   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12141 
12142   // We want to recurse on the RHS as normal unless we're assigning to
12143   // a bitfield.
12144   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12145     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12146                                   E->getOperatorLoc())) {
12147       // Recurse, ignoring any implicit conversions on the RHS.
12148       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12149                                         E->getOperatorLoc());
12150     }
12151   }
12152 
12153   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12154 
12155   // Diagnose implicitly sequentially-consistent atomic assignment.
12156   if (E->getLHS()->getType()->isAtomicType())
12157     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12158 }
12159 
12160 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12161 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12162                             SourceLocation CContext, unsigned diag,
12163                             bool pruneControlFlow = false) {
12164   if (pruneControlFlow) {
12165     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12166                           S.PDiag(diag)
12167                               << SourceType << T << E->getSourceRange()
12168                               << SourceRange(CContext));
12169     return;
12170   }
12171   S.Diag(E->getExprLoc(), diag)
12172     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12173 }
12174 
12175 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12176 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12177                             SourceLocation CContext,
12178                             unsigned diag, bool pruneControlFlow = false) {
12179   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12180 }
12181 
12182 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12183   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12184       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12185 }
12186 
12187 static void adornObjCBoolConversionDiagWithTernaryFixit(
12188     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12189   Expr *Ignored = SourceExpr->IgnoreImplicit();
12190   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12191     Ignored = OVE->getSourceExpr();
12192   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12193                      isa<BinaryOperator>(Ignored) ||
12194                      isa<CXXOperatorCallExpr>(Ignored);
12195   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12196   if (NeedsParens)
12197     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12198             << FixItHint::CreateInsertion(EndLoc, ")");
12199   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12200 }
12201 
12202 /// Diagnose an implicit cast from a floating point value to an integer value.
12203 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12204                                     SourceLocation CContext) {
12205   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12206   const bool PruneWarnings = S.inTemplateInstantiation();
12207 
12208   Expr *InnerE = E->IgnoreParenImpCasts();
12209   // We also want to warn on, e.g., "int i = -1.234"
12210   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12211     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12212       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12213 
12214   const bool IsLiteral =
12215       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12216 
12217   llvm::APFloat Value(0.0);
12218   bool IsConstant =
12219     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12220   if (!IsConstant) {
12221     if (isObjCSignedCharBool(S, T)) {
12222       return adornObjCBoolConversionDiagWithTernaryFixit(
12223           S, E,
12224           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12225               << E->getType());
12226     }
12227 
12228     return DiagnoseImpCast(S, E, T, CContext,
12229                            diag::warn_impcast_float_integer, PruneWarnings);
12230   }
12231 
12232   bool isExact = false;
12233 
12234   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12235                             T->hasUnsignedIntegerRepresentation());
12236   llvm::APFloat::opStatus Result = Value.convertToInteger(
12237       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12238 
12239   // FIXME: Force the precision of the source value down so we don't print
12240   // digits which are usually useless (we don't really care here if we
12241   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12242   // would automatically print the shortest representation, but it's a bit
12243   // tricky to implement.
12244   SmallString<16> PrettySourceValue;
12245   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12246   precision = (precision * 59 + 195) / 196;
12247   Value.toString(PrettySourceValue, precision);
12248 
12249   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12250     return adornObjCBoolConversionDiagWithTernaryFixit(
12251         S, E,
12252         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12253             << PrettySourceValue);
12254   }
12255 
12256   if (Result == llvm::APFloat::opOK && isExact) {
12257     if (IsLiteral) return;
12258     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12259                            PruneWarnings);
12260   }
12261 
12262   // Conversion of a floating-point value to a non-bool integer where the
12263   // integral part cannot be represented by the integer type is undefined.
12264   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12265     return DiagnoseImpCast(
12266         S, E, T, CContext,
12267         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12268                   : diag::warn_impcast_float_to_integer_out_of_range,
12269         PruneWarnings);
12270 
12271   unsigned DiagID = 0;
12272   if (IsLiteral) {
12273     // Warn on floating point literal to integer.
12274     DiagID = diag::warn_impcast_literal_float_to_integer;
12275   } else if (IntegerValue == 0) {
12276     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12277       return DiagnoseImpCast(S, E, T, CContext,
12278                              diag::warn_impcast_float_integer, PruneWarnings);
12279     }
12280     // Warn on non-zero to zero conversion.
12281     DiagID = diag::warn_impcast_float_to_integer_zero;
12282   } else {
12283     if (IntegerValue.isUnsigned()) {
12284       if (!IntegerValue.isMaxValue()) {
12285         return DiagnoseImpCast(S, E, T, CContext,
12286                                diag::warn_impcast_float_integer, PruneWarnings);
12287       }
12288     } else {  // IntegerValue.isSigned()
12289       if (!IntegerValue.isMaxSignedValue() &&
12290           !IntegerValue.isMinSignedValue()) {
12291         return DiagnoseImpCast(S, E, T, CContext,
12292                                diag::warn_impcast_float_integer, PruneWarnings);
12293       }
12294     }
12295     // Warn on evaluatable floating point expression to integer conversion.
12296     DiagID = diag::warn_impcast_float_to_integer;
12297   }
12298 
12299   SmallString<16> PrettyTargetValue;
12300   if (IsBool)
12301     PrettyTargetValue = Value.isZero() ? "false" : "true";
12302   else
12303     IntegerValue.toString(PrettyTargetValue);
12304 
12305   if (PruneWarnings) {
12306     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12307                           S.PDiag(DiagID)
12308                               << E->getType() << T.getUnqualifiedType()
12309                               << PrettySourceValue << PrettyTargetValue
12310                               << E->getSourceRange() << SourceRange(CContext));
12311   } else {
12312     S.Diag(E->getExprLoc(), DiagID)
12313         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12314         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12315   }
12316 }
12317 
12318 /// Analyze the given compound assignment for the possible losing of
12319 /// floating-point precision.
12320 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12321   assert(isa<CompoundAssignOperator>(E) &&
12322          "Must be compound assignment operation");
12323   // Recurse on the LHS and RHS in here
12324   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12325   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12326 
12327   if (E->getLHS()->getType()->isAtomicType())
12328     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12329 
12330   // Now check the outermost expression
12331   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12332   const auto *RBT = cast<CompoundAssignOperator>(E)
12333                         ->getComputationResultType()
12334                         ->getAs<BuiltinType>();
12335 
12336   // The below checks assume source is floating point.
12337   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12338 
12339   // If source is floating point but target is an integer.
12340   if (ResultBT->isInteger())
12341     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12342                            E->getExprLoc(), diag::warn_impcast_float_integer);
12343 
12344   if (!ResultBT->isFloatingPoint())
12345     return;
12346 
12347   // If both source and target are floating points, warn about losing precision.
12348   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12349       QualType(ResultBT, 0), QualType(RBT, 0));
12350   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12351     // warn about dropping FP rank.
12352     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12353                     diag::warn_impcast_float_result_precision);
12354 }
12355 
12356 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12357                                       IntRange Range) {
12358   if (!Range.Width) return "0";
12359 
12360   llvm::APSInt ValueInRange = Value;
12361   ValueInRange.setIsSigned(!Range.NonNegative);
12362   ValueInRange = ValueInRange.trunc(Range.Width);
12363   return toString(ValueInRange, 10);
12364 }
12365 
12366 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12367   if (!isa<ImplicitCastExpr>(Ex))
12368     return false;
12369 
12370   Expr *InnerE = Ex->IgnoreParenImpCasts();
12371   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12372   const Type *Source =
12373     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12374   if (Target->isDependentType())
12375     return false;
12376 
12377   const BuiltinType *FloatCandidateBT =
12378     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12379   const Type *BoolCandidateType = ToBool ? Target : Source;
12380 
12381   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12382           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12383 }
12384 
12385 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12386                                              SourceLocation CC) {
12387   unsigned NumArgs = TheCall->getNumArgs();
12388   for (unsigned i = 0; i < NumArgs; ++i) {
12389     Expr *CurrA = TheCall->getArg(i);
12390     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12391       continue;
12392 
12393     bool IsSwapped = ((i > 0) &&
12394         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12395     IsSwapped |= ((i < (NumArgs - 1)) &&
12396         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12397     if (IsSwapped) {
12398       // Warn on this floating-point to bool conversion.
12399       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12400                       CurrA->getType(), CC,
12401                       diag::warn_impcast_floating_point_to_bool);
12402     }
12403   }
12404 }
12405 
12406 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12407                                    SourceLocation CC) {
12408   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12409                         E->getExprLoc()))
12410     return;
12411 
12412   // Don't warn on functions which have return type nullptr_t.
12413   if (isa<CallExpr>(E))
12414     return;
12415 
12416   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12417   const Expr::NullPointerConstantKind NullKind =
12418       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12419   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12420     return;
12421 
12422   // Return if target type is a safe conversion.
12423   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12424       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12425     return;
12426 
12427   SourceLocation Loc = E->getSourceRange().getBegin();
12428 
12429   // Venture through the macro stacks to get to the source of macro arguments.
12430   // The new location is a better location than the complete location that was
12431   // passed in.
12432   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12433   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12434 
12435   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12436   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12437     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12438         Loc, S.SourceMgr, S.getLangOpts());
12439     if (MacroName == "NULL")
12440       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12441   }
12442 
12443   // Only warn if the null and context location are in the same macro expansion.
12444   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12445     return;
12446 
12447   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12448       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12449       << FixItHint::CreateReplacement(Loc,
12450                                       S.getFixItZeroLiteralForType(T, Loc));
12451 }
12452 
12453 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12454                                   ObjCArrayLiteral *ArrayLiteral);
12455 
12456 static void
12457 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12458                            ObjCDictionaryLiteral *DictionaryLiteral);
12459 
12460 /// Check a single element within a collection literal against the
12461 /// target element type.
12462 static void checkObjCCollectionLiteralElement(Sema &S,
12463                                               QualType TargetElementType,
12464                                               Expr *Element,
12465                                               unsigned ElementKind) {
12466   // Skip a bitcast to 'id' or qualified 'id'.
12467   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12468     if (ICE->getCastKind() == CK_BitCast &&
12469         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12470       Element = ICE->getSubExpr();
12471   }
12472 
12473   QualType ElementType = Element->getType();
12474   ExprResult ElementResult(Element);
12475   if (ElementType->getAs<ObjCObjectPointerType>() &&
12476       S.CheckSingleAssignmentConstraints(TargetElementType,
12477                                          ElementResult,
12478                                          false, false)
12479         != Sema::Compatible) {
12480     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12481         << ElementType << ElementKind << TargetElementType
12482         << Element->getSourceRange();
12483   }
12484 
12485   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12486     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12487   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12488     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12489 }
12490 
12491 /// Check an Objective-C array literal being converted to the given
12492 /// target type.
12493 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12494                                   ObjCArrayLiteral *ArrayLiteral) {
12495   if (!S.NSArrayDecl)
12496     return;
12497 
12498   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12499   if (!TargetObjCPtr)
12500     return;
12501 
12502   if (TargetObjCPtr->isUnspecialized() ||
12503       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12504         != S.NSArrayDecl->getCanonicalDecl())
12505     return;
12506 
12507   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12508   if (TypeArgs.size() != 1)
12509     return;
12510 
12511   QualType TargetElementType = TypeArgs[0];
12512   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12513     checkObjCCollectionLiteralElement(S, TargetElementType,
12514                                       ArrayLiteral->getElement(I),
12515                                       0);
12516   }
12517 }
12518 
12519 /// Check an Objective-C dictionary literal being converted to the given
12520 /// target type.
12521 static void
12522 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12523                            ObjCDictionaryLiteral *DictionaryLiteral) {
12524   if (!S.NSDictionaryDecl)
12525     return;
12526 
12527   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12528   if (!TargetObjCPtr)
12529     return;
12530 
12531   if (TargetObjCPtr->isUnspecialized() ||
12532       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12533         != S.NSDictionaryDecl->getCanonicalDecl())
12534     return;
12535 
12536   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12537   if (TypeArgs.size() != 2)
12538     return;
12539 
12540   QualType TargetKeyType = TypeArgs[0];
12541   QualType TargetObjectType = TypeArgs[1];
12542   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12543     auto Element = DictionaryLiteral->getKeyValueElement(I);
12544     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12545     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12546   }
12547 }
12548 
12549 // Helper function to filter out cases for constant width constant conversion.
12550 // Don't warn on char array initialization or for non-decimal values.
12551 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12552                                           SourceLocation CC) {
12553   // If initializing from a constant, and the constant starts with '0',
12554   // then it is a binary, octal, or hexadecimal.  Allow these constants
12555   // to fill all the bits, even if there is a sign change.
12556   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12557     const char FirstLiteralCharacter =
12558         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12559     if (FirstLiteralCharacter == '0')
12560       return false;
12561   }
12562 
12563   // If the CC location points to a '{', and the type is char, then assume
12564   // assume it is an array initialization.
12565   if (CC.isValid() && T->isCharType()) {
12566     const char FirstContextCharacter =
12567         S.getSourceManager().getCharacterData(CC)[0];
12568     if (FirstContextCharacter == '{')
12569       return false;
12570   }
12571 
12572   return true;
12573 }
12574 
12575 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12576   const auto *IL = dyn_cast<IntegerLiteral>(E);
12577   if (!IL) {
12578     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12579       if (UO->getOpcode() == UO_Minus)
12580         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12581     }
12582   }
12583 
12584   return IL;
12585 }
12586 
12587 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12588   E = E->IgnoreParenImpCasts();
12589   SourceLocation ExprLoc = E->getExprLoc();
12590 
12591   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12592     BinaryOperator::Opcode Opc = BO->getOpcode();
12593     Expr::EvalResult Result;
12594     // Do not diagnose unsigned shifts.
12595     if (Opc == BO_Shl) {
12596       const auto *LHS = getIntegerLiteral(BO->getLHS());
12597       const auto *RHS = getIntegerLiteral(BO->getRHS());
12598       if (LHS && LHS->getValue() == 0)
12599         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12600       else if (!E->isValueDependent() && LHS && RHS &&
12601                RHS->getValue().isNonNegative() &&
12602                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12603         S.Diag(ExprLoc, diag::warn_left_shift_always)
12604             << (Result.Val.getInt() != 0);
12605       else if (E->getType()->isSignedIntegerType())
12606         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12607     }
12608   }
12609 
12610   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12611     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12612     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12613     if (!LHS || !RHS)
12614       return;
12615     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12616         (RHS->getValue() == 0 || RHS->getValue() == 1))
12617       // Do not diagnose common idioms.
12618       return;
12619     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12620       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12621   }
12622 }
12623 
12624 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12625                                     SourceLocation CC,
12626                                     bool *ICContext = nullptr,
12627                                     bool IsListInit = false) {
12628   if (E->isTypeDependent() || E->isValueDependent()) return;
12629 
12630   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12631   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12632   if (Source == Target) return;
12633   if (Target->isDependentType()) return;
12634 
12635   // If the conversion context location is invalid don't complain. We also
12636   // don't want to emit a warning if the issue occurs from the expansion of
12637   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12638   // delay this check as long as possible. Once we detect we are in that
12639   // scenario, we just return.
12640   if (CC.isInvalid())
12641     return;
12642 
12643   if (Source->isAtomicType())
12644     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12645 
12646   // Diagnose implicit casts to bool.
12647   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12648     if (isa<StringLiteral>(E))
12649       // Warn on string literal to bool.  Checks for string literals in logical
12650       // and expressions, for instance, assert(0 && "error here"), are
12651       // prevented by a check in AnalyzeImplicitConversions().
12652       return DiagnoseImpCast(S, E, T, CC,
12653                              diag::warn_impcast_string_literal_to_bool);
12654     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12655         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12656       // This covers the literal expressions that evaluate to Objective-C
12657       // objects.
12658       return DiagnoseImpCast(S, E, T, CC,
12659                              diag::warn_impcast_objective_c_literal_to_bool);
12660     }
12661     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12662       // Warn on pointer to bool conversion that is always true.
12663       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12664                                      SourceRange(CC));
12665     }
12666   }
12667 
12668   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12669   // is a typedef for signed char (macOS), then that constant value has to be 1
12670   // or 0.
12671   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12672     Expr::EvalResult Result;
12673     if (E->EvaluateAsInt(Result, S.getASTContext(),
12674                          Expr::SE_AllowSideEffects)) {
12675       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12676         adornObjCBoolConversionDiagWithTernaryFixit(
12677             S, E,
12678             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12679                 << toString(Result.Val.getInt(), 10));
12680       }
12681       return;
12682     }
12683   }
12684 
12685   // Check implicit casts from Objective-C collection literals to specialized
12686   // collection types, e.g., NSArray<NSString *> *.
12687   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12688     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12689   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12690     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12691 
12692   // Strip vector types.
12693   if (isa<VectorType>(Source)) {
12694     if (Target->isVLSTBuiltinType() &&
12695         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12696                                          QualType(Source, 0)) ||
12697          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12698                                             QualType(Source, 0))))
12699       return;
12700 
12701     if (!isa<VectorType>(Target)) {
12702       if (S.SourceMgr.isInSystemMacro(CC))
12703         return;
12704       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12705     }
12706 
12707     // If the vector cast is cast between two vectors of the same size, it is
12708     // a bitcast, not a conversion.
12709     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12710       return;
12711 
12712     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12713     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12714   }
12715   if (auto VecTy = dyn_cast<VectorType>(Target))
12716     Target = VecTy->getElementType().getTypePtr();
12717 
12718   // Strip complex types.
12719   if (isa<ComplexType>(Source)) {
12720     if (!isa<ComplexType>(Target)) {
12721       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12722         return;
12723 
12724       return DiagnoseImpCast(S, E, T, CC,
12725                              S.getLangOpts().CPlusPlus
12726                                  ? diag::err_impcast_complex_scalar
12727                                  : diag::warn_impcast_complex_scalar);
12728     }
12729 
12730     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12731     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12732   }
12733 
12734   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12735   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12736 
12737   // If the source is floating point...
12738   if (SourceBT && SourceBT->isFloatingPoint()) {
12739     // ...and the target is floating point...
12740     if (TargetBT && TargetBT->isFloatingPoint()) {
12741       // ...then warn if we're dropping FP rank.
12742 
12743       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12744           QualType(SourceBT, 0), QualType(TargetBT, 0));
12745       if (Order > 0) {
12746         // Don't warn about float constants that are precisely
12747         // representable in the target type.
12748         Expr::EvalResult result;
12749         if (E->EvaluateAsRValue(result, S.Context)) {
12750           // Value might be a float, a float vector, or a float complex.
12751           if (IsSameFloatAfterCast(result.Val,
12752                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12753                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12754             return;
12755         }
12756 
12757         if (S.SourceMgr.isInSystemMacro(CC))
12758           return;
12759 
12760         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12761       }
12762       // ... or possibly if we're increasing rank, too
12763       else if (Order < 0) {
12764         if (S.SourceMgr.isInSystemMacro(CC))
12765           return;
12766 
12767         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12768       }
12769       return;
12770     }
12771 
12772     // If the target is integral, always warn.
12773     if (TargetBT && TargetBT->isInteger()) {
12774       if (S.SourceMgr.isInSystemMacro(CC))
12775         return;
12776 
12777       DiagnoseFloatingImpCast(S, E, T, CC);
12778     }
12779 
12780     // Detect the case where a call result is converted from floating-point to
12781     // to bool, and the final argument to the call is converted from bool, to
12782     // discover this typo:
12783     //
12784     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12785     //
12786     // FIXME: This is an incredibly special case; is there some more general
12787     // way to detect this class of misplaced-parentheses bug?
12788     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12789       // Check last argument of function call to see if it is an
12790       // implicit cast from a type matching the type the result
12791       // is being cast to.
12792       CallExpr *CEx = cast<CallExpr>(E);
12793       if (unsigned NumArgs = CEx->getNumArgs()) {
12794         Expr *LastA = CEx->getArg(NumArgs - 1);
12795         Expr *InnerE = LastA->IgnoreParenImpCasts();
12796         if (isa<ImplicitCastExpr>(LastA) &&
12797             InnerE->getType()->isBooleanType()) {
12798           // Warn on this floating-point to bool conversion
12799           DiagnoseImpCast(S, E, T, CC,
12800                           diag::warn_impcast_floating_point_to_bool);
12801         }
12802       }
12803     }
12804     return;
12805   }
12806 
12807   // Valid casts involving fixed point types should be accounted for here.
12808   if (Source->isFixedPointType()) {
12809     if (Target->isUnsaturatedFixedPointType()) {
12810       Expr::EvalResult Result;
12811       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12812                                   S.isConstantEvaluated())) {
12813         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12814         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12815         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12816         if (Value > MaxVal || Value < MinVal) {
12817           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12818                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12819                                     << Value.toString() << T
12820                                     << E->getSourceRange()
12821                                     << clang::SourceRange(CC));
12822           return;
12823         }
12824       }
12825     } else if (Target->isIntegerType()) {
12826       Expr::EvalResult Result;
12827       if (!S.isConstantEvaluated() &&
12828           E->EvaluateAsFixedPoint(Result, S.Context,
12829                                   Expr::SE_AllowSideEffects)) {
12830         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12831 
12832         bool Overflowed;
12833         llvm::APSInt IntResult = FXResult.convertToInt(
12834             S.Context.getIntWidth(T),
12835             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12836 
12837         if (Overflowed) {
12838           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12839                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12840                                     << FXResult.toString() << T
12841                                     << E->getSourceRange()
12842                                     << clang::SourceRange(CC));
12843           return;
12844         }
12845       }
12846     }
12847   } else if (Target->isUnsaturatedFixedPointType()) {
12848     if (Source->isIntegerType()) {
12849       Expr::EvalResult Result;
12850       if (!S.isConstantEvaluated() &&
12851           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12852         llvm::APSInt Value = Result.Val.getInt();
12853 
12854         bool Overflowed;
12855         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12856             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12857 
12858         if (Overflowed) {
12859           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12860                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12861                                     << toString(Value, /*Radix=*/10) << T
12862                                     << E->getSourceRange()
12863                                     << clang::SourceRange(CC));
12864           return;
12865         }
12866       }
12867     }
12868   }
12869 
12870   // If we are casting an integer type to a floating point type without
12871   // initialization-list syntax, we might lose accuracy if the floating
12872   // point type has a narrower significand than the integer type.
12873   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12874       TargetBT->isFloatingType() && !IsListInit) {
12875     // Determine the number of precision bits in the source integer type.
12876     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12877                                         /*Approximate*/ true);
12878     unsigned int SourcePrecision = SourceRange.Width;
12879 
12880     // Determine the number of precision bits in the
12881     // target floating point type.
12882     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12883         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12884 
12885     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12886         SourcePrecision > TargetPrecision) {
12887 
12888       if (Optional<llvm::APSInt> SourceInt =
12889               E->getIntegerConstantExpr(S.Context)) {
12890         // If the source integer is a constant, convert it to the target
12891         // floating point type. Issue a warning if the value changes
12892         // during the whole conversion.
12893         llvm::APFloat TargetFloatValue(
12894             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12895         llvm::APFloat::opStatus ConversionStatus =
12896             TargetFloatValue.convertFromAPInt(
12897                 *SourceInt, SourceBT->isSignedInteger(),
12898                 llvm::APFloat::rmNearestTiesToEven);
12899 
12900         if (ConversionStatus != llvm::APFloat::opOK) {
12901           SmallString<32> PrettySourceValue;
12902           SourceInt->toString(PrettySourceValue, 10);
12903           SmallString<32> PrettyTargetValue;
12904           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12905 
12906           S.DiagRuntimeBehavior(
12907               E->getExprLoc(), E,
12908               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12909                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12910                   << E->getSourceRange() << clang::SourceRange(CC));
12911         }
12912       } else {
12913         // Otherwise, the implicit conversion may lose precision.
12914         DiagnoseImpCast(S, E, T, CC,
12915                         diag::warn_impcast_integer_float_precision);
12916       }
12917     }
12918   }
12919 
12920   DiagnoseNullConversion(S, E, T, CC);
12921 
12922   S.DiscardMisalignedMemberAddress(Target, E);
12923 
12924   if (Target->isBooleanType())
12925     DiagnoseIntInBoolContext(S, E);
12926 
12927   if (!Source->isIntegerType() || !Target->isIntegerType())
12928     return;
12929 
12930   // TODO: remove this early return once the false positives for constant->bool
12931   // in templates, macros, etc, are reduced or removed.
12932   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12933     return;
12934 
12935   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12936       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12937     return adornObjCBoolConversionDiagWithTernaryFixit(
12938         S, E,
12939         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12940             << E->getType());
12941   }
12942 
12943   IntRange SourceTypeRange =
12944       IntRange::forTargetOfCanonicalType(S.Context, Source);
12945   IntRange LikelySourceRange =
12946       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12947   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12948 
12949   if (LikelySourceRange.Width > TargetRange.Width) {
12950     // If the source is a constant, use a default-on diagnostic.
12951     // TODO: this should happen for bitfield stores, too.
12952     Expr::EvalResult Result;
12953     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12954                          S.isConstantEvaluated())) {
12955       llvm::APSInt Value(32);
12956       Value = Result.Val.getInt();
12957 
12958       if (S.SourceMgr.isInSystemMacro(CC))
12959         return;
12960 
12961       std::string PrettySourceValue = toString(Value, 10);
12962       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12963 
12964       S.DiagRuntimeBehavior(
12965           E->getExprLoc(), E,
12966           S.PDiag(diag::warn_impcast_integer_precision_constant)
12967               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12968               << E->getSourceRange() << SourceRange(CC));
12969       return;
12970     }
12971 
12972     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12973     if (S.SourceMgr.isInSystemMacro(CC))
12974       return;
12975 
12976     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12977       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12978                              /* pruneControlFlow */ true);
12979     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12980   }
12981 
12982   if (TargetRange.Width > SourceTypeRange.Width) {
12983     if (auto *UO = dyn_cast<UnaryOperator>(E))
12984       if (UO->getOpcode() == UO_Minus)
12985         if (Source->isUnsignedIntegerType()) {
12986           if (Target->isUnsignedIntegerType())
12987             return DiagnoseImpCast(S, E, T, CC,
12988                                    diag::warn_impcast_high_order_zero_bits);
12989           if (Target->isSignedIntegerType())
12990             return DiagnoseImpCast(S, E, T, CC,
12991                                    diag::warn_impcast_nonnegative_result);
12992         }
12993   }
12994 
12995   if (TargetRange.Width == LikelySourceRange.Width &&
12996       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12997       Source->isSignedIntegerType()) {
12998     // Warn when doing a signed to signed conversion, warn if the positive
12999     // source value is exactly the width of the target type, which will
13000     // cause a negative value to be stored.
13001 
13002     Expr::EvalResult Result;
13003     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13004         !S.SourceMgr.isInSystemMacro(CC)) {
13005       llvm::APSInt Value = Result.Val.getInt();
13006       if (isSameWidthConstantConversion(S, E, T, CC)) {
13007         std::string PrettySourceValue = toString(Value, 10);
13008         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13009 
13010         S.DiagRuntimeBehavior(
13011             E->getExprLoc(), E,
13012             S.PDiag(diag::warn_impcast_integer_precision_constant)
13013                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13014                 << E->getSourceRange() << SourceRange(CC));
13015         return;
13016       }
13017     }
13018 
13019     // Fall through for non-constants to give a sign conversion warning.
13020   }
13021 
13022   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13023       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13024        LikelySourceRange.Width == TargetRange.Width)) {
13025     if (S.SourceMgr.isInSystemMacro(CC))
13026       return;
13027 
13028     unsigned DiagID = diag::warn_impcast_integer_sign;
13029 
13030     // Traditionally, gcc has warned about this under -Wsign-compare.
13031     // We also want to warn about it in -Wconversion.
13032     // So if -Wconversion is off, use a completely identical diagnostic
13033     // in the sign-compare group.
13034     // The conditional-checking code will
13035     if (ICContext) {
13036       DiagID = diag::warn_impcast_integer_sign_conditional;
13037       *ICContext = true;
13038     }
13039 
13040     return DiagnoseImpCast(S, E, T, CC, DiagID);
13041   }
13042 
13043   // Diagnose conversions between different enumeration types.
13044   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13045   // type, to give us better diagnostics.
13046   QualType SourceType = E->getType();
13047   if (!S.getLangOpts().CPlusPlus) {
13048     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13049       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13050         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13051         SourceType = S.Context.getTypeDeclType(Enum);
13052         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13053       }
13054   }
13055 
13056   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13057     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13058       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13059           TargetEnum->getDecl()->hasNameForLinkage() &&
13060           SourceEnum != TargetEnum) {
13061         if (S.SourceMgr.isInSystemMacro(CC))
13062           return;
13063 
13064         return DiagnoseImpCast(S, E, SourceType, T, CC,
13065                                diag::warn_impcast_different_enum_types);
13066       }
13067 }
13068 
13069 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13070                                      SourceLocation CC, QualType T);
13071 
13072 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13073                                     SourceLocation CC, bool &ICContext) {
13074   E = E->IgnoreParenImpCasts();
13075 
13076   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13077     return CheckConditionalOperator(S, CO, CC, T);
13078 
13079   AnalyzeImplicitConversions(S, E, CC);
13080   if (E->getType() != T)
13081     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13082 }
13083 
13084 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13085                                      SourceLocation CC, QualType T) {
13086   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13087 
13088   Expr *TrueExpr = E->getTrueExpr();
13089   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13090     TrueExpr = BCO->getCommon();
13091 
13092   bool Suspicious = false;
13093   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13094   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13095 
13096   if (T->isBooleanType())
13097     DiagnoseIntInBoolContext(S, E);
13098 
13099   // If -Wconversion would have warned about either of the candidates
13100   // for a signedness conversion to the context type...
13101   if (!Suspicious) return;
13102 
13103   // ...but it's currently ignored...
13104   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13105     return;
13106 
13107   // ...then check whether it would have warned about either of the
13108   // candidates for a signedness conversion to the condition type.
13109   if (E->getType() == T) return;
13110 
13111   Suspicious = false;
13112   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13113                           E->getType(), CC, &Suspicious);
13114   if (!Suspicious)
13115     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13116                             E->getType(), CC, &Suspicious);
13117 }
13118 
13119 /// Check conversion of given expression to boolean.
13120 /// Input argument E is a logical expression.
13121 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13122   if (S.getLangOpts().Bool)
13123     return;
13124   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13125     return;
13126   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13127 }
13128 
13129 namespace {
13130 struct AnalyzeImplicitConversionsWorkItem {
13131   Expr *E;
13132   SourceLocation CC;
13133   bool IsListInit;
13134 };
13135 }
13136 
13137 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13138 /// that should be visited are added to WorkList.
13139 static void AnalyzeImplicitConversions(
13140     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13141     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13142   Expr *OrigE = Item.E;
13143   SourceLocation CC = Item.CC;
13144 
13145   QualType T = OrigE->getType();
13146   Expr *E = OrigE->IgnoreParenImpCasts();
13147 
13148   // Propagate whether we are in a C++ list initialization expression.
13149   // If so, we do not issue warnings for implicit int-float conversion
13150   // precision loss, because C++11 narrowing already handles it.
13151   bool IsListInit = Item.IsListInit ||
13152                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13153 
13154   if (E->isTypeDependent() || E->isValueDependent())
13155     return;
13156 
13157   Expr *SourceExpr = E;
13158   // Examine, but don't traverse into the source expression of an
13159   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13160   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13161   // evaluate it in the context of checking the specific conversion to T though.
13162   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13163     if (auto *Src = OVE->getSourceExpr())
13164       SourceExpr = Src;
13165 
13166   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13167     if (UO->getOpcode() == UO_Not &&
13168         UO->getSubExpr()->isKnownToHaveBooleanValue())
13169       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13170           << OrigE->getSourceRange() << T->isBooleanType()
13171           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13172 
13173   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13174     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13175         BO->getLHS()->isKnownToHaveBooleanValue() &&
13176         BO->getRHS()->isKnownToHaveBooleanValue() &&
13177         BO->getLHS()->HasSideEffects(S.Context) &&
13178         BO->getRHS()->HasSideEffects(S.Context)) {
13179       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13180           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13181           << FixItHint::CreateReplacement(
13182                  BO->getOperatorLoc(),
13183                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13184       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13185     }
13186 
13187   // For conditional operators, we analyze the arguments as if they
13188   // were being fed directly into the output.
13189   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13190     CheckConditionalOperator(S, CO, CC, T);
13191     return;
13192   }
13193 
13194   // Check implicit argument conversions for function calls.
13195   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13196     CheckImplicitArgumentConversions(S, Call, CC);
13197 
13198   // Go ahead and check any implicit conversions we might have skipped.
13199   // The non-canonical typecheck is just an optimization;
13200   // CheckImplicitConversion will filter out dead implicit conversions.
13201   if (SourceExpr->getType() != T)
13202     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13203 
13204   // Now continue drilling into this expression.
13205 
13206   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13207     // The bound subexpressions in a PseudoObjectExpr are not reachable
13208     // as transitive children.
13209     // FIXME: Use a more uniform representation for this.
13210     for (auto *SE : POE->semantics())
13211       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13212         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13213   }
13214 
13215   // Skip past explicit casts.
13216   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13217     E = CE->getSubExpr()->IgnoreParenImpCasts();
13218     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13219       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13220     WorkList.push_back({E, CC, IsListInit});
13221     return;
13222   }
13223 
13224   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13225     // Do a somewhat different check with comparison operators.
13226     if (BO->isComparisonOp())
13227       return AnalyzeComparison(S, BO);
13228 
13229     // And with simple assignments.
13230     if (BO->getOpcode() == BO_Assign)
13231       return AnalyzeAssignment(S, BO);
13232     // And with compound assignments.
13233     if (BO->isAssignmentOp())
13234       return AnalyzeCompoundAssignment(S, BO);
13235   }
13236 
13237   // These break the otherwise-useful invariant below.  Fortunately,
13238   // we don't really need to recurse into them, because any internal
13239   // expressions should have been analyzed already when they were
13240   // built into statements.
13241   if (isa<StmtExpr>(E)) return;
13242 
13243   // Don't descend into unevaluated contexts.
13244   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13245 
13246   // Now just recurse over the expression's children.
13247   CC = E->getExprLoc();
13248   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13249   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13250   for (Stmt *SubStmt : E->children()) {
13251     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13252     if (!ChildExpr)
13253       continue;
13254 
13255     if (IsLogicalAndOperator &&
13256         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13257       // Ignore checking string literals that are in logical and operators.
13258       // This is a common pattern for asserts.
13259       continue;
13260     WorkList.push_back({ChildExpr, CC, IsListInit});
13261   }
13262 
13263   if (BO && BO->isLogicalOp()) {
13264     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13265     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13266       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13267 
13268     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13269     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13270       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13271   }
13272 
13273   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13274     if (U->getOpcode() == UO_LNot) {
13275       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13276     } else if (U->getOpcode() != UO_AddrOf) {
13277       if (U->getSubExpr()->getType()->isAtomicType())
13278         S.Diag(U->getSubExpr()->getBeginLoc(),
13279                diag::warn_atomic_implicit_seq_cst);
13280     }
13281   }
13282 }
13283 
13284 /// AnalyzeImplicitConversions - Find and report any interesting
13285 /// implicit conversions in the given expression.  There are a couple
13286 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13287 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13288                                        bool IsListInit/*= false*/) {
13289   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13290   WorkList.push_back({OrigE, CC, IsListInit});
13291   while (!WorkList.empty())
13292     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13293 }
13294 
13295 /// Diagnose integer type and any valid implicit conversion to it.
13296 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13297   // Taking into account implicit conversions,
13298   // allow any integer.
13299   if (!E->getType()->isIntegerType()) {
13300     S.Diag(E->getBeginLoc(),
13301            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13302     return true;
13303   }
13304   // Potentially emit standard warnings for implicit conversions if enabled
13305   // using -Wconversion.
13306   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13307   return false;
13308 }
13309 
13310 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13311 // Returns true when emitting a warning about taking the address of a reference.
13312 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13313                               const PartialDiagnostic &PD) {
13314   E = E->IgnoreParenImpCasts();
13315 
13316   const FunctionDecl *FD = nullptr;
13317 
13318   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13319     if (!DRE->getDecl()->getType()->isReferenceType())
13320       return false;
13321   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13322     if (!M->getMemberDecl()->getType()->isReferenceType())
13323       return false;
13324   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13325     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13326       return false;
13327     FD = Call->getDirectCallee();
13328   } else {
13329     return false;
13330   }
13331 
13332   SemaRef.Diag(E->getExprLoc(), PD);
13333 
13334   // If possible, point to location of function.
13335   if (FD) {
13336     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13337   }
13338 
13339   return true;
13340 }
13341 
13342 // Returns true if the SourceLocation is expanded from any macro body.
13343 // Returns false if the SourceLocation is invalid, is from not in a macro
13344 // expansion, or is from expanded from a top-level macro argument.
13345 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13346   if (Loc.isInvalid())
13347     return false;
13348 
13349   while (Loc.isMacroID()) {
13350     if (SM.isMacroBodyExpansion(Loc))
13351       return true;
13352     Loc = SM.getImmediateMacroCallerLoc(Loc);
13353   }
13354 
13355   return false;
13356 }
13357 
13358 /// Diagnose pointers that are always non-null.
13359 /// \param E the expression containing the pointer
13360 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13361 /// compared to a null pointer
13362 /// \param IsEqual True when the comparison is equal to a null pointer
13363 /// \param Range Extra SourceRange to highlight in the diagnostic
13364 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13365                                         Expr::NullPointerConstantKind NullKind,
13366                                         bool IsEqual, SourceRange Range) {
13367   if (!E)
13368     return;
13369 
13370   // Don't warn inside macros.
13371   if (E->getExprLoc().isMacroID()) {
13372     const SourceManager &SM = getSourceManager();
13373     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13374         IsInAnyMacroBody(SM, Range.getBegin()))
13375       return;
13376   }
13377   E = E->IgnoreImpCasts();
13378 
13379   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13380 
13381   if (isa<CXXThisExpr>(E)) {
13382     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13383                                 : diag::warn_this_bool_conversion;
13384     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13385     return;
13386   }
13387 
13388   bool IsAddressOf = false;
13389 
13390   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13391     if (UO->getOpcode() != UO_AddrOf)
13392       return;
13393     IsAddressOf = true;
13394     E = UO->getSubExpr();
13395   }
13396 
13397   if (IsAddressOf) {
13398     unsigned DiagID = IsCompare
13399                           ? diag::warn_address_of_reference_null_compare
13400                           : diag::warn_address_of_reference_bool_conversion;
13401     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13402                                          << IsEqual;
13403     if (CheckForReference(*this, E, PD)) {
13404       return;
13405     }
13406   }
13407 
13408   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13409     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13410     std::string Str;
13411     llvm::raw_string_ostream S(Str);
13412     E->printPretty(S, nullptr, getPrintingPolicy());
13413     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13414                                 : diag::warn_cast_nonnull_to_bool;
13415     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13416       << E->getSourceRange() << Range << IsEqual;
13417     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13418   };
13419 
13420   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13421   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13422     if (auto *Callee = Call->getDirectCallee()) {
13423       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13424         ComplainAboutNonnullParamOrCall(A);
13425         return;
13426       }
13427     }
13428   }
13429 
13430   // Expect to find a single Decl.  Skip anything more complicated.
13431   ValueDecl *D = nullptr;
13432   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13433     D = R->getDecl();
13434   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13435     D = M->getMemberDecl();
13436   }
13437 
13438   // Weak Decls can be null.
13439   if (!D || D->isWeak())
13440     return;
13441 
13442   // Check for parameter decl with nonnull attribute
13443   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13444     if (getCurFunction() &&
13445         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13446       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13447         ComplainAboutNonnullParamOrCall(A);
13448         return;
13449       }
13450 
13451       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13452         // Skip function template not specialized yet.
13453         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13454           return;
13455         auto ParamIter = llvm::find(FD->parameters(), PV);
13456         assert(ParamIter != FD->param_end());
13457         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13458 
13459         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13460           if (!NonNull->args_size()) {
13461               ComplainAboutNonnullParamOrCall(NonNull);
13462               return;
13463           }
13464 
13465           for (const ParamIdx &ArgNo : NonNull->args()) {
13466             if (ArgNo.getASTIndex() == ParamNo) {
13467               ComplainAboutNonnullParamOrCall(NonNull);
13468               return;
13469             }
13470           }
13471         }
13472       }
13473     }
13474   }
13475 
13476   QualType T = D->getType();
13477   const bool IsArray = T->isArrayType();
13478   const bool IsFunction = T->isFunctionType();
13479 
13480   // Address of function is used to silence the function warning.
13481   if (IsAddressOf && IsFunction) {
13482     return;
13483   }
13484 
13485   // Found nothing.
13486   if (!IsAddressOf && !IsFunction && !IsArray)
13487     return;
13488 
13489   // Pretty print the expression for the diagnostic.
13490   std::string Str;
13491   llvm::raw_string_ostream S(Str);
13492   E->printPretty(S, nullptr, getPrintingPolicy());
13493 
13494   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13495                               : diag::warn_impcast_pointer_to_bool;
13496   enum {
13497     AddressOf,
13498     FunctionPointer,
13499     ArrayPointer
13500   } DiagType;
13501   if (IsAddressOf)
13502     DiagType = AddressOf;
13503   else if (IsFunction)
13504     DiagType = FunctionPointer;
13505   else if (IsArray)
13506     DiagType = ArrayPointer;
13507   else
13508     llvm_unreachable("Could not determine diagnostic.");
13509   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13510                                 << Range << IsEqual;
13511 
13512   if (!IsFunction)
13513     return;
13514 
13515   // Suggest '&' to silence the function warning.
13516   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13517       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13518 
13519   // Check to see if '()' fixit should be emitted.
13520   QualType ReturnType;
13521   UnresolvedSet<4> NonTemplateOverloads;
13522   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13523   if (ReturnType.isNull())
13524     return;
13525 
13526   if (IsCompare) {
13527     // There are two cases here.  If there is null constant, the only suggest
13528     // for a pointer return type.  If the null is 0, then suggest if the return
13529     // type is a pointer or an integer type.
13530     if (!ReturnType->isPointerType()) {
13531       if (NullKind == Expr::NPCK_ZeroExpression ||
13532           NullKind == Expr::NPCK_ZeroLiteral) {
13533         if (!ReturnType->isIntegerType())
13534           return;
13535       } else {
13536         return;
13537       }
13538     }
13539   } else { // !IsCompare
13540     // For function to bool, only suggest if the function pointer has bool
13541     // return type.
13542     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13543       return;
13544   }
13545   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13546       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13547 }
13548 
13549 /// Diagnoses "dangerous" implicit conversions within the given
13550 /// expression (which is a full expression).  Implements -Wconversion
13551 /// and -Wsign-compare.
13552 ///
13553 /// \param CC the "context" location of the implicit conversion, i.e.
13554 ///   the most location of the syntactic entity requiring the implicit
13555 ///   conversion
13556 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13557   // Don't diagnose in unevaluated contexts.
13558   if (isUnevaluatedContext())
13559     return;
13560 
13561   // Don't diagnose for value- or type-dependent expressions.
13562   if (E->isTypeDependent() || E->isValueDependent())
13563     return;
13564 
13565   // Check for array bounds violations in cases where the check isn't triggered
13566   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13567   // ArraySubscriptExpr is on the RHS of a variable initialization.
13568   CheckArrayAccess(E);
13569 
13570   // This is not the right CC for (e.g.) a variable initialization.
13571   AnalyzeImplicitConversions(*this, E, CC);
13572 }
13573 
13574 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13575 /// Input argument E is a logical expression.
13576 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13577   ::CheckBoolLikeConversion(*this, E, CC);
13578 }
13579 
13580 /// Diagnose when expression is an integer constant expression and its evaluation
13581 /// results in integer overflow
13582 void Sema::CheckForIntOverflow (Expr *E) {
13583   // Use a work list to deal with nested struct initializers.
13584   SmallVector<Expr *, 2> Exprs(1, E);
13585 
13586   do {
13587     Expr *OriginalE = Exprs.pop_back_val();
13588     Expr *E = OriginalE->IgnoreParenCasts();
13589 
13590     if (isa<BinaryOperator>(E)) {
13591       E->EvaluateForOverflow(Context);
13592       continue;
13593     }
13594 
13595     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13596       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13597     else if (isa<ObjCBoxedExpr>(OriginalE))
13598       E->EvaluateForOverflow(Context);
13599     else if (auto Call = dyn_cast<CallExpr>(E))
13600       Exprs.append(Call->arg_begin(), Call->arg_end());
13601     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13602       Exprs.append(Message->arg_begin(), Message->arg_end());
13603   } while (!Exprs.empty());
13604 }
13605 
13606 namespace {
13607 
13608 /// Visitor for expressions which looks for unsequenced operations on the
13609 /// same object.
13610 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13611   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13612 
13613   /// A tree of sequenced regions within an expression. Two regions are
13614   /// unsequenced if one is an ancestor or a descendent of the other. When we
13615   /// finish processing an expression with sequencing, such as a comma
13616   /// expression, we fold its tree nodes into its parent, since they are
13617   /// unsequenced with respect to nodes we will visit later.
13618   class SequenceTree {
13619     struct Value {
13620       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13621       unsigned Parent : 31;
13622       unsigned Merged : 1;
13623     };
13624     SmallVector<Value, 8> Values;
13625 
13626   public:
13627     /// A region within an expression which may be sequenced with respect
13628     /// to some other region.
13629     class Seq {
13630       friend class SequenceTree;
13631 
13632       unsigned Index;
13633 
13634       explicit Seq(unsigned N) : Index(N) {}
13635 
13636     public:
13637       Seq() : Index(0) {}
13638     };
13639 
13640     SequenceTree() { Values.push_back(Value(0)); }
13641     Seq root() const { return Seq(0); }
13642 
13643     /// Create a new sequence of operations, which is an unsequenced
13644     /// subset of \p Parent. This sequence of operations is sequenced with
13645     /// respect to other children of \p Parent.
13646     Seq allocate(Seq Parent) {
13647       Values.push_back(Value(Parent.Index));
13648       return Seq(Values.size() - 1);
13649     }
13650 
13651     /// Merge a sequence of operations into its parent.
13652     void merge(Seq S) {
13653       Values[S.Index].Merged = true;
13654     }
13655 
13656     /// Determine whether two operations are unsequenced. This operation
13657     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13658     /// should have been merged into its parent as appropriate.
13659     bool isUnsequenced(Seq Cur, Seq Old) {
13660       unsigned C = representative(Cur.Index);
13661       unsigned Target = representative(Old.Index);
13662       while (C >= Target) {
13663         if (C == Target)
13664           return true;
13665         C = Values[C].Parent;
13666       }
13667       return false;
13668     }
13669 
13670   private:
13671     /// Pick a representative for a sequence.
13672     unsigned representative(unsigned K) {
13673       if (Values[K].Merged)
13674         // Perform path compression as we go.
13675         return Values[K].Parent = representative(Values[K].Parent);
13676       return K;
13677     }
13678   };
13679 
13680   /// An object for which we can track unsequenced uses.
13681   using Object = const NamedDecl *;
13682 
13683   /// Different flavors of object usage which we track. We only track the
13684   /// least-sequenced usage of each kind.
13685   enum UsageKind {
13686     /// A read of an object. Multiple unsequenced reads are OK.
13687     UK_Use,
13688 
13689     /// A modification of an object which is sequenced before the value
13690     /// computation of the expression, such as ++n in C++.
13691     UK_ModAsValue,
13692 
13693     /// A modification of an object which is not sequenced before the value
13694     /// computation of the expression, such as n++.
13695     UK_ModAsSideEffect,
13696 
13697     UK_Count = UK_ModAsSideEffect + 1
13698   };
13699 
13700   /// Bundle together a sequencing region and the expression corresponding
13701   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13702   struct Usage {
13703     const Expr *UsageExpr;
13704     SequenceTree::Seq Seq;
13705 
13706     Usage() : UsageExpr(nullptr), Seq() {}
13707   };
13708 
13709   struct UsageInfo {
13710     Usage Uses[UK_Count];
13711 
13712     /// Have we issued a diagnostic for this object already?
13713     bool Diagnosed;
13714 
13715     UsageInfo() : Uses(), Diagnosed(false) {}
13716   };
13717   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13718 
13719   Sema &SemaRef;
13720 
13721   /// Sequenced regions within the expression.
13722   SequenceTree Tree;
13723 
13724   /// Declaration modifications and references which we have seen.
13725   UsageInfoMap UsageMap;
13726 
13727   /// The region we are currently within.
13728   SequenceTree::Seq Region;
13729 
13730   /// Filled in with declarations which were modified as a side-effect
13731   /// (that is, post-increment operations).
13732   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13733 
13734   /// Expressions to check later. We defer checking these to reduce
13735   /// stack usage.
13736   SmallVectorImpl<const Expr *> &WorkList;
13737 
13738   /// RAII object wrapping the visitation of a sequenced subexpression of an
13739   /// expression. At the end of this process, the side-effects of the evaluation
13740   /// become sequenced with respect to the value computation of the result, so
13741   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13742   /// UK_ModAsValue.
13743   struct SequencedSubexpression {
13744     SequencedSubexpression(SequenceChecker &Self)
13745       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13746       Self.ModAsSideEffect = &ModAsSideEffect;
13747     }
13748 
13749     ~SequencedSubexpression() {
13750       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13751         // Add a new usage with usage kind UK_ModAsValue, and then restore
13752         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13753         // the previous one was empty).
13754         UsageInfo &UI = Self.UsageMap[M.first];
13755         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13756         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13757         SideEffectUsage = M.second;
13758       }
13759       Self.ModAsSideEffect = OldModAsSideEffect;
13760     }
13761 
13762     SequenceChecker &Self;
13763     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13764     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13765   };
13766 
13767   /// RAII object wrapping the visitation of a subexpression which we might
13768   /// choose to evaluate as a constant. If any subexpression is evaluated and
13769   /// found to be non-constant, this allows us to suppress the evaluation of
13770   /// the outer expression.
13771   class EvaluationTracker {
13772   public:
13773     EvaluationTracker(SequenceChecker &Self)
13774         : Self(Self), Prev(Self.EvalTracker) {
13775       Self.EvalTracker = this;
13776     }
13777 
13778     ~EvaluationTracker() {
13779       Self.EvalTracker = Prev;
13780       if (Prev)
13781         Prev->EvalOK &= EvalOK;
13782     }
13783 
13784     bool evaluate(const Expr *E, bool &Result) {
13785       if (!EvalOK || E->isValueDependent())
13786         return false;
13787       EvalOK = E->EvaluateAsBooleanCondition(
13788           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13789       return EvalOK;
13790     }
13791 
13792   private:
13793     SequenceChecker &Self;
13794     EvaluationTracker *Prev;
13795     bool EvalOK = true;
13796   } *EvalTracker = nullptr;
13797 
13798   /// Find the object which is produced by the specified expression,
13799   /// if any.
13800   Object getObject(const Expr *E, bool Mod) const {
13801     E = E->IgnoreParenCasts();
13802     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13803       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13804         return getObject(UO->getSubExpr(), Mod);
13805     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13806       if (BO->getOpcode() == BO_Comma)
13807         return getObject(BO->getRHS(), Mod);
13808       if (Mod && BO->isAssignmentOp())
13809         return getObject(BO->getLHS(), Mod);
13810     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13811       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13812       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13813         return ME->getMemberDecl();
13814     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13815       // FIXME: If this is a reference, map through to its value.
13816       return DRE->getDecl();
13817     return nullptr;
13818   }
13819 
13820   /// Note that an object \p O was modified or used by an expression
13821   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13822   /// the object \p O as obtained via the \p UsageMap.
13823   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13824     // Get the old usage for the given object and usage kind.
13825     Usage &U = UI.Uses[UK];
13826     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13827       // If we have a modification as side effect and are in a sequenced
13828       // subexpression, save the old Usage so that we can restore it later
13829       // in SequencedSubexpression::~SequencedSubexpression.
13830       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13831         ModAsSideEffect->push_back(std::make_pair(O, U));
13832       // Then record the new usage with the current sequencing region.
13833       U.UsageExpr = UsageExpr;
13834       U.Seq = Region;
13835     }
13836   }
13837 
13838   /// Check whether a modification or use of an object \p O in an expression
13839   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13840   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13841   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13842   /// usage and false we are checking for a mod-use unsequenced usage.
13843   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13844                   UsageKind OtherKind, bool IsModMod) {
13845     if (UI.Diagnosed)
13846       return;
13847 
13848     const Usage &U = UI.Uses[OtherKind];
13849     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13850       return;
13851 
13852     const Expr *Mod = U.UsageExpr;
13853     const Expr *ModOrUse = UsageExpr;
13854     if (OtherKind == UK_Use)
13855       std::swap(Mod, ModOrUse);
13856 
13857     SemaRef.DiagRuntimeBehavior(
13858         Mod->getExprLoc(), {Mod, ModOrUse},
13859         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13860                                : diag::warn_unsequenced_mod_use)
13861             << O << SourceRange(ModOrUse->getExprLoc()));
13862     UI.Diagnosed = true;
13863   }
13864 
13865   // A note on note{Pre, Post}{Use, Mod}:
13866   //
13867   // (It helps to follow the algorithm with an expression such as
13868   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13869   //  operations before C++17 and both are well-defined in C++17).
13870   //
13871   // When visiting a node which uses/modify an object we first call notePreUse
13872   // or notePreMod before visiting its sub-expression(s). At this point the
13873   // children of the current node have not yet been visited and so the eventual
13874   // uses/modifications resulting from the children of the current node have not
13875   // been recorded yet.
13876   //
13877   // We then visit the children of the current node. After that notePostUse or
13878   // notePostMod is called. These will 1) detect an unsequenced modification
13879   // as side effect (as in "k++ + k") and 2) add a new usage with the
13880   // appropriate usage kind.
13881   //
13882   // We also have to be careful that some operation sequences modification as
13883   // side effect as well (for example: || or ,). To account for this we wrap
13884   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13885   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13886   // which record usages which are modifications as side effect, and then
13887   // downgrade them (or more accurately restore the previous usage which was a
13888   // modification as side effect) when exiting the scope of the sequenced
13889   // subexpression.
13890 
13891   void notePreUse(Object O, const Expr *UseExpr) {
13892     UsageInfo &UI = UsageMap[O];
13893     // Uses conflict with other modifications.
13894     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13895   }
13896 
13897   void notePostUse(Object O, const Expr *UseExpr) {
13898     UsageInfo &UI = UsageMap[O];
13899     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13900                /*IsModMod=*/false);
13901     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13902   }
13903 
13904   void notePreMod(Object O, const Expr *ModExpr) {
13905     UsageInfo &UI = UsageMap[O];
13906     // Modifications conflict with other modifications and with uses.
13907     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13908     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13909   }
13910 
13911   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13912     UsageInfo &UI = UsageMap[O];
13913     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13914                /*IsModMod=*/true);
13915     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13916   }
13917 
13918 public:
13919   SequenceChecker(Sema &S, const Expr *E,
13920                   SmallVectorImpl<const Expr *> &WorkList)
13921       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13922     Visit(E);
13923     // Silence a -Wunused-private-field since WorkList is now unused.
13924     // TODO: Evaluate if it can be used, and if not remove it.
13925     (void)this->WorkList;
13926   }
13927 
13928   void VisitStmt(const Stmt *S) {
13929     // Skip all statements which aren't expressions for now.
13930   }
13931 
13932   void VisitExpr(const Expr *E) {
13933     // By default, just recurse to evaluated subexpressions.
13934     Base::VisitStmt(E);
13935   }
13936 
13937   void VisitCastExpr(const CastExpr *E) {
13938     Object O = Object();
13939     if (E->getCastKind() == CK_LValueToRValue)
13940       O = getObject(E->getSubExpr(), false);
13941 
13942     if (O)
13943       notePreUse(O, E);
13944     VisitExpr(E);
13945     if (O)
13946       notePostUse(O, E);
13947   }
13948 
13949   void VisitSequencedExpressions(const Expr *SequencedBefore,
13950                                  const Expr *SequencedAfter) {
13951     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13952     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13953     SequenceTree::Seq OldRegion = Region;
13954 
13955     {
13956       SequencedSubexpression SeqBefore(*this);
13957       Region = BeforeRegion;
13958       Visit(SequencedBefore);
13959     }
13960 
13961     Region = AfterRegion;
13962     Visit(SequencedAfter);
13963 
13964     Region = OldRegion;
13965 
13966     Tree.merge(BeforeRegion);
13967     Tree.merge(AfterRegion);
13968   }
13969 
13970   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13971     // C++17 [expr.sub]p1:
13972     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13973     //   expression E1 is sequenced before the expression E2.
13974     if (SemaRef.getLangOpts().CPlusPlus17)
13975       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13976     else {
13977       Visit(ASE->getLHS());
13978       Visit(ASE->getRHS());
13979     }
13980   }
13981 
13982   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13983   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13984   void VisitBinPtrMem(const BinaryOperator *BO) {
13985     // C++17 [expr.mptr.oper]p4:
13986     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13987     //  the expression E1 is sequenced before the expression E2.
13988     if (SemaRef.getLangOpts().CPlusPlus17)
13989       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13990     else {
13991       Visit(BO->getLHS());
13992       Visit(BO->getRHS());
13993     }
13994   }
13995 
13996   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13997   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13998   void VisitBinShlShr(const BinaryOperator *BO) {
13999     // C++17 [expr.shift]p4:
14000     //  The expression E1 is sequenced before the expression E2.
14001     if (SemaRef.getLangOpts().CPlusPlus17)
14002       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14003     else {
14004       Visit(BO->getLHS());
14005       Visit(BO->getRHS());
14006     }
14007   }
14008 
14009   void VisitBinComma(const BinaryOperator *BO) {
14010     // C++11 [expr.comma]p1:
14011     //   Every value computation and side effect associated with the left
14012     //   expression is sequenced before every value computation and side
14013     //   effect associated with the right expression.
14014     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14015   }
14016 
14017   void VisitBinAssign(const BinaryOperator *BO) {
14018     SequenceTree::Seq RHSRegion;
14019     SequenceTree::Seq LHSRegion;
14020     if (SemaRef.getLangOpts().CPlusPlus17) {
14021       RHSRegion = Tree.allocate(Region);
14022       LHSRegion = Tree.allocate(Region);
14023     } else {
14024       RHSRegion = Region;
14025       LHSRegion = Region;
14026     }
14027     SequenceTree::Seq OldRegion = Region;
14028 
14029     // C++11 [expr.ass]p1:
14030     //  [...] the assignment is sequenced after the value computation
14031     //  of the right and left operands, [...]
14032     //
14033     // so check it before inspecting the operands and update the
14034     // map afterwards.
14035     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14036     if (O)
14037       notePreMod(O, BO);
14038 
14039     if (SemaRef.getLangOpts().CPlusPlus17) {
14040       // C++17 [expr.ass]p1:
14041       //  [...] The right operand is sequenced before the left operand. [...]
14042       {
14043         SequencedSubexpression SeqBefore(*this);
14044         Region = RHSRegion;
14045         Visit(BO->getRHS());
14046       }
14047 
14048       Region = LHSRegion;
14049       Visit(BO->getLHS());
14050 
14051       if (O && isa<CompoundAssignOperator>(BO))
14052         notePostUse(O, BO);
14053 
14054     } else {
14055       // C++11 does not specify any sequencing between the LHS and RHS.
14056       Region = LHSRegion;
14057       Visit(BO->getLHS());
14058 
14059       if (O && isa<CompoundAssignOperator>(BO))
14060         notePostUse(O, BO);
14061 
14062       Region = RHSRegion;
14063       Visit(BO->getRHS());
14064     }
14065 
14066     // C++11 [expr.ass]p1:
14067     //  the assignment is sequenced [...] before the value computation of the
14068     //  assignment expression.
14069     // C11 6.5.16/3 has no such rule.
14070     Region = OldRegion;
14071     if (O)
14072       notePostMod(O, BO,
14073                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14074                                                   : UK_ModAsSideEffect);
14075     if (SemaRef.getLangOpts().CPlusPlus17) {
14076       Tree.merge(RHSRegion);
14077       Tree.merge(LHSRegion);
14078     }
14079   }
14080 
14081   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14082     VisitBinAssign(CAO);
14083   }
14084 
14085   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14086   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14087   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14088     Object O = getObject(UO->getSubExpr(), true);
14089     if (!O)
14090       return VisitExpr(UO);
14091 
14092     notePreMod(O, UO);
14093     Visit(UO->getSubExpr());
14094     // C++11 [expr.pre.incr]p1:
14095     //   the expression ++x is equivalent to x+=1
14096     notePostMod(O, UO,
14097                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14098                                                 : UK_ModAsSideEffect);
14099   }
14100 
14101   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14102   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14103   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14104     Object O = getObject(UO->getSubExpr(), true);
14105     if (!O)
14106       return VisitExpr(UO);
14107 
14108     notePreMod(O, UO);
14109     Visit(UO->getSubExpr());
14110     notePostMod(O, UO, UK_ModAsSideEffect);
14111   }
14112 
14113   void VisitBinLOr(const BinaryOperator *BO) {
14114     // C++11 [expr.log.or]p2:
14115     //  If the second expression is evaluated, every value computation and
14116     //  side effect associated with the first expression is sequenced before
14117     //  every value computation and side effect associated with the
14118     //  second expression.
14119     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14120     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14121     SequenceTree::Seq OldRegion = Region;
14122 
14123     EvaluationTracker Eval(*this);
14124     {
14125       SequencedSubexpression Sequenced(*this);
14126       Region = LHSRegion;
14127       Visit(BO->getLHS());
14128     }
14129 
14130     // C++11 [expr.log.or]p1:
14131     //  [...] the second operand is not evaluated if the first operand
14132     //  evaluates to true.
14133     bool EvalResult = false;
14134     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14135     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14136     if (ShouldVisitRHS) {
14137       Region = RHSRegion;
14138       Visit(BO->getRHS());
14139     }
14140 
14141     Region = OldRegion;
14142     Tree.merge(LHSRegion);
14143     Tree.merge(RHSRegion);
14144   }
14145 
14146   void VisitBinLAnd(const BinaryOperator *BO) {
14147     // C++11 [expr.log.and]p2:
14148     //  If the second expression is evaluated, every value computation and
14149     //  side effect associated with the first expression is sequenced before
14150     //  every value computation and side effect associated with the
14151     //  second expression.
14152     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14153     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14154     SequenceTree::Seq OldRegion = Region;
14155 
14156     EvaluationTracker Eval(*this);
14157     {
14158       SequencedSubexpression Sequenced(*this);
14159       Region = LHSRegion;
14160       Visit(BO->getLHS());
14161     }
14162 
14163     // C++11 [expr.log.and]p1:
14164     //  [...] the second operand is not evaluated if the first operand is false.
14165     bool EvalResult = false;
14166     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14167     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14168     if (ShouldVisitRHS) {
14169       Region = RHSRegion;
14170       Visit(BO->getRHS());
14171     }
14172 
14173     Region = OldRegion;
14174     Tree.merge(LHSRegion);
14175     Tree.merge(RHSRegion);
14176   }
14177 
14178   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14179     // C++11 [expr.cond]p1:
14180     //  [...] Every value computation and side effect associated with the first
14181     //  expression is sequenced before every value computation and side effect
14182     //  associated with the second or third expression.
14183     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14184 
14185     // No sequencing is specified between the true and false expression.
14186     // However since exactly one of both is going to be evaluated we can
14187     // consider them to be sequenced. This is needed to avoid warning on
14188     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14189     // both the true and false expressions because we can't evaluate x.
14190     // This will still allow us to detect an expression like (pre C++17)
14191     // "(x ? y += 1 : y += 2) = y".
14192     //
14193     // We don't wrap the visitation of the true and false expression with
14194     // SequencedSubexpression because we don't want to downgrade modifications
14195     // as side effect in the true and false expressions after the visition
14196     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14197     // not warn between the two "y++", but we should warn between the "y++"
14198     // and the "y".
14199     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14200     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14201     SequenceTree::Seq OldRegion = Region;
14202 
14203     EvaluationTracker Eval(*this);
14204     {
14205       SequencedSubexpression Sequenced(*this);
14206       Region = ConditionRegion;
14207       Visit(CO->getCond());
14208     }
14209 
14210     // C++11 [expr.cond]p1:
14211     // [...] The first expression is contextually converted to bool (Clause 4).
14212     // It is evaluated and if it is true, the result of the conditional
14213     // expression is the value of the second expression, otherwise that of the
14214     // third expression. Only one of the second and third expressions is
14215     // evaluated. [...]
14216     bool EvalResult = false;
14217     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14218     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14219     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14220     if (ShouldVisitTrueExpr) {
14221       Region = TrueRegion;
14222       Visit(CO->getTrueExpr());
14223     }
14224     if (ShouldVisitFalseExpr) {
14225       Region = FalseRegion;
14226       Visit(CO->getFalseExpr());
14227     }
14228 
14229     Region = OldRegion;
14230     Tree.merge(ConditionRegion);
14231     Tree.merge(TrueRegion);
14232     Tree.merge(FalseRegion);
14233   }
14234 
14235   void VisitCallExpr(const CallExpr *CE) {
14236     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14237 
14238     if (CE->isUnevaluatedBuiltinCall(Context))
14239       return;
14240 
14241     // C++11 [intro.execution]p15:
14242     //   When calling a function [...], every value computation and side effect
14243     //   associated with any argument expression, or with the postfix expression
14244     //   designating the called function, is sequenced before execution of every
14245     //   expression or statement in the body of the function [and thus before
14246     //   the value computation of its result].
14247     SequencedSubexpression Sequenced(*this);
14248     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14249       // C++17 [expr.call]p5
14250       //   The postfix-expression is sequenced before each expression in the
14251       //   expression-list and any default argument. [...]
14252       SequenceTree::Seq CalleeRegion;
14253       SequenceTree::Seq OtherRegion;
14254       if (SemaRef.getLangOpts().CPlusPlus17) {
14255         CalleeRegion = Tree.allocate(Region);
14256         OtherRegion = Tree.allocate(Region);
14257       } else {
14258         CalleeRegion = Region;
14259         OtherRegion = Region;
14260       }
14261       SequenceTree::Seq OldRegion = Region;
14262 
14263       // Visit the callee expression first.
14264       Region = CalleeRegion;
14265       if (SemaRef.getLangOpts().CPlusPlus17) {
14266         SequencedSubexpression Sequenced(*this);
14267         Visit(CE->getCallee());
14268       } else {
14269         Visit(CE->getCallee());
14270       }
14271 
14272       // Then visit the argument expressions.
14273       Region = OtherRegion;
14274       for (const Expr *Argument : CE->arguments())
14275         Visit(Argument);
14276 
14277       Region = OldRegion;
14278       if (SemaRef.getLangOpts().CPlusPlus17) {
14279         Tree.merge(CalleeRegion);
14280         Tree.merge(OtherRegion);
14281       }
14282     });
14283   }
14284 
14285   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14286     // C++17 [over.match.oper]p2:
14287     //   [...] the operator notation is first transformed to the equivalent
14288     //   function-call notation as summarized in Table 12 (where @ denotes one
14289     //   of the operators covered in the specified subclause). However, the
14290     //   operands are sequenced in the order prescribed for the built-in
14291     //   operator (Clause 8).
14292     //
14293     // From the above only overloaded binary operators and overloaded call
14294     // operators have sequencing rules in C++17 that we need to handle
14295     // separately.
14296     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14297         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14298       return VisitCallExpr(CXXOCE);
14299 
14300     enum {
14301       NoSequencing,
14302       LHSBeforeRHS,
14303       RHSBeforeLHS,
14304       LHSBeforeRest
14305     } SequencingKind;
14306     switch (CXXOCE->getOperator()) {
14307     case OO_Equal:
14308     case OO_PlusEqual:
14309     case OO_MinusEqual:
14310     case OO_StarEqual:
14311     case OO_SlashEqual:
14312     case OO_PercentEqual:
14313     case OO_CaretEqual:
14314     case OO_AmpEqual:
14315     case OO_PipeEqual:
14316     case OO_LessLessEqual:
14317     case OO_GreaterGreaterEqual:
14318       SequencingKind = RHSBeforeLHS;
14319       break;
14320 
14321     case OO_LessLess:
14322     case OO_GreaterGreater:
14323     case OO_AmpAmp:
14324     case OO_PipePipe:
14325     case OO_Comma:
14326     case OO_ArrowStar:
14327     case OO_Subscript:
14328       SequencingKind = LHSBeforeRHS;
14329       break;
14330 
14331     case OO_Call:
14332       SequencingKind = LHSBeforeRest;
14333       break;
14334 
14335     default:
14336       SequencingKind = NoSequencing;
14337       break;
14338     }
14339 
14340     if (SequencingKind == NoSequencing)
14341       return VisitCallExpr(CXXOCE);
14342 
14343     // This is a call, so all subexpressions are sequenced before the result.
14344     SequencedSubexpression Sequenced(*this);
14345 
14346     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14347       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14348              "Should only get there with C++17 and above!");
14349       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14350              "Should only get there with an overloaded binary operator"
14351              " or an overloaded call operator!");
14352 
14353       if (SequencingKind == LHSBeforeRest) {
14354         assert(CXXOCE->getOperator() == OO_Call &&
14355                "We should only have an overloaded call operator here!");
14356 
14357         // This is very similar to VisitCallExpr, except that we only have the
14358         // C++17 case. The postfix-expression is the first argument of the
14359         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14360         // are in the following arguments.
14361         //
14362         // Note that we intentionally do not visit the callee expression since
14363         // it is just a decayed reference to a function.
14364         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14365         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14366         SequenceTree::Seq OldRegion = Region;
14367 
14368         assert(CXXOCE->getNumArgs() >= 1 &&
14369                "An overloaded call operator must have at least one argument"
14370                " for the postfix-expression!");
14371         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14372         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14373                                           CXXOCE->getNumArgs() - 1);
14374 
14375         // Visit the postfix-expression first.
14376         {
14377           Region = PostfixExprRegion;
14378           SequencedSubexpression Sequenced(*this);
14379           Visit(PostfixExpr);
14380         }
14381 
14382         // Then visit the argument expressions.
14383         Region = ArgsRegion;
14384         for (const Expr *Arg : Args)
14385           Visit(Arg);
14386 
14387         Region = OldRegion;
14388         Tree.merge(PostfixExprRegion);
14389         Tree.merge(ArgsRegion);
14390       } else {
14391         assert(CXXOCE->getNumArgs() == 2 &&
14392                "Should only have two arguments here!");
14393         assert((SequencingKind == LHSBeforeRHS ||
14394                 SequencingKind == RHSBeforeLHS) &&
14395                "Unexpected sequencing kind!");
14396 
14397         // We do not visit the callee expression since it is just a decayed
14398         // reference to a function.
14399         const Expr *E1 = CXXOCE->getArg(0);
14400         const Expr *E2 = CXXOCE->getArg(1);
14401         if (SequencingKind == RHSBeforeLHS)
14402           std::swap(E1, E2);
14403 
14404         return VisitSequencedExpressions(E1, E2);
14405       }
14406     });
14407   }
14408 
14409   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14410     // This is a call, so all subexpressions are sequenced before the result.
14411     SequencedSubexpression Sequenced(*this);
14412 
14413     if (!CCE->isListInitialization())
14414       return VisitExpr(CCE);
14415 
14416     // In C++11, list initializations are sequenced.
14417     SmallVector<SequenceTree::Seq, 32> Elts;
14418     SequenceTree::Seq Parent = Region;
14419     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14420                                               E = CCE->arg_end();
14421          I != E; ++I) {
14422       Region = Tree.allocate(Parent);
14423       Elts.push_back(Region);
14424       Visit(*I);
14425     }
14426 
14427     // Forget that the initializers are sequenced.
14428     Region = Parent;
14429     for (unsigned I = 0; I < Elts.size(); ++I)
14430       Tree.merge(Elts[I]);
14431   }
14432 
14433   void VisitInitListExpr(const InitListExpr *ILE) {
14434     if (!SemaRef.getLangOpts().CPlusPlus11)
14435       return VisitExpr(ILE);
14436 
14437     // In C++11, list initializations are sequenced.
14438     SmallVector<SequenceTree::Seq, 32> Elts;
14439     SequenceTree::Seq Parent = Region;
14440     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14441       const Expr *E = ILE->getInit(I);
14442       if (!E)
14443         continue;
14444       Region = Tree.allocate(Parent);
14445       Elts.push_back(Region);
14446       Visit(E);
14447     }
14448 
14449     // Forget that the initializers are sequenced.
14450     Region = Parent;
14451     for (unsigned I = 0; I < Elts.size(); ++I)
14452       Tree.merge(Elts[I]);
14453   }
14454 };
14455 
14456 } // namespace
14457 
14458 void Sema::CheckUnsequencedOperations(const Expr *E) {
14459   SmallVector<const Expr *, 8> WorkList;
14460   WorkList.push_back(E);
14461   while (!WorkList.empty()) {
14462     const Expr *Item = WorkList.pop_back_val();
14463     SequenceChecker(*this, Item, WorkList);
14464   }
14465 }
14466 
14467 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14468                               bool IsConstexpr) {
14469   llvm::SaveAndRestore<bool> ConstantContext(
14470       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14471   CheckImplicitConversions(E, CheckLoc);
14472   if (!E->isInstantiationDependent())
14473     CheckUnsequencedOperations(E);
14474   if (!IsConstexpr && !E->isValueDependent())
14475     CheckForIntOverflow(E);
14476   DiagnoseMisalignedMembers();
14477 }
14478 
14479 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14480                                        FieldDecl *BitField,
14481                                        Expr *Init) {
14482   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14483 }
14484 
14485 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14486                                          SourceLocation Loc) {
14487   if (!PType->isVariablyModifiedType())
14488     return;
14489   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14490     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14491     return;
14492   }
14493   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14494     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14495     return;
14496   }
14497   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14498     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14499     return;
14500   }
14501 
14502   const ArrayType *AT = S.Context.getAsArrayType(PType);
14503   if (!AT)
14504     return;
14505 
14506   if (AT->getSizeModifier() != ArrayType::Star) {
14507     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14508     return;
14509   }
14510 
14511   S.Diag(Loc, diag::err_array_star_in_function_definition);
14512 }
14513 
14514 /// CheckParmsForFunctionDef - Check that the parameters of the given
14515 /// function are appropriate for the definition of a function. This
14516 /// takes care of any checks that cannot be performed on the
14517 /// declaration itself, e.g., that the types of each of the function
14518 /// parameters are complete.
14519 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14520                                     bool CheckParameterNames) {
14521   bool HasInvalidParm = false;
14522   for (ParmVarDecl *Param : Parameters) {
14523     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14524     // function declarator that is part of a function definition of
14525     // that function shall not have incomplete type.
14526     //
14527     // This is also C++ [dcl.fct]p6.
14528     if (!Param->isInvalidDecl() &&
14529         RequireCompleteType(Param->getLocation(), Param->getType(),
14530                             diag::err_typecheck_decl_incomplete_type)) {
14531       Param->setInvalidDecl();
14532       HasInvalidParm = true;
14533     }
14534 
14535     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14536     // declaration of each parameter shall include an identifier.
14537     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14538         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14539       // Diagnose this as an extension in C17 and earlier.
14540       if (!getLangOpts().C2x)
14541         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14542     }
14543 
14544     // C99 6.7.5.3p12:
14545     //   If the function declarator is not part of a definition of that
14546     //   function, parameters may have incomplete type and may use the [*]
14547     //   notation in their sequences of declarator specifiers to specify
14548     //   variable length array types.
14549     QualType PType = Param->getOriginalType();
14550     // FIXME: This diagnostic should point the '[*]' if source-location
14551     // information is added for it.
14552     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14553 
14554     // If the parameter is a c++ class type and it has to be destructed in the
14555     // callee function, declare the destructor so that it can be called by the
14556     // callee function. Do not perform any direct access check on the dtor here.
14557     if (!Param->isInvalidDecl()) {
14558       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14559         if (!ClassDecl->isInvalidDecl() &&
14560             !ClassDecl->hasIrrelevantDestructor() &&
14561             !ClassDecl->isDependentContext() &&
14562             ClassDecl->isParamDestroyedInCallee()) {
14563           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14564           MarkFunctionReferenced(Param->getLocation(), Destructor);
14565           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14566         }
14567       }
14568     }
14569 
14570     // Parameters with the pass_object_size attribute only need to be marked
14571     // constant at function definitions. Because we lack information about
14572     // whether we're on a declaration or definition when we're instantiating the
14573     // attribute, we need to check for constness here.
14574     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14575       if (!Param->getType().isConstQualified())
14576         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14577             << Attr->getSpelling() << 1;
14578 
14579     // Check for parameter names shadowing fields from the class.
14580     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14581       // The owning context for the parameter should be the function, but we
14582       // want to see if this function's declaration context is a record.
14583       DeclContext *DC = Param->getDeclContext();
14584       if (DC && DC->isFunctionOrMethod()) {
14585         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14586           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14587                                      RD, /*DeclIsField*/ false);
14588       }
14589     }
14590   }
14591 
14592   return HasInvalidParm;
14593 }
14594 
14595 Optional<std::pair<CharUnits, CharUnits>>
14596 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14597 
14598 /// Compute the alignment and offset of the base class object given the
14599 /// derived-to-base cast expression and the alignment and offset of the derived
14600 /// class object.
14601 static std::pair<CharUnits, CharUnits>
14602 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14603                                    CharUnits BaseAlignment, CharUnits Offset,
14604                                    ASTContext &Ctx) {
14605   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14606        ++PathI) {
14607     const CXXBaseSpecifier *Base = *PathI;
14608     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14609     if (Base->isVirtual()) {
14610       // The complete object may have a lower alignment than the non-virtual
14611       // alignment of the base, in which case the base may be misaligned. Choose
14612       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14613       // conservative lower bound of the complete object alignment.
14614       CharUnits NonVirtualAlignment =
14615           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14616       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14617       Offset = CharUnits::Zero();
14618     } else {
14619       const ASTRecordLayout &RL =
14620           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14621       Offset += RL.getBaseClassOffset(BaseDecl);
14622     }
14623     DerivedType = Base->getType();
14624   }
14625 
14626   return std::make_pair(BaseAlignment, Offset);
14627 }
14628 
14629 /// Compute the alignment and offset of a binary additive operator.
14630 static Optional<std::pair<CharUnits, CharUnits>>
14631 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14632                                      bool IsSub, ASTContext &Ctx) {
14633   QualType PointeeType = PtrE->getType()->getPointeeType();
14634 
14635   if (!PointeeType->isConstantSizeType())
14636     return llvm::None;
14637 
14638   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14639 
14640   if (!P)
14641     return llvm::None;
14642 
14643   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14644   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14645     CharUnits Offset = EltSize * IdxRes->getExtValue();
14646     if (IsSub)
14647       Offset = -Offset;
14648     return std::make_pair(P->first, P->second + Offset);
14649   }
14650 
14651   // If the integer expression isn't a constant expression, compute the lower
14652   // bound of the alignment using the alignment and offset of the pointer
14653   // expression and the element size.
14654   return std::make_pair(
14655       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14656       CharUnits::Zero());
14657 }
14658 
14659 /// This helper function takes an lvalue expression and returns the alignment of
14660 /// a VarDecl and a constant offset from the VarDecl.
14661 Optional<std::pair<CharUnits, CharUnits>>
14662 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14663   E = E->IgnoreParens();
14664   switch (E->getStmtClass()) {
14665   default:
14666     break;
14667   case Stmt::CStyleCastExprClass:
14668   case Stmt::CXXStaticCastExprClass:
14669   case Stmt::ImplicitCastExprClass: {
14670     auto *CE = cast<CastExpr>(E);
14671     const Expr *From = CE->getSubExpr();
14672     switch (CE->getCastKind()) {
14673     default:
14674       break;
14675     case CK_NoOp:
14676       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14677     case CK_UncheckedDerivedToBase:
14678     case CK_DerivedToBase: {
14679       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14680       if (!P)
14681         break;
14682       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14683                                                 P->second, Ctx);
14684     }
14685     }
14686     break;
14687   }
14688   case Stmt::ArraySubscriptExprClass: {
14689     auto *ASE = cast<ArraySubscriptExpr>(E);
14690     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14691                                                 false, Ctx);
14692   }
14693   case Stmt::DeclRefExprClass: {
14694     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14695       // FIXME: If VD is captured by copy or is an escaping __block variable,
14696       // use the alignment of VD's type.
14697       if (!VD->getType()->isReferenceType())
14698         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14699       if (VD->hasInit())
14700         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14701     }
14702     break;
14703   }
14704   case Stmt::MemberExprClass: {
14705     auto *ME = cast<MemberExpr>(E);
14706     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14707     if (!FD || FD->getType()->isReferenceType() ||
14708         FD->getParent()->isInvalidDecl())
14709       break;
14710     Optional<std::pair<CharUnits, CharUnits>> P;
14711     if (ME->isArrow())
14712       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14713     else
14714       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14715     if (!P)
14716       break;
14717     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14718     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14719     return std::make_pair(P->first,
14720                           P->second + CharUnits::fromQuantity(Offset));
14721   }
14722   case Stmt::UnaryOperatorClass: {
14723     auto *UO = cast<UnaryOperator>(E);
14724     switch (UO->getOpcode()) {
14725     default:
14726       break;
14727     case UO_Deref:
14728       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14729     }
14730     break;
14731   }
14732   case Stmt::BinaryOperatorClass: {
14733     auto *BO = cast<BinaryOperator>(E);
14734     auto Opcode = BO->getOpcode();
14735     switch (Opcode) {
14736     default:
14737       break;
14738     case BO_Comma:
14739       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14740     }
14741     break;
14742   }
14743   }
14744   return llvm::None;
14745 }
14746 
14747 /// This helper function takes a pointer expression and returns the alignment of
14748 /// a VarDecl and a constant offset from the VarDecl.
14749 Optional<std::pair<CharUnits, CharUnits>>
14750 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14751   E = E->IgnoreParens();
14752   switch (E->getStmtClass()) {
14753   default:
14754     break;
14755   case Stmt::CStyleCastExprClass:
14756   case Stmt::CXXStaticCastExprClass:
14757   case Stmt::ImplicitCastExprClass: {
14758     auto *CE = cast<CastExpr>(E);
14759     const Expr *From = CE->getSubExpr();
14760     switch (CE->getCastKind()) {
14761     default:
14762       break;
14763     case CK_NoOp:
14764       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14765     case CK_ArrayToPointerDecay:
14766       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14767     case CK_UncheckedDerivedToBase:
14768     case CK_DerivedToBase: {
14769       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14770       if (!P)
14771         break;
14772       return getDerivedToBaseAlignmentAndOffset(
14773           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14774     }
14775     }
14776     break;
14777   }
14778   case Stmt::CXXThisExprClass: {
14779     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14780     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14781     return std::make_pair(Alignment, CharUnits::Zero());
14782   }
14783   case Stmt::UnaryOperatorClass: {
14784     auto *UO = cast<UnaryOperator>(E);
14785     if (UO->getOpcode() == UO_AddrOf)
14786       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14787     break;
14788   }
14789   case Stmt::BinaryOperatorClass: {
14790     auto *BO = cast<BinaryOperator>(E);
14791     auto Opcode = BO->getOpcode();
14792     switch (Opcode) {
14793     default:
14794       break;
14795     case BO_Add:
14796     case BO_Sub: {
14797       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14798       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14799         std::swap(LHS, RHS);
14800       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14801                                                   Ctx);
14802     }
14803     case BO_Comma:
14804       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14805     }
14806     break;
14807   }
14808   }
14809   return llvm::None;
14810 }
14811 
14812 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14813   // See if we can compute the alignment of a VarDecl and an offset from it.
14814   Optional<std::pair<CharUnits, CharUnits>> P =
14815       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14816 
14817   if (P)
14818     return P->first.alignmentAtOffset(P->second);
14819 
14820   // If that failed, return the type's alignment.
14821   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14822 }
14823 
14824 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14825 /// pointer cast increases the alignment requirements.
14826 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14827   // This is actually a lot of work to potentially be doing on every
14828   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14829   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14830     return;
14831 
14832   // Ignore dependent types.
14833   if (T->isDependentType() || Op->getType()->isDependentType())
14834     return;
14835 
14836   // Require that the destination be a pointer type.
14837   const PointerType *DestPtr = T->getAs<PointerType>();
14838   if (!DestPtr) return;
14839 
14840   // If the destination has alignment 1, we're done.
14841   QualType DestPointee = DestPtr->getPointeeType();
14842   if (DestPointee->isIncompleteType()) return;
14843   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14844   if (DestAlign.isOne()) return;
14845 
14846   // Require that the source be a pointer type.
14847   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14848   if (!SrcPtr) return;
14849   QualType SrcPointee = SrcPtr->getPointeeType();
14850 
14851   // Explicitly allow casts from cv void*.  We already implicitly
14852   // allowed casts to cv void*, since they have alignment 1.
14853   // Also allow casts involving incomplete types, which implicitly
14854   // includes 'void'.
14855   if (SrcPointee->isIncompleteType()) return;
14856 
14857   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14858 
14859   if (SrcAlign >= DestAlign) return;
14860 
14861   Diag(TRange.getBegin(), diag::warn_cast_align)
14862     << Op->getType() << T
14863     << static_cast<unsigned>(SrcAlign.getQuantity())
14864     << static_cast<unsigned>(DestAlign.getQuantity())
14865     << TRange << Op->getSourceRange();
14866 }
14867 
14868 /// Check whether this array fits the idiom of a size-one tail padded
14869 /// array member of a struct.
14870 ///
14871 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14872 /// commonly used to emulate flexible arrays in C89 code.
14873 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14874                                     const NamedDecl *ND) {
14875   if (Size != 1 || !ND) return false;
14876 
14877   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14878   if (!FD) return false;
14879 
14880   // Don't consider sizes resulting from macro expansions or template argument
14881   // substitution to form C89 tail-padded arrays.
14882 
14883   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14884   while (TInfo) {
14885     TypeLoc TL = TInfo->getTypeLoc();
14886     // Look through typedefs.
14887     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14888       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14889       TInfo = TDL->getTypeSourceInfo();
14890       continue;
14891     }
14892     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14893       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14894       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14895         return false;
14896     }
14897     break;
14898   }
14899 
14900   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14901   if (!RD) return false;
14902   if (RD->isUnion()) return false;
14903   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14904     if (!CRD->isStandardLayout()) return false;
14905   }
14906 
14907   // See if this is the last field decl in the record.
14908   const Decl *D = FD;
14909   while ((D = D->getNextDeclInContext()))
14910     if (isa<FieldDecl>(D))
14911       return false;
14912   return true;
14913 }
14914 
14915 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14916                             const ArraySubscriptExpr *ASE,
14917                             bool AllowOnePastEnd, bool IndexNegated) {
14918   // Already diagnosed by the constant evaluator.
14919   if (isConstantEvaluated())
14920     return;
14921 
14922   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14923   if (IndexExpr->isValueDependent())
14924     return;
14925 
14926   const Type *EffectiveType =
14927       BaseExpr->getType()->getPointeeOrArrayElementType();
14928   BaseExpr = BaseExpr->IgnoreParenCasts();
14929   const ConstantArrayType *ArrayTy =
14930       Context.getAsConstantArrayType(BaseExpr->getType());
14931 
14932   const Type *BaseType =
14933       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14934   bool IsUnboundedArray = (BaseType == nullptr);
14935   if (EffectiveType->isDependentType() ||
14936       (!IsUnboundedArray && BaseType->isDependentType()))
14937     return;
14938 
14939   Expr::EvalResult Result;
14940   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14941     return;
14942 
14943   llvm::APSInt index = Result.Val.getInt();
14944   if (IndexNegated) {
14945     index.setIsUnsigned(false);
14946     index = -index;
14947   }
14948 
14949   const NamedDecl *ND = nullptr;
14950   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14951     ND = DRE->getDecl();
14952   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14953     ND = ME->getMemberDecl();
14954 
14955   if (IsUnboundedArray) {
14956     if (index.isUnsigned() || !index.isNegative()) {
14957       const auto &ASTC = getASTContext();
14958       unsigned AddrBits =
14959           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14960               EffectiveType->getCanonicalTypeInternal()));
14961       if (index.getBitWidth() < AddrBits)
14962         index = index.zext(AddrBits);
14963       Optional<CharUnits> ElemCharUnits =
14964           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14965       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14966       // pointer) bounds-checking isn't meaningful.
14967       if (!ElemCharUnits)
14968         return;
14969       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14970       // If index has more active bits than address space, we already know
14971       // we have a bounds violation to warn about.  Otherwise, compute
14972       // address of (index + 1)th element, and warn about bounds violation
14973       // only if that address exceeds address space.
14974       if (index.getActiveBits() <= AddrBits) {
14975         bool Overflow;
14976         llvm::APInt Product(index);
14977         Product += 1;
14978         Product = Product.umul_ov(ElemBytes, Overflow);
14979         if (!Overflow && Product.getActiveBits() <= AddrBits)
14980           return;
14981       }
14982 
14983       // Need to compute max possible elements in address space, since that
14984       // is included in diag message.
14985       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14986       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14987       MaxElems += 1;
14988       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14989       MaxElems = MaxElems.udiv(ElemBytes);
14990 
14991       unsigned DiagID =
14992           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14993               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14994 
14995       // Diag message shows element size in bits and in "bytes" (platform-
14996       // dependent CharUnits)
14997       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14998                           PDiag(DiagID)
14999                               << toString(index, 10, true) << AddrBits
15000                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15001                               << toString(ElemBytes, 10, false)
15002                               << toString(MaxElems, 10, false)
15003                               << (unsigned)MaxElems.getLimitedValue(~0U)
15004                               << IndexExpr->getSourceRange());
15005 
15006       if (!ND) {
15007         // Try harder to find a NamedDecl to point at in the note.
15008         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15009           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15010         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15011           ND = DRE->getDecl();
15012         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15013           ND = ME->getMemberDecl();
15014       }
15015 
15016       if (ND)
15017         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15018                             PDiag(diag::note_array_declared_here) << ND);
15019     }
15020     return;
15021   }
15022 
15023   if (index.isUnsigned() || !index.isNegative()) {
15024     // It is possible that the type of the base expression after
15025     // IgnoreParenCasts is incomplete, even though the type of the base
15026     // expression before IgnoreParenCasts is complete (see PR39746 for an
15027     // example). In this case we have no information about whether the array
15028     // access exceeds the array bounds. However we can still diagnose an array
15029     // access which precedes the array bounds.
15030     if (BaseType->isIncompleteType())
15031       return;
15032 
15033     llvm::APInt size = ArrayTy->getSize();
15034     if (!size.isStrictlyPositive())
15035       return;
15036 
15037     if (BaseType != EffectiveType) {
15038       // Make sure we're comparing apples to apples when comparing index to size
15039       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15040       uint64_t array_typesize = Context.getTypeSize(BaseType);
15041       // Handle ptrarith_typesize being zero, such as when casting to void*
15042       if (!ptrarith_typesize) ptrarith_typesize = 1;
15043       if (ptrarith_typesize != array_typesize) {
15044         // There's a cast to a different size type involved
15045         uint64_t ratio = array_typesize / ptrarith_typesize;
15046         // TODO: Be smarter about handling cases where array_typesize is not a
15047         // multiple of ptrarith_typesize
15048         if (ptrarith_typesize * ratio == array_typesize)
15049           size *= llvm::APInt(size.getBitWidth(), ratio);
15050       }
15051     }
15052 
15053     if (size.getBitWidth() > index.getBitWidth())
15054       index = index.zext(size.getBitWidth());
15055     else if (size.getBitWidth() < index.getBitWidth())
15056       size = size.zext(index.getBitWidth());
15057 
15058     // For array subscripting the index must be less than size, but for pointer
15059     // arithmetic also allow the index (offset) to be equal to size since
15060     // computing the next address after the end of the array is legal and
15061     // commonly done e.g. in C++ iterators and range-based for loops.
15062     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15063       return;
15064 
15065     // Also don't warn for arrays of size 1 which are members of some
15066     // structure. These are often used to approximate flexible arrays in C89
15067     // code.
15068     if (IsTailPaddedMemberArray(*this, size, ND))
15069       return;
15070 
15071     // Suppress the warning if the subscript expression (as identified by the
15072     // ']' location) and the index expression are both from macro expansions
15073     // within a system header.
15074     if (ASE) {
15075       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15076           ASE->getRBracketLoc());
15077       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15078         SourceLocation IndexLoc =
15079             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15080         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15081           return;
15082       }
15083     }
15084 
15085     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15086                           : diag::warn_ptr_arith_exceeds_bounds;
15087 
15088     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15089                         PDiag(DiagID) << toString(index, 10, true)
15090                                       << toString(size, 10, true)
15091                                       << (unsigned)size.getLimitedValue(~0U)
15092                                       << IndexExpr->getSourceRange());
15093   } else {
15094     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15095     if (!ASE) {
15096       DiagID = diag::warn_ptr_arith_precedes_bounds;
15097       if (index.isNegative()) index = -index;
15098     }
15099 
15100     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15101                         PDiag(DiagID) << toString(index, 10, true)
15102                                       << IndexExpr->getSourceRange());
15103   }
15104 
15105   if (!ND) {
15106     // Try harder to find a NamedDecl to point at in the note.
15107     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15108       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15109     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15110       ND = DRE->getDecl();
15111     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15112       ND = ME->getMemberDecl();
15113   }
15114 
15115   if (ND)
15116     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15117                         PDiag(diag::note_array_declared_here) << ND);
15118 }
15119 
15120 void Sema::CheckArrayAccess(const Expr *expr) {
15121   int AllowOnePastEnd = 0;
15122   while (expr) {
15123     expr = expr->IgnoreParenImpCasts();
15124     switch (expr->getStmtClass()) {
15125       case Stmt::ArraySubscriptExprClass: {
15126         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15127         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15128                          AllowOnePastEnd > 0);
15129         expr = ASE->getBase();
15130         break;
15131       }
15132       case Stmt::MemberExprClass: {
15133         expr = cast<MemberExpr>(expr)->getBase();
15134         break;
15135       }
15136       case Stmt::OMPArraySectionExprClass: {
15137         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15138         if (ASE->getLowerBound())
15139           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15140                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15141         return;
15142       }
15143       case Stmt::UnaryOperatorClass: {
15144         // Only unwrap the * and & unary operators
15145         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15146         expr = UO->getSubExpr();
15147         switch (UO->getOpcode()) {
15148           case UO_AddrOf:
15149             AllowOnePastEnd++;
15150             break;
15151           case UO_Deref:
15152             AllowOnePastEnd--;
15153             break;
15154           default:
15155             return;
15156         }
15157         break;
15158       }
15159       case Stmt::ConditionalOperatorClass: {
15160         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15161         if (const Expr *lhs = cond->getLHS())
15162           CheckArrayAccess(lhs);
15163         if (const Expr *rhs = cond->getRHS())
15164           CheckArrayAccess(rhs);
15165         return;
15166       }
15167       case Stmt::CXXOperatorCallExprClass: {
15168         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15169         for (const auto *Arg : OCE->arguments())
15170           CheckArrayAccess(Arg);
15171         return;
15172       }
15173       default:
15174         return;
15175     }
15176   }
15177 }
15178 
15179 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15180 
15181 namespace {
15182 
15183 struct RetainCycleOwner {
15184   VarDecl *Variable = nullptr;
15185   SourceRange Range;
15186   SourceLocation Loc;
15187   bool Indirect = false;
15188 
15189   RetainCycleOwner() = default;
15190 
15191   void setLocsFrom(Expr *e) {
15192     Loc = e->getExprLoc();
15193     Range = e->getSourceRange();
15194   }
15195 };
15196 
15197 } // namespace
15198 
15199 /// Consider whether capturing the given variable can possibly lead to
15200 /// a retain cycle.
15201 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15202   // In ARC, it's captured strongly iff the variable has __strong
15203   // lifetime.  In MRR, it's captured strongly if the variable is
15204   // __block and has an appropriate type.
15205   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15206     return false;
15207 
15208   owner.Variable = var;
15209   if (ref)
15210     owner.setLocsFrom(ref);
15211   return true;
15212 }
15213 
15214 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15215   while (true) {
15216     e = e->IgnoreParens();
15217     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15218       switch (cast->getCastKind()) {
15219       case CK_BitCast:
15220       case CK_LValueBitCast:
15221       case CK_LValueToRValue:
15222       case CK_ARCReclaimReturnedObject:
15223         e = cast->getSubExpr();
15224         continue;
15225 
15226       default:
15227         return false;
15228       }
15229     }
15230 
15231     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15232       ObjCIvarDecl *ivar = ref->getDecl();
15233       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15234         return false;
15235 
15236       // Try to find a retain cycle in the base.
15237       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15238         return false;
15239 
15240       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15241       owner.Indirect = true;
15242       return true;
15243     }
15244 
15245     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15246       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15247       if (!var) return false;
15248       return considerVariable(var, ref, owner);
15249     }
15250 
15251     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15252       if (member->isArrow()) return false;
15253 
15254       // Don't count this as an indirect ownership.
15255       e = member->getBase();
15256       continue;
15257     }
15258 
15259     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15260       // Only pay attention to pseudo-objects on property references.
15261       ObjCPropertyRefExpr *pre
15262         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15263                                               ->IgnoreParens());
15264       if (!pre) return false;
15265       if (pre->isImplicitProperty()) return false;
15266       ObjCPropertyDecl *property = pre->getExplicitProperty();
15267       if (!property->isRetaining() &&
15268           !(property->getPropertyIvarDecl() &&
15269             property->getPropertyIvarDecl()->getType()
15270               .getObjCLifetime() == Qualifiers::OCL_Strong))
15271           return false;
15272 
15273       owner.Indirect = true;
15274       if (pre->isSuperReceiver()) {
15275         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15276         if (!owner.Variable)
15277           return false;
15278         owner.Loc = pre->getLocation();
15279         owner.Range = pre->getSourceRange();
15280         return true;
15281       }
15282       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15283                               ->getSourceExpr());
15284       continue;
15285     }
15286 
15287     // Array ivars?
15288 
15289     return false;
15290   }
15291 }
15292 
15293 namespace {
15294 
15295   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15296     ASTContext &Context;
15297     VarDecl *Variable;
15298     Expr *Capturer = nullptr;
15299     bool VarWillBeReased = false;
15300 
15301     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15302         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15303           Context(Context), Variable(variable) {}
15304 
15305     void VisitDeclRefExpr(DeclRefExpr *ref) {
15306       if (ref->getDecl() == Variable && !Capturer)
15307         Capturer = ref;
15308     }
15309 
15310     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15311       if (Capturer) return;
15312       Visit(ref->getBase());
15313       if (Capturer && ref->isFreeIvar())
15314         Capturer = ref;
15315     }
15316 
15317     void VisitBlockExpr(BlockExpr *block) {
15318       // Look inside nested blocks
15319       if (block->getBlockDecl()->capturesVariable(Variable))
15320         Visit(block->getBlockDecl()->getBody());
15321     }
15322 
15323     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15324       if (Capturer) return;
15325       if (OVE->getSourceExpr())
15326         Visit(OVE->getSourceExpr());
15327     }
15328 
15329     void VisitBinaryOperator(BinaryOperator *BinOp) {
15330       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15331         return;
15332       Expr *LHS = BinOp->getLHS();
15333       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15334         if (DRE->getDecl() != Variable)
15335           return;
15336         if (Expr *RHS = BinOp->getRHS()) {
15337           RHS = RHS->IgnoreParenCasts();
15338           Optional<llvm::APSInt> Value;
15339           VarWillBeReased =
15340               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15341                *Value == 0);
15342         }
15343       }
15344     }
15345   };
15346 
15347 } // namespace
15348 
15349 /// Check whether the given argument is a block which captures a
15350 /// variable.
15351 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15352   assert(owner.Variable && owner.Loc.isValid());
15353 
15354   e = e->IgnoreParenCasts();
15355 
15356   // Look through [^{...} copy] and Block_copy(^{...}).
15357   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15358     Selector Cmd = ME->getSelector();
15359     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15360       e = ME->getInstanceReceiver();
15361       if (!e)
15362         return nullptr;
15363       e = e->IgnoreParenCasts();
15364     }
15365   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15366     if (CE->getNumArgs() == 1) {
15367       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15368       if (Fn) {
15369         const IdentifierInfo *FnI = Fn->getIdentifier();
15370         if (FnI && FnI->isStr("_Block_copy")) {
15371           e = CE->getArg(0)->IgnoreParenCasts();
15372         }
15373       }
15374     }
15375   }
15376 
15377   BlockExpr *block = dyn_cast<BlockExpr>(e);
15378   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15379     return nullptr;
15380 
15381   FindCaptureVisitor visitor(S.Context, owner.Variable);
15382   visitor.Visit(block->getBlockDecl()->getBody());
15383   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15384 }
15385 
15386 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15387                                 RetainCycleOwner &owner) {
15388   assert(capturer);
15389   assert(owner.Variable && owner.Loc.isValid());
15390 
15391   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15392     << owner.Variable << capturer->getSourceRange();
15393   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15394     << owner.Indirect << owner.Range;
15395 }
15396 
15397 /// Check for a keyword selector that starts with the word 'add' or
15398 /// 'set'.
15399 static bool isSetterLikeSelector(Selector sel) {
15400   if (sel.isUnarySelector()) return false;
15401 
15402   StringRef str = sel.getNameForSlot(0);
15403   while (!str.empty() && str.front() == '_') str = str.substr(1);
15404   if (str.startswith("set"))
15405     str = str.substr(3);
15406   else if (str.startswith("add")) {
15407     // Specially allow 'addOperationWithBlock:'.
15408     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15409       return false;
15410     str = str.substr(3);
15411   }
15412   else
15413     return false;
15414 
15415   if (str.empty()) return true;
15416   return !isLowercase(str.front());
15417 }
15418 
15419 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15420                                                     ObjCMessageExpr *Message) {
15421   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15422                                                 Message->getReceiverInterface(),
15423                                                 NSAPI::ClassId_NSMutableArray);
15424   if (!IsMutableArray) {
15425     return None;
15426   }
15427 
15428   Selector Sel = Message->getSelector();
15429 
15430   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15431     S.NSAPIObj->getNSArrayMethodKind(Sel);
15432   if (!MKOpt) {
15433     return None;
15434   }
15435 
15436   NSAPI::NSArrayMethodKind MK = *MKOpt;
15437 
15438   switch (MK) {
15439     case NSAPI::NSMutableArr_addObject:
15440     case NSAPI::NSMutableArr_insertObjectAtIndex:
15441     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15442       return 0;
15443     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15444       return 1;
15445 
15446     default:
15447       return None;
15448   }
15449 
15450   return None;
15451 }
15452 
15453 static
15454 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15455                                                   ObjCMessageExpr *Message) {
15456   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15457                                             Message->getReceiverInterface(),
15458                                             NSAPI::ClassId_NSMutableDictionary);
15459   if (!IsMutableDictionary) {
15460     return None;
15461   }
15462 
15463   Selector Sel = Message->getSelector();
15464 
15465   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15466     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15467   if (!MKOpt) {
15468     return None;
15469   }
15470 
15471   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15472 
15473   switch (MK) {
15474     case NSAPI::NSMutableDict_setObjectForKey:
15475     case NSAPI::NSMutableDict_setValueForKey:
15476     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15477       return 0;
15478 
15479     default:
15480       return None;
15481   }
15482 
15483   return None;
15484 }
15485 
15486 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15487   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15488                                                 Message->getReceiverInterface(),
15489                                                 NSAPI::ClassId_NSMutableSet);
15490 
15491   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15492                                             Message->getReceiverInterface(),
15493                                             NSAPI::ClassId_NSMutableOrderedSet);
15494   if (!IsMutableSet && !IsMutableOrderedSet) {
15495     return None;
15496   }
15497 
15498   Selector Sel = Message->getSelector();
15499 
15500   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15501   if (!MKOpt) {
15502     return None;
15503   }
15504 
15505   NSAPI::NSSetMethodKind MK = *MKOpt;
15506 
15507   switch (MK) {
15508     case NSAPI::NSMutableSet_addObject:
15509     case NSAPI::NSOrderedSet_setObjectAtIndex:
15510     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15511     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15512       return 0;
15513     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15514       return 1;
15515   }
15516 
15517   return None;
15518 }
15519 
15520 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15521   if (!Message->isInstanceMessage()) {
15522     return;
15523   }
15524 
15525   Optional<int> ArgOpt;
15526 
15527   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15528       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15529       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15530     return;
15531   }
15532 
15533   int ArgIndex = *ArgOpt;
15534 
15535   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15536   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15537     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15538   }
15539 
15540   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15541     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15542       if (ArgRE->isObjCSelfExpr()) {
15543         Diag(Message->getSourceRange().getBegin(),
15544              diag::warn_objc_circular_container)
15545           << ArgRE->getDecl() << StringRef("'super'");
15546       }
15547     }
15548   } else {
15549     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15550 
15551     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15552       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15553     }
15554 
15555     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15556       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15557         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15558           ValueDecl *Decl = ReceiverRE->getDecl();
15559           Diag(Message->getSourceRange().getBegin(),
15560                diag::warn_objc_circular_container)
15561             << Decl << Decl;
15562           if (!ArgRE->isObjCSelfExpr()) {
15563             Diag(Decl->getLocation(),
15564                  diag::note_objc_circular_container_declared_here)
15565               << Decl;
15566           }
15567         }
15568       }
15569     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15570       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15571         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15572           ObjCIvarDecl *Decl = IvarRE->getDecl();
15573           Diag(Message->getSourceRange().getBegin(),
15574                diag::warn_objc_circular_container)
15575             << Decl << Decl;
15576           Diag(Decl->getLocation(),
15577                diag::note_objc_circular_container_declared_here)
15578             << Decl;
15579         }
15580       }
15581     }
15582   }
15583 }
15584 
15585 /// Check a message send to see if it's likely to cause a retain cycle.
15586 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15587   // Only check instance methods whose selector looks like a setter.
15588   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15589     return;
15590 
15591   // Try to find a variable that the receiver is strongly owned by.
15592   RetainCycleOwner owner;
15593   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15594     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15595       return;
15596   } else {
15597     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15598     owner.Variable = getCurMethodDecl()->getSelfDecl();
15599     owner.Loc = msg->getSuperLoc();
15600     owner.Range = msg->getSuperLoc();
15601   }
15602 
15603   // Check whether the receiver is captured by any of the arguments.
15604   const ObjCMethodDecl *MD = msg->getMethodDecl();
15605   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15606     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15607       // noescape blocks should not be retained by the method.
15608       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15609         continue;
15610       return diagnoseRetainCycle(*this, capturer, owner);
15611     }
15612   }
15613 }
15614 
15615 /// Check a property assign to see if it's likely to cause a retain cycle.
15616 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15617   RetainCycleOwner owner;
15618   if (!findRetainCycleOwner(*this, receiver, owner))
15619     return;
15620 
15621   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15622     diagnoseRetainCycle(*this, capturer, owner);
15623 }
15624 
15625 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15626   RetainCycleOwner Owner;
15627   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15628     return;
15629 
15630   // Because we don't have an expression for the variable, we have to set the
15631   // location explicitly here.
15632   Owner.Loc = Var->getLocation();
15633   Owner.Range = Var->getSourceRange();
15634 
15635   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15636     diagnoseRetainCycle(*this, Capturer, Owner);
15637 }
15638 
15639 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15640                                      Expr *RHS, bool isProperty) {
15641   // Check if RHS is an Objective-C object literal, which also can get
15642   // immediately zapped in a weak reference.  Note that we explicitly
15643   // allow ObjCStringLiterals, since those are designed to never really die.
15644   RHS = RHS->IgnoreParenImpCasts();
15645 
15646   // This enum needs to match with the 'select' in
15647   // warn_objc_arc_literal_assign (off-by-1).
15648   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15649   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15650     return false;
15651 
15652   S.Diag(Loc, diag::warn_arc_literal_assign)
15653     << (unsigned) Kind
15654     << (isProperty ? 0 : 1)
15655     << RHS->getSourceRange();
15656 
15657   return true;
15658 }
15659 
15660 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15661                                     Qualifiers::ObjCLifetime LT,
15662                                     Expr *RHS, bool isProperty) {
15663   // Strip off any implicit cast added to get to the one ARC-specific.
15664   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15665     if (cast->getCastKind() == CK_ARCConsumeObject) {
15666       S.Diag(Loc, diag::warn_arc_retained_assign)
15667         << (LT == Qualifiers::OCL_ExplicitNone)
15668         << (isProperty ? 0 : 1)
15669         << RHS->getSourceRange();
15670       return true;
15671     }
15672     RHS = cast->getSubExpr();
15673   }
15674 
15675   if (LT == Qualifiers::OCL_Weak &&
15676       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15677     return true;
15678 
15679   return false;
15680 }
15681 
15682 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15683                               QualType LHS, Expr *RHS) {
15684   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15685 
15686   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15687     return false;
15688 
15689   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15690     return true;
15691 
15692   return false;
15693 }
15694 
15695 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15696                               Expr *LHS, Expr *RHS) {
15697   QualType LHSType;
15698   // PropertyRef on LHS type need be directly obtained from
15699   // its declaration as it has a PseudoType.
15700   ObjCPropertyRefExpr *PRE
15701     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15702   if (PRE && !PRE->isImplicitProperty()) {
15703     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15704     if (PD)
15705       LHSType = PD->getType();
15706   }
15707 
15708   if (LHSType.isNull())
15709     LHSType = LHS->getType();
15710 
15711   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15712 
15713   if (LT == Qualifiers::OCL_Weak) {
15714     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15715       getCurFunction()->markSafeWeakUse(LHS);
15716   }
15717 
15718   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15719     return;
15720 
15721   // FIXME. Check for other life times.
15722   if (LT != Qualifiers::OCL_None)
15723     return;
15724 
15725   if (PRE) {
15726     if (PRE->isImplicitProperty())
15727       return;
15728     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15729     if (!PD)
15730       return;
15731 
15732     unsigned Attributes = PD->getPropertyAttributes();
15733     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15734       // when 'assign' attribute was not explicitly specified
15735       // by user, ignore it and rely on property type itself
15736       // for lifetime info.
15737       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15738       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15739           LHSType->isObjCRetainableType())
15740         return;
15741 
15742       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15743         if (cast->getCastKind() == CK_ARCConsumeObject) {
15744           Diag(Loc, diag::warn_arc_retained_property_assign)
15745           << RHS->getSourceRange();
15746           return;
15747         }
15748         RHS = cast->getSubExpr();
15749       }
15750     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15751       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15752         return;
15753     }
15754   }
15755 }
15756 
15757 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15758 
15759 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15760                                         SourceLocation StmtLoc,
15761                                         const NullStmt *Body) {
15762   // Do not warn if the body is a macro that expands to nothing, e.g:
15763   //
15764   // #define CALL(x)
15765   // if (condition)
15766   //   CALL(0);
15767   if (Body->hasLeadingEmptyMacro())
15768     return false;
15769 
15770   // Get line numbers of statement and body.
15771   bool StmtLineInvalid;
15772   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15773                                                       &StmtLineInvalid);
15774   if (StmtLineInvalid)
15775     return false;
15776 
15777   bool BodyLineInvalid;
15778   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15779                                                       &BodyLineInvalid);
15780   if (BodyLineInvalid)
15781     return false;
15782 
15783   // Warn if null statement and body are on the same line.
15784   if (StmtLine != BodyLine)
15785     return false;
15786 
15787   return true;
15788 }
15789 
15790 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15791                                  const Stmt *Body,
15792                                  unsigned DiagID) {
15793   // Since this is a syntactic check, don't emit diagnostic for template
15794   // instantiations, this just adds noise.
15795   if (CurrentInstantiationScope)
15796     return;
15797 
15798   // The body should be a null statement.
15799   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15800   if (!NBody)
15801     return;
15802 
15803   // Do the usual checks.
15804   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15805     return;
15806 
15807   Diag(NBody->getSemiLoc(), DiagID);
15808   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15809 }
15810 
15811 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15812                                  const Stmt *PossibleBody) {
15813   assert(!CurrentInstantiationScope); // Ensured by caller
15814 
15815   SourceLocation StmtLoc;
15816   const Stmt *Body;
15817   unsigned DiagID;
15818   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15819     StmtLoc = FS->getRParenLoc();
15820     Body = FS->getBody();
15821     DiagID = diag::warn_empty_for_body;
15822   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15823     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15824     Body = WS->getBody();
15825     DiagID = diag::warn_empty_while_body;
15826   } else
15827     return; // Neither `for' nor `while'.
15828 
15829   // The body should be a null statement.
15830   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15831   if (!NBody)
15832     return;
15833 
15834   // Skip expensive checks if diagnostic is disabled.
15835   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15836     return;
15837 
15838   // Do the usual checks.
15839   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15840     return;
15841 
15842   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15843   // noise level low, emit diagnostics only if for/while is followed by a
15844   // CompoundStmt, e.g.:
15845   //    for (int i = 0; i < n; i++);
15846   //    {
15847   //      a(i);
15848   //    }
15849   // or if for/while is followed by a statement with more indentation
15850   // than for/while itself:
15851   //    for (int i = 0; i < n; i++);
15852   //      a(i);
15853   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15854   if (!ProbableTypo) {
15855     bool BodyColInvalid;
15856     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15857         PossibleBody->getBeginLoc(), &BodyColInvalid);
15858     if (BodyColInvalid)
15859       return;
15860 
15861     bool StmtColInvalid;
15862     unsigned StmtCol =
15863         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15864     if (StmtColInvalid)
15865       return;
15866 
15867     if (BodyCol > StmtCol)
15868       ProbableTypo = true;
15869   }
15870 
15871   if (ProbableTypo) {
15872     Diag(NBody->getSemiLoc(), DiagID);
15873     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15874   }
15875 }
15876 
15877 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15878 
15879 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15880 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15881                              SourceLocation OpLoc) {
15882   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15883     return;
15884 
15885   if (inTemplateInstantiation())
15886     return;
15887 
15888   // Strip parens and casts away.
15889   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15890   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15891 
15892   // Check for a call expression
15893   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15894   if (!CE || CE->getNumArgs() != 1)
15895     return;
15896 
15897   // Check for a call to std::move
15898   if (!CE->isCallToStdMove())
15899     return;
15900 
15901   // Get argument from std::move
15902   RHSExpr = CE->getArg(0);
15903 
15904   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15905   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15906 
15907   // Two DeclRefExpr's, check that the decls are the same.
15908   if (LHSDeclRef && RHSDeclRef) {
15909     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15910       return;
15911     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15912         RHSDeclRef->getDecl()->getCanonicalDecl())
15913       return;
15914 
15915     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15916                                         << LHSExpr->getSourceRange()
15917                                         << RHSExpr->getSourceRange();
15918     return;
15919   }
15920 
15921   // Member variables require a different approach to check for self moves.
15922   // MemberExpr's are the same if every nested MemberExpr refers to the same
15923   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15924   // the base Expr's are CXXThisExpr's.
15925   const Expr *LHSBase = LHSExpr;
15926   const Expr *RHSBase = RHSExpr;
15927   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15928   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15929   if (!LHSME || !RHSME)
15930     return;
15931 
15932   while (LHSME && RHSME) {
15933     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15934         RHSME->getMemberDecl()->getCanonicalDecl())
15935       return;
15936 
15937     LHSBase = LHSME->getBase();
15938     RHSBase = RHSME->getBase();
15939     LHSME = dyn_cast<MemberExpr>(LHSBase);
15940     RHSME = dyn_cast<MemberExpr>(RHSBase);
15941   }
15942 
15943   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15944   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15945   if (LHSDeclRef && RHSDeclRef) {
15946     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15947       return;
15948     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15949         RHSDeclRef->getDecl()->getCanonicalDecl())
15950       return;
15951 
15952     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15953                                         << LHSExpr->getSourceRange()
15954                                         << RHSExpr->getSourceRange();
15955     return;
15956   }
15957 
15958   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15959     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15960                                         << LHSExpr->getSourceRange()
15961                                         << RHSExpr->getSourceRange();
15962 }
15963 
15964 //===--- Layout compatibility ----------------------------------------------//
15965 
15966 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15967 
15968 /// Check if two enumeration types are layout-compatible.
15969 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15970   // C++11 [dcl.enum] p8:
15971   // Two enumeration types are layout-compatible if they have the same
15972   // underlying type.
15973   return ED1->isComplete() && ED2->isComplete() &&
15974          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15975 }
15976 
15977 /// Check if two fields are layout-compatible.
15978 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15979                                FieldDecl *Field2) {
15980   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15981     return false;
15982 
15983   if (Field1->isBitField() != Field2->isBitField())
15984     return false;
15985 
15986   if (Field1->isBitField()) {
15987     // Make sure that the bit-fields are the same length.
15988     unsigned Bits1 = Field1->getBitWidthValue(C);
15989     unsigned Bits2 = Field2->getBitWidthValue(C);
15990 
15991     if (Bits1 != Bits2)
15992       return false;
15993   }
15994 
15995   return true;
15996 }
15997 
15998 /// Check if two standard-layout structs are layout-compatible.
15999 /// (C++11 [class.mem] p17)
16000 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16001                                      RecordDecl *RD2) {
16002   // If both records are C++ classes, check that base classes match.
16003   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16004     // If one of records is a CXXRecordDecl we are in C++ mode,
16005     // thus the other one is a CXXRecordDecl, too.
16006     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16007     // Check number of base classes.
16008     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16009       return false;
16010 
16011     // Check the base classes.
16012     for (CXXRecordDecl::base_class_const_iterator
16013                Base1 = D1CXX->bases_begin(),
16014            BaseEnd1 = D1CXX->bases_end(),
16015               Base2 = D2CXX->bases_begin();
16016          Base1 != BaseEnd1;
16017          ++Base1, ++Base2) {
16018       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16019         return false;
16020     }
16021   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16022     // If only RD2 is a C++ class, it should have zero base classes.
16023     if (D2CXX->getNumBases() > 0)
16024       return false;
16025   }
16026 
16027   // Check the fields.
16028   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16029                              Field2End = RD2->field_end(),
16030                              Field1 = RD1->field_begin(),
16031                              Field1End = RD1->field_end();
16032   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16033     if (!isLayoutCompatible(C, *Field1, *Field2))
16034       return false;
16035   }
16036   if (Field1 != Field1End || Field2 != Field2End)
16037     return false;
16038 
16039   return true;
16040 }
16041 
16042 /// Check if two standard-layout unions are layout-compatible.
16043 /// (C++11 [class.mem] p18)
16044 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16045                                     RecordDecl *RD2) {
16046   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16047   for (auto *Field2 : RD2->fields())
16048     UnmatchedFields.insert(Field2);
16049 
16050   for (auto *Field1 : RD1->fields()) {
16051     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16052         I = UnmatchedFields.begin(),
16053         E = UnmatchedFields.end();
16054 
16055     for ( ; I != E; ++I) {
16056       if (isLayoutCompatible(C, Field1, *I)) {
16057         bool Result = UnmatchedFields.erase(*I);
16058         (void) Result;
16059         assert(Result);
16060         break;
16061       }
16062     }
16063     if (I == E)
16064       return false;
16065   }
16066 
16067   return UnmatchedFields.empty();
16068 }
16069 
16070 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16071                                RecordDecl *RD2) {
16072   if (RD1->isUnion() != RD2->isUnion())
16073     return false;
16074 
16075   if (RD1->isUnion())
16076     return isLayoutCompatibleUnion(C, RD1, RD2);
16077   else
16078     return isLayoutCompatibleStruct(C, RD1, RD2);
16079 }
16080 
16081 /// Check if two types are layout-compatible in C++11 sense.
16082 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16083   if (T1.isNull() || T2.isNull())
16084     return false;
16085 
16086   // C++11 [basic.types] p11:
16087   // If two types T1 and T2 are the same type, then T1 and T2 are
16088   // layout-compatible types.
16089   if (C.hasSameType(T1, T2))
16090     return true;
16091 
16092   T1 = T1.getCanonicalType().getUnqualifiedType();
16093   T2 = T2.getCanonicalType().getUnqualifiedType();
16094 
16095   const Type::TypeClass TC1 = T1->getTypeClass();
16096   const Type::TypeClass TC2 = T2->getTypeClass();
16097 
16098   if (TC1 != TC2)
16099     return false;
16100 
16101   if (TC1 == Type::Enum) {
16102     return isLayoutCompatible(C,
16103                               cast<EnumType>(T1)->getDecl(),
16104                               cast<EnumType>(T2)->getDecl());
16105   } else if (TC1 == Type::Record) {
16106     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16107       return false;
16108 
16109     return isLayoutCompatible(C,
16110                               cast<RecordType>(T1)->getDecl(),
16111                               cast<RecordType>(T2)->getDecl());
16112   }
16113 
16114   return false;
16115 }
16116 
16117 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16118 
16119 /// Given a type tag expression find the type tag itself.
16120 ///
16121 /// \param TypeExpr Type tag expression, as it appears in user's code.
16122 ///
16123 /// \param VD Declaration of an identifier that appears in a type tag.
16124 ///
16125 /// \param MagicValue Type tag magic value.
16126 ///
16127 /// \param isConstantEvaluated whether the evalaution should be performed in
16128 
16129 /// constant context.
16130 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16131                             const ValueDecl **VD, uint64_t *MagicValue,
16132                             bool isConstantEvaluated) {
16133   while(true) {
16134     if (!TypeExpr)
16135       return false;
16136 
16137     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16138 
16139     switch (TypeExpr->getStmtClass()) {
16140     case Stmt::UnaryOperatorClass: {
16141       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16142       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16143         TypeExpr = UO->getSubExpr();
16144         continue;
16145       }
16146       return false;
16147     }
16148 
16149     case Stmt::DeclRefExprClass: {
16150       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16151       *VD = DRE->getDecl();
16152       return true;
16153     }
16154 
16155     case Stmt::IntegerLiteralClass: {
16156       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16157       llvm::APInt MagicValueAPInt = IL->getValue();
16158       if (MagicValueAPInt.getActiveBits() <= 64) {
16159         *MagicValue = MagicValueAPInt.getZExtValue();
16160         return true;
16161       } else
16162         return false;
16163     }
16164 
16165     case Stmt::BinaryConditionalOperatorClass:
16166     case Stmt::ConditionalOperatorClass: {
16167       const AbstractConditionalOperator *ACO =
16168           cast<AbstractConditionalOperator>(TypeExpr);
16169       bool Result;
16170       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16171                                                      isConstantEvaluated)) {
16172         if (Result)
16173           TypeExpr = ACO->getTrueExpr();
16174         else
16175           TypeExpr = ACO->getFalseExpr();
16176         continue;
16177       }
16178       return false;
16179     }
16180 
16181     case Stmt::BinaryOperatorClass: {
16182       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16183       if (BO->getOpcode() == BO_Comma) {
16184         TypeExpr = BO->getRHS();
16185         continue;
16186       }
16187       return false;
16188     }
16189 
16190     default:
16191       return false;
16192     }
16193   }
16194 }
16195 
16196 /// Retrieve the C type corresponding to type tag TypeExpr.
16197 ///
16198 /// \param TypeExpr Expression that specifies a type tag.
16199 ///
16200 /// \param MagicValues Registered magic values.
16201 ///
16202 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16203 ///        kind.
16204 ///
16205 /// \param TypeInfo Information about the corresponding C type.
16206 ///
16207 /// \param isConstantEvaluated whether the evalaution should be performed in
16208 /// constant context.
16209 ///
16210 /// \returns true if the corresponding C type was found.
16211 static bool GetMatchingCType(
16212     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16213     const ASTContext &Ctx,
16214     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16215         *MagicValues,
16216     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16217     bool isConstantEvaluated) {
16218   FoundWrongKind = false;
16219 
16220   // Variable declaration that has type_tag_for_datatype attribute.
16221   const ValueDecl *VD = nullptr;
16222 
16223   uint64_t MagicValue;
16224 
16225   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16226     return false;
16227 
16228   if (VD) {
16229     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16230       if (I->getArgumentKind() != ArgumentKind) {
16231         FoundWrongKind = true;
16232         return false;
16233       }
16234       TypeInfo.Type = I->getMatchingCType();
16235       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16236       TypeInfo.MustBeNull = I->getMustBeNull();
16237       return true;
16238     }
16239     return false;
16240   }
16241 
16242   if (!MagicValues)
16243     return false;
16244 
16245   llvm::DenseMap<Sema::TypeTagMagicValue,
16246                  Sema::TypeTagData>::const_iterator I =
16247       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16248   if (I == MagicValues->end())
16249     return false;
16250 
16251   TypeInfo = I->second;
16252   return true;
16253 }
16254 
16255 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16256                                       uint64_t MagicValue, QualType Type,
16257                                       bool LayoutCompatible,
16258                                       bool MustBeNull) {
16259   if (!TypeTagForDatatypeMagicValues)
16260     TypeTagForDatatypeMagicValues.reset(
16261         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16262 
16263   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16264   (*TypeTagForDatatypeMagicValues)[Magic] =
16265       TypeTagData(Type, LayoutCompatible, MustBeNull);
16266 }
16267 
16268 static bool IsSameCharType(QualType T1, QualType T2) {
16269   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16270   if (!BT1)
16271     return false;
16272 
16273   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16274   if (!BT2)
16275     return false;
16276 
16277   BuiltinType::Kind T1Kind = BT1->getKind();
16278   BuiltinType::Kind T2Kind = BT2->getKind();
16279 
16280   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16281          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16282          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16283          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16284 }
16285 
16286 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16287                                     const ArrayRef<const Expr *> ExprArgs,
16288                                     SourceLocation CallSiteLoc) {
16289   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16290   bool IsPointerAttr = Attr->getIsPointer();
16291 
16292   // Retrieve the argument representing the 'type_tag'.
16293   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16294   if (TypeTagIdxAST >= ExprArgs.size()) {
16295     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16296         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16297     return;
16298   }
16299   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16300   bool FoundWrongKind;
16301   TypeTagData TypeInfo;
16302   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16303                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16304                         TypeInfo, isConstantEvaluated())) {
16305     if (FoundWrongKind)
16306       Diag(TypeTagExpr->getExprLoc(),
16307            diag::warn_type_tag_for_datatype_wrong_kind)
16308         << TypeTagExpr->getSourceRange();
16309     return;
16310   }
16311 
16312   // Retrieve the argument representing the 'arg_idx'.
16313   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16314   if (ArgumentIdxAST >= ExprArgs.size()) {
16315     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16316         << 1 << Attr->getArgumentIdx().getSourceIndex();
16317     return;
16318   }
16319   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16320   if (IsPointerAttr) {
16321     // Skip implicit cast of pointer to `void *' (as a function argument).
16322     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16323       if (ICE->getType()->isVoidPointerType() &&
16324           ICE->getCastKind() == CK_BitCast)
16325         ArgumentExpr = ICE->getSubExpr();
16326   }
16327   QualType ArgumentType = ArgumentExpr->getType();
16328 
16329   // Passing a `void*' pointer shouldn't trigger a warning.
16330   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16331     return;
16332 
16333   if (TypeInfo.MustBeNull) {
16334     // Type tag with matching void type requires a null pointer.
16335     if (!ArgumentExpr->isNullPointerConstant(Context,
16336                                              Expr::NPC_ValueDependentIsNotNull)) {
16337       Diag(ArgumentExpr->getExprLoc(),
16338            diag::warn_type_safety_null_pointer_required)
16339           << ArgumentKind->getName()
16340           << ArgumentExpr->getSourceRange()
16341           << TypeTagExpr->getSourceRange();
16342     }
16343     return;
16344   }
16345 
16346   QualType RequiredType = TypeInfo.Type;
16347   if (IsPointerAttr)
16348     RequiredType = Context.getPointerType(RequiredType);
16349 
16350   bool mismatch = false;
16351   if (!TypeInfo.LayoutCompatible) {
16352     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16353 
16354     // C++11 [basic.fundamental] p1:
16355     // Plain char, signed char, and unsigned char are three distinct types.
16356     //
16357     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16358     // char' depending on the current char signedness mode.
16359     if (mismatch)
16360       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16361                                            RequiredType->getPointeeType())) ||
16362           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16363         mismatch = false;
16364   } else
16365     if (IsPointerAttr)
16366       mismatch = !isLayoutCompatible(Context,
16367                                      ArgumentType->getPointeeType(),
16368                                      RequiredType->getPointeeType());
16369     else
16370       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16371 
16372   if (mismatch)
16373     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16374         << ArgumentType << ArgumentKind
16375         << TypeInfo.LayoutCompatible << RequiredType
16376         << ArgumentExpr->getSourceRange()
16377         << TypeTagExpr->getSourceRange();
16378 }
16379 
16380 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16381                                          CharUnits Alignment) {
16382   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16383 }
16384 
16385 void Sema::DiagnoseMisalignedMembers() {
16386   for (MisalignedMember &m : MisalignedMembers) {
16387     const NamedDecl *ND = m.RD;
16388     if (ND->getName().empty()) {
16389       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16390         ND = TD;
16391     }
16392     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16393         << m.MD << ND << m.E->getSourceRange();
16394   }
16395   MisalignedMembers.clear();
16396 }
16397 
16398 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16399   E = E->IgnoreParens();
16400   if (!T->isPointerType() && !T->isIntegerType())
16401     return;
16402   if (isa<UnaryOperator>(E) &&
16403       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16404     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16405     if (isa<MemberExpr>(Op)) {
16406       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16407       if (MA != MisalignedMembers.end() &&
16408           (T->isIntegerType() ||
16409            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16410                                    Context.getTypeAlignInChars(
16411                                        T->getPointeeType()) <= MA->Alignment))))
16412         MisalignedMembers.erase(MA);
16413     }
16414   }
16415 }
16416 
16417 void Sema::RefersToMemberWithReducedAlignment(
16418     Expr *E,
16419     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16420         Action) {
16421   const auto *ME = dyn_cast<MemberExpr>(E);
16422   if (!ME)
16423     return;
16424 
16425   // No need to check expressions with an __unaligned-qualified type.
16426   if (E->getType().getQualifiers().hasUnaligned())
16427     return;
16428 
16429   // For a chain of MemberExpr like "a.b.c.d" this list
16430   // will keep FieldDecl's like [d, c, b].
16431   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16432   const MemberExpr *TopME = nullptr;
16433   bool AnyIsPacked = false;
16434   do {
16435     QualType BaseType = ME->getBase()->getType();
16436     if (BaseType->isDependentType())
16437       return;
16438     if (ME->isArrow())
16439       BaseType = BaseType->getPointeeType();
16440     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16441     if (RD->isInvalidDecl())
16442       return;
16443 
16444     ValueDecl *MD = ME->getMemberDecl();
16445     auto *FD = dyn_cast<FieldDecl>(MD);
16446     // We do not care about non-data members.
16447     if (!FD || FD->isInvalidDecl())
16448       return;
16449 
16450     AnyIsPacked =
16451         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16452     ReverseMemberChain.push_back(FD);
16453 
16454     TopME = ME;
16455     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16456   } while (ME);
16457   assert(TopME && "We did not compute a topmost MemberExpr!");
16458 
16459   // Not the scope of this diagnostic.
16460   if (!AnyIsPacked)
16461     return;
16462 
16463   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16464   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16465   // TODO: The innermost base of the member expression may be too complicated.
16466   // For now, just disregard these cases. This is left for future
16467   // improvement.
16468   if (!DRE && !isa<CXXThisExpr>(TopBase))
16469       return;
16470 
16471   // Alignment expected by the whole expression.
16472   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16473 
16474   // No need to do anything else with this case.
16475   if (ExpectedAlignment.isOne())
16476     return;
16477 
16478   // Synthesize offset of the whole access.
16479   CharUnits Offset;
16480   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16481        I++) {
16482     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16483   }
16484 
16485   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16486   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16487       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16488 
16489   // The base expression of the innermost MemberExpr may give
16490   // stronger guarantees than the class containing the member.
16491   if (DRE && !TopME->isArrow()) {
16492     const ValueDecl *VD = DRE->getDecl();
16493     if (!VD->getType()->isReferenceType())
16494       CompleteObjectAlignment =
16495           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16496   }
16497 
16498   // Check if the synthesized offset fulfills the alignment.
16499   if (Offset % ExpectedAlignment != 0 ||
16500       // It may fulfill the offset it but the effective alignment may still be
16501       // lower than the expected expression alignment.
16502       CompleteObjectAlignment < ExpectedAlignment) {
16503     // If this happens, we want to determine a sensible culprit of this.
16504     // Intuitively, watching the chain of member expressions from right to
16505     // left, we start with the required alignment (as required by the field
16506     // type) but some packed attribute in that chain has reduced the alignment.
16507     // It may happen that another packed structure increases it again. But if
16508     // we are here such increase has not been enough. So pointing the first
16509     // FieldDecl that either is packed or else its RecordDecl is,
16510     // seems reasonable.
16511     FieldDecl *FD = nullptr;
16512     CharUnits Alignment;
16513     for (FieldDecl *FDI : ReverseMemberChain) {
16514       if (FDI->hasAttr<PackedAttr>() ||
16515           FDI->getParent()->hasAttr<PackedAttr>()) {
16516         FD = FDI;
16517         Alignment = std::min(
16518             Context.getTypeAlignInChars(FD->getType()),
16519             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16520         break;
16521       }
16522     }
16523     assert(FD && "We did not find a packed FieldDecl!");
16524     Action(E, FD->getParent(), FD, Alignment);
16525   }
16526 }
16527 
16528 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16529   using namespace std::placeholders;
16530 
16531   RefersToMemberWithReducedAlignment(
16532       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16533                      _2, _3, _4));
16534 }
16535 
16536 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16537 // not a valid type, emit an error message and return true. Otherwise return
16538 // false.
16539 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16540                                         QualType Ty) {
16541   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16542     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16543         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16544     return true;
16545   }
16546   return false;
16547 }
16548 
16549 bool Sema::SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall) {
16550   if (checkArgCount(*this, TheCall, 1))
16551     return true;
16552 
16553   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16554   SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16555   if (A.isInvalid())
16556     return true;
16557 
16558   TheCall->setArg(0, A.get());
16559   QualType TyA = A.get()->getType();
16560   if (checkMathBuiltinElementType(*this, ArgLoc, TyA))
16561     return true;
16562 
16563   QualType EltTy = TyA;
16564   if (auto *VecTy = EltTy->getAs<VectorType>())
16565     EltTy = VecTy->getElementType();
16566   if (EltTy->isUnsignedIntegerType())
16567     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16568            << 1 << /*signed integer or float ty*/ 3 << TyA;
16569 
16570   TheCall->setType(TyA);
16571   return false;
16572 }
16573 
16574 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16575   if (checkArgCount(*this, TheCall, 2))
16576     return true;
16577 
16578   ExprResult A = TheCall->getArg(0);
16579   ExprResult B = TheCall->getArg(1);
16580   // Do standard promotions between the two arguments, returning their common
16581   // type.
16582   QualType Res =
16583       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16584   if (A.isInvalid() || B.isInvalid())
16585     return true;
16586 
16587   QualType TyA = A.get()->getType();
16588   QualType TyB = B.get()->getType();
16589 
16590   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16591     return Diag(A.get()->getBeginLoc(),
16592                 diag::err_typecheck_call_different_arg_types)
16593            << TyA << TyB;
16594 
16595   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16596     return true;
16597 
16598   TheCall->setArg(0, A.get());
16599   TheCall->setArg(1, B.get());
16600   TheCall->setType(Res);
16601   return false;
16602 }
16603 
16604 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) {
16605   if (checkArgCount(*this, TheCall, 1))
16606     return true;
16607 
16608   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16609   if (A.isInvalid())
16610     return true;
16611 
16612   TheCall->setArg(0, A.get());
16613   const VectorType *TyA = A.get()->getType()->getAs<VectorType>();
16614   if (!TyA) {
16615     SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16616     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16617            << 1 << /* vector ty*/ 4 << A.get()->getType();
16618   }
16619 
16620   TheCall->setType(TyA->getElementType());
16621   return false;
16622 }
16623 
16624 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16625                                             ExprResult CallResult) {
16626   if (checkArgCount(*this, TheCall, 1))
16627     return ExprError();
16628 
16629   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16630   if (MatrixArg.isInvalid())
16631     return MatrixArg;
16632   Expr *Matrix = MatrixArg.get();
16633 
16634   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16635   if (!MType) {
16636     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16637         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16638     return ExprError();
16639   }
16640 
16641   // Create returned matrix type by swapping rows and columns of the argument
16642   // matrix type.
16643   QualType ResultType = Context.getConstantMatrixType(
16644       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16645 
16646   // Change the return type to the type of the returned matrix.
16647   TheCall->setType(ResultType);
16648 
16649   // Update call argument to use the possibly converted matrix argument.
16650   TheCall->setArg(0, Matrix);
16651   return CallResult;
16652 }
16653 
16654 // Get and verify the matrix dimensions.
16655 static llvm::Optional<unsigned>
16656 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16657   SourceLocation ErrorPos;
16658   Optional<llvm::APSInt> Value =
16659       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16660   if (!Value) {
16661     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16662         << Name;
16663     return {};
16664   }
16665   uint64_t Dim = Value->getZExtValue();
16666   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16667     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16668         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16669     return {};
16670   }
16671   return Dim;
16672 }
16673 
16674 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16675                                                   ExprResult CallResult) {
16676   if (!getLangOpts().MatrixTypes) {
16677     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16678     return ExprError();
16679   }
16680 
16681   if (checkArgCount(*this, TheCall, 4))
16682     return ExprError();
16683 
16684   unsigned PtrArgIdx = 0;
16685   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16686   Expr *RowsExpr = TheCall->getArg(1);
16687   Expr *ColumnsExpr = TheCall->getArg(2);
16688   Expr *StrideExpr = TheCall->getArg(3);
16689 
16690   bool ArgError = false;
16691 
16692   // Check pointer argument.
16693   {
16694     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16695     if (PtrConv.isInvalid())
16696       return PtrConv;
16697     PtrExpr = PtrConv.get();
16698     TheCall->setArg(0, PtrExpr);
16699     if (PtrExpr->isTypeDependent()) {
16700       TheCall->setType(Context.DependentTy);
16701       return TheCall;
16702     }
16703   }
16704 
16705   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16706   QualType ElementTy;
16707   if (!PtrTy) {
16708     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16709         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16710     ArgError = true;
16711   } else {
16712     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16713 
16714     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16715       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16716           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
16717           << PtrExpr->getType();
16718       ArgError = true;
16719     }
16720   }
16721 
16722   // Apply default Lvalue conversions and convert the expression to size_t.
16723   auto ApplyArgumentConversions = [this](Expr *E) {
16724     ExprResult Conv = DefaultLvalueConversion(E);
16725     if (Conv.isInvalid())
16726       return Conv;
16727 
16728     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16729   };
16730 
16731   // Apply conversion to row and column expressions.
16732   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16733   if (!RowsConv.isInvalid()) {
16734     RowsExpr = RowsConv.get();
16735     TheCall->setArg(1, RowsExpr);
16736   } else
16737     RowsExpr = nullptr;
16738 
16739   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16740   if (!ColumnsConv.isInvalid()) {
16741     ColumnsExpr = ColumnsConv.get();
16742     TheCall->setArg(2, ColumnsExpr);
16743   } else
16744     ColumnsExpr = nullptr;
16745 
16746   // If any any part of the result matrix type is still pending, just use
16747   // Context.DependentTy, until all parts are resolved.
16748   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16749       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16750     TheCall->setType(Context.DependentTy);
16751     return CallResult;
16752   }
16753 
16754   // Check row and column dimensions.
16755   llvm::Optional<unsigned> MaybeRows;
16756   if (RowsExpr)
16757     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16758 
16759   llvm::Optional<unsigned> MaybeColumns;
16760   if (ColumnsExpr)
16761     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16762 
16763   // Check stride argument.
16764   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16765   if (StrideConv.isInvalid())
16766     return ExprError();
16767   StrideExpr = StrideConv.get();
16768   TheCall->setArg(3, StrideExpr);
16769 
16770   if (MaybeRows) {
16771     if (Optional<llvm::APSInt> Value =
16772             StrideExpr->getIntegerConstantExpr(Context)) {
16773       uint64_t Stride = Value->getZExtValue();
16774       if (Stride < *MaybeRows) {
16775         Diag(StrideExpr->getBeginLoc(),
16776              diag::err_builtin_matrix_stride_too_small);
16777         ArgError = true;
16778       }
16779     }
16780   }
16781 
16782   if (ArgError || !MaybeRows || !MaybeColumns)
16783     return ExprError();
16784 
16785   TheCall->setType(
16786       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16787   return CallResult;
16788 }
16789 
16790 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16791                                                    ExprResult CallResult) {
16792   if (checkArgCount(*this, TheCall, 3))
16793     return ExprError();
16794 
16795   unsigned PtrArgIdx = 1;
16796   Expr *MatrixExpr = TheCall->getArg(0);
16797   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16798   Expr *StrideExpr = TheCall->getArg(2);
16799 
16800   bool ArgError = false;
16801 
16802   {
16803     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16804     if (MatrixConv.isInvalid())
16805       return MatrixConv;
16806     MatrixExpr = MatrixConv.get();
16807     TheCall->setArg(0, MatrixExpr);
16808   }
16809   if (MatrixExpr->isTypeDependent()) {
16810     TheCall->setType(Context.DependentTy);
16811     return TheCall;
16812   }
16813 
16814   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16815   if (!MatrixTy) {
16816     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16817         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
16818     ArgError = true;
16819   }
16820 
16821   {
16822     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16823     if (PtrConv.isInvalid())
16824       return PtrConv;
16825     PtrExpr = PtrConv.get();
16826     TheCall->setArg(1, PtrExpr);
16827     if (PtrExpr->isTypeDependent()) {
16828       TheCall->setType(Context.DependentTy);
16829       return TheCall;
16830     }
16831   }
16832 
16833   // Check pointer argument.
16834   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16835   if (!PtrTy) {
16836     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16837         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16838     ArgError = true;
16839   } else {
16840     QualType ElementTy = PtrTy->getPointeeType();
16841     if (ElementTy.isConstQualified()) {
16842       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16843       ArgError = true;
16844     }
16845     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16846     if (MatrixTy &&
16847         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16848       Diag(PtrExpr->getBeginLoc(),
16849            diag::err_builtin_matrix_pointer_arg_mismatch)
16850           << ElementTy << MatrixTy->getElementType();
16851       ArgError = true;
16852     }
16853   }
16854 
16855   // Apply default Lvalue conversions and convert the stride expression to
16856   // size_t.
16857   {
16858     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16859     if (StrideConv.isInvalid())
16860       return StrideConv;
16861 
16862     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16863     if (StrideConv.isInvalid())
16864       return StrideConv;
16865     StrideExpr = StrideConv.get();
16866     TheCall->setArg(2, StrideExpr);
16867   }
16868 
16869   // Check stride argument.
16870   if (MatrixTy) {
16871     if (Optional<llvm::APSInt> Value =
16872             StrideExpr->getIntegerConstantExpr(Context)) {
16873       uint64_t Stride = Value->getZExtValue();
16874       if (Stride < MatrixTy->getNumRows()) {
16875         Diag(StrideExpr->getBeginLoc(),
16876              diag::err_builtin_matrix_stride_too_small);
16877         ArgError = true;
16878       }
16879     }
16880   }
16881 
16882   if (ArgError)
16883     return ExprError();
16884 
16885   return CallResult;
16886 }
16887 
16888 /// \brief Enforce the bounds of a TCB
16889 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16890 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16891 /// and enforce_tcb_leaf attributes.
16892 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16893                                const FunctionDecl *Callee) {
16894   const FunctionDecl *Caller = getCurFunctionDecl();
16895 
16896   // Calls to builtins are not enforced.
16897   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16898       Callee->getBuiltinID() != 0)
16899     return;
16900 
16901   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16902   // all TCBs the callee is a part of.
16903   llvm::StringSet<> CalleeTCBs;
16904   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16905            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16906   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16907            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16908 
16909   // Go through the TCBs the caller is a part of and emit warnings if Caller
16910   // is in a TCB that the Callee is not.
16911   for_each(
16912       Caller->specific_attrs<EnforceTCBAttr>(),
16913       [&](const auto *A) {
16914         StringRef CallerTCB = A->getTCBName();
16915         if (CalleeTCBs.count(CallerTCB) == 0) {
16916           this->Diag(TheCall->getExprLoc(),
16917                      diag::warn_tcb_enforcement_violation) << Callee
16918                                                            << CallerTCB;
16919         }
16920       });
16921 }
16922