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 unlikley 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).isNullValue()) {
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_matrix_transpose:
1980     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1981 
1982   case Builtin::BI__builtin_matrix_column_major_load:
1983     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1984 
1985   case Builtin::BI__builtin_matrix_column_major_store:
1986     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1987 
1988   case Builtin::BI__builtin_get_device_side_mangled_name: {
1989     auto Check = [](CallExpr *TheCall) {
1990       if (TheCall->getNumArgs() != 1)
1991         return false;
1992       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1993       if (!DRE)
1994         return false;
1995       auto *D = DRE->getDecl();
1996       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1997         return false;
1998       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1999              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2000     };
2001     if (!Check(TheCall)) {
2002       Diag(TheCall->getBeginLoc(),
2003            diag::err_hip_invalid_args_builtin_mangled_name);
2004       return ExprError();
2005     }
2006   }
2007   }
2008 
2009   // Since the target specific builtins for each arch overlap, only check those
2010   // of the arch we are compiling for.
2011   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2012     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2013       assert(Context.getAuxTargetInfo() &&
2014              "Aux Target Builtin, but not an aux target?");
2015 
2016       if (CheckTSBuiltinFunctionCall(
2017               *Context.getAuxTargetInfo(),
2018               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2019         return ExprError();
2020     } else {
2021       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2022                                      TheCall))
2023         return ExprError();
2024     }
2025   }
2026 
2027   return TheCallResult;
2028 }
2029 
2030 // Get the valid immediate range for the specified NEON type code.
2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2032   NeonTypeFlags Type(t);
2033   int IsQuad = ForceQuad ? true : Type.isQuad();
2034   switch (Type.getEltType()) {
2035   case NeonTypeFlags::Int8:
2036   case NeonTypeFlags::Poly8:
2037     return shift ? 7 : (8 << IsQuad) - 1;
2038   case NeonTypeFlags::Int16:
2039   case NeonTypeFlags::Poly16:
2040     return shift ? 15 : (4 << IsQuad) - 1;
2041   case NeonTypeFlags::Int32:
2042     return shift ? 31 : (2 << IsQuad) - 1;
2043   case NeonTypeFlags::Int64:
2044   case NeonTypeFlags::Poly64:
2045     return shift ? 63 : (1 << IsQuad) - 1;
2046   case NeonTypeFlags::Poly128:
2047     return shift ? 127 : (1 << IsQuad) - 1;
2048   case NeonTypeFlags::Float16:
2049     assert(!shift && "cannot shift float types!");
2050     return (4 << IsQuad) - 1;
2051   case NeonTypeFlags::Float32:
2052     assert(!shift && "cannot shift float types!");
2053     return (2 << IsQuad) - 1;
2054   case NeonTypeFlags::Float64:
2055     assert(!shift && "cannot shift float types!");
2056     return (1 << IsQuad) - 1;
2057   case NeonTypeFlags::BFloat16:
2058     assert(!shift && "cannot shift float types!");
2059     return (4 << IsQuad) - 1;
2060   }
2061   llvm_unreachable("Invalid NeonTypeFlag!");
2062 }
2063 
2064 /// getNeonEltType - Return the QualType corresponding to the elements of
2065 /// the vector type specified by the NeonTypeFlags.  This is used to check
2066 /// the pointer arguments for Neon load/store intrinsics.
2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2068                                bool IsPolyUnsigned, bool IsInt64Long) {
2069   switch (Flags.getEltType()) {
2070   case NeonTypeFlags::Int8:
2071     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2072   case NeonTypeFlags::Int16:
2073     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2074   case NeonTypeFlags::Int32:
2075     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2076   case NeonTypeFlags::Int64:
2077     if (IsInt64Long)
2078       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2079     else
2080       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2081                                 : Context.LongLongTy;
2082   case NeonTypeFlags::Poly8:
2083     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2084   case NeonTypeFlags::Poly16:
2085     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2086   case NeonTypeFlags::Poly64:
2087     if (IsInt64Long)
2088       return Context.UnsignedLongTy;
2089     else
2090       return Context.UnsignedLongLongTy;
2091   case NeonTypeFlags::Poly128:
2092     break;
2093   case NeonTypeFlags::Float16:
2094     return Context.HalfTy;
2095   case NeonTypeFlags::Float32:
2096     return Context.FloatTy;
2097   case NeonTypeFlags::Float64:
2098     return Context.DoubleTy;
2099   case NeonTypeFlags::BFloat16:
2100     return Context.BFloat16Ty;
2101   }
2102   llvm_unreachable("Invalid NeonTypeFlag!");
2103 }
2104 
2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2106   // Range check SVE intrinsics that take immediate values.
2107   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2108 
2109   switch (BuiltinID) {
2110   default:
2111     return false;
2112 #define GET_SVE_IMMEDIATE_CHECK
2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2114 #undef GET_SVE_IMMEDIATE_CHECK
2115   }
2116 
2117   // Perform all the immediate checks for this builtin call.
2118   bool HasError = false;
2119   for (auto &I : ImmChecks) {
2120     int ArgNum, CheckTy, ElementSizeInBits;
2121     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2122 
2123     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2124 
2125     // Function that checks whether the operand (ArgNum) is an immediate
2126     // that is one of the predefined values.
2127     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2128                                    int ErrDiag) -> bool {
2129       // We can't check the value of a dependent argument.
2130       Expr *Arg = TheCall->getArg(ArgNum);
2131       if (Arg->isTypeDependent() || Arg->isValueDependent())
2132         return false;
2133 
2134       // Check constant-ness first.
2135       llvm::APSInt Imm;
2136       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2137         return true;
2138 
2139       if (!CheckImm(Imm.getSExtValue()))
2140         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2141       return false;
2142     };
2143 
2144     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2145     case SVETypeFlags::ImmCheck0_31:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2147         HasError = true;
2148       break;
2149     case SVETypeFlags::ImmCheck0_13:
2150       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2151         HasError = true;
2152       break;
2153     case SVETypeFlags::ImmCheck1_16:
2154       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheck0_7:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckExtract:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       (2048 / ElementSizeInBits) - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckShiftRight:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2168         HasError = true;
2169       break;
2170     case SVETypeFlags::ImmCheckShiftRightNarrow:
2171       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2172                                       ElementSizeInBits / 2))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheckShiftLeft:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2177                                       ElementSizeInBits - 1))
2178         HasError = true;
2179       break;
2180     case SVETypeFlags::ImmCheckLaneIndex:
2181       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2182                                       (128 / (1 * ElementSizeInBits)) - 1))
2183         HasError = true;
2184       break;
2185     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2186       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2187                                       (128 / (2 * ElementSizeInBits)) - 1))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheckLaneIndexDot:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2192                                       (128 / (4 * ElementSizeInBits)) - 1))
2193         HasError = true;
2194       break;
2195     case SVETypeFlags::ImmCheckComplexRot90_270:
2196       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2197                               diag::err_rotation_argument_to_cadd))
2198         HasError = true;
2199       break;
2200     case SVETypeFlags::ImmCheckComplexRotAll90:
2201       if (CheckImmediateInSet(
2202               [](int64_t V) {
2203                 return V == 0 || V == 90 || V == 180 || V == 270;
2204               },
2205               diag::err_rotation_argument_to_cmla))
2206         HasError = true;
2207       break;
2208     case SVETypeFlags::ImmCheck0_1:
2209       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2210         HasError = true;
2211       break;
2212     case SVETypeFlags::ImmCheck0_2:
2213       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2214         HasError = true;
2215       break;
2216     case SVETypeFlags::ImmCheck0_3:
2217       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2218         HasError = true;
2219       break;
2220     }
2221   }
2222 
2223   return HasError;
2224 }
2225 
2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2227                                         unsigned BuiltinID, CallExpr *TheCall) {
2228   llvm::APSInt Result;
2229   uint64_t mask = 0;
2230   unsigned TV = 0;
2231   int PtrArgNum = -1;
2232   bool HasConstPtr = false;
2233   switch (BuiltinID) {
2234 #define GET_NEON_OVERLOAD_CHECK
2235 #include "clang/Basic/arm_neon.inc"
2236 #include "clang/Basic/arm_fp16.inc"
2237 #undef GET_NEON_OVERLOAD_CHECK
2238   }
2239 
2240   // For NEON intrinsics which are overloaded on vector element type, validate
2241   // the immediate which specifies which variant to emit.
2242   unsigned ImmArg = TheCall->getNumArgs()-1;
2243   if (mask) {
2244     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2245       return true;
2246 
2247     TV = Result.getLimitedValue(64);
2248     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2249       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2250              << TheCall->getArg(ImmArg)->getSourceRange();
2251   }
2252 
2253   if (PtrArgNum >= 0) {
2254     // Check that pointer arguments have the specified type.
2255     Expr *Arg = TheCall->getArg(PtrArgNum);
2256     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2257       Arg = ICE->getSubExpr();
2258     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2259     QualType RHSTy = RHS.get()->getType();
2260 
2261     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2262     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2263                           Arch == llvm::Triple::aarch64_32 ||
2264                           Arch == llvm::Triple::aarch64_be;
2265     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2266     QualType EltTy =
2267         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2268     if (HasConstPtr)
2269       EltTy = EltTy.withConst();
2270     QualType LHSTy = Context.getPointerType(EltTy);
2271     AssignConvertType ConvTy;
2272     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2273     if (RHS.isInvalid())
2274       return true;
2275     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2276                                  RHS.get(), AA_Assigning))
2277       return true;
2278   }
2279 
2280   // For NEON intrinsics which take an immediate value as part of the
2281   // instruction, range check them here.
2282   unsigned i = 0, l = 0, u = 0;
2283   switch (BuiltinID) {
2284   default:
2285     return false;
2286   #define GET_NEON_IMMEDIATE_CHECK
2287   #include "clang/Basic/arm_neon.inc"
2288   #include "clang/Basic/arm_fp16.inc"
2289   #undef GET_NEON_IMMEDIATE_CHECK
2290   }
2291 
2292   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2293 }
2294 
2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2296   switch (BuiltinID) {
2297   default:
2298     return false;
2299   #include "clang/Basic/arm_mve_builtin_sema.inc"
2300   }
2301 }
2302 
2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2304                                        CallExpr *TheCall) {
2305   bool Err = false;
2306   switch (BuiltinID) {
2307   default:
2308     return false;
2309 #include "clang/Basic/arm_cde_builtin_sema.inc"
2310   }
2311 
2312   if (Err)
2313     return true;
2314 
2315   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2316 }
2317 
2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2319                                         const Expr *CoprocArg, bool WantCDE) {
2320   if (isConstantEvaluated())
2321     return false;
2322 
2323   // We can't check the value of a dependent argument.
2324   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2325     return false;
2326 
2327   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2328   int64_t CoprocNo = CoprocNoAP.getExtValue();
2329   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2330 
2331   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2332   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2333 
2334   if (IsCDECoproc != WantCDE)
2335     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2336            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2337 
2338   return false;
2339 }
2340 
2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2342                                         unsigned MaxWidth) {
2343   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2344           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2345           BuiltinID == ARM::BI__builtin_arm_strex ||
2346           BuiltinID == ARM::BI__builtin_arm_stlex ||
2347           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2348           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2349           BuiltinID == AArch64::BI__builtin_arm_strex ||
2350           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2351          "unexpected ARM builtin");
2352   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2353                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2354                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2355                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2356 
2357   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2358 
2359   // Ensure that we have the proper number of arguments.
2360   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2361     return true;
2362 
2363   // Inspect the pointer argument of the atomic builtin.  This should always be
2364   // a pointer type, whose element is an integral scalar or pointer type.
2365   // Because it is a pointer type, we don't have to worry about any implicit
2366   // casts here.
2367   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2368   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2369   if (PointerArgRes.isInvalid())
2370     return true;
2371   PointerArg = PointerArgRes.get();
2372 
2373   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2374   if (!pointerType) {
2375     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2376         << PointerArg->getType() << PointerArg->getSourceRange();
2377     return true;
2378   }
2379 
2380   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2381   // task is to insert the appropriate casts into the AST. First work out just
2382   // what the appropriate type is.
2383   QualType ValType = pointerType->getPointeeType();
2384   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2385   if (IsLdrex)
2386     AddrType.addConst();
2387 
2388   // Issue a warning if the cast is dodgy.
2389   CastKind CastNeeded = CK_NoOp;
2390   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2391     CastNeeded = CK_BitCast;
2392     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2393         << PointerArg->getType() << Context.getPointerType(AddrType)
2394         << AA_Passing << PointerArg->getSourceRange();
2395   }
2396 
2397   // Finally, do the cast and replace the argument with the corrected version.
2398   AddrType = Context.getPointerType(AddrType);
2399   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2400   if (PointerArgRes.isInvalid())
2401     return true;
2402   PointerArg = PointerArgRes.get();
2403 
2404   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2405 
2406   // In general, we allow ints, floats and pointers to be loaded and stored.
2407   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2408       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2409     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2410         << PointerArg->getType() << PointerArg->getSourceRange();
2411     return true;
2412   }
2413 
2414   // But ARM doesn't have instructions to deal with 128-bit versions.
2415   if (Context.getTypeSize(ValType) > MaxWidth) {
2416     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2417     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2418         << PointerArg->getType() << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   switch (ValType.getObjCLifetime()) {
2423   case Qualifiers::OCL_None:
2424   case Qualifiers::OCL_ExplicitNone:
2425     // okay
2426     break;
2427 
2428   case Qualifiers::OCL_Weak:
2429   case Qualifiers::OCL_Strong:
2430   case Qualifiers::OCL_Autoreleasing:
2431     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2432         << ValType << PointerArg->getSourceRange();
2433     return true;
2434   }
2435 
2436   if (IsLdrex) {
2437     TheCall->setType(ValType);
2438     return false;
2439   }
2440 
2441   // Initialize the argument to be stored.
2442   ExprResult ValArg = TheCall->getArg(0);
2443   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2444       Context, ValType, /*consume*/ false);
2445   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2446   if (ValArg.isInvalid())
2447     return true;
2448   TheCall->setArg(0, ValArg.get());
2449 
2450   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2451   // but the custom checker bypasses all default analysis.
2452   TheCall->setType(Context.IntTy);
2453   return false;
2454 }
2455 
2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2457                                        CallExpr *TheCall) {
2458   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2459       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2460       BuiltinID == ARM::BI__builtin_arm_strex ||
2461       BuiltinID == ARM::BI__builtin_arm_stlex) {
2462     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2463   }
2464 
2465   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2466     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2467       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2468   }
2469 
2470   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2471       BuiltinID == ARM::BI__builtin_arm_wsr64)
2472     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2473 
2474   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2475       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2476       BuiltinID == ARM::BI__builtin_arm_wsr ||
2477       BuiltinID == ARM::BI__builtin_arm_wsrp)
2478     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2479 
2480   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2481     return true;
2482   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2483     return true;
2484   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2485     return true;
2486 
2487   // For intrinsics which take an immediate value as part of the instruction,
2488   // range check them here.
2489   // FIXME: VFP Intrinsics should error if VFP not present.
2490   switch (BuiltinID) {
2491   default: return false;
2492   case ARM::BI__builtin_arm_ssat:
2493     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2494   case ARM::BI__builtin_arm_usat:
2495     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2496   case ARM::BI__builtin_arm_ssat16:
2497     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2498   case ARM::BI__builtin_arm_usat16:
2499     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2500   case ARM::BI__builtin_arm_vcvtr_f:
2501   case ARM::BI__builtin_arm_vcvtr_d:
2502     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2503   case ARM::BI__builtin_arm_dmb:
2504   case ARM::BI__builtin_arm_dsb:
2505   case ARM::BI__builtin_arm_isb:
2506   case ARM::BI__builtin_arm_dbg:
2507     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2508   case ARM::BI__builtin_arm_cdp:
2509   case ARM::BI__builtin_arm_cdp2:
2510   case ARM::BI__builtin_arm_mcr:
2511   case ARM::BI__builtin_arm_mcr2:
2512   case ARM::BI__builtin_arm_mrc:
2513   case ARM::BI__builtin_arm_mrc2:
2514   case ARM::BI__builtin_arm_mcrr:
2515   case ARM::BI__builtin_arm_mcrr2:
2516   case ARM::BI__builtin_arm_mrrc:
2517   case ARM::BI__builtin_arm_mrrc2:
2518   case ARM::BI__builtin_arm_ldc:
2519   case ARM::BI__builtin_arm_ldcl:
2520   case ARM::BI__builtin_arm_ldc2:
2521   case ARM::BI__builtin_arm_ldc2l:
2522   case ARM::BI__builtin_arm_stc:
2523   case ARM::BI__builtin_arm_stcl:
2524   case ARM::BI__builtin_arm_stc2:
2525   case ARM::BI__builtin_arm_stc2l:
2526     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2527            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2528                                         /*WantCDE*/ false);
2529   }
2530 }
2531 
2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2533                                            unsigned BuiltinID,
2534                                            CallExpr *TheCall) {
2535   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2536       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2537       BuiltinID == AArch64::BI__builtin_arm_strex ||
2538       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2539     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2540   }
2541 
2542   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2543     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2544       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2545       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2546       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2550       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2551     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2552 
2553   // Memory Tagging Extensions (MTE) Intrinsics
2554   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2555       BuiltinID == AArch64::BI__builtin_arm_addg ||
2556       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2557       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2558       BuiltinID == AArch64::BI__builtin_arm_stg ||
2559       BuiltinID == AArch64::BI__builtin_arm_subp) {
2560     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2561   }
2562 
2563   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2564       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2565       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2566       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2567     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2568 
2569   // Only check the valid encoding range. Any constant in this range would be
2570   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2571   // an exception for incorrect registers. This matches MSVC behavior.
2572   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2573       BuiltinID == AArch64::BI_WriteStatusReg)
2574     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2575 
2576   if (BuiltinID == AArch64::BI__getReg)
2577     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2578 
2579   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2580     return true;
2581 
2582   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2583     return true;
2584 
2585   // For intrinsics which take an immediate value as part of the instruction,
2586   // range check them here.
2587   unsigned i = 0, l = 0, u = 0;
2588   switch (BuiltinID) {
2589   default: return false;
2590   case AArch64::BI__builtin_arm_dmb:
2591   case AArch64::BI__builtin_arm_dsb:
2592   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2593   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2594   }
2595 
2596   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2597 }
2598 
2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2600   if (Arg->getType()->getAsPlaceholderType())
2601     return false;
2602 
2603   // The first argument needs to be a record field access.
2604   // If it is an array element access, we delay decision
2605   // to BPF backend to check whether the access is a
2606   // field access or not.
2607   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2608           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2609           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2610 }
2611 
2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2613                             QualType VectorTy, QualType EltTy) {
2614   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2615   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2616     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2617         << Call->getSourceRange() << VectorEltTy << EltTy;
2618     return false;
2619   }
2620   return true;
2621 }
2622 
2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2624   QualType ArgType = Arg->getType();
2625   if (ArgType->getAsPlaceholderType())
2626     return false;
2627 
2628   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2629   // format:
2630   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2631   //   2. <type> var;
2632   //      __builtin_preserve_type_info(var, flag);
2633   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2634       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2635     return false;
2636 
2637   // Typedef type.
2638   if (ArgType->getAs<TypedefType>())
2639     return true;
2640 
2641   // Record type or Enum type.
2642   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2643   if (const auto *RT = Ty->getAs<RecordType>()) {
2644     if (!RT->getDecl()->getDeclName().isEmpty())
2645       return true;
2646   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2647     if (!ET->getDecl()->getDeclName().isEmpty())
2648       return true;
2649   }
2650 
2651   return false;
2652 }
2653 
2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2655   QualType ArgType = Arg->getType();
2656   if (ArgType->getAsPlaceholderType())
2657     return false;
2658 
2659   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2660   // format:
2661   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2662   //                                 flag);
2663   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2664   if (!UO)
2665     return false;
2666 
2667   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2668   if (!CE)
2669     return false;
2670   if (CE->getCastKind() != CK_IntegralToPointer &&
2671       CE->getCastKind() != CK_NullToPointer)
2672     return false;
2673 
2674   // The integer must be from an EnumConstantDecl.
2675   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2676   if (!DR)
2677     return false;
2678 
2679   const EnumConstantDecl *Enumerator =
2680       dyn_cast<EnumConstantDecl>(DR->getDecl());
2681   if (!Enumerator)
2682     return false;
2683 
2684   // The type must be EnumType.
2685   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2686   const auto *ET = Ty->getAs<EnumType>();
2687   if (!ET)
2688     return false;
2689 
2690   // The enum value must be supported.
2691   for (auto *EDI : ET->getDecl()->enumerators()) {
2692     if (EDI == Enumerator)
2693       return true;
2694   }
2695 
2696   return false;
2697 }
2698 
2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2700                                        CallExpr *TheCall) {
2701   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2702           BuiltinID == BPF::BI__builtin_btf_type_id ||
2703           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2704           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2705          "unexpected BPF builtin");
2706 
2707   if (checkArgCount(*this, TheCall, 2))
2708     return true;
2709 
2710   // The second argument needs to be a constant int
2711   Expr *Arg = TheCall->getArg(1);
2712   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2713   diag::kind kind;
2714   if (!Value) {
2715     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2716       kind = diag::err_preserve_field_info_not_const;
2717     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2718       kind = diag::err_btf_type_id_not_const;
2719     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2720       kind = diag::err_preserve_type_info_not_const;
2721     else
2722       kind = diag::err_preserve_enum_value_not_const;
2723     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2724     return true;
2725   }
2726 
2727   // The first argument
2728   Arg = TheCall->getArg(0);
2729   bool InvalidArg = false;
2730   bool ReturnUnsignedInt = true;
2731   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2732     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2733       InvalidArg = true;
2734       kind = diag::err_preserve_field_info_not_field;
2735     }
2736   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2737     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2738       InvalidArg = true;
2739       kind = diag::err_preserve_type_info_invalid;
2740     }
2741   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2742     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2743       InvalidArg = true;
2744       kind = diag::err_preserve_enum_value_invalid;
2745     }
2746     ReturnUnsignedInt = false;
2747   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2748     ReturnUnsignedInt = false;
2749   }
2750 
2751   if (InvalidArg) {
2752     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2753     return true;
2754   }
2755 
2756   if (ReturnUnsignedInt)
2757     TheCall->setType(Context.UnsignedIntTy);
2758   else
2759     TheCall->setType(Context.UnsignedLongTy);
2760   return false;
2761 }
2762 
2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2764   struct ArgInfo {
2765     uint8_t OpNum;
2766     bool IsSigned;
2767     uint8_t BitWidth;
2768     uint8_t Align;
2769   };
2770   struct BuiltinInfo {
2771     unsigned BuiltinID;
2772     ArgInfo Infos[2];
2773   };
2774 
2775   static BuiltinInfo Infos[] = {
2776     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2777     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2778     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2780     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2782     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2783     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2785     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2786     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2787 
2788     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2791     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2792     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2793     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2799 
2800     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2852                                                       {{ 1, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2860                                                       {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2867                                                        { 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2869                                                        { 2, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2871                                                        { 3, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2873                                                        { 3, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2890                                                       {{ 2, false, 4,  0 },
2891                                                        { 3, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2893                                                       {{ 2, false, 4,  0 },
2894                                                        { 3, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2896                                                       {{ 2, false, 4,  0 },
2897                                                        { 3, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2899                                                       {{ 2, false, 4,  0 },
2900                                                        { 3, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2912                                                        { 2, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2914                                                        { 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2924                                                       {{ 1, false, 4,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2927                                                       {{ 1, false, 4,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2948                                                       {{ 3, false, 1,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2953                                                       {{ 3, false, 1,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2958                                                       {{ 3, false, 1,  0 }} },
2959   };
2960 
2961   // Use a dynamically initialized static to sort the table exactly once on
2962   // first run.
2963   static const bool SortOnce =
2964       (llvm::sort(Infos,
2965                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2966                    return LHS.BuiltinID < RHS.BuiltinID;
2967                  }),
2968        true);
2969   (void)SortOnce;
2970 
2971   const BuiltinInfo *F = llvm::partition_point(
2972       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2973   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2974     return false;
2975 
2976   bool Error = false;
2977 
2978   for (const ArgInfo &A : F->Infos) {
2979     // Ignore empty ArgInfo elements.
2980     if (A.BitWidth == 0)
2981       continue;
2982 
2983     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2984     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2985     if (!A.Align) {
2986       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2987     } else {
2988       unsigned M = 1 << A.Align;
2989       Min *= M;
2990       Max *= M;
2991       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2992                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2993     }
2994   }
2995   return Error;
2996 }
2997 
2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2999                                            CallExpr *TheCall) {
3000   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3001 }
3002 
3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3004                                         unsigned BuiltinID, CallExpr *TheCall) {
3005   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3006          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3007 }
3008 
3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3010                                CallExpr *TheCall) {
3011 
3012   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3013       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3014     if (!TI.hasFeature("dsp"))
3015       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3016   }
3017 
3018   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3019       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3020     if (!TI.hasFeature("dspr2"))
3021       return Diag(TheCall->getBeginLoc(),
3022                   diag::err_mips_builtin_requires_dspr2);
3023   }
3024 
3025   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3026       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3027     if (!TI.hasFeature("msa"))
3028       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3029   }
3030 
3031   return false;
3032 }
3033 
3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3036 // ordering for DSP is unspecified. MSA is ordered by the data format used
3037 // by the underlying instruction i.e., df/m, df/n and then by size.
3038 //
3039 // FIXME: The size tests here should instead be tablegen'd along with the
3040 //        definitions from include/clang/Basic/BuiltinsMips.def.
3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3042 //        be too.
3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3044   unsigned i = 0, l = 0, u = 0, m = 0;
3045   switch (BuiltinID) {
3046   default: return false;
3047   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3048   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3049   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3050   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3051   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3052   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3053   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3054   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3055   // df/m field.
3056   // These intrinsics take an unsigned 3 bit immediate.
3057   case Mips::BI__builtin_msa_bclri_b:
3058   case Mips::BI__builtin_msa_bnegi_b:
3059   case Mips::BI__builtin_msa_bseti_b:
3060   case Mips::BI__builtin_msa_sat_s_b:
3061   case Mips::BI__builtin_msa_sat_u_b:
3062   case Mips::BI__builtin_msa_slli_b:
3063   case Mips::BI__builtin_msa_srai_b:
3064   case Mips::BI__builtin_msa_srari_b:
3065   case Mips::BI__builtin_msa_srli_b:
3066   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3067   case Mips::BI__builtin_msa_binsli_b:
3068   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3069   // These intrinsics take an unsigned 4 bit immediate.
3070   case Mips::BI__builtin_msa_bclri_h:
3071   case Mips::BI__builtin_msa_bnegi_h:
3072   case Mips::BI__builtin_msa_bseti_h:
3073   case Mips::BI__builtin_msa_sat_s_h:
3074   case Mips::BI__builtin_msa_sat_u_h:
3075   case Mips::BI__builtin_msa_slli_h:
3076   case Mips::BI__builtin_msa_srai_h:
3077   case Mips::BI__builtin_msa_srari_h:
3078   case Mips::BI__builtin_msa_srli_h:
3079   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3080   case Mips::BI__builtin_msa_binsli_h:
3081   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3082   // These intrinsics take an unsigned 5 bit immediate.
3083   // The first block of intrinsics actually have an unsigned 5 bit field,
3084   // not a df/n field.
3085   case Mips::BI__builtin_msa_cfcmsa:
3086   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3087   case Mips::BI__builtin_msa_clei_u_b:
3088   case Mips::BI__builtin_msa_clei_u_h:
3089   case Mips::BI__builtin_msa_clei_u_w:
3090   case Mips::BI__builtin_msa_clei_u_d:
3091   case Mips::BI__builtin_msa_clti_u_b:
3092   case Mips::BI__builtin_msa_clti_u_h:
3093   case Mips::BI__builtin_msa_clti_u_w:
3094   case Mips::BI__builtin_msa_clti_u_d:
3095   case Mips::BI__builtin_msa_maxi_u_b:
3096   case Mips::BI__builtin_msa_maxi_u_h:
3097   case Mips::BI__builtin_msa_maxi_u_w:
3098   case Mips::BI__builtin_msa_maxi_u_d:
3099   case Mips::BI__builtin_msa_mini_u_b:
3100   case Mips::BI__builtin_msa_mini_u_h:
3101   case Mips::BI__builtin_msa_mini_u_w:
3102   case Mips::BI__builtin_msa_mini_u_d:
3103   case Mips::BI__builtin_msa_addvi_b:
3104   case Mips::BI__builtin_msa_addvi_h:
3105   case Mips::BI__builtin_msa_addvi_w:
3106   case Mips::BI__builtin_msa_addvi_d:
3107   case Mips::BI__builtin_msa_bclri_w:
3108   case Mips::BI__builtin_msa_bnegi_w:
3109   case Mips::BI__builtin_msa_bseti_w:
3110   case Mips::BI__builtin_msa_sat_s_w:
3111   case Mips::BI__builtin_msa_sat_u_w:
3112   case Mips::BI__builtin_msa_slli_w:
3113   case Mips::BI__builtin_msa_srai_w:
3114   case Mips::BI__builtin_msa_srari_w:
3115   case Mips::BI__builtin_msa_srli_w:
3116   case Mips::BI__builtin_msa_srlri_w:
3117   case Mips::BI__builtin_msa_subvi_b:
3118   case Mips::BI__builtin_msa_subvi_h:
3119   case Mips::BI__builtin_msa_subvi_w:
3120   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3121   case Mips::BI__builtin_msa_binsli_w:
3122   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3123   // These intrinsics take an unsigned 6 bit immediate.
3124   case Mips::BI__builtin_msa_bclri_d:
3125   case Mips::BI__builtin_msa_bnegi_d:
3126   case Mips::BI__builtin_msa_bseti_d:
3127   case Mips::BI__builtin_msa_sat_s_d:
3128   case Mips::BI__builtin_msa_sat_u_d:
3129   case Mips::BI__builtin_msa_slli_d:
3130   case Mips::BI__builtin_msa_srai_d:
3131   case Mips::BI__builtin_msa_srari_d:
3132   case Mips::BI__builtin_msa_srli_d:
3133   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3134   case Mips::BI__builtin_msa_binsli_d:
3135   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3136   // These intrinsics take a signed 5 bit immediate.
3137   case Mips::BI__builtin_msa_ceqi_b:
3138   case Mips::BI__builtin_msa_ceqi_h:
3139   case Mips::BI__builtin_msa_ceqi_w:
3140   case Mips::BI__builtin_msa_ceqi_d:
3141   case Mips::BI__builtin_msa_clti_s_b:
3142   case Mips::BI__builtin_msa_clti_s_h:
3143   case Mips::BI__builtin_msa_clti_s_w:
3144   case Mips::BI__builtin_msa_clti_s_d:
3145   case Mips::BI__builtin_msa_clei_s_b:
3146   case Mips::BI__builtin_msa_clei_s_h:
3147   case Mips::BI__builtin_msa_clei_s_w:
3148   case Mips::BI__builtin_msa_clei_s_d:
3149   case Mips::BI__builtin_msa_maxi_s_b:
3150   case Mips::BI__builtin_msa_maxi_s_h:
3151   case Mips::BI__builtin_msa_maxi_s_w:
3152   case Mips::BI__builtin_msa_maxi_s_d:
3153   case Mips::BI__builtin_msa_mini_s_b:
3154   case Mips::BI__builtin_msa_mini_s_h:
3155   case Mips::BI__builtin_msa_mini_s_w:
3156   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3157   // These intrinsics take an unsigned 8 bit immediate.
3158   case Mips::BI__builtin_msa_andi_b:
3159   case Mips::BI__builtin_msa_nori_b:
3160   case Mips::BI__builtin_msa_ori_b:
3161   case Mips::BI__builtin_msa_shf_b:
3162   case Mips::BI__builtin_msa_shf_h:
3163   case Mips::BI__builtin_msa_shf_w:
3164   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3165   case Mips::BI__builtin_msa_bseli_b:
3166   case Mips::BI__builtin_msa_bmnzi_b:
3167   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3168   // df/n format
3169   // These intrinsics take an unsigned 4 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_b:
3171   case Mips::BI__builtin_msa_copy_u_b:
3172   case Mips::BI__builtin_msa_insve_b:
3173   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3174   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3175   // These intrinsics take an unsigned 3 bit immediate.
3176   case Mips::BI__builtin_msa_copy_s_h:
3177   case Mips::BI__builtin_msa_copy_u_h:
3178   case Mips::BI__builtin_msa_insve_h:
3179   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3180   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3181   // These intrinsics take an unsigned 2 bit immediate.
3182   case Mips::BI__builtin_msa_copy_s_w:
3183   case Mips::BI__builtin_msa_copy_u_w:
3184   case Mips::BI__builtin_msa_insve_w:
3185   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3186   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3187   // These intrinsics take an unsigned 1 bit immediate.
3188   case Mips::BI__builtin_msa_copy_s_d:
3189   case Mips::BI__builtin_msa_copy_u_d:
3190   case Mips::BI__builtin_msa_insve_d:
3191   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3192   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3193   // Memory offsets and immediate loads.
3194   // These intrinsics take a signed 10 bit immediate.
3195   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3196   case Mips::BI__builtin_msa_ldi_h:
3197   case Mips::BI__builtin_msa_ldi_w:
3198   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3199   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3200   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3201   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3202   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3203   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3204   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3205   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3206   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3207   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3208   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3209   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3210   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3211   }
3212 
3213   if (!m)
3214     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3215 
3216   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3217          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3218 }
3219 
3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3221 /// advancing the pointer over the consumed characters. The decoded type is
3222 /// returned. If the decoded type represents a constant integer with a
3223 /// constraint on its value then Mask is set to that value. The type descriptors
3224 /// used in Str are specific to PPC MMA builtins and are documented in the file
3225 /// defining the PPC builtins.
3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3227                                         unsigned &Mask) {
3228   bool RequireICE = false;
3229   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3230   switch (*Str++) {
3231   case 'V':
3232     return Context.getVectorType(Context.UnsignedCharTy, 16,
3233                                  VectorType::VectorKind::AltiVecVector);
3234   case 'i': {
3235     char *End;
3236     unsigned size = strtoul(Str, &End, 10);
3237     assert(End != Str && "Missing constant parameter constraint");
3238     Str = End;
3239     Mask = size;
3240     return Context.IntTy;
3241   }
3242   case 'W': {
3243     char *End;
3244     unsigned size = strtoul(Str, &End, 10);
3245     assert(End != Str && "Missing PowerPC MMA type size");
3246     Str = End;
3247     QualType Type;
3248     switch (size) {
3249   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3250     case size: Type = Context.Id##Ty; break;
3251   #include "clang/Basic/PPCTypes.def"
3252     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3253     }
3254     bool CheckVectorArgs = false;
3255     while (!CheckVectorArgs) {
3256       switch (*Str++) {
3257       case '*':
3258         Type = Context.getPointerType(Type);
3259         break;
3260       case 'C':
3261         Type = Type.withConst();
3262         break;
3263       default:
3264         CheckVectorArgs = true;
3265         --Str;
3266         break;
3267       }
3268     }
3269     return Type;
3270   }
3271   default:
3272     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3273   }
3274 }
3275 
3276 static bool isPPC_64Builtin(unsigned BuiltinID) {
3277   // These builtins only work on PPC 64bit targets.
3278   switch (BuiltinID) {
3279   case PPC::BI__builtin_divde:
3280   case PPC::BI__builtin_divdeu:
3281   case PPC::BI__builtin_bpermd:
3282   case PPC::BI__builtin_ppc_ldarx:
3283   case PPC::BI__builtin_ppc_stdcx:
3284   case PPC::BI__builtin_ppc_tdw:
3285   case PPC::BI__builtin_ppc_trapd:
3286   case PPC::BI__builtin_ppc_cmpeqb:
3287   case PPC::BI__builtin_ppc_setb:
3288   case PPC::BI__builtin_ppc_mulhd:
3289   case PPC::BI__builtin_ppc_mulhdu:
3290   case PPC::BI__builtin_ppc_maddhd:
3291   case PPC::BI__builtin_ppc_maddhdu:
3292   case PPC::BI__builtin_ppc_maddld:
3293   case PPC::BI__builtin_ppc_load8r:
3294   case PPC::BI__builtin_ppc_store8r:
3295   case PPC::BI__builtin_ppc_insert_exp:
3296   case PPC::BI__builtin_ppc_extract_sig:
3297   case PPC::BI__builtin_ppc_addex:
3298     return true;
3299   }
3300   return false;
3301 }
3302 
3303 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3304                              StringRef FeatureToCheck, unsigned DiagID,
3305                              StringRef DiagArg = "") {
3306   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3307     return false;
3308 
3309   if (DiagArg.empty())
3310     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3311   else
3312     S.Diag(TheCall->getBeginLoc(), DiagID)
3313         << DiagArg << TheCall->getSourceRange();
3314 
3315   return true;
3316 }
3317 
3318 /// Returns true if the argument consists of one contiguous run of 1s with any
3319 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3320 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3321 /// since all 1s are not contiguous.
3322 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3323   llvm::APSInt Result;
3324   // We can't check the value of a dependent argument.
3325   Expr *Arg = TheCall->getArg(ArgNum);
3326   if (Arg->isTypeDependent() || Arg->isValueDependent())
3327     return false;
3328 
3329   // Check constant-ness first.
3330   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3331     return true;
3332 
3333   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3334   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3335     return false;
3336 
3337   return Diag(TheCall->getBeginLoc(),
3338               diag::err_argument_not_contiguous_bit_field)
3339          << ArgNum << Arg->getSourceRange();
3340 }
3341 
3342 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3343                                        CallExpr *TheCall) {
3344   unsigned i = 0, l = 0, u = 0;
3345   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3346   llvm::APSInt Result;
3347 
3348   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3349     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3350            << TheCall->getSourceRange();
3351 
3352   switch (BuiltinID) {
3353   default: return false;
3354   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3355   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3356     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3357            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3358   case PPC::BI__builtin_altivec_dss:
3359     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3360   case PPC::BI__builtin_tbegin:
3361   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3362   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3363   case PPC::BI__builtin_tabortwc:
3364   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3365   case PPC::BI__builtin_tabortwci:
3366   case PPC::BI__builtin_tabortdci:
3367     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3368            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3369   case PPC::BI__builtin_altivec_dst:
3370   case PPC::BI__builtin_altivec_dstt:
3371   case PPC::BI__builtin_altivec_dstst:
3372   case PPC::BI__builtin_altivec_dststt:
3373     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3374   case PPC::BI__builtin_vsx_xxpermdi:
3375   case PPC::BI__builtin_vsx_xxsldwi:
3376     return SemaBuiltinVSX(TheCall);
3377   case PPC::BI__builtin_divwe:
3378   case PPC::BI__builtin_divweu:
3379   case PPC::BI__builtin_divde:
3380   case PPC::BI__builtin_divdeu:
3381     return SemaFeatureCheck(*this, TheCall, "extdiv",
3382                             diag::err_ppc_builtin_only_on_arch, "7");
3383   case PPC::BI__builtin_bpermd:
3384     return SemaFeatureCheck(*this, TheCall, "bpermd",
3385                             diag::err_ppc_builtin_only_on_arch, "7");
3386   case PPC::BI__builtin_unpack_vector_int128:
3387     return SemaFeatureCheck(*this, TheCall, "vsx",
3388                             diag::err_ppc_builtin_only_on_arch, "7") ||
3389            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3390   case PPC::BI__builtin_pack_vector_int128:
3391     return SemaFeatureCheck(*this, TheCall, "vsx",
3392                             diag::err_ppc_builtin_only_on_arch, "7");
3393   case PPC::BI__builtin_altivec_vgnb:
3394      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3395   case PPC::BI__builtin_altivec_vec_replace_elt:
3396   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3397     QualType VecTy = TheCall->getArg(0)->getType();
3398     QualType EltTy = TheCall->getArg(1)->getType();
3399     unsigned Width = Context.getIntWidth(EltTy);
3400     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3401            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3402   }
3403   case PPC::BI__builtin_vsx_xxeval:
3404      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3405   case PPC::BI__builtin_altivec_vsldbi:
3406      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3407   case PPC::BI__builtin_altivec_vsrdbi:
3408      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3409   case PPC::BI__builtin_vsx_xxpermx:
3410      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3411   case PPC::BI__builtin_ppc_tw:
3412   case PPC::BI__builtin_ppc_tdw:
3413     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3414   case PPC::BI__builtin_ppc_cmpeqb:
3415   case PPC::BI__builtin_ppc_setb:
3416   case PPC::BI__builtin_ppc_maddhd:
3417   case PPC::BI__builtin_ppc_maddhdu:
3418   case PPC::BI__builtin_ppc_maddld:
3419     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3420                             diag::err_ppc_builtin_only_on_arch, "9");
3421   case PPC::BI__builtin_ppc_cmprb:
3422     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3423                             diag::err_ppc_builtin_only_on_arch, "9") ||
3424            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3425   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3426   // be a constant that represents a contiguous bit field.
3427   case PPC::BI__builtin_ppc_rlwnm:
3428     return SemaBuiltinConstantArg(TheCall, 1, Result) ||
3429            SemaValueIsRunOfOnes(TheCall, 2);
3430   case PPC::BI__builtin_ppc_rlwimi:
3431   case PPC::BI__builtin_ppc_rldimi:
3432     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3433            SemaValueIsRunOfOnes(TheCall, 3);
3434   case PPC::BI__builtin_ppc_extract_exp:
3435   case PPC::BI__builtin_ppc_extract_sig:
3436   case PPC::BI__builtin_ppc_insert_exp:
3437     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3438                             diag::err_ppc_builtin_only_on_arch, "9");
3439   case PPC::BI__builtin_ppc_addex: {
3440     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3441                          diag::err_ppc_builtin_only_on_arch, "9") ||
3442         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3443       return true;
3444     // Output warning for reserved values 1 to 3.
3445     int ArgValue =
3446         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3447     if (ArgValue != 0)
3448       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3449           << ArgValue;
3450     return false;
3451   }
3452   case PPC::BI__builtin_ppc_mtfsb0:
3453   case PPC::BI__builtin_ppc_mtfsb1:
3454     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3455   case PPC::BI__builtin_ppc_mtfsf:
3456     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3457   case PPC::BI__builtin_ppc_mtfsfi:
3458     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3459            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3460   case PPC::BI__builtin_ppc_alignx:
3461     return SemaBuiltinConstantArgPower2(TheCall, 0);
3462   case PPC::BI__builtin_ppc_rdlam:
3463     return SemaValueIsRunOfOnes(TheCall, 2);
3464   case PPC::BI__builtin_ppc_icbt:
3465   case PPC::BI__builtin_ppc_sthcx:
3466   case PPC::BI__builtin_ppc_stbcx:
3467   case PPC::BI__builtin_ppc_lharx:
3468   case PPC::BI__builtin_ppc_lbarx:
3469     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3470                             diag::err_ppc_builtin_only_on_arch, "8");
3471   case PPC::BI__builtin_vsx_ldrmb:
3472   case PPC::BI__builtin_vsx_strmb:
3473     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3474                             diag::err_ppc_builtin_only_on_arch, "8") ||
3475            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3476 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3477   case PPC::BI__builtin_##Name: \
3478     return SemaBuiltinPPCMMACall(TheCall, Types);
3479 #include "clang/Basic/BuiltinsPPC.def"
3480   }
3481   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3482 }
3483 
3484 // Check if the given type is a non-pointer PPC MMA type. This function is used
3485 // in Sema to prevent invalid uses of restricted PPC MMA types.
3486 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3487   if (Type->isPointerType() || Type->isArrayType())
3488     return false;
3489 
3490   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3491 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3492   if (false
3493 #include "clang/Basic/PPCTypes.def"
3494      ) {
3495     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3496     return true;
3497   }
3498   return false;
3499 }
3500 
3501 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3502                                           CallExpr *TheCall) {
3503   // position of memory order and scope arguments in the builtin
3504   unsigned OrderIndex, ScopeIndex;
3505   switch (BuiltinID) {
3506   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3507   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3508   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3509   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3510     OrderIndex = 2;
3511     ScopeIndex = 3;
3512     break;
3513   case AMDGPU::BI__builtin_amdgcn_fence:
3514     OrderIndex = 0;
3515     ScopeIndex = 1;
3516     break;
3517   default:
3518     return false;
3519   }
3520 
3521   ExprResult Arg = TheCall->getArg(OrderIndex);
3522   auto ArgExpr = Arg.get();
3523   Expr::EvalResult ArgResult;
3524 
3525   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3526     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3527            << ArgExpr->getType();
3528   auto Ord = ArgResult.Val.getInt().getZExtValue();
3529 
3530   // Check valididty of memory ordering as per C11 / C++11's memody model.
3531   // Only fence needs check. Atomic dec/inc allow all memory orders.
3532   if (!llvm::isValidAtomicOrderingCABI(Ord))
3533     return Diag(ArgExpr->getBeginLoc(),
3534                 diag::warn_atomic_op_has_invalid_memory_order)
3535            << ArgExpr->getSourceRange();
3536   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3537   case llvm::AtomicOrderingCABI::relaxed:
3538   case llvm::AtomicOrderingCABI::consume:
3539     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3540       return Diag(ArgExpr->getBeginLoc(),
3541                   diag::warn_atomic_op_has_invalid_memory_order)
3542              << ArgExpr->getSourceRange();
3543     break;
3544   case llvm::AtomicOrderingCABI::acquire:
3545   case llvm::AtomicOrderingCABI::release:
3546   case llvm::AtomicOrderingCABI::acq_rel:
3547   case llvm::AtomicOrderingCABI::seq_cst:
3548     break;
3549   }
3550 
3551   Arg = TheCall->getArg(ScopeIndex);
3552   ArgExpr = Arg.get();
3553   Expr::EvalResult ArgResult1;
3554   // Check that sync scope is a constant literal
3555   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3556     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3557            << ArgExpr->getType();
3558 
3559   return false;
3560 }
3561 
3562 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3563   llvm::APSInt Result;
3564 
3565   // We can't check the value of a dependent argument.
3566   Expr *Arg = TheCall->getArg(ArgNum);
3567   if (Arg->isTypeDependent() || Arg->isValueDependent())
3568     return false;
3569 
3570   // Check constant-ness first.
3571   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3572     return true;
3573 
3574   int64_t Val = Result.getSExtValue();
3575   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3576     return false;
3577 
3578   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3579          << Arg->getSourceRange();
3580 }
3581 
3582 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3583                                          unsigned BuiltinID,
3584                                          CallExpr *TheCall) {
3585   // CodeGenFunction can also detect this, but this gives a better error
3586   // message.
3587   bool FeatureMissing = false;
3588   SmallVector<StringRef> ReqFeatures;
3589   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3590   Features.split(ReqFeatures, ',');
3591 
3592   // Check if each required feature is included
3593   for (StringRef F : ReqFeatures) {
3594     if (TI.hasFeature(F))
3595       continue;
3596 
3597     // If the feature is 64bit, alter the string so it will print better in
3598     // the diagnostic.
3599     if (F == "64bit")
3600       F = "RV64";
3601 
3602     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3603     F.consume_front("experimental-");
3604     std::string FeatureStr = F.str();
3605     FeatureStr[0] = std::toupper(FeatureStr[0]);
3606 
3607     // Error message
3608     FeatureMissing = true;
3609     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3610         << TheCall->getSourceRange() << StringRef(FeatureStr);
3611   }
3612 
3613   if (FeatureMissing)
3614     return true;
3615 
3616   switch (BuiltinID) {
3617   case RISCV::BI__builtin_rvv_vsetvli:
3618     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3619            CheckRISCVLMUL(TheCall, 2);
3620   case RISCV::BI__builtin_rvv_vsetvlimax:
3621     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3622            CheckRISCVLMUL(TheCall, 1);
3623   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3624   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3625   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3626   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3627   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3628   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3629   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3630   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3631   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3632   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3633   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3634   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3635   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3636   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3637   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3638   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3639   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3640   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3641   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3642   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3643   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3644   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3645   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3646   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3647   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3648   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3649   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3650   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3651   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3652   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3653     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3654   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3655   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3656   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3657   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3658   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3659   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3660   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3661   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3662   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3663   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3664   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3665   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3666   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3667   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3668   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3669   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3670   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3671   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3672   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3673   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3674     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3675   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3676   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3677   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3678   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3679   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3680   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3681   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3682   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3683   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3684   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3685     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3686   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3687   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3688   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3689   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3690   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3691   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3692   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3693   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3694   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3695   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3696   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3697   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3698   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3699   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3700   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3701   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3702   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3703   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3704   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3705   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3706   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3707   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3708   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3709   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3710   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3711   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3712   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3713   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3714   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3715   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3716     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3717   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3718   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3719   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3720   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3721   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3722   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3723   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3724   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3725   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3726   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3727   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3728   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3729   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3730   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3731   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3732   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3733   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3734   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3735   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3736   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3737     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3738   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3739   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3740   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3741   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3742   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3743   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3744   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3745   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3746   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3747   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3748     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3749   }
3750 
3751   return false;
3752 }
3753 
3754 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3755                                            CallExpr *TheCall) {
3756   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3757     Expr *Arg = TheCall->getArg(0);
3758     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3759       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3760         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3761                << Arg->getSourceRange();
3762   }
3763 
3764   // For intrinsics which take an immediate value as part of the instruction,
3765   // range check them here.
3766   unsigned i = 0, l = 0, u = 0;
3767   switch (BuiltinID) {
3768   default: return false;
3769   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3770   case SystemZ::BI__builtin_s390_verimb:
3771   case SystemZ::BI__builtin_s390_verimh:
3772   case SystemZ::BI__builtin_s390_verimf:
3773   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3774   case SystemZ::BI__builtin_s390_vfaeb:
3775   case SystemZ::BI__builtin_s390_vfaeh:
3776   case SystemZ::BI__builtin_s390_vfaef:
3777   case SystemZ::BI__builtin_s390_vfaebs:
3778   case SystemZ::BI__builtin_s390_vfaehs:
3779   case SystemZ::BI__builtin_s390_vfaefs:
3780   case SystemZ::BI__builtin_s390_vfaezb:
3781   case SystemZ::BI__builtin_s390_vfaezh:
3782   case SystemZ::BI__builtin_s390_vfaezf:
3783   case SystemZ::BI__builtin_s390_vfaezbs:
3784   case SystemZ::BI__builtin_s390_vfaezhs:
3785   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3786   case SystemZ::BI__builtin_s390_vfisb:
3787   case SystemZ::BI__builtin_s390_vfidb:
3788     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3789            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3790   case SystemZ::BI__builtin_s390_vftcisb:
3791   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3792   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3793   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3794   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3795   case SystemZ::BI__builtin_s390_vstrcb:
3796   case SystemZ::BI__builtin_s390_vstrch:
3797   case SystemZ::BI__builtin_s390_vstrcf:
3798   case SystemZ::BI__builtin_s390_vstrczb:
3799   case SystemZ::BI__builtin_s390_vstrczh:
3800   case SystemZ::BI__builtin_s390_vstrczf:
3801   case SystemZ::BI__builtin_s390_vstrcbs:
3802   case SystemZ::BI__builtin_s390_vstrchs:
3803   case SystemZ::BI__builtin_s390_vstrcfs:
3804   case SystemZ::BI__builtin_s390_vstrczbs:
3805   case SystemZ::BI__builtin_s390_vstrczhs:
3806   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3807   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3808   case SystemZ::BI__builtin_s390_vfminsb:
3809   case SystemZ::BI__builtin_s390_vfmaxsb:
3810   case SystemZ::BI__builtin_s390_vfmindb:
3811   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3812   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3813   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3814   case SystemZ::BI__builtin_s390_vclfnhs:
3815   case SystemZ::BI__builtin_s390_vclfnls:
3816   case SystemZ::BI__builtin_s390_vcfn:
3817   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3818   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3819   }
3820   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3821 }
3822 
3823 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3824 /// This checks that the target supports __builtin_cpu_supports and
3825 /// that the string argument is constant and valid.
3826 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3827                                    CallExpr *TheCall) {
3828   Expr *Arg = TheCall->getArg(0);
3829 
3830   // Check if the argument is a string literal.
3831   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3832     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3833            << Arg->getSourceRange();
3834 
3835   // Check the contents of the string.
3836   StringRef Feature =
3837       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3838   if (!TI.validateCpuSupports(Feature))
3839     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3840            << Arg->getSourceRange();
3841   return false;
3842 }
3843 
3844 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3845 /// This checks that the target supports __builtin_cpu_is and
3846 /// that the string argument is constant and valid.
3847 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3848   Expr *Arg = TheCall->getArg(0);
3849 
3850   // Check if the argument is a string literal.
3851   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3852     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3853            << Arg->getSourceRange();
3854 
3855   // Check the contents of the string.
3856   StringRef Feature =
3857       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3858   if (!TI.validateCpuIs(Feature))
3859     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3860            << Arg->getSourceRange();
3861   return false;
3862 }
3863 
3864 // Check if the rounding mode is legal.
3865 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3866   // Indicates if this instruction has rounding control or just SAE.
3867   bool HasRC = false;
3868 
3869   unsigned ArgNum = 0;
3870   switch (BuiltinID) {
3871   default:
3872     return false;
3873   case X86::BI__builtin_ia32_vcvttsd2si32:
3874   case X86::BI__builtin_ia32_vcvttsd2si64:
3875   case X86::BI__builtin_ia32_vcvttsd2usi32:
3876   case X86::BI__builtin_ia32_vcvttsd2usi64:
3877   case X86::BI__builtin_ia32_vcvttss2si32:
3878   case X86::BI__builtin_ia32_vcvttss2si64:
3879   case X86::BI__builtin_ia32_vcvttss2usi32:
3880   case X86::BI__builtin_ia32_vcvttss2usi64:
3881   case X86::BI__builtin_ia32_vcvttsh2si32:
3882   case X86::BI__builtin_ia32_vcvttsh2si64:
3883   case X86::BI__builtin_ia32_vcvttsh2usi32:
3884   case X86::BI__builtin_ia32_vcvttsh2usi64:
3885     ArgNum = 1;
3886     break;
3887   case X86::BI__builtin_ia32_maxpd512:
3888   case X86::BI__builtin_ia32_maxps512:
3889   case X86::BI__builtin_ia32_minpd512:
3890   case X86::BI__builtin_ia32_minps512:
3891   case X86::BI__builtin_ia32_maxph512:
3892   case X86::BI__builtin_ia32_minph512:
3893     ArgNum = 2;
3894     break;
3895   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3896   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3897   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3898   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3899   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3900   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3901   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3902   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3903   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3904   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3905   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3906   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3907   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3908   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3909   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3910   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3911   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3912   case X86::BI__builtin_ia32_exp2pd_mask:
3913   case X86::BI__builtin_ia32_exp2ps_mask:
3914   case X86::BI__builtin_ia32_getexppd512_mask:
3915   case X86::BI__builtin_ia32_getexpps512_mask:
3916   case X86::BI__builtin_ia32_getexpph512_mask:
3917   case X86::BI__builtin_ia32_rcp28pd_mask:
3918   case X86::BI__builtin_ia32_rcp28ps_mask:
3919   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3920   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3921   case X86::BI__builtin_ia32_vcomisd:
3922   case X86::BI__builtin_ia32_vcomiss:
3923   case X86::BI__builtin_ia32_vcomish:
3924   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3925     ArgNum = 3;
3926     break;
3927   case X86::BI__builtin_ia32_cmppd512_mask:
3928   case X86::BI__builtin_ia32_cmpps512_mask:
3929   case X86::BI__builtin_ia32_cmpsd_mask:
3930   case X86::BI__builtin_ia32_cmpss_mask:
3931   case X86::BI__builtin_ia32_cmpsh_mask:
3932   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3933   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3934   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3935   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3936   case X86::BI__builtin_ia32_getexpss128_round_mask:
3937   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3938   case X86::BI__builtin_ia32_getmantpd512_mask:
3939   case X86::BI__builtin_ia32_getmantps512_mask:
3940   case X86::BI__builtin_ia32_getmantph512_mask:
3941   case X86::BI__builtin_ia32_maxsd_round_mask:
3942   case X86::BI__builtin_ia32_maxss_round_mask:
3943   case X86::BI__builtin_ia32_maxsh_round_mask:
3944   case X86::BI__builtin_ia32_minsd_round_mask:
3945   case X86::BI__builtin_ia32_minss_round_mask:
3946   case X86::BI__builtin_ia32_minsh_round_mask:
3947   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3948   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3949   case X86::BI__builtin_ia32_reducepd512_mask:
3950   case X86::BI__builtin_ia32_reduceps512_mask:
3951   case X86::BI__builtin_ia32_reduceph512_mask:
3952   case X86::BI__builtin_ia32_rndscalepd_mask:
3953   case X86::BI__builtin_ia32_rndscaleps_mask:
3954   case X86::BI__builtin_ia32_rndscaleph_mask:
3955   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3956   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3957     ArgNum = 4;
3958     break;
3959   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3960   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3961   case X86::BI__builtin_ia32_fixupimmps512_mask:
3962   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3963   case X86::BI__builtin_ia32_fixupimmsd_mask:
3964   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3965   case X86::BI__builtin_ia32_fixupimmss_mask:
3966   case X86::BI__builtin_ia32_fixupimmss_maskz:
3967   case X86::BI__builtin_ia32_getmantsd_round_mask:
3968   case X86::BI__builtin_ia32_getmantss_round_mask:
3969   case X86::BI__builtin_ia32_getmantsh_round_mask:
3970   case X86::BI__builtin_ia32_rangepd512_mask:
3971   case X86::BI__builtin_ia32_rangeps512_mask:
3972   case X86::BI__builtin_ia32_rangesd128_round_mask:
3973   case X86::BI__builtin_ia32_rangess128_round_mask:
3974   case X86::BI__builtin_ia32_reducesd_mask:
3975   case X86::BI__builtin_ia32_reducess_mask:
3976   case X86::BI__builtin_ia32_reducesh_mask:
3977   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3978   case X86::BI__builtin_ia32_rndscaless_round_mask:
3979   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3980     ArgNum = 5;
3981     break;
3982   case X86::BI__builtin_ia32_vcvtsd2si64:
3983   case X86::BI__builtin_ia32_vcvtsd2si32:
3984   case X86::BI__builtin_ia32_vcvtsd2usi32:
3985   case X86::BI__builtin_ia32_vcvtsd2usi64:
3986   case X86::BI__builtin_ia32_vcvtss2si32:
3987   case X86::BI__builtin_ia32_vcvtss2si64:
3988   case X86::BI__builtin_ia32_vcvtss2usi32:
3989   case X86::BI__builtin_ia32_vcvtss2usi64:
3990   case X86::BI__builtin_ia32_vcvtsh2si32:
3991   case X86::BI__builtin_ia32_vcvtsh2si64:
3992   case X86::BI__builtin_ia32_vcvtsh2usi32:
3993   case X86::BI__builtin_ia32_vcvtsh2usi64:
3994   case X86::BI__builtin_ia32_sqrtpd512:
3995   case X86::BI__builtin_ia32_sqrtps512:
3996   case X86::BI__builtin_ia32_sqrtph512:
3997     ArgNum = 1;
3998     HasRC = true;
3999     break;
4000   case X86::BI__builtin_ia32_addph512:
4001   case X86::BI__builtin_ia32_divph512:
4002   case X86::BI__builtin_ia32_mulph512:
4003   case X86::BI__builtin_ia32_subph512:
4004   case X86::BI__builtin_ia32_addpd512:
4005   case X86::BI__builtin_ia32_addps512:
4006   case X86::BI__builtin_ia32_divpd512:
4007   case X86::BI__builtin_ia32_divps512:
4008   case X86::BI__builtin_ia32_mulpd512:
4009   case X86::BI__builtin_ia32_mulps512:
4010   case X86::BI__builtin_ia32_subpd512:
4011   case X86::BI__builtin_ia32_subps512:
4012   case X86::BI__builtin_ia32_cvtsi2sd64:
4013   case X86::BI__builtin_ia32_cvtsi2ss32:
4014   case X86::BI__builtin_ia32_cvtsi2ss64:
4015   case X86::BI__builtin_ia32_cvtusi2sd64:
4016   case X86::BI__builtin_ia32_cvtusi2ss32:
4017   case X86::BI__builtin_ia32_cvtusi2ss64:
4018   case X86::BI__builtin_ia32_vcvtusi2sh:
4019   case X86::BI__builtin_ia32_vcvtusi642sh:
4020   case X86::BI__builtin_ia32_vcvtsi2sh:
4021   case X86::BI__builtin_ia32_vcvtsi642sh:
4022     ArgNum = 2;
4023     HasRC = true;
4024     break;
4025   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4026   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4027   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4028   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4029   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4030   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4031   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4032   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4033   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4034   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4035   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4036   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4037   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4038   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4039   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4040   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4041   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4042   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4043   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4044   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4045   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4046   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4047   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4048   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4049   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4050   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4051   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4052   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4053   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4054     ArgNum = 3;
4055     HasRC = true;
4056     break;
4057   case X86::BI__builtin_ia32_addsh_round_mask:
4058   case X86::BI__builtin_ia32_addss_round_mask:
4059   case X86::BI__builtin_ia32_addsd_round_mask:
4060   case X86::BI__builtin_ia32_divsh_round_mask:
4061   case X86::BI__builtin_ia32_divss_round_mask:
4062   case X86::BI__builtin_ia32_divsd_round_mask:
4063   case X86::BI__builtin_ia32_mulsh_round_mask:
4064   case X86::BI__builtin_ia32_mulss_round_mask:
4065   case X86::BI__builtin_ia32_mulsd_round_mask:
4066   case X86::BI__builtin_ia32_subsh_round_mask:
4067   case X86::BI__builtin_ia32_subss_round_mask:
4068   case X86::BI__builtin_ia32_subsd_round_mask:
4069   case X86::BI__builtin_ia32_scalefph512_mask:
4070   case X86::BI__builtin_ia32_scalefpd512_mask:
4071   case X86::BI__builtin_ia32_scalefps512_mask:
4072   case X86::BI__builtin_ia32_scalefsd_round_mask:
4073   case X86::BI__builtin_ia32_scalefss_round_mask:
4074   case X86::BI__builtin_ia32_scalefsh_round_mask:
4075   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4076   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4077   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4078   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4079   case X86::BI__builtin_ia32_sqrtss_round_mask:
4080   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4081   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4082   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4083   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4084   case X86::BI__builtin_ia32_vfmaddss3_mask:
4085   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4086   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4087   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4088   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4089   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4090   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4091   case X86::BI__builtin_ia32_vfmaddps512_mask:
4092   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4093   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4094   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4095   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4096   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4097   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4098   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4099   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4100   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4101   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4102   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4103     ArgNum = 4;
4104     HasRC = true;
4105     break;
4106   }
4107 
4108   llvm::APSInt Result;
4109 
4110   // We can't check the value of a dependent argument.
4111   Expr *Arg = TheCall->getArg(ArgNum);
4112   if (Arg->isTypeDependent() || Arg->isValueDependent())
4113     return false;
4114 
4115   // Check constant-ness first.
4116   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4117     return true;
4118 
4119   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4120   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4121   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4122   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4123   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4124       Result == 8/*ROUND_NO_EXC*/ ||
4125       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4126       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4127     return false;
4128 
4129   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4130          << Arg->getSourceRange();
4131 }
4132 
4133 // Check if the gather/scatter scale is legal.
4134 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4135                                              CallExpr *TheCall) {
4136   unsigned ArgNum = 0;
4137   switch (BuiltinID) {
4138   default:
4139     return false;
4140   case X86::BI__builtin_ia32_gatherpfdpd:
4141   case X86::BI__builtin_ia32_gatherpfdps:
4142   case X86::BI__builtin_ia32_gatherpfqpd:
4143   case X86::BI__builtin_ia32_gatherpfqps:
4144   case X86::BI__builtin_ia32_scatterpfdpd:
4145   case X86::BI__builtin_ia32_scatterpfdps:
4146   case X86::BI__builtin_ia32_scatterpfqpd:
4147   case X86::BI__builtin_ia32_scatterpfqps:
4148     ArgNum = 3;
4149     break;
4150   case X86::BI__builtin_ia32_gatherd_pd:
4151   case X86::BI__builtin_ia32_gatherd_pd256:
4152   case X86::BI__builtin_ia32_gatherq_pd:
4153   case X86::BI__builtin_ia32_gatherq_pd256:
4154   case X86::BI__builtin_ia32_gatherd_ps:
4155   case X86::BI__builtin_ia32_gatherd_ps256:
4156   case X86::BI__builtin_ia32_gatherq_ps:
4157   case X86::BI__builtin_ia32_gatherq_ps256:
4158   case X86::BI__builtin_ia32_gatherd_q:
4159   case X86::BI__builtin_ia32_gatherd_q256:
4160   case X86::BI__builtin_ia32_gatherq_q:
4161   case X86::BI__builtin_ia32_gatherq_q256:
4162   case X86::BI__builtin_ia32_gatherd_d:
4163   case X86::BI__builtin_ia32_gatherd_d256:
4164   case X86::BI__builtin_ia32_gatherq_d:
4165   case X86::BI__builtin_ia32_gatherq_d256:
4166   case X86::BI__builtin_ia32_gather3div2df:
4167   case X86::BI__builtin_ia32_gather3div2di:
4168   case X86::BI__builtin_ia32_gather3div4df:
4169   case X86::BI__builtin_ia32_gather3div4di:
4170   case X86::BI__builtin_ia32_gather3div4sf:
4171   case X86::BI__builtin_ia32_gather3div4si:
4172   case X86::BI__builtin_ia32_gather3div8sf:
4173   case X86::BI__builtin_ia32_gather3div8si:
4174   case X86::BI__builtin_ia32_gather3siv2df:
4175   case X86::BI__builtin_ia32_gather3siv2di:
4176   case X86::BI__builtin_ia32_gather3siv4df:
4177   case X86::BI__builtin_ia32_gather3siv4di:
4178   case X86::BI__builtin_ia32_gather3siv4sf:
4179   case X86::BI__builtin_ia32_gather3siv4si:
4180   case X86::BI__builtin_ia32_gather3siv8sf:
4181   case X86::BI__builtin_ia32_gather3siv8si:
4182   case X86::BI__builtin_ia32_gathersiv8df:
4183   case X86::BI__builtin_ia32_gathersiv16sf:
4184   case X86::BI__builtin_ia32_gatherdiv8df:
4185   case X86::BI__builtin_ia32_gatherdiv16sf:
4186   case X86::BI__builtin_ia32_gathersiv8di:
4187   case X86::BI__builtin_ia32_gathersiv16si:
4188   case X86::BI__builtin_ia32_gatherdiv8di:
4189   case X86::BI__builtin_ia32_gatherdiv16si:
4190   case X86::BI__builtin_ia32_scatterdiv2df:
4191   case X86::BI__builtin_ia32_scatterdiv2di:
4192   case X86::BI__builtin_ia32_scatterdiv4df:
4193   case X86::BI__builtin_ia32_scatterdiv4di:
4194   case X86::BI__builtin_ia32_scatterdiv4sf:
4195   case X86::BI__builtin_ia32_scatterdiv4si:
4196   case X86::BI__builtin_ia32_scatterdiv8sf:
4197   case X86::BI__builtin_ia32_scatterdiv8si:
4198   case X86::BI__builtin_ia32_scattersiv2df:
4199   case X86::BI__builtin_ia32_scattersiv2di:
4200   case X86::BI__builtin_ia32_scattersiv4df:
4201   case X86::BI__builtin_ia32_scattersiv4di:
4202   case X86::BI__builtin_ia32_scattersiv4sf:
4203   case X86::BI__builtin_ia32_scattersiv4si:
4204   case X86::BI__builtin_ia32_scattersiv8sf:
4205   case X86::BI__builtin_ia32_scattersiv8si:
4206   case X86::BI__builtin_ia32_scattersiv8df:
4207   case X86::BI__builtin_ia32_scattersiv16sf:
4208   case X86::BI__builtin_ia32_scatterdiv8df:
4209   case X86::BI__builtin_ia32_scatterdiv16sf:
4210   case X86::BI__builtin_ia32_scattersiv8di:
4211   case X86::BI__builtin_ia32_scattersiv16si:
4212   case X86::BI__builtin_ia32_scatterdiv8di:
4213   case X86::BI__builtin_ia32_scatterdiv16si:
4214     ArgNum = 4;
4215     break;
4216   }
4217 
4218   llvm::APSInt Result;
4219 
4220   // We can't check the value of a dependent argument.
4221   Expr *Arg = TheCall->getArg(ArgNum);
4222   if (Arg->isTypeDependent() || Arg->isValueDependent())
4223     return false;
4224 
4225   // Check constant-ness first.
4226   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4227     return true;
4228 
4229   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4230     return false;
4231 
4232   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4233          << Arg->getSourceRange();
4234 }
4235 
4236 enum { TileRegLow = 0, TileRegHigh = 7 };
4237 
4238 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4239                                              ArrayRef<int> ArgNums) {
4240   for (int ArgNum : ArgNums) {
4241     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4242       return true;
4243   }
4244   return false;
4245 }
4246 
4247 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4248                                         ArrayRef<int> ArgNums) {
4249   // Because the max number of tile register is TileRegHigh + 1, so here we use
4250   // each bit to represent the usage of them in bitset.
4251   std::bitset<TileRegHigh + 1> ArgValues;
4252   for (int ArgNum : ArgNums) {
4253     Expr *Arg = TheCall->getArg(ArgNum);
4254     if (Arg->isTypeDependent() || Arg->isValueDependent())
4255       continue;
4256 
4257     llvm::APSInt Result;
4258     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4259       return true;
4260     int ArgExtValue = Result.getExtValue();
4261     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4262            "Incorrect tile register num.");
4263     if (ArgValues.test(ArgExtValue))
4264       return Diag(TheCall->getBeginLoc(),
4265                   diag::err_x86_builtin_tile_arg_duplicate)
4266              << TheCall->getArg(ArgNum)->getSourceRange();
4267     ArgValues.set(ArgExtValue);
4268   }
4269   return false;
4270 }
4271 
4272 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4273                                                 ArrayRef<int> ArgNums) {
4274   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4275          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4276 }
4277 
4278 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4279   switch (BuiltinID) {
4280   default:
4281     return false;
4282   case X86::BI__builtin_ia32_tileloadd64:
4283   case X86::BI__builtin_ia32_tileloaddt164:
4284   case X86::BI__builtin_ia32_tilestored64:
4285   case X86::BI__builtin_ia32_tilezero:
4286     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4287   case X86::BI__builtin_ia32_tdpbssd:
4288   case X86::BI__builtin_ia32_tdpbsud:
4289   case X86::BI__builtin_ia32_tdpbusd:
4290   case X86::BI__builtin_ia32_tdpbuud:
4291   case X86::BI__builtin_ia32_tdpbf16ps:
4292     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4293   }
4294 }
4295 static bool isX86_32Builtin(unsigned BuiltinID) {
4296   // These builtins only work on x86-32 targets.
4297   switch (BuiltinID) {
4298   case X86::BI__builtin_ia32_readeflags_u32:
4299   case X86::BI__builtin_ia32_writeeflags_u32:
4300     return true;
4301   }
4302 
4303   return false;
4304 }
4305 
4306 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4307                                        CallExpr *TheCall) {
4308   if (BuiltinID == X86::BI__builtin_cpu_supports)
4309     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4310 
4311   if (BuiltinID == X86::BI__builtin_cpu_is)
4312     return SemaBuiltinCpuIs(*this, TI, TheCall);
4313 
4314   // Check for 32-bit only builtins on a 64-bit target.
4315   const llvm::Triple &TT = TI.getTriple();
4316   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4317     return Diag(TheCall->getCallee()->getBeginLoc(),
4318                 diag::err_32_bit_builtin_64_bit_tgt);
4319 
4320   // If the intrinsic has rounding or SAE make sure its valid.
4321   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4322     return true;
4323 
4324   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4325   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4326     return true;
4327 
4328   // If the intrinsic has a tile arguments, make sure they are valid.
4329   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4330     return true;
4331 
4332   // For intrinsics which take an immediate value as part of the instruction,
4333   // range check them here.
4334   int i = 0, l = 0, u = 0;
4335   switch (BuiltinID) {
4336   default:
4337     return false;
4338   case X86::BI__builtin_ia32_vec_ext_v2si:
4339   case X86::BI__builtin_ia32_vec_ext_v2di:
4340   case X86::BI__builtin_ia32_vextractf128_pd256:
4341   case X86::BI__builtin_ia32_vextractf128_ps256:
4342   case X86::BI__builtin_ia32_vextractf128_si256:
4343   case X86::BI__builtin_ia32_extract128i256:
4344   case X86::BI__builtin_ia32_extractf64x4_mask:
4345   case X86::BI__builtin_ia32_extracti64x4_mask:
4346   case X86::BI__builtin_ia32_extractf32x8_mask:
4347   case X86::BI__builtin_ia32_extracti32x8_mask:
4348   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4349   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4350   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4351   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4352     i = 1; l = 0; u = 1;
4353     break;
4354   case X86::BI__builtin_ia32_vec_set_v2di:
4355   case X86::BI__builtin_ia32_vinsertf128_pd256:
4356   case X86::BI__builtin_ia32_vinsertf128_ps256:
4357   case X86::BI__builtin_ia32_vinsertf128_si256:
4358   case X86::BI__builtin_ia32_insert128i256:
4359   case X86::BI__builtin_ia32_insertf32x8:
4360   case X86::BI__builtin_ia32_inserti32x8:
4361   case X86::BI__builtin_ia32_insertf64x4:
4362   case X86::BI__builtin_ia32_inserti64x4:
4363   case X86::BI__builtin_ia32_insertf64x2_256:
4364   case X86::BI__builtin_ia32_inserti64x2_256:
4365   case X86::BI__builtin_ia32_insertf32x4_256:
4366   case X86::BI__builtin_ia32_inserti32x4_256:
4367     i = 2; l = 0; u = 1;
4368     break;
4369   case X86::BI__builtin_ia32_vpermilpd:
4370   case X86::BI__builtin_ia32_vec_ext_v4hi:
4371   case X86::BI__builtin_ia32_vec_ext_v4si:
4372   case X86::BI__builtin_ia32_vec_ext_v4sf:
4373   case X86::BI__builtin_ia32_vec_ext_v4di:
4374   case X86::BI__builtin_ia32_extractf32x4_mask:
4375   case X86::BI__builtin_ia32_extracti32x4_mask:
4376   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4377   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4378     i = 1; l = 0; u = 3;
4379     break;
4380   case X86::BI_mm_prefetch:
4381   case X86::BI__builtin_ia32_vec_ext_v8hi:
4382   case X86::BI__builtin_ia32_vec_ext_v8si:
4383     i = 1; l = 0; u = 7;
4384     break;
4385   case X86::BI__builtin_ia32_sha1rnds4:
4386   case X86::BI__builtin_ia32_blendpd:
4387   case X86::BI__builtin_ia32_shufpd:
4388   case X86::BI__builtin_ia32_vec_set_v4hi:
4389   case X86::BI__builtin_ia32_vec_set_v4si:
4390   case X86::BI__builtin_ia32_vec_set_v4di:
4391   case X86::BI__builtin_ia32_shuf_f32x4_256:
4392   case X86::BI__builtin_ia32_shuf_f64x2_256:
4393   case X86::BI__builtin_ia32_shuf_i32x4_256:
4394   case X86::BI__builtin_ia32_shuf_i64x2_256:
4395   case X86::BI__builtin_ia32_insertf64x2_512:
4396   case X86::BI__builtin_ia32_inserti64x2_512:
4397   case X86::BI__builtin_ia32_insertf32x4:
4398   case X86::BI__builtin_ia32_inserti32x4:
4399     i = 2; l = 0; u = 3;
4400     break;
4401   case X86::BI__builtin_ia32_vpermil2pd:
4402   case X86::BI__builtin_ia32_vpermil2pd256:
4403   case X86::BI__builtin_ia32_vpermil2ps:
4404   case X86::BI__builtin_ia32_vpermil2ps256:
4405     i = 3; l = 0; u = 3;
4406     break;
4407   case X86::BI__builtin_ia32_cmpb128_mask:
4408   case X86::BI__builtin_ia32_cmpw128_mask:
4409   case X86::BI__builtin_ia32_cmpd128_mask:
4410   case X86::BI__builtin_ia32_cmpq128_mask:
4411   case X86::BI__builtin_ia32_cmpb256_mask:
4412   case X86::BI__builtin_ia32_cmpw256_mask:
4413   case X86::BI__builtin_ia32_cmpd256_mask:
4414   case X86::BI__builtin_ia32_cmpq256_mask:
4415   case X86::BI__builtin_ia32_cmpb512_mask:
4416   case X86::BI__builtin_ia32_cmpw512_mask:
4417   case X86::BI__builtin_ia32_cmpd512_mask:
4418   case X86::BI__builtin_ia32_cmpq512_mask:
4419   case X86::BI__builtin_ia32_ucmpb128_mask:
4420   case X86::BI__builtin_ia32_ucmpw128_mask:
4421   case X86::BI__builtin_ia32_ucmpd128_mask:
4422   case X86::BI__builtin_ia32_ucmpq128_mask:
4423   case X86::BI__builtin_ia32_ucmpb256_mask:
4424   case X86::BI__builtin_ia32_ucmpw256_mask:
4425   case X86::BI__builtin_ia32_ucmpd256_mask:
4426   case X86::BI__builtin_ia32_ucmpq256_mask:
4427   case X86::BI__builtin_ia32_ucmpb512_mask:
4428   case X86::BI__builtin_ia32_ucmpw512_mask:
4429   case X86::BI__builtin_ia32_ucmpd512_mask:
4430   case X86::BI__builtin_ia32_ucmpq512_mask:
4431   case X86::BI__builtin_ia32_vpcomub:
4432   case X86::BI__builtin_ia32_vpcomuw:
4433   case X86::BI__builtin_ia32_vpcomud:
4434   case X86::BI__builtin_ia32_vpcomuq:
4435   case X86::BI__builtin_ia32_vpcomb:
4436   case X86::BI__builtin_ia32_vpcomw:
4437   case X86::BI__builtin_ia32_vpcomd:
4438   case X86::BI__builtin_ia32_vpcomq:
4439   case X86::BI__builtin_ia32_vec_set_v8hi:
4440   case X86::BI__builtin_ia32_vec_set_v8si:
4441     i = 2; l = 0; u = 7;
4442     break;
4443   case X86::BI__builtin_ia32_vpermilpd256:
4444   case X86::BI__builtin_ia32_roundps:
4445   case X86::BI__builtin_ia32_roundpd:
4446   case X86::BI__builtin_ia32_roundps256:
4447   case X86::BI__builtin_ia32_roundpd256:
4448   case X86::BI__builtin_ia32_getmantpd128_mask:
4449   case X86::BI__builtin_ia32_getmantpd256_mask:
4450   case X86::BI__builtin_ia32_getmantps128_mask:
4451   case X86::BI__builtin_ia32_getmantps256_mask:
4452   case X86::BI__builtin_ia32_getmantpd512_mask:
4453   case X86::BI__builtin_ia32_getmantps512_mask:
4454   case X86::BI__builtin_ia32_getmantph128_mask:
4455   case X86::BI__builtin_ia32_getmantph256_mask:
4456   case X86::BI__builtin_ia32_getmantph512_mask:
4457   case X86::BI__builtin_ia32_vec_ext_v16qi:
4458   case X86::BI__builtin_ia32_vec_ext_v16hi:
4459     i = 1; l = 0; u = 15;
4460     break;
4461   case X86::BI__builtin_ia32_pblendd128:
4462   case X86::BI__builtin_ia32_blendps:
4463   case X86::BI__builtin_ia32_blendpd256:
4464   case X86::BI__builtin_ia32_shufpd256:
4465   case X86::BI__builtin_ia32_roundss:
4466   case X86::BI__builtin_ia32_roundsd:
4467   case X86::BI__builtin_ia32_rangepd128_mask:
4468   case X86::BI__builtin_ia32_rangepd256_mask:
4469   case X86::BI__builtin_ia32_rangepd512_mask:
4470   case X86::BI__builtin_ia32_rangeps128_mask:
4471   case X86::BI__builtin_ia32_rangeps256_mask:
4472   case X86::BI__builtin_ia32_rangeps512_mask:
4473   case X86::BI__builtin_ia32_getmantsd_round_mask:
4474   case X86::BI__builtin_ia32_getmantss_round_mask:
4475   case X86::BI__builtin_ia32_getmantsh_round_mask:
4476   case X86::BI__builtin_ia32_vec_set_v16qi:
4477   case X86::BI__builtin_ia32_vec_set_v16hi:
4478     i = 2; l = 0; u = 15;
4479     break;
4480   case X86::BI__builtin_ia32_vec_ext_v32qi:
4481     i = 1; l = 0; u = 31;
4482     break;
4483   case X86::BI__builtin_ia32_cmpps:
4484   case X86::BI__builtin_ia32_cmpss:
4485   case X86::BI__builtin_ia32_cmppd:
4486   case X86::BI__builtin_ia32_cmpsd:
4487   case X86::BI__builtin_ia32_cmpps256:
4488   case X86::BI__builtin_ia32_cmppd256:
4489   case X86::BI__builtin_ia32_cmpps128_mask:
4490   case X86::BI__builtin_ia32_cmppd128_mask:
4491   case X86::BI__builtin_ia32_cmpps256_mask:
4492   case X86::BI__builtin_ia32_cmppd256_mask:
4493   case X86::BI__builtin_ia32_cmpps512_mask:
4494   case X86::BI__builtin_ia32_cmppd512_mask:
4495   case X86::BI__builtin_ia32_cmpsd_mask:
4496   case X86::BI__builtin_ia32_cmpss_mask:
4497   case X86::BI__builtin_ia32_vec_set_v32qi:
4498     i = 2; l = 0; u = 31;
4499     break;
4500   case X86::BI__builtin_ia32_permdf256:
4501   case X86::BI__builtin_ia32_permdi256:
4502   case X86::BI__builtin_ia32_permdf512:
4503   case X86::BI__builtin_ia32_permdi512:
4504   case X86::BI__builtin_ia32_vpermilps:
4505   case X86::BI__builtin_ia32_vpermilps256:
4506   case X86::BI__builtin_ia32_vpermilpd512:
4507   case X86::BI__builtin_ia32_vpermilps512:
4508   case X86::BI__builtin_ia32_pshufd:
4509   case X86::BI__builtin_ia32_pshufd256:
4510   case X86::BI__builtin_ia32_pshufd512:
4511   case X86::BI__builtin_ia32_pshufhw:
4512   case X86::BI__builtin_ia32_pshufhw256:
4513   case X86::BI__builtin_ia32_pshufhw512:
4514   case X86::BI__builtin_ia32_pshuflw:
4515   case X86::BI__builtin_ia32_pshuflw256:
4516   case X86::BI__builtin_ia32_pshuflw512:
4517   case X86::BI__builtin_ia32_vcvtps2ph:
4518   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4519   case X86::BI__builtin_ia32_vcvtps2ph256:
4520   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4521   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4522   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4523   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4524   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4525   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4526   case X86::BI__builtin_ia32_rndscaleps_mask:
4527   case X86::BI__builtin_ia32_rndscalepd_mask:
4528   case X86::BI__builtin_ia32_rndscaleph_mask:
4529   case X86::BI__builtin_ia32_reducepd128_mask:
4530   case X86::BI__builtin_ia32_reducepd256_mask:
4531   case X86::BI__builtin_ia32_reducepd512_mask:
4532   case X86::BI__builtin_ia32_reduceps128_mask:
4533   case X86::BI__builtin_ia32_reduceps256_mask:
4534   case X86::BI__builtin_ia32_reduceps512_mask:
4535   case X86::BI__builtin_ia32_reduceph128_mask:
4536   case X86::BI__builtin_ia32_reduceph256_mask:
4537   case X86::BI__builtin_ia32_reduceph512_mask:
4538   case X86::BI__builtin_ia32_prold512:
4539   case X86::BI__builtin_ia32_prolq512:
4540   case X86::BI__builtin_ia32_prold128:
4541   case X86::BI__builtin_ia32_prold256:
4542   case X86::BI__builtin_ia32_prolq128:
4543   case X86::BI__builtin_ia32_prolq256:
4544   case X86::BI__builtin_ia32_prord512:
4545   case X86::BI__builtin_ia32_prorq512:
4546   case X86::BI__builtin_ia32_prord128:
4547   case X86::BI__builtin_ia32_prord256:
4548   case X86::BI__builtin_ia32_prorq128:
4549   case X86::BI__builtin_ia32_prorq256:
4550   case X86::BI__builtin_ia32_fpclasspd128_mask:
4551   case X86::BI__builtin_ia32_fpclasspd256_mask:
4552   case X86::BI__builtin_ia32_fpclassps128_mask:
4553   case X86::BI__builtin_ia32_fpclassps256_mask:
4554   case X86::BI__builtin_ia32_fpclassps512_mask:
4555   case X86::BI__builtin_ia32_fpclasspd512_mask:
4556   case X86::BI__builtin_ia32_fpclassph128_mask:
4557   case X86::BI__builtin_ia32_fpclassph256_mask:
4558   case X86::BI__builtin_ia32_fpclassph512_mask:
4559   case X86::BI__builtin_ia32_fpclasssd_mask:
4560   case X86::BI__builtin_ia32_fpclassss_mask:
4561   case X86::BI__builtin_ia32_fpclasssh_mask:
4562   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4563   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4564   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4565   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4566   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4567   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4568   case X86::BI__builtin_ia32_kshiftliqi:
4569   case X86::BI__builtin_ia32_kshiftlihi:
4570   case X86::BI__builtin_ia32_kshiftlisi:
4571   case X86::BI__builtin_ia32_kshiftlidi:
4572   case X86::BI__builtin_ia32_kshiftriqi:
4573   case X86::BI__builtin_ia32_kshiftrihi:
4574   case X86::BI__builtin_ia32_kshiftrisi:
4575   case X86::BI__builtin_ia32_kshiftridi:
4576     i = 1; l = 0; u = 255;
4577     break;
4578   case X86::BI__builtin_ia32_vperm2f128_pd256:
4579   case X86::BI__builtin_ia32_vperm2f128_ps256:
4580   case X86::BI__builtin_ia32_vperm2f128_si256:
4581   case X86::BI__builtin_ia32_permti256:
4582   case X86::BI__builtin_ia32_pblendw128:
4583   case X86::BI__builtin_ia32_pblendw256:
4584   case X86::BI__builtin_ia32_blendps256:
4585   case X86::BI__builtin_ia32_pblendd256:
4586   case X86::BI__builtin_ia32_palignr128:
4587   case X86::BI__builtin_ia32_palignr256:
4588   case X86::BI__builtin_ia32_palignr512:
4589   case X86::BI__builtin_ia32_alignq512:
4590   case X86::BI__builtin_ia32_alignd512:
4591   case X86::BI__builtin_ia32_alignd128:
4592   case X86::BI__builtin_ia32_alignd256:
4593   case X86::BI__builtin_ia32_alignq128:
4594   case X86::BI__builtin_ia32_alignq256:
4595   case X86::BI__builtin_ia32_vcomisd:
4596   case X86::BI__builtin_ia32_vcomiss:
4597   case X86::BI__builtin_ia32_shuf_f32x4:
4598   case X86::BI__builtin_ia32_shuf_f64x2:
4599   case X86::BI__builtin_ia32_shuf_i32x4:
4600   case X86::BI__builtin_ia32_shuf_i64x2:
4601   case X86::BI__builtin_ia32_shufpd512:
4602   case X86::BI__builtin_ia32_shufps:
4603   case X86::BI__builtin_ia32_shufps256:
4604   case X86::BI__builtin_ia32_shufps512:
4605   case X86::BI__builtin_ia32_dbpsadbw128:
4606   case X86::BI__builtin_ia32_dbpsadbw256:
4607   case X86::BI__builtin_ia32_dbpsadbw512:
4608   case X86::BI__builtin_ia32_vpshldd128:
4609   case X86::BI__builtin_ia32_vpshldd256:
4610   case X86::BI__builtin_ia32_vpshldd512:
4611   case X86::BI__builtin_ia32_vpshldq128:
4612   case X86::BI__builtin_ia32_vpshldq256:
4613   case X86::BI__builtin_ia32_vpshldq512:
4614   case X86::BI__builtin_ia32_vpshldw128:
4615   case X86::BI__builtin_ia32_vpshldw256:
4616   case X86::BI__builtin_ia32_vpshldw512:
4617   case X86::BI__builtin_ia32_vpshrdd128:
4618   case X86::BI__builtin_ia32_vpshrdd256:
4619   case X86::BI__builtin_ia32_vpshrdd512:
4620   case X86::BI__builtin_ia32_vpshrdq128:
4621   case X86::BI__builtin_ia32_vpshrdq256:
4622   case X86::BI__builtin_ia32_vpshrdq512:
4623   case X86::BI__builtin_ia32_vpshrdw128:
4624   case X86::BI__builtin_ia32_vpshrdw256:
4625   case X86::BI__builtin_ia32_vpshrdw512:
4626     i = 2; l = 0; u = 255;
4627     break;
4628   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4629   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4630   case X86::BI__builtin_ia32_fixupimmps512_mask:
4631   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4632   case X86::BI__builtin_ia32_fixupimmsd_mask:
4633   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4634   case X86::BI__builtin_ia32_fixupimmss_mask:
4635   case X86::BI__builtin_ia32_fixupimmss_maskz:
4636   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4637   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4638   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4639   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4640   case X86::BI__builtin_ia32_fixupimmps128_mask:
4641   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4642   case X86::BI__builtin_ia32_fixupimmps256_mask:
4643   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4644   case X86::BI__builtin_ia32_pternlogd512_mask:
4645   case X86::BI__builtin_ia32_pternlogd512_maskz:
4646   case X86::BI__builtin_ia32_pternlogq512_mask:
4647   case X86::BI__builtin_ia32_pternlogq512_maskz:
4648   case X86::BI__builtin_ia32_pternlogd128_mask:
4649   case X86::BI__builtin_ia32_pternlogd128_maskz:
4650   case X86::BI__builtin_ia32_pternlogd256_mask:
4651   case X86::BI__builtin_ia32_pternlogd256_maskz:
4652   case X86::BI__builtin_ia32_pternlogq128_mask:
4653   case X86::BI__builtin_ia32_pternlogq128_maskz:
4654   case X86::BI__builtin_ia32_pternlogq256_mask:
4655   case X86::BI__builtin_ia32_pternlogq256_maskz:
4656     i = 3; l = 0; u = 255;
4657     break;
4658   case X86::BI__builtin_ia32_gatherpfdpd:
4659   case X86::BI__builtin_ia32_gatherpfdps:
4660   case X86::BI__builtin_ia32_gatherpfqpd:
4661   case X86::BI__builtin_ia32_gatherpfqps:
4662   case X86::BI__builtin_ia32_scatterpfdpd:
4663   case X86::BI__builtin_ia32_scatterpfdps:
4664   case X86::BI__builtin_ia32_scatterpfqpd:
4665   case X86::BI__builtin_ia32_scatterpfqps:
4666     i = 4; l = 2; u = 3;
4667     break;
4668   case X86::BI__builtin_ia32_reducesd_mask:
4669   case X86::BI__builtin_ia32_reducess_mask:
4670   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4671   case X86::BI__builtin_ia32_rndscaless_round_mask:
4672   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4673   case X86::BI__builtin_ia32_reducesh_mask:
4674     i = 4; l = 0; u = 255;
4675     break;
4676   }
4677 
4678   // Note that we don't force a hard error on the range check here, allowing
4679   // template-generated or macro-generated dead code to potentially have out-of-
4680   // range values. These need to code generate, but don't need to necessarily
4681   // make any sense. We use a warning that defaults to an error.
4682   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4683 }
4684 
4685 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4686 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4687 /// Returns true when the format fits the function and the FormatStringInfo has
4688 /// been populated.
4689 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4690                                FormatStringInfo *FSI) {
4691   FSI->HasVAListArg = Format->getFirstArg() == 0;
4692   FSI->FormatIdx = Format->getFormatIdx() - 1;
4693   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4694 
4695   // The way the format attribute works in GCC, the implicit this argument
4696   // of member functions is counted. However, it doesn't appear in our own
4697   // lists, so decrement format_idx in that case.
4698   if (IsCXXMember) {
4699     if(FSI->FormatIdx == 0)
4700       return false;
4701     --FSI->FormatIdx;
4702     if (FSI->FirstDataArg != 0)
4703       --FSI->FirstDataArg;
4704   }
4705   return true;
4706 }
4707 
4708 /// Checks if a the given expression evaluates to null.
4709 ///
4710 /// Returns true if the value evaluates to null.
4711 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4712   // If the expression has non-null type, it doesn't evaluate to null.
4713   if (auto nullability
4714         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4715     if (*nullability == NullabilityKind::NonNull)
4716       return false;
4717   }
4718 
4719   // As a special case, transparent unions initialized with zero are
4720   // considered null for the purposes of the nonnull attribute.
4721   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4722     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4723       if (const CompoundLiteralExpr *CLE =
4724           dyn_cast<CompoundLiteralExpr>(Expr))
4725         if (const InitListExpr *ILE =
4726             dyn_cast<InitListExpr>(CLE->getInitializer()))
4727           Expr = ILE->getInit(0);
4728   }
4729 
4730   bool Result;
4731   return (!Expr->isValueDependent() &&
4732           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4733           !Result);
4734 }
4735 
4736 static void CheckNonNullArgument(Sema &S,
4737                                  const Expr *ArgExpr,
4738                                  SourceLocation CallSiteLoc) {
4739   if (CheckNonNullExpr(S, ArgExpr))
4740     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4741                           S.PDiag(diag::warn_null_arg)
4742                               << ArgExpr->getSourceRange());
4743 }
4744 
4745 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4746   FormatStringInfo FSI;
4747   if ((GetFormatStringType(Format) == FST_NSString) &&
4748       getFormatStringInfo(Format, false, &FSI)) {
4749     Idx = FSI.FormatIdx;
4750     return true;
4751   }
4752   return false;
4753 }
4754 
4755 /// Diagnose use of %s directive in an NSString which is being passed
4756 /// as formatting string to formatting method.
4757 static void
4758 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4759                                         const NamedDecl *FDecl,
4760                                         Expr **Args,
4761                                         unsigned NumArgs) {
4762   unsigned Idx = 0;
4763   bool Format = false;
4764   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4765   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4766     Idx = 2;
4767     Format = true;
4768   }
4769   else
4770     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4771       if (S.GetFormatNSStringIdx(I, Idx)) {
4772         Format = true;
4773         break;
4774       }
4775     }
4776   if (!Format || NumArgs <= Idx)
4777     return;
4778   const Expr *FormatExpr = Args[Idx];
4779   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4780     FormatExpr = CSCE->getSubExpr();
4781   const StringLiteral *FormatString;
4782   if (const ObjCStringLiteral *OSL =
4783       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4784     FormatString = OSL->getString();
4785   else
4786     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4787   if (!FormatString)
4788     return;
4789   if (S.FormatStringHasSArg(FormatString)) {
4790     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4791       << "%s" << 1 << 1;
4792     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4793       << FDecl->getDeclName();
4794   }
4795 }
4796 
4797 /// Determine whether the given type has a non-null nullability annotation.
4798 static bool isNonNullType(ASTContext &ctx, QualType type) {
4799   if (auto nullability = type->getNullability(ctx))
4800     return *nullability == NullabilityKind::NonNull;
4801 
4802   return false;
4803 }
4804 
4805 static void CheckNonNullArguments(Sema &S,
4806                                   const NamedDecl *FDecl,
4807                                   const FunctionProtoType *Proto,
4808                                   ArrayRef<const Expr *> Args,
4809                                   SourceLocation CallSiteLoc) {
4810   assert((FDecl || Proto) && "Need a function declaration or prototype");
4811 
4812   // Already checked by by constant evaluator.
4813   if (S.isConstantEvaluated())
4814     return;
4815   // Check the attributes attached to the method/function itself.
4816   llvm::SmallBitVector NonNullArgs;
4817   if (FDecl) {
4818     // Handle the nonnull attribute on the function/method declaration itself.
4819     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4820       if (!NonNull->args_size()) {
4821         // Easy case: all pointer arguments are nonnull.
4822         for (const auto *Arg : Args)
4823           if (S.isValidPointerAttrType(Arg->getType()))
4824             CheckNonNullArgument(S, Arg, CallSiteLoc);
4825         return;
4826       }
4827 
4828       for (const ParamIdx &Idx : NonNull->args()) {
4829         unsigned IdxAST = Idx.getASTIndex();
4830         if (IdxAST >= Args.size())
4831           continue;
4832         if (NonNullArgs.empty())
4833           NonNullArgs.resize(Args.size());
4834         NonNullArgs.set(IdxAST);
4835       }
4836     }
4837   }
4838 
4839   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4840     // Handle the nonnull attribute on the parameters of the
4841     // function/method.
4842     ArrayRef<ParmVarDecl*> parms;
4843     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4844       parms = FD->parameters();
4845     else
4846       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4847 
4848     unsigned ParamIndex = 0;
4849     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4850          I != E; ++I, ++ParamIndex) {
4851       const ParmVarDecl *PVD = *I;
4852       if (PVD->hasAttr<NonNullAttr>() ||
4853           isNonNullType(S.Context, PVD->getType())) {
4854         if (NonNullArgs.empty())
4855           NonNullArgs.resize(Args.size());
4856 
4857         NonNullArgs.set(ParamIndex);
4858       }
4859     }
4860   } else {
4861     // If we have a non-function, non-method declaration but no
4862     // function prototype, try to dig out the function prototype.
4863     if (!Proto) {
4864       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4865         QualType type = VD->getType().getNonReferenceType();
4866         if (auto pointerType = type->getAs<PointerType>())
4867           type = pointerType->getPointeeType();
4868         else if (auto blockType = type->getAs<BlockPointerType>())
4869           type = blockType->getPointeeType();
4870         // FIXME: data member pointers?
4871 
4872         // Dig out the function prototype, if there is one.
4873         Proto = type->getAs<FunctionProtoType>();
4874       }
4875     }
4876 
4877     // Fill in non-null argument information from the nullability
4878     // information on the parameter types (if we have them).
4879     if (Proto) {
4880       unsigned Index = 0;
4881       for (auto paramType : Proto->getParamTypes()) {
4882         if (isNonNullType(S.Context, paramType)) {
4883           if (NonNullArgs.empty())
4884             NonNullArgs.resize(Args.size());
4885 
4886           NonNullArgs.set(Index);
4887         }
4888 
4889         ++Index;
4890       }
4891     }
4892   }
4893 
4894   // Check for non-null arguments.
4895   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4896        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4897     if (NonNullArgs[ArgIndex])
4898       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4899   }
4900 }
4901 
4902 /// Warn if a pointer or reference argument passed to a function points to an
4903 /// object that is less aligned than the parameter. This can happen when
4904 /// creating a typedef with a lower alignment than the original type and then
4905 /// calling functions defined in terms of the original type.
4906 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4907                              StringRef ParamName, QualType ArgTy,
4908                              QualType ParamTy) {
4909 
4910   // If a function accepts a pointer or reference type
4911   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4912     return;
4913 
4914   // If the parameter is a pointer type, get the pointee type for the
4915   // argument too. If the parameter is a reference type, don't try to get
4916   // the pointee type for the argument.
4917   if (ParamTy->isPointerType())
4918     ArgTy = ArgTy->getPointeeType();
4919 
4920   // Remove reference or pointer
4921   ParamTy = ParamTy->getPointeeType();
4922 
4923   // Find expected alignment, and the actual alignment of the passed object.
4924   // getTypeAlignInChars requires complete types
4925   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4926       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4927       ArgTy->isUndeducedType())
4928     return;
4929 
4930   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4931   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4932 
4933   // If the argument is less aligned than the parameter, there is a
4934   // potential alignment issue.
4935   if (ArgAlign < ParamAlign)
4936     Diag(Loc, diag::warn_param_mismatched_alignment)
4937         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4938         << ParamName << FDecl;
4939 }
4940 
4941 /// Handles the checks for format strings, non-POD arguments to vararg
4942 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4943 /// attributes.
4944 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4945                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4946                      bool IsMemberFunction, SourceLocation Loc,
4947                      SourceRange Range, VariadicCallType CallType) {
4948   // FIXME: We should check as much as we can in the template definition.
4949   if (CurContext->isDependentContext())
4950     return;
4951 
4952   // Printf and scanf checking.
4953   llvm::SmallBitVector CheckedVarArgs;
4954   if (FDecl) {
4955     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4956       // Only create vector if there are format attributes.
4957       CheckedVarArgs.resize(Args.size());
4958 
4959       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4960                            CheckedVarArgs);
4961     }
4962   }
4963 
4964   // Refuse POD arguments that weren't caught by the format string
4965   // checks above.
4966   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4967   if (CallType != VariadicDoesNotApply &&
4968       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4969     unsigned NumParams = Proto ? Proto->getNumParams()
4970                        : FDecl && isa<FunctionDecl>(FDecl)
4971                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4972                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4973                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4974                        : 0;
4975 
4976     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4977       // Args[ArgIdx] can be null in malformed code.
4978       if (const Expr *Arg = Args[ArgIdx]) {
4979         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4980           checkVariadicArgument(Arg, CallType);
4981       }
4982     }
4983   }
4984 
4985   if (FDecl || Proto) {
4986     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4987 
4988     // Type safety checking.
4989     if (FDecl) {
4990       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4991         CheckArgumentWithTypeTag(I, Args, Loc);
4992     }
4993   }
4994 
4995   // Check that passed arguments match the alignment of original arguments.
4996   // Try to get the missing prototype from the declaration.
4997   if (!Proto && FDecl) {
4998     const auto *FT = FDecl->getFunctionType();
4999     if (isa_and_nonnull<FunctionProtoType>(FT))
5000       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5001   }
5002   if (Proto) {
5003     // For variadic functions, we may have more args than parameters.
5004     // For some K&R functions, we may have less args than parameters.
5005     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5006     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5007       // Args[ArgIdx] can be null in malformed code.
5008       if (const Expr *Arg = Args[ArgIdx]) {
5009         if (Arg->containsErrors())
5010           continue;
5011 
5012         QualType ParamTy = Proto->getParamType(ArgIdx);
5013         QualType ArgTy = Arg->getType();
5014         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5015                           ArgTy, ParamTy);
5016       }
5017     }
5018   }
5019 
5020   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5021     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5022     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5023     if (!Arg->isValueDependent()) {
5024       Expr::EvalResult Align;
5025       if (Arg->EvaluateAsInt(Align, Context)) {
5026         const llvm::APSInt &I = Align.Val.getInt();
5027         if (!I.isPowerOf2())
5028           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5029               << Arg->getSourceRange();
5030 
5031         if (I > Sema::MaximumAlignment)
5032           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5033               << Arg->getSourceRange() << Sema::MaximumAlignment;
5034       }
5035     }
5036   }
5037 
5038   if (FD)
5039     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5040 }
5041 
5042 /// CheckConstructorCall - Check a constructor call for correctness and safety
5043 /// properties not enforced by the C type system.
5044 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5045                                 ArrayRef<const Expr *> Args,
5046                                 const FunctionProtoType *Proto,
5047                                 SourceLocation Loc) {
5048   VariadicCallType CallType =
5049       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5050 
5051   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5052   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5053                     Context.getPointerType(Ctor->getThisObjectType()));
5054 
5055   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5056             Loc, SourceRange(), CallType);
5057 }
5058 
5059 /// CheckFunctionCall - Check a direct function call for various correctness
5060 /// and safety properties not strictly enforced by the C type system.
5061 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5062                              const FunctionProtoType *Proto) {
5063   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5064                               isa<CXXMethodDecl>(FDecl);
5065   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5066                           IsMemberOperatorCall;
5067   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5068                                                   TheCall->getCallee());
5069   Expr** Args = TheCall->getArgs();
5070   unsigned NumArgs = TheCall->getNumArgs();
5071 
5072   Expr *ImplicitThis = nullptr;
5073   if (IsMemberOperatorCall) {
5074     // If this is a call to a member operator, hide the first argument
5075     // from checkCall.
5076     // FIXME: Our choice of AST representation here is less than ideal.
5077     ImplicitThis = Args[0];
5078     ++Args;
5079     --NumArgs;
5080   } else if (IsMemberFunction)
5081     ImplicitThis =
5082         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5083 
5084   if (ImplicitThis) {
5085     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5086     // used.
5087     QualType ThisType = ImplicitThis->getType();
5088     if (!ThisType->isPointerType()) {
5089       assert(!ThisType->isReferenceType());
5090       ThisType = Context.getPointerType(ThisType);
5091     }
5092 
5093     QualType ThisTypeFromDecl =
5094         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5095 
5096     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5097                       ThisTypeFromDecl);
5098   }
5099 
5100   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5101             IsMemberFunction, TheCall->getRParenLoc(),
5102             TheCall->getCallee()->getSourceRange(), CallType);
5103 
5104   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5105   // None of the checks below are needed for functions that don't have
5106   // simple names (e.g., C++ conversion functions).
5107   if (!FnInfo)
5108     return false;
5109 
5110   CheckTCBEnforcement(TheCall, FDecl);
5111 
5112   CheckAbsoluteValueFunction(TheCall, FDecl);
5113   CheckMaxUnsignedZero(TheCall, FDecl);
5114 
5115   if (getLangOpts().ObjC)
5116     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5117 
5118   unsigned CMId = FDecl->getMemoryFunctionKind();
5119 
5120   // Handle memory setting and copying functions.
5121   switch (CMId) {
5122   case 0:
5123     return false;
5124   case Builtin::BIstrlcpy: // fallthrough
5125   case Builtin::BIstrlcat:
5126     CheckStrlcpycatArguments(TheCall, FnInfo);
5127     break;
5128   case Builtin::BIstrncat:
5129     CheckStrncatArguments(TheCall, FnInfo);
5130     break;
5131   case Builtin::BIfree:
5132     CheckFreeArguments(TheCall);
5133     break;
5134   default:
5135     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5136   }
5137 
5138   return false;
5139 }
5140 
5141 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5142                                ArrayRef<const Expr *> Args) {
5143   VariadicCallType CallType =
5144       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5145 
5146   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5147             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5148             CallType);
5149 
5150   return false;
5151 }
5152 
5153 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5154                             const FunctionProtoType *Proto) {
5155   QualType Ty;
5156   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5157     Ty = V->getType().getNonReferenceType();
5158   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5159     Ty = F->getType().getNonReferenceType();
5160   else
5161     return false;
5162 
5163   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5164       !Ty->isFunctionProtoType())
5165     return false;
5166 
5167   VariadicCallType CallType;
5168   if (!Proto || !Proto->isVariadic()) {
5169     CallType = VariadicDoesNotApply;
5170   } else if (Ty->isBlockPointerType()) {
5171     CallType = VariadicBlock;
5172   } else { // Ty->isFunctionPointerType()
5173     CallType = VariadicFunction;
5174   }
5175 
5176   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5177             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5178             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5179             TheCall->getCallee()->getSourceRange(), CallType);
5180 
5181   return false;
5182 }
5183 
5184 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5185 /// such as function pointers returned from functions.
5186 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5187   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5188                                                   TheCall->getCallee());
5189   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5190             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5191             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5192             TheCall->getCallee()->getSourceRange(), CallType);
5193 
5194   return false;
5195 }
5196 
5197 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5198   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5199     return false;
5200 
5201   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5202   switch (Op) {
5203   case AtomicExpr::AO__c11_atomic_init:
5204   case AtomicExpr::AO__opencl_atomic_init:
5205     llvm_unreachable("There is no ordering argument for an init");
5206 
5207   case AtomicExpr::AO__c11_atomic_load:
5208   case AtomicExpr::AO__opencl_atomic_load:
5209   case AtomicExpr::AO__atomic_load_n:
5210   case AtomicExpr::AO__atomic_load:
5211     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5212            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5213 
5214   case AtomicExpr::AO__c11_atomic_store:
5215   case AtomicExpr::AO__opencl_atomic_store:
5216   case AtomicExpr::AO__atomic_store:
5217   case AtomicExpr::AO__atomic_store_n:
5218     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5219            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5220            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5221 
5222   default:
5223     return true;
5224   }
5225 }
5226 
5227 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5228                                          AtomicExpr::AtomicOp Op) {
5229   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5230   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5231   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5232   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5233                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5234                          Op);
5235 }
5236 
5237 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5238                                  SourceLocation RParenLoc, MultiExprArg Args,
5239                                  AtomicExpr::AtomicOp Op,
5240                                  AtomicArgumentOrder ArgOrder) {
5241   // All the non-OpenCL operations take one of the following forms.
5242   // The OpenCL operations take the __c11 forms with one extra argument for
5243   // synchronization scope.
5244   enum {
5245     // C    __c11_atomic_init(A *, C)
5246     Init,
5247 
5248     // C    __c11_atomic_load(A *, int)
5249     Load,
5250 
5251     // void __atomic_load(A *, CP, int)
5252     LoadCopy,
5253 
5254     // void __atomic_store(A *, CP, int)
5255     Copy,
5256 
5257     // C    __c11_atomic_add(A *, M, int)
5258     Arithmetic,
5259 
5260     // C    __atomic_exchange_n(A *, CP, int)
5261     Xchg,
5262 
5263     // void __atomic_exchange(A *, C *, CP, int)
5264     GNUXchg,
5265 
5266     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5267     C11CmpXchg,
5268 
5269     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5270     GNUCmpXchg
5271   } Form = Init;
5272 
5273   const unsigned NumForm = GNUCmpXchg + 1;
5274   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5275   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5276   // where:
5277   //   C is an appropriate type,
5278   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5279   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5280   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5281   //   the int parameters are for orderings.
5282 
5283   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5284       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5285       "need to update code for modified forms");
5286   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5287                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5288                         AtomicExpr::AO__atomic_load,
5289                 "need to update code for modified C11 atomics");
5290   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5291                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5292   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5293                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5294                IsOpenCL;
5295   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5296              Op == AtomicExpr::AO__atomic_store_n ||
5297              Op == AtomicExpr::AO__atomic_exchange_n ||
5298              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5299   bool IsAddSub = false;
5300 
5301   switch (Op) {
5302   case AtomicExpr::AO__c11_atomic_init:
5303   case AtomicExpr::AO__opencl_atomic_init:
5304     Form = Init;
5305     break;
5306 
5307   case AtomicExpr::AO__c11_atomic_load:
5308   case AtomicExpr::AO__opencl_atomic_load:
5309   case AtomicExpr::AO__atomic_load_n:
5310     Form = Load;
5311     break;
5312 
5313   case AtomicExpr::AO__atomic_load:
5314     Form = LoadCopy;
5315     break;
5316 
5317   case AtomicExpr::AO__c11_atomic_store:
5318   case AtomicExpr::AO__opencl_atomic_store:
5319   case AtomicExpr::AO__atomic_store:
5320   case AtomicExpr::AO__atomic_store_n:
5321     Form = Copy;
5322     break;
5323 
5324   case AtomicExpr::AO__c11_atomic_fetch_add:
5325   case AtomicExpr::AO__c11_atomic_fetch_sub:
5326   case AtomicExpr::AO__opencl_atomic_fetch_add:
5327   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5328   case AtomicExpr::AO__atomic_fetch_add:
5329   case AtomicExpr::AO__atomic_fetch_sub:
5330   case AtomicExpr::AO__atomic_add_fetch:
5331   case AtomicExpr::AO__atomic_sub_fetch:
5332     IsAddSub = true;
5333     Form = Arithmetic;
5334     break;
5335   case AtomicExpr::AO__c11_atomic_fetch_and:
5336   case AtomicExpr::AO__c11_atomic_fetch_or:
5337   case AtomicExpr::AO__c11_atomic_fetch_xor:
5338   case AtomicExpr::AO__opencl_atomic_fetch_and:
5339   case AtomicExpr::AO__opencl_atomic_fetch_or:
5340   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5341   case AtomicExpr::AO__atomic_fetch_and:
5342   case AtomicExpr::AO__atomic_fetch_or:
5343   case AtomicExpr::AO__atomic_fetch_xor:
5344   case AtomicExpr::AO__atomic_fetch_nand:
5345   case AtomicExpr::AO__atomic_and_fetch:
5346   case AtomicExpr::AO__atomic_or_fetch:
5347   case AtomicExpr::AO__atomic_xor_fetch:
5348   case AtomicExpr::AO__atomic_nand_fetch:
5349     Form = Arithmetic;
5350     break;
5351   case AtomicExpr::AO__c11_atomic_fetch_min:
5352   case AtomicExpr::AO__c11_atomic_fetch_max:
5353   case AtomicExpr::AO__opencl_atomic_fetch_min:
5354   case AtomicExpr::AO__opencl_atomic_fetch_max:
5355   case AtomicExpr::AO__atomic_min_fetch:
5356   case AtomicExpr::AO__atomic_max_fetch:
5357   case AtomicExpr::AO__atomic_fetch_min:
5358   case AtomicExpr::AO__atomic_fetch_max:
5359     Form = Arithmetic;
5360     break;
5361 
5362   case AtomicExpr::AO__c11_atomic_exchange:
5363   case AtomicExpr::AO__opencl_atomic_exchange:
5364   case AtomicExpr::AO__atomic_exchange_n:
5365     Form = Xchg;
5366     break;
5367 
5368   case AtomicExpr::AO__atomic_exchange:
5369     Form = GNUXchg;
5370     break;
5371 
5372   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5373   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5374   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5375   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5376     Form = C11CmpXchg;
5377     break;
5378 
5379   case AtomicExpr::AO__atomic_compare_exchange:
5380   case AtomicExpr::AO__atomic_compare_exchange_n:
5381     Form = GNUCmpXchg;
5382     break;
5383   }
5384 
5385   unsigned AdjustedNumArgs = NumArgs[Form];
5386   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5387     ++AdjustedNumArgs;
5388   // Check we have the right number of arguments.
5389   if (Args.size() < AdjustedNumArgs) {
5390     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5391         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5392         << ExprRange;
5393     return ExprError();
5394   } else if (Args.size() > AdjustedNumArgs) {
5395     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5396          diag::err_typecheck_call_too_many_args)
5397         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5398         << ExprRange;
5399     return ExprError();
5400   }
5401 
5402   // Inspect the first argument of the atomic operation.
5403   Expr *Ptr = Args[0];
5404   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5405   if (ConvertedPtr.isInvalid())
5406     return ExprError();
5407 
5408   Ptr = ConvertedPtr.get();
5409   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5410   if (!pointerType) {
5411     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5412         << Ptr->getType() << Ptr->getSourceRange();
5413     return ExprError();
5414   }
5415 
5416   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5417   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5418   QualType ValType = AtomTy; // 'C'
5419   if (IsC11) {
5420     if (!AtomTy->isAtomicType()) {
5421       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5422           << Ptr->getType() << Ptr->getSourceRange();
5423       return ExprError();
5424     }
5425     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5426         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5427       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5428           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5429           << Ptr->getSourceRange();
5430       return ExprError();
5431     }
5432     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5433   } else if (Form != Load && Form != LoadCopy) {
5434     if (ValType.isConstQualified()) {
5435       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5436           << Ptr->getType() << Ptr->getSourceRange();
5437       return ExprError();
5438     }
5439   }
5440 
5441   // For an arithmetic operation, the implied arithmetic must be well-formed.
5442   if (Form == Arithmetic) {
5443     // gcc does not enforce these rules for GNU atomics, but we do so for
5444     // sanity.
5445     auto IsAllowedValueType = [&](QualType ValType) {
5446       if (ValType->isIntegerType())
5447         return true;
5448       if (ValType->isPointerType())
5449         return true;
5450       if (!ValType->isFloatingType())
5451         return false;
5452       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5453       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5454           &Context.getTargetInfo().getLongDoubleFormat() ==
5455               &llvm::APFloat::x87DoubleExtended())
5456         return false;
5457       return true;
5458     };
5459     if (IsAddSub && !IsAllowedValueType(ValType)) {
5460       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5461           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5462       return ExprError();
5463     }
5464     if (!IsAddSub && !ValType->isIntegerType()) {
5465       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5466           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5467       return ExprError();
5468     }
5469     if (IsC11 && ValType->isPointerType() &&
5470         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5471                             diag::err_incomplete_type)) {
5472       return ExprError();
5473     }
5474   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5475     // For __atomic_*_n operations, the value type must be a scalar integral or
5476     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5477     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5478         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5479     return ExprError();
5480   }
5481 
5482   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5483       !AtomTy->isScalarType()) {
5484     // For GNU atomics, require a trivially-copyable type. This is not part of
5485     // the GNU atomics specification, but we enforce it for sanity.
5486     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5487         << Ptr->getType() << Ptr->getSourceRange();
5488     return ExprError();
5489   }
5490 
5491   switch (ValType.getObjCLifetime()) {
5492   case Qualifiers::OCL_None:
5493   case Qualifiers::OCL_ExplicitNone:
5494     // okay
5495     break;
5496 
5497   case Qualifiers::OCL_Weak:
5498   case Qualifiers::OCL_Strong:
5499   case Qualifiers::OCL_Autoreleasing:
5500     // FIXME: Can this happen? By this point, ValType should be known
5501     // to be trivially copyable.
5502     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5503         << ValType << Ptr->getSourceRange();
5504     return ExprError();
5505   }
5506 
5507   // All atomic operations have an overload which takes a pointer to a volatile
5508   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5509   // into the result or the other operands. Similarly atomic_load takes a
5510   // pointer to a const 'A'.
5511   ValType.removeLocalVolatile();
5512   ValType.removeLocalConst();
5513   QualType ResultType = ValType;
5514   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5515       Form == Init)
5516     ResultType = Context.VoidTy;
5517   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5518     ResultType = Context.BoolTy;
5519 
5520   // The type of a parameter passed 'by value'. In the GNU atomics, such
5521   // arguments are actually passed as pointers.
5522   QualType ByValType = ValType; // 'CP'
5523   bool IsPassedByAddress = false;
5524   if (!IsC11 && !IsN) {
5525     ByValType = Ptr->getType();
5526     IsPassedByAddress = true;
5527   }
5528 
5529   SmallVector<Expr *, 5> APIOrderedArgs;
5530   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5531     APIOrderedArgs.push_back(Args[0]);
5532     switch (Form) {
5533     case Init:
5534     case Load:
5535       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5536       break;
5537     case LoadCopy:
5538     case Copy:
5539     case Arithmetic:
5540     case Xchg:
5541       APIOrderedArgs.push_back(Args[2]); // Val1
5542       APIOrderedArgs.push_back(Args[1]); // Order
5543       break;
5544     case GNUXchg:
5545       APIOrderedArgs.push_back(Args[2]); // Val1
5546       APIOrderedArgs.push_back(Args[3]); // Val2
5547       APIOrderedArgs.push_back(Args[1]); // Order
5548       break;
5549     case C11CmpXchg:
5550       APIOrderedArgs.push_back(Args[2]); // Val1
5551       APIOrderedArgs.push_back(Args[4]); // Val2
5552       APIOrderedArgs.push_back(Args[1]); // Order
5553       APIOrderedArgs.push_back(Args[3]); // OrderFail
5554       break;
5555     case GNUCmpXchg:
5556       APIOrderedArgs.push_back(Args[2]); // Val1
5557       APIOrderedArgs.push_back(Args[4]); // Val2
5558       APIOrderedArgs.push_back(Args[5]); // Weak
5559       APIOrderedArgs.push_back(Args[1]); // Order
5560       APIOrderedArgs.push_back(Args[3]); // OrderFail
5561       break;
5562     }
5563   } else
5564     APIOrderedArgs.append(Args.begin(), Args.end());
5565 
5566   // The first argument's non-CV pointer type is used to deduce the type of
5567   // subsequent arguments, except for:
5568   //  - weak flag (always converted to bool)
5569   //  - memory order (always converted to int)
5570   //  - scope  (always converted to int)
5571   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5572     QualType Ty;
5573     if (i < NumVals[Form] + 1) {
5574       switch (i) {
5575       case 0:
5576         // The first argument is always a pointer. It has a fixed type.
5577         // It is always dereferenced, a nullptr is undefined.
5578         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5579         // Nothing else to do: we already know all we want about this pointer.
5580         continue;
5581       case 1:
5582         // The second argument is the non-atomic operand. For arithmetic, this
5583         // is always passed by value, and for a compare_exchange it is always
5584         // passed by address. For the rest, GNU uses by-address and C11 uses
5585         // by-value.
5586         assert(Form != Load);
5587         if (Form == Arithmetic && ValType->isPointerType())
5588           Ty = Context.getPointerDiffType();
5589         else if (Form == Init || Form == Arithmetic)
5590           Ty = ValType;
5591         else if (Form == Copy || Form == Xchg) {
5592           if (IsPassedByAddress) {
5593             // The value pointer is always dereferenced, a nullptr is undefined.
5594             CheckNonNullArgument(*this, APIOrderedArgs[i],
5595                                  ExprRange.getBegin());
5596           }
5597           Ty = ByValType;
5598         } else {
5599           Expr *ValArg = APIOrderedArgs[i];
5600           // The value pointer is always dereferenced, a nullptr is undefined.
5601           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5602           LangAS AS = LangAS::Default;
5603           // Keep address space of non-atomic pointer type.
5604           if (const PointerType *PtrTy =
5605                   ValArg->getType()->getAs<PointerType>()) {
5606             AS = PtrTy->getPointeeType().getAddressSpace();
5607           }
5608           Ty = Context.getPointerType(
5609               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5610         }
5611         break;
5612       case 2:
5613         // The third argument to compare_exchange / GNU exchange is the desired
5614         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5615         if (IsPassedByAddress)
5616           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5617         Ty = ByValType;
5618         break;
5619       case 3:
5620         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5621         Ty = Context.BoolTy;
5622         break;
5623       }
5624     } else {
5625       // The order(s) and scope are always converted to int.
5626       Ty = Context.IntTy;
5627     }
5628 
5629     InitializedEntity Entity =
5630         InitializedEntity::InitializeParameter(Context, Ty, false);
5631     ExprResult Arg = APIOrderedArgs[i];
5632     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5633     if (Arg.isInvalid())
5634       return true;
5635     APIOrderedArgs[i] = Arg.get();
5636   }
5637 
5638   // Permute the arguments into a 'consistent' order.
5639   SmallVector<Expr*, 5> SubExprs;
5640   SubExprs.push_back(Ptr);
5641   switch (Form) {
5642   case Init:
5643     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5644     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5645     break;
5646   case Load:
5647     SubExprs.push_back(APIOrderedArgs[1]); // Order
5648     break;
5649   case LoadCopy:
5650   case Copy:
5651   case Arithmetic:
5652   case Xchg:
5653     SubExprs.push_back(APIOrderedArgs[2]); // Order
5654     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5655     break;
5656   case GNUXchg:
5657     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5658     SubExprs.push_back(APIOrderedArgs[3]); // Order
5659     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5660     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5661     break;
5662   case C11CmpXchg:
5663     SubExprs.push_back(APIOrderedArgs[3]); // Order
5664     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5665     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5666     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5667     break;
5668   case GNUCmpXchg:
5669     SubExprs.push_back(APIOrderedArgs[4]); // Order
5670     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5671     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5672     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5673     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5674     break;
5675   }
5676 
5677   if (SubExprs.size() >= 2 && Form != Init) {
5678     if (Optional<llvm::APSInt> Result =
5679             SubExprs[1]->getIntegerConstantExpr(Context))
5680       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5681         Diag(SubExprs[1]->getBeginLoc(),
5682              diag::warn_atomic_op_has_invalid_memory_order)
5683             << SubExprs[1]->getSourceRange();
5684   }
5685 
5686   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5687     auto *Scope = Args[Args.size() - 1];
5688     if (Optional<llvm::APSInt> Result =
5689             Scope->getIntegerConstantExpr(Context)) {
5690       if (!ScopeModel->isValid(Result->getZExtValue()))
5691         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5692             << Scope->getSourceRange();
5693     }
5694     SubExprs.push_back(Scope);
5695   }
5696 
5697   AtomicExpr *AE = new (Context)
5698       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5699 
5700   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5701        Op == AtomicExpr::AO__c11_atomic_store ||
5702        Op == AtomicExpr::AO__opencl_atomic_load ||
5703        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5704       Context.AtomicUsesUnsupportedLibcall(AE))
5705     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5706         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5707              Op == AtomicExpr::AO__opencl_atomic_load)
5708                 ? 0
5709                 : 1);
5710 
5711   if (ValType->isExtIntType()) {
5712     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5713     return ExprError();
5714   }
5715 
5716   return AE;
5717 }
5718 
5719 /// checkBuiltinArgument - Given a call to a builtin function, perform
5720 /// normal type-checking on the given argument, updating the call in
5721 /// place.  This is useful when a builtin function requires custom
5722 /// type-checking for some of its arguments but not necessarily all of
5723 /// them.
5724 ///
5725 /// Returns true on error.
5726 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5727   FunctionDecl *Fn = E->getDirectCallee();
5728   assert(Fn && "builtin call without direct callee!");
5729 
5730   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5731   InitializedEntity Entity =
5732     InitializedEntity::InitializeParameter(S.Context, Param);
5733 
5734   ExprResult Arg = E->getArg(0);
5735   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5736   if (Arg.isInvalid())
5737     return true;
5738 
5739   E->setArg(ArgIndex, Arg.get());
5740   return false;
5741 }
5742 
5743 /// We have a call to a function like __sync_fetch_and_add, which is an
5744 /// overloaded function based on the pointer type of its first argument.
5745 /// The main BuildCallExpr routines have already promoted the types of
5746 /// arguments because all of these calls are prototyped as void(...).
5747 ///
5748 /// This function goes through and does final semantic checking for these
5749 /// builtins, as well as generating any warnings.
5750 ExprResult
5751 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5752   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5753   Expr *Callee = TheCall->getCallee();
5754   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5755   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5756 
5757   // Ensure that we have at least one argument to do type inference from.
5758   if (TheCall->getNumArgs() < 1) {
5759     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5760         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5761     return ExprError();
5762   }
5763 
5764   // Inspect the first argument of the atomic builtin.  This should always be
5765   // a pointer type, whose element is an integral scalar or pointer type.
5766   // Because it is a pointer type, we don't have to worry about any implicit
5767   // casts here.
5768   // FIXME: We don't allow floating point scalars as input.
5769   Expr *FirstArg = TheCall->getArg(0);
5770   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5771   if (FirstArgResult.isInvalid())
5772     return ExprError();
5773   FirstArg = FirstArgResult.get();
5774   TheCall->setArg(0, FirstArg);
5775 
5776   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5777   if (!pointerType) {
5778     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5779         << FirstArg->getType() << FirstArg->getSourceRange();
5780     return ExprError();
5781   }
5782 
5783   QualType ValType = pointerType->getPointeeType();
5784   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5785       !ValType->isBlockPointerType()) {
5786     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5787         << FirstArg->getType() << FirstArg->getSourceRange();
5788     return ExprError();
5789   }
5790 
5791   if (ValType.isConstQualified()) {
5792     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5793         << FirstArg->getType() << FirstArg->getSourceRange();
5794     return ExprError();
5795   }
5796 
5797   switch (ValType.getObjCLifetime()) {
5798   case Qualifiers::OCL_None:
5799   case Qualifiers::OCL_ExplicitNone:
5800     // okay
5801     break;
5802 
5803   case Qualifiers::OCL_Weak:
5804   case Qualifiers::OCL_Strong:
5805   case Qualifiers::OCL_Autoreleasing:
5806     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5807         << ValType << FirstArg->getSourceRange();
5808     return ExprError();
5809   }
5810 
5811   // Strip any qualifiers off ValType.
5812   ValType = ValType.getUnqualifiedType();
5813 
5814   // The majority of builtins return a value, but a few have special return
5815   // types, so allow them to override appropriately below.
5816   QualType ResultType = ValType;
5817 
5818   // We need to figure out which concrete builtin this maps onto.  For example,
5819   // __sync_fetch_and_add with a 2 byte object turns into
5820   // __sync_fetch_and_add_2.
5821 #define BUILTIN_ROW(x) \
5822   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5823     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5824 
5825   static const unsigned BuiltinIndices[][5] = {
5826     BUILTIN_ROW(__sync_fetch_and_add),
5827     BUILTIN_ROW(__sync_fetch_and_sub),
5828     BUILTIN_ROW(__sync_fetch_and_or),
5829     BUILTIN_ROW(__sync_fetch_and_and),
5830     BUILTIN_ROW(__sync_fetch_and_xor),
5831     BUILTIN_ROW(__sync_fetch_and_nand),
5832 
5833     BUILTIN_ROW(__sync_add_and_fetch),
5834     BUILTIN_ROW(__sync_sub_and_fetch),
5835     BUILTIN_ROW(__sync_and_and_fetch),
5836     BUILTIN_ROW(__sync_or_and_fetch),
5837     BUILTIN_ROW(__sync_xor_and_fetch),
5838     BUILTIN_ROW(__sync_nand_and_fetch),
5839 
5840     BUILTIN_ROW(__sync_val_compare_and_swap),
5841     BUILTIN_ROW(__sync_bool_compare_and_swap),
5842     BUILTIN_ROW(__sync_lock_test_and_set),
5843     BUILTIN_ROW(__sync_lock_release),
5844     BUILTIN_ROW(__sync_swap)
5845   };
5846 #undef BUILTIN_ROW
5847 
5848   // Determine the index of the size.
5849   unsigned SizeIndex;
5850   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5851   case 1: SizeIndex = 0; break;
5852   case 2: SizeIndex = 1; break;
5853   case 4: SizeIndex = 2; break;
5854   case 8: SizeIndex = 3; break;
5855   case 16: SizeIndex = 4; break;
5856   default:
5857     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5858         << FirstArg->getType() << FirstArg->getSourceRange();
5859     return ExprError();
5860   }
5861 
5862   // Each of these builtins has one pointer argument, followed by some number of
5863   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5864   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5865   // as the number of fixed args.
5866   unsigned BuiltinID = FDecl->getBuiltinID();
5867   unsigned BuiltinIndex, NumFixed = 1;
5868   bool WarnAboutSemanticsChange = false;
5869   switch (BuiltinID) {
5870   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5871   case Builtin::BI__sync_fetch_and_add:
5872   case Builtin::BI__sync_fetch_and_add_1:
5873   case Builtin::BI__sync_fetch_and_add_2:
5874   case Builtin::BI__sync_fetch_and_add_4:
5875   case Builtin::BI__sync_fetch_and_add_8:
5876   case Builtin::BI__sync_fetch_and_add_16:
5877     BuiltinIndex = 0;
5878     break;
5879 
5880   case Builtin::BI__sync_fetch_and_sub:
5881   case Builtin::BI__sync_fetch_and_sub_1:
5882   case Builtin::BI__sync_fetch_and_sub_2:
5883   case Builtin::BI__sync_fetch_and_sub_4:
5884   case Builtin::BI__sync_fetch_and_sub_8:
5885   case Builtin::BI__sync_fetch_and_sub_16:
5886     BuiltinIndex = 1;
5887     break;
5888 
5889   case Builtin::BI__sync_fetch_and_or:
5890   case Builtin::BI__sync_fetch_and_or_1:
5891   case Builtin::BI__sync_fetch_and_or_2:
5892   case Builtin::BI__sync_fetch_and_or_4:
5893   case Builtin::BI__sync_fetch_and_or_8:
5894   case Builtin::BI__sync_fetch_and_or_16:
5895     BuiltinIndex = 2;
5896     break;
5897 
5898   case Builtin::BI__sync_fetch_and_and:
5899   case Builtin::BI__sync_fetch_and_and_1:
5900   case Builtin::BI__sync_fetch_and_and_2:
5901   case Builtin::BI__sync_fetch_and_and_4:
5902   case Builtin::BI__sync_fetch_and_and_8:
5903   case Builtin::BI__sync_fetch_and_and_16:
5904     BuiltinIndex = 3;
5905     break;
5906 
5907   case Builtin::BI__sync_fetch_and_xor:
5908   case Builtin::BI__sync_fetch_and_xor_1:
5909   case Builtin::BI__sync_fetch_and_xor_2:
5910   case Builtin::BI__sync_fetch_and_xor_4:
5911   case Builtin::BI__sync_fetch_and_xor_8:
5912   case Builtin::BI__sync_fetch_and_xor_16:
5913     BuiltinIndex = 4;
5914     break;
5915 
5916   case Builtin::BI__sync_fetch_and_nand:
5917   case Builtin::BI__sync_fetch_and_nand_1:
5918   case Builtin::BI__sync_fetch_and_nand_2:
5919   case Builtin::BI__sync_fetch_and_nand_4:
5920   case Builtin::BI__sync_fetch_and_nand_8:
5921   case Builtin::BI__sync_fetch_and_nand_16:
5922     BuiltinIndex = 5;
5923     WarnAboutSemanticsChange = true;
5924     break;
5925 
5926   case Builtin::BI__sync_add_and_fetch:
5927   case Builtin::BI__sync_add_and_fetch_1:
5928   case Builtin::BI__sync_add_and_fetch_2:
5929   case Builtin::BI__sync_add_and_fetch_4:
5930   case Builtin::BI__sync_add_and_fetch_8:
5931   case Builtin::BI__sync_add_and_fetch_16:
5932     BuiltinIndex = 6;
5933     break;
5934 
5935   case Builtin::BI__sync_sub_and_fetch:
5936   case Builtin::BI__sync_sub_and_fetch_1:
5937   case Builtin::BI__sync_sub_and_fetch_2:
5938   case Builtin::BI__sync_sub_and_fetch_4:
5939   case Builtin::BI__sync_sub_and_fetch_8:
5940   case Builtin::BI__sync_sub_and_fetch_16:
5941     BuiltinIndex = 7;
5942     break;
5943 
5944   case Builtin::BI__sync_and_and_fetch:
5945   case Builtin::BI__sync_and_and_fetch_1:
5946   case Builtin::BI__sync_and_and_fetch_2:
5947   case Builtin::BI__sync_and_and_fetch_4:
5948   case Builtin::BI__sync_and_and_fetch_8:
5949   case Builtin::BI__sync_and_and_fetch_16:
5950     BuiltinIndex = 8;
5951     break;
5952 
5953   case Builtin::BI__sync_or_and_fetch:
5954   case Builtin::BI__sync_or_and_fetch_1:
5955   case Builtin::BI__sync_or_and_fetch_2:
5956   case Builtin::BI__sync_or_and_fetch_4:
5957   case Builtin::BI__sync_or_and_fetch_8:
5958   case Builtin::BI__sync_or_and_fetch_16:
5959     BuiltinIndex = 9;
5960     break;
5961 
5962   case Builtin::BI__sync_xor_and_fetch:
5963   case Builtin::BI__sync_xor_and_fetch_1:
5964   case Builtin::BI__sync_xor_and_fetch_2:
5965   case Builtin::BI__sync_xor_and_fetch_4:
5966   case Builtin::BI__sync_xor_and_fetch_8:
5967   case Builtin::BI__sync_xor_and_fetch_16:
5968     BuiltinIndex = 10;
5969     break;
5970 
5971   case Builtin::BI__sync_nand_and_fetch:
5972   case Builtin::BI__sync_nand_and_fetch_1:
5973   case Builtin::BI__sync_nand_and_fetch_2:
5974   case Builtin::BI__sync_nand_and_fetch_4:
5975   case Builtin::BI__sync_nand_and_fetch_8:
5976   case Builtin::BI__sync_nand_and_fetch_16:
5977     BuiltinIndex = 11;
5978     WarnAboutSemanticsChange = true;
5979     break;
5980 
5981   case Builtin::BI__sync_val_compare_and_swap:
5982   case Builtin::BI__sync_val_compare_and_swap_1:
5983   case Builtin::BI__sync_val_compare_and_swap_2:
5984   case Builtin::BI__sync_val_compare_and_swap_4:
5985   case Builtin::BI__sync_val_compare_and_swap_8:
5986   case Builtin::BI__sync_val_compare_and_swap_16:
5987     BuiltinIndex = 12;
5988     NumFixed = 2;
5989     break;
5990 
5991   case Builtin::BI__sync_bool_compare_and_swap:
5992   case Builtin::BI__sync_bool_compare_and_swap_1:
5993   case Builtin::BI__sync_bool_compare_and_swap_2:
5994   case Builtin::BI__sync_bool_compare_and_swap_4:
5995   case Builtin::BI__sync_bool_compare_and_swap_8:
5996   case Builtin::BI__sync_bool_compare_and_swap_16:
5997     BuiltinIndex = 13;
5998     NumFixed = 2;
5999     ResultType = Context.BoolTy;
6000     break;
6001 
6002   case Builtin::BI__sync_lock_test_and_set:
6003   case Builtin::BI__sync_lock_test_and_set_1:
6004   case Builtin::BI__sync_lock_test_and_set_2:
6005   case Builtin::BI__sync_lock_test_and_set_4:
6006   case Builtin::BI__sync_lock_test_and_set_8:
6007   case Builtin::BI__sync_lock_test_and_set_16:
6008     BuiltinIndex = 14;
6009     break;
6010 
6011   case Builtin::BI__sync_lock_release:
6012   case Builtin::BI__sync_lock_release_1:
6013   case Builtin::BI__sync_lock_release_2:
6014   case Builtin::BI__sync_lock_release_4:
6015   case Builtin::BI__sync_lock_release_8:
6016   case Builtin::BI__sync_lock_release_16:
6017     BuiltinIndex = 15;
6018     NumFixed = 0;
6019     ResultType = Context.VoidTy;
6020     break;
6021 
6022   case Builtin::BI__sync_swap:
6023   case Builtin::BI__sync_swap_1:
6024   case Builtin::BI__sync_swap_2:
6025   case Builtin::BI__sync_swap_4:
6026   case Builtin::BI__sync_swap_8:
6027   case Builtin::BI__sync_swap_16:
6028     BuiltinIndex = 16;
6029     break;
6030   }
6031 
6032   // Now that we know how many fixed arguments we expect, first check that we
6033   // have at least that many.
6034   if (TheCall->getNumArgs() < 1+NumFixed) {
6035     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6036         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6037         << Callee->getSourceRange();
6038     return ExprError();
6039   }
6040 
6041   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6042       << Callee->getSourceRange();
6043 
6044   if (WarnAboutSemanticsChange) {
6045     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6046         << Callee->getSourceRange();
6047   }
6048 
6049   // Get the decl for the concrete builtin from this, we can tell what the
6050   // concrete integer type we should convert to is.
6051   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6052   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6053   FunctionDecl *NewBuiltinDecl;
6054   if (NewBuiltinID == BuiltinID)
6055     NewBuiltinDecl = FDecl;
6056   else {
6057     // Perform builtin lookup to avoid redeclaring it.
6058     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6059     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6060     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6061     assert(Res.getFoundDecl());
6062     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6063     if (!NewBuiltinDecl)
6064       return ExprError();
6065   }
6066 
6067   // The first argument --- the pointer --- has a fixed type; we
6068   // deduce the types of the rest of the arguments accordingly.  Walk
6069   // the remaining arguments, converting them to the deduced value type.
6070   for (unsigned i = 0; i != NumFixed; ++i) {
6071     ExprResult Arg = TheCall->getArg(i+1);
6072 
6073     // GCC does an implicit conversion to the pointer or integer ValType.  This
6074     // can fail in some cases (1i -> int**), check for this error case now.
6075     // Initialize the argument.
6076     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6077                                                    ValType, /*consume*/ false);
6078     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6079     if (Arg.isInvalid())
6080       return ExprError();
6081 
6082     // Okay, we have something that *can* be converted to the right type.  Check
6083     // to see if there is a potentially weird extension going on here.  This can
6084     // happen when you do an atomic operation on something like an char* and
6085     // pass in 42.  The 42 gets converted to char.  This is even more strange
6086     // for things like 45.123 -> char, etc.
6087     // FIXME: Do this check.
6088     TheCall->setArg(i+1, Arg.get());
6089   }
6090 
6091   // Create a new DeclRefExpr to refer to the new decl.
6092   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6093       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6094       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6095       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6096 
6097   // Set the callee in the CallExpr.
6098   // FIXME: This loses syntactic information.
6099   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6100   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6101                                               CK_BuiltinFnToFnPtr);
6102   TheCall->setCallee(PromotedCall.get());
6103 
6104   // Change the result type of the call to match the original value type. This
6105   // is arbitrary, but the codegen for these builtins ins design to handle it
6106   // gracefully.
6107   TheCall->setType(ResultType);
6108 
6109   // Prohibit use of _ExtInt with atomic builtins.
6110   // The arguments would have already been converted to the first argument's
6111   // type, so only need to check the first argument.
6112   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6113   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6114     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6115     return ExprError();
6116   }
6117 
6118   return TheCallResult;
6119 }
6120 
6121 /// SemaBuiltinNontemporalOverloaded - We have a call to
6122 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6123 /// overloaded function based on the pointer type of its last argument.
6124 ///
6125 /// This function goes through and does final semantic checking for these
6126 /// builtins.
6127 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6128   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6129   DeclRefExpr *DRE =
6130       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6131   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6132   unsigned BuiltinID = FDecl->getBuiltinID();
6133   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6134           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6135          "Unexpected nontemporal load/store builtin!");
6136   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6137   unsigned numArgs = isStore ? 2 : 1;
6138 
6139   // Ensure that we have the proper number of arguments.
6140   if (checkArgCount(*this, TheCall, numArgs))
6141     return ExprError();
6142 
6143   // Inspect the last argument of the nontemporal builtin.  This should always
6144   // be a pointer type, from which we imply the type of the memory access.
6145   // Because it is a pointer type, we don't have to worry about any implicit
6146   // casts here.
6147   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6148   ExprResult PointerArgResult =
6149       DefaultFunctionArrayLvalueConversion(PointerArg);
6150 
6151   if (PointerArgResult.isInvalid())
6152     return ExprError();
6153   PointerArg = PointerArgResult.get();
6154   TheCall->setArg(numArgs - 1, PointerArg);
6155 
6156   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6157   if (!pointerType) {
6158     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6159         << PointerArg->getType() << PointerArg->getSourceRange();
6160     return ExprError();
6161   }
6162 
6163   QualType ValType = pointerType->getPointeeType();
6164 
6165   // Strip any qualifiers off ValType.
6166   ValType = ValType.getUnqualifiedType();
6167   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6168       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6169       !ValType->isVectorType()) {
6170     Diag(DRE->getBeginLoc(),
6171          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6172         << PointerArg->getType() << PointerArg->getSourceRange();
6173     return ExprError();
6174   }
6175 
6176   if (!isStore) {
6177     TheCall->setType(ValType);
6178     return TheCallResult;
6179   }
6180 
6181   ExprResult ValArg = TheCall->getArg(0);
6182   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6183       Context, ValType, /*consume*/ false);
6184   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6185   if (ValArg.isInvalid())
6186     return ExprError();
6187 
6188   TheCall->setArg(0, ValArg.get());
6189   TheCall->setType(Context.VoidTy);
6190   return TheCallResult;
6191 }
6192 
6193 /// CheckObjCString - Checks that the argument to the builtin
6194 /// CFString constructor is correct
6195 /// Note: It might also make sense to do the UTF-16 conversion here (would
6196 /// simplify the backend).
6197 bool Sema::CheckObjCString(Expr *Arg) {
6198   Arg = Arg->IgnoreParenCasts();
6199   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6200 
6201   if (!Literal || !Literal->isAscii()) {
6202     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6203         << Arg->getSourceRange();
6204     return true;
6205   }
6206 
6207   if (Literal->containsNonAsciiOrNull()) {
6208     StringRef String = Literal->getString();
6209     unsigned NumBytes = String.size();
6210     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6211     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6212     llvm::UTF16 *ToPtr = &ToBuf[0];
6213 
6214     llvm::ConversionResult Result =
6215         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6216                                  ToPtr + NumBytes, llvm::strictConversion);
6217     // Check for conversion failure.
6218     if (Result != llvm::conversionOK)
6219       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6220           << Arg->getSourceRange();
6221   }
6222   return false;
6223 }
6224 
6225 /// CheckObjCString - Checks that the format string argument to the os_log()
6226 /// and os_trace() functions is correct, and converts it to const char *.
6227 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6228   Arg = Arg->IgnoreParenCasts();
6229   auto *Literal = dyn_cast<StringLiteral>(Arg);
6230   if (!Literal) {
6231     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6232       Literal = ObjcLiteral->getString();
6233     }
6234   }
6235 
6236   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6237     return ExprError(
6238         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6239         << Arg->getSourceRange());
6240   }
6241 
6242   ExprResult Result(Literal);
6243   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6244   InitializedEntity Entity =
6245       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6246   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6247   return Result;
6248 }
6249 
6250 /// Check that the user is calling the appropriate va_start builtin for the
6251 /// target and calling convention.
6252 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6253   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6254   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6255   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6256                     TT.getArch() == llvm::Triple::aarch64_32);
6257   bool IsWindows = TT.isOSWindows();
6258   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6259   if (IsX64 || IsAArch64) {
6260     CallingConv CC = CC_C;
6261     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6262       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6263     if (IsMSVAStart) {
6264       // Don't allow this in System V ABI functions.
6265       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6266         return S.Diag(Fn->getBeginLoc(),
6267                       diag::err_ms_va_start_used_in_sysv_function);
6268     } else {
6269       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6270       // On x64 Windows, don't allow this in System V ABI functions.
6271       // (Yes, that means there's no corresponding way to support variadic
6272       // System V ABI functions on Windows.)
6273       if ((IsWindows && CC == CC_X86_64SysV) ||
6274           (!IsWindows && CC == CC_Win64))
6275         return S.Diag(Fn->getBeginLoc(),
6276                       diag::err_va_start_used_in_wrong_abi_function)
6277                << !IsWindows;
6278     }
6279     return false;
6280   }
6281 
6282   if (IsMSVAStart)
6283     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6284   return false;
6285 }
6286 
6287 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6288                                              ParmVarDecl **LastParam = nullptr) {
6289   // Determine whether the current function, block, or obj-c method is variadic
6290   // and get its parameter list.
6291   bool IsVariadic = false;
6292   ArrayRef<ParmVarDecl *> Params;
6293   DeclContext *Caller = S.CurContext;
6294   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6295     IsVariadic = Block->isVariadic();
6296     Params = Block->parameters();
6297   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6298     IsVariadic = FD->isVariadic();
6299     Params = FD->parameters();
6300   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6301     IsVariadic = MD->isVariadic();
6302     // FIXME: This isn't correct for methods (results in bogus warning).
6303     Params = MD->parameters();
6304   } else if (isa<CapturedDecl>(Caller)) {
6305     // We don't support va_start in a CapturedDecl.
6306     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6307     return true;
6308   } else {
6309     // This must be some other declcontext that parses exprs.
6310     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6311     return true;
6312   }
6313 
6314   if (!IsVariadic) {
6315     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6316     return true;
6317   }
6318 
6319   if (LastParam)
6320     *LastParam = Params.empty() ? nullptr : Params.back();
6321 
6322   return false;
6323 }
6324 
6325 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6326 /// for validity.  Emit an error and return true on failure; return false
6327 /// on success.
6328 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6329   Expr *Fn = TheCall->getCallee();
6330 
6331   if (checkVAStartABI(*this, BuiltinID, Fn))
6332     return true;
6333 
6334   if (checkArgCount(*this, TheCall, 2))
6335     return true;
6336 
6337   // Type-check the first argument normally.
6338   if (checkBuiltinArgument(*this, TheCall, 0))
6339     return true;
6340 
6341   // Check that the current function is variadic, and get its last parameter.
6342   ParmVarDecl *LastParam;
6343   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6344     return true;
6345 
6346   // Verify that the second argument to the builtin is the last argument of the
6347   // current function or method.
6348   bool SecondArgIsLastNamedArgument = false;
6349   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6350 
6351   // These are valid if SecondArgIsLastNamedArgument is false after the next
6352   // block.
6353   QualType Type;
6354   SourceLocation ParamLoc;
6355   bool IsCRegister = false;
6356 
6357   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6358     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6359       SecondArgIsLastNamedArgument = PV == LastParam;
6360 
6361       Type = PV->getType();
6362       ParamLoc = PV->getLocation();
6363       IsCRegister =
6364           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6365     }
6366   }
6367 
6368   if (!SecondArgIsLastNamedArgument)
6369     Diag(TheCall->getArg(1)->getBeginLoc(),
6370          diag::warn_second_arg_of_va_start_not_last_named_param);
6371   else if (IsCRegister || Type->isReferenceType() ||
6372            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6373              // Promotable integers are UB, but enumerations need a bit of
6374              // extra checking to see what their promotable type actually is.
6375              if (!Type->isPromotableIntegerType())
6376                return false;
6377              if (!Type->isEnumeralType())
6378                return true;
6379              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6380              return !(ED &&
6381                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6382            }()) {
6383     unsigned Reason = 0;
6384     if (Type->isReferenceType())  Reason = 1;
6385     else if (IsCRegister)         Reason = 2;
6386     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6387     Diag(ParamLoc, diag::note_parameter_type) << Type;
6388   }
6389 
6390   TheCall->setType(Context.VoidTy);
6391   return false;
6392 }
6393 
6394 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6395   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6396   //                 const char *named_addr);
6397 
6398   Expr *Func = Call->getCallee();
6399 
6400   if (Call->getNumArgs() < 3)
6401     return Diag(Call->getEndLoc(),
6402                 diag::err_typecheck_call_too_few_args_at_least)
6403            << 0 /*function call*/ << 3 << Call->getNumArgs();
6404 
6405   // Type-check the first argument normally.
6406   if (checkBuiltinArgument(*this, Call, 0))
6407     return true;
6408 
6409   // Check that the current function is variadic.
6410   if (checkVAStartIsInVariadicFunction(*this, Func))
6411     return true;
6412 
6413   // __va_start on Windows does not validate the parameter qualifiers
6414 
6415   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6416   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6417 
6418   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6419   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6420 
6421   const QualType &ConstCharPtrTy =
6422       Context.getPointerType(Context.CharTy.withConst());
6423   if (!Arg1Ty->isPointerType() ||
6424       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6425     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6426         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6427         << 0                                      /* qualifier difference */
6428         << 3                                      /* parameter mismatch */
6429         << 2 << Arg1->getType() << ConstCharPtrTy;
6430 
6431   const QualType SizeTy = Context.getSizeType();
6432   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6433     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6434         << Arg2->getType() << SizeTy << 1 /* different class */
6435         << 0                              /* qualifier difference */
6436         << 3                              /* parameter mismatch */
6437         << 3 << Arg2->getType() << SizeTy;
6438 
6439   return false;
6440 }
6441 
6442 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6443 /// friends.  This is declared to take (...), so we have to check everything.
6444 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6445   if (checkArgCount(*this, TheCall, 2))
6446     return true;
6447 
6448   ExprResult OrigArg0 = TheCall->getArg(0);
6449   ExprResult OrigArg1 = TheCall->getArg(1);
6450 
6451   // Do standard promotions between the two arguments, returning their common
6452   // type.
6453   QualType Res = UsualArithmeticConversions(
6454       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6455   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6456     return true;
6457 
6458   // Make sure any conversions are pushed back into the call; this is
6459   // type safe since unordered compare builtins are declared as "_Bool
6460   // foo(...)".
6461   TheCall->setArg(0, OrigArg0.get());
6462   TheCall->setArg(1, OrigArg1.get());
6463 
6464   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6465     return false;
6466 
6467   // If the common type isn't a real floating type, then the arguments were
6468   // invalid for this operation.
6469   if (Res.isNull() || !Res->isRealFloatingType())
6470     return Diag(OrigArg0.get()->getBeginLoc(),
6471                 diag::err_typecheck_call_invalid_ordered_compare)
6472            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6473            << SourceRange(OrigArg0.get()->getBeginLoc(),
6474                           OrigArg1.get()->getEndLoc());
6475 
6476   return false;
6477 }
6478 
6479 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6480 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6481 /// to check everything. We expect the last argument to be a floating point
6482 /// value.
6483 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6484   if (checkArgCount(*this, TheCall, NumArgs))
6485     return true;
6486 
6487   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6488   // on all preceding parameters just being int.  Try all of those.
6489   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6490     Expr *Arg = TheCall->getArg(i);
6491 
6492     if (Arg->isTypeDependent())
6493       return false;
6494 
6495     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6496 
6497     if (Res.isInvalid())
6498       return true;
6499     TheCall->setArg(i, Res.get());
6500   }
6501 
6502   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6503 
6504   if (OrigArg->isTypeDependent())
6505     return false;
6506 
6507   // Usual Unary Conversions will convert half to float, which we want for
6508   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6509   // type how it is, but do normal L->Rvalue conversions.
6510   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6511     OrigArg = UsualUnaryConversions(OrigArg).get();
6512   else
6513     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6514   TheCall->setArg(NumArgs - 1, OrigArg);
6515 
6516   // This operation requires a non-_Complex floating-point number.
6517   if (!OrigArg->getType()->isRealFloatingType())
6518     return Diag(OrigArg->getBeginLoc(),
6519                 diag::err_typecheck_call_invalid_unary_fp)
6520            << OrigArg->getType() << OrigArg->getSourceRange();
6521 
6522   return false;
6523 }
6524 
6525 /// Perform semantic analysis for a call to __builtin_complex.
6526 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6527   if (checkArgCount(*this, TheCall, 2))
6528     return true;
6529 
6530   bool Dependent = false;
6531   for (unsigned I = 0; I != 2; ++I) {
6532     Expr *Arg = TheCall->getArg(I);
6533     QualType T = Arg->getType();
6534     if (T->isDependentType()) {
6535       Dependent = true;
6536       continue;
6537     }
6538 
6539     // Despite supporting _Complex int, GCC requires a real floating point type
6540     // for the operands of __builtin_complex.
6541     if (!T->isRealFloatingType()) {
6542       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6543              << Arg->getType() << Arg->getSourceRange();
6544     }
6545 
6546     ExprResult Converted = DefaultLvalueConversion(Arg);
6547     if (Converted.isInvalid())
6548       return true;
6549     TheCall->setArg(I, Converted.get());
6550   }
6551 
6552   if (Dependent) {
6553     TheCall->setType(Context.DependentTy);
6554     return false;
6555   }
6556 
6557   Expr *Real = TheCall->getArg(0);
6558   Expr *Imag = TheCall->getArg(1);
6559   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6560     return Diag(Real->getBeginLoc(),
6561                 diag::err_typecheck_call_different_arg_types)
6562            << Real->getType() << Imag->getType()
6563            << Real->getSourceRange() << Imag->getSourceRange();
6564   }
6565 
6566   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6567   // don't allow this builtin to form those types either.
6568   // FIXME: Should we allow these types?
6569   if (Real->getType()->isFloat16Type())
6570     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6571            << "_Float16";
6572   if (Real->getType()->isHalfType())
6573     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6574            << "half";
6575 
6576   TheCall->setType(Context.getComplexType(Real->getType()));
6577   return false;
6578 }
6579 
6580 // Customized Sema Checking for VSX builtins that have the following signature:
6581 // vector [...] builtinName(vector [...], vector [...], const int);
6582 // Which takes the same type of vectors (any legal vector type) for the first
6583 // two arguments and takes compile time constant for the third argument.
6584 // Example builtins are :
6585 // vector double vec_xxpermdi(vector double, vector double, int);
6586 // vector short vec_xxsldwi(vector short, vector short, int);
6587 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6588   unsigned ExpectedNumArgs = 3;
6589   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6590     return true;
6591 
6592   // Check the third argument is a compile time constant
6593   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6594     return Diag(TheCall->getBeginLoc(),
6595                 diag::err_vsx_builtin_nonconstant_argument)
6596            << 3 /* argument index */ << TheCall->getDirectCallee()
6597            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6598                           TheCall->getArg(2)->getEndLoc());
6599 
6600   QualType Arg1Ty = TheCall->getArg(0)->getType();
6601   QualType Arg2Ty = TheCall->getArg(1)->getType();
6602 
6603   // Check the type of argument 1 and argument 2 are vectors.
6604   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6605   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6606       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6607     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6608            << TheCall->getDirectCallee()
6609            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6610                           TheCall->getArg(1)->getEndLoc());
6611   }
6612 
6613   // Check the first two arguments are the same type.
6614   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6615     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6616            << TheCall->getDirectCallee()
6617            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6618                           TheCall->getArg(1)->getEndLoc());
6619   }
6620 
6621   // When default clang type checking is turned off and the customized type
6622   // checking is used, the returning type of the function must be explicitly
6623   // set. Otherwise it is _Bool by default.
6624   TheCall->setType(Arg1Ty);
6625 
6626   return false;
6627 }
6628 
6629 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6630 // This is declared to take (...), so we have to check everything.
6631 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6632   if (TheCall->getNumArgs() < 2)
6633     return ExprError(Diag(TheCall->getEndLoc(),
6634                           diag::err_typecheck_call_too_few_args_at_least)
6635                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6636                      << TheCall->getSourceRange());
6637 
6638   // Determine which of the following types of shufflevector we're checking:
6639   // 1) unary, vector mask: (lhs, mask)
6640   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6641   QualType resType = TheCall->getArg(0)->getType();
6642   unsigned numElements = 0;
6643 
6644   if (!TheCall->getArg(0)->isTypeDependent() &&
6645       !TheCall->getArg(1)->isTypeDependent()) {
6646     QualType LHSType = TheCall->getArg(0)->getType();
6647     QualType RHSType = TheCall->getArg(1)->getType();
6648 
6649     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6650       return ExprError(
6651           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6652           << TheCall->getDirectCallee()
6653           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6654                          TheCall->getArg(1)->getEndLoc()));
6655 
6656     numElements = LHSType->castAs<VectorType>()->getNumElements();
6657     unsigned numResElements = TheCall->getNumArgs() - 2;
6658 
6659     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6660     // with mask.  If so, verify that RHS is an integer vector type with the
6661     // same number of elts as lhs.
6662     if (TheCall->getNumArgs() == 2) {
6663       if (!RHSType->hasIntegerRepresentation() ||
6664           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6665         return ExprError(Diag(TheCall->getBeginLoc(),
6666                               diag::err_vec_builtin_incompatible_vector)
6667                          << TheCall->getDirectCallee()
6668                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6669                                         TheCall->getArg(1)->getEndLoc()));
6670     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6671       return ExprError(Diag(TheCall->getBeginLoc(),
6672                             diag::err_vec_builtin_incompatible_vector)
6673                        << TheCall->getDirectCallee()
6674                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6675                                       TheCall->getArg(1)->getEndLoc()));
6676     } else if (numElements != numResElements) {
6677       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6678       resType = Context.getVectorType(eltType, numResElements,
6679                                       VectorType::GenericVector);
6680     }
6681   }
6682 
6683   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6684     if (TheCall->getArg(i)->isTypeDependent() ||
6685         TheCall->getArg(i)->isValueDependent())
6686       continue;
6687 
6688     Optional<llvm::APSInt> Result;
6689     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6690       return ExprError(Diag(TheCall->getBeginLoc(),
6691                             diag::err_shufflevector_nonconstant_argument)
6692                        << TheCall->getArg(i)->getSourceRange());
6693 
6694     // Allow -1 which will be translated to undef in the IR.
6695     if (Result->isSigned() && Result->isAllOnesValue())
6696       continue;
6697 
6698     if (Result->getActiveBits() > 64 ||
6699         Result->getZExtValue() >= numElements * 2)
6700       return ExprError(Diag(TheCall->getBeginLoc(),
6701                             diag::err_shufflevector_argument_too_large)
6702                        << TheCall->getArg(i)->getSourceRange());
6703   }
6704 
6705   SmallVector<Expr*, 32> exprs;
6706 
6707   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6708     exprs.push_back(TheCall->getArg(i));
6709     TheCall->setArg(i, nullptr);
6710   }
6711 
6712   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6713                                          TheCall->getCallee()->getBeginLoc(),
6714                                          TheCall->getRParenLoc());
6715 }
6716 
6717 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6718 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6719                                        SourceLocation BuiltinLoc,
6720                                        SourceLocation RParenLoc) {
6721   ExprValueKind VK = VK_PRValue;
6722   ExprObjectKind OK = OK_Ordinary;
6723   QualType DstTy = TInfo->getType();
6724   QualType SrcTy = E->getType();
6725 
6726   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6727     return ExprError(Diag(BuiltinLoc,
6728                           diag::err_convertvector_non_vector)
6729                      << E->getSourceRange());
6730   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6731     return ExprError(Diag(BuiltinLoc,
6732                           diag::err_convertvector_non_vector_type));
6733 
6734   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6735     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6736     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6737     if (SrcElts != DstElts)
6738       return ExprError(Diag(BuiltinLoc,
6739                             diag::err_convertvector_incompatible_vector)
6740                        << E->getSourceRange());
6741   }
6742 
6743   return new (Context)
6744       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6745 }
6746 
6747 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6748 // This is declared to take (const void*, ...) and can take two
6749 // optional constant int args.
6750 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6751   unsigned NumArgs = TheCall->getNumArgs();
6752 
6753   if (NumArgs > 3)
6754     return Diag(TheCall->getEndLoc(),
6755                 diag::err_typecheck_call_too_many_args_at_most)
6756            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6757 
6758   // Argument 0 is checked for us and the remaining arguments must be
6759   // constant integers.
6760   for (unsigned i = 1; i != NumArgs; ++i)
6761     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6762       return true;
6763 
6764   return false;
6765 }
6766 
6767 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6768 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6769   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6770     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6771            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6772   if (checkArgCount(*this, TheCall, 1))
6773     return true;
6774   Expr *Arg = TheCall->getArg(0);
6775   if (Arg->isInstantiationDependent())
6776     return false;
6777 
6778   QualType ArgTy = Arg->getType();
6779   if (!ArgTy->hasFloatingRepresentation())
6780     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6781            << ArgTy;
6782   if (Arg->isLValue()) {
6783     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6784     TheCall->setArg(0, FirstArg.get());
6785   }
6786   TheCall->setType(TheCall->getArg(0)->getType());
6787   return false;
6788 }
6789 
6790 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6791 // __assume does not evaluate its arguments, and should warn if its argument
6792 // has side effects.
6793 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6794   Expr *Arg = TheCall->getArg(0);
6795   if (Arg->isInstantiationDependent()) return false;
6796 
6797   if (Arg->HasSideEffects(Context))
6798     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6799         << Arg->getSourceRange()
6800         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6801 
6802   return false;
6803 }
6804 
6805 /// Handle __builtin_alloca_with_align. This is declared
6806 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6807 /// than 8.
6808 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6809   // The alignment must be a constant integer.
6810   Expr *Arg = TheCall->getArg(1);
6811 
6812   // We can't check the value of a dependent argument.
6813   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6814     if (const auto *UE =
6815             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6816       if (UE->getKind() == UETT_AlignOf ||
6817           UE->getKind() == UETT_PreferredAlignOf)
6818         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6819             << Arg->getSourceRange();
6820 
6821     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6822 
6823     if (!Result.isPowerOf2())
6824       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6825              << Arg->getSourceRange();
6826 
6827     if (Result < Context.getCharWidth())
6828       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6829              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6830 
6831     if (Result > std::numeric_limits<int32_t>::max())
6832       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6833              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6834   }
6835 
6836   return false;
6837 }
6838 
6839 /// Handle __builtin_assume_aligned. This is declared
6840 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6841 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6842   unsigned NumArgs = TheCall->getNumArgs();
6843 
6844   if (NumArgs > 3)
6845     return Diag(TheCall->getEndLoc(),
6846                 diag::err_typecheck_call_too_many_args_at_most)
6847            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6848 
6849   // The alignment must be a constant integer.
6850   Expr *Arg = TheCall->getArg(1);
6851 
6852   // We can't check the value of a dependent argument.
6853   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6854     llvm::APSInt Result;
6855     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6856       return true;
6857 
6858     if (!Result.isPowerOf2())
6859       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6860              << Arg->getSourceRange();
6861 
6862     if (Result > Sema::MaximumAlignment)
6863       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6864           << Arg->getSourceRange() << Sema::MaximumAlignment;
6865   }
6866 
6867   if (NumArgs > 2) {
6868     ExprResult Arg(TheCall->getArg(2));
6869     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6870       Context.getSizeType(), false);
6871     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6872     if (Arg.isInvalid()) return true;
6873     TheCall->setArg(2, Arg.get());
6874   }
6875 
6876   return false;
6877 }
6878 
6879 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6880   unsigned BuiltinID =
6881       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6882   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6883 
6884   unsigned NumArgs = TheCall->getNumArgs();
6885   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6886   if (NumArgs < NumRequiredArgs) {
6887     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6888            << 0 /* function call */ << NumRequiredArgs << NumArgs
6889            << TheCall->getSourceRange();
6890   }
6891   if (NumArgs >= NumRequiredArgs + 0x100) {
6892     return Diag(TheCall->getEndLoc(),
6893                 diag::err_typecheck_call_too_many_args_at_most)
6894            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6895            << TheCall->getSourceRange();
6896   }
6897   unsigned i = 0;
6898 
6899   // For formatting call, check buffer arg.
6900   if (!IsSizeCall) {
6901     ExprResult Arg(TheCall->getArg(i));
6902     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6903         Context, Context.VoidPtrTy, false);
6904     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6905     if (Arg.isInvalid())
6906       return true;
6907     TheCall->setArg(i, Arg.get());
6908     i++;
6909   }
6910 
6911   // Check string literal arg.
6912   unsigned FormatIdx = i;
6913   {
6914     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6915     if (Arg.isInvalid())
6916       return true;
6917     TheCall->setArg(i, Arg.get());
6918     i++;
6919   }
6920 
6921   // Make sure variadic args are scalar.
6922   unsigned FirstDataArg = i;
6923   while (i < NumArgs) {
6924     ExprResult Arg = DefaultVariadicArgumentPromotion(
6925         TheCall->getArg(i), VariadicFunction, nullptr);
6926     if (Arg.isInvalid())
6927       return true;
6928     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6929     if (ArgSize.getQuantity() >= 0x100) {
6930       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6931              << i << (int)ArgSize.getQuantity() << 0xff
6932              << TheCall->getSourceRange();
6933     }
6934     TheCall->setArg(i, Arg.get());
6935     i++;
6936   }
6937 
6938   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6939   // call to avoid duplicate diagnostics.
6940   if (!IsSizeCall) {
6941     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6942     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6943     bool Success = CheckFormatArguments(
6944         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6945         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6946         CheckedVarArgs);
6947     if (!Success)
6948       return true;
6949   }
6950 
6951   if (IsSizeCall) {
6952     TheCall->setType(Context.getSizeType());
6953   } else {
6954     TheCall->setType(Context.VoidPtrTy);
6955   }
6956   return false;
6957 }
6958 
6959 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6960 /// TheCall is a constant expression.
6961 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6962                                   llvm::APSInt &Result) {
6963   Expr *Arg = TheCall->getArg(ArgNum);
6964   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6965   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6966 
6967   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6968 
6969   Optional<llvm::APSInt> R;
6970   if (!(R = Arg->getIntegerConstantExpr(Context)))
6971     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6972            << FDecl->getDeclName() << Arg->getSourceRange();
6973   Result = *R;
6974   return false;
6975 }
6976 
6977 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6978 /// TheCall is a constant expression in the range [Low, High].
6979 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6980                                        int Low, int High, bool RangeIsError) {
6981   if (isConstantEvaluated())
6982     return false;
6983   llvm::APSInt Result;
6984 
6985   // We can't check the value of a dependent argument.
6986   Expr *Arg = TheCall->getArg(ArgNum);
6987   if (Arg->isTypeDependent() || Arg->isValueDependent())
6988     return false;
6989 
6990   // Check constant-ness first.
6991   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6992     return true;
6993 
6994   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6995     if (RangeIsError)
6996       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6997              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6998     else
6999       // Defer the warning until we know if the code will be emitted so that
7000       // dead code can ignore this.
7001       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7002                           PDiag(diag::warn_argument_invalid_range)
7003                               << toString(Result, 10) << Low << High
7004                               << Arg->getSourceRange());
7005   }
7006 
7007   return false;
7008 }
7009 
7010 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7011 /// TheCall is a constant expression is a multiple of Num..
7012 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7013                                           unsigned Num) {
7014   llvm::APSInt Result;
7015 
7016   // We can't check the value of a dependent argument.
7017   Expr *Arg = TheCall->getArg(ArgNum);
7018   if (Arg->isTypeDependent() || Arg->isValueDependent())
7019     return false;
7020 
7021   // Check constant-ness first.
7022   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7023     return true;
7024 
7025   if (Result.getSExtValue() % Num != 0)
7026     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7027            << Num << Arg->getSourceRange();
7028 
7029   return false;
7030 }
7031 
7032 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7033 /// constant expression representing a power of 2.
7034 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7035   llvm::APSInt Result;
7036 
7037   // We can't check the value of a dependent argument.
7038   Expr *Arg = TheCall->getArg(ArgNum);
7039   if (Arg->isTypeDependent() || Arg->isValueDependent())
7040     return false;
7041 
7042   // Check constant-ness first.
7043   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7044     return true;
7045 
7046   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7047   // and only if x is a power of 2.
7048   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7049     return false;
7050 
7051   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7052          << Arg->getSourceRange();
7053 }
7054 
7055 static bool IsShiftedByte(llvm::APSInt Value) {
7056   if (Value.isNegative())
7057     return false;
7058 
7059   // Check if it's a shifted byte, by shifting it down
7060   while (true) {
7061     // If the value fits in the bottom byte, the check passes.
7062     if (Value < 0x100)
7063       return true;
7064 
7065     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7066     // fails.
7067     if ((Value & 0xFF) != 0)
7068       return false;
7069 
7070     // If the bottom 8 bits are all 0, but something above that is nonzero,
7071     // then shifting the value right by 8 bits won't affect whether it's a
7072     // shifted byte or not. So do that, and go round again.
7073     Value >>= 8;
7074   }
7075 }
7076 
7077 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7078 /// a constant expression representing an arbitrary byte value shifted left by
7079 /// a multiple of 8 bits.
7080 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7081                                              unsigned ArgBits) {
7082   llvm::APSInt Result;
7083 
7084   // We can't check the value of a dependent argument.
7085   Expr *Arg = TheCall->getArg(ArgNum);
7086   if (Arg->isTypeDependent() || Arg->isValueDependent())
7087     return false;
7088 
7089   // Check constant-ness first.
7090   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7091     return true;
7092 
7093   // Truncate to the given size.
7094   Result = Result.getLoBits(ArgBits);
7095   Result.setIsUnsigned(true);
7096 
7097   if (IsShiftedByte(Result))
7098     return false;
7099 
7100   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7101          << Arg->getSourceRange();
7102 }
7103 
7104 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7105 /// TheCall is a constant expression representing either a shifted byte value,
7106 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7107 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7108 /// Arm MVE intrinsics.
7109 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7110                                                    int ArgNum,
7111                                                    unsigned ArgBits) {
7112   llvm::APSInt Result;
7113 
7114   // We can't check the value of a dependent argument.
7115   Expr *Arg = TheCall->getArg(ArgNum);
7116   if (Arg->isTypeDependent() || Arg->isValueDependent())
7117     return false;
7118 
7119   // Check constant-ness first.
7120   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7121     return true;
7122 
7123   // Truncate to the given size.
7124   Result = Result.getLoBits(ArgBits);
7125   Result.setIsUnsigned(true);
7126 
7127   // Check to see if it's in either of the required forms.
7128   if (IsShiftedByte(Result) ||
7129       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7130     return false;
7131 
7132   return Diag(TheCall->getBeginLoc(),
7133               diag::err_argument_not_shifted_byte_or_xxff)
7134          << Arg->getSourceRange();
7135 }
7136 
7137 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7138 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7139   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7140     if (checkArgCount(*this, TheCall, 2))
7141       return true;
7142     Expr *Arg0 = TheCall->getArg(0);
7143     Expr *Arg1 = TheCall->getArg(1);
7144 
7145     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7146     if (FirstArg.isInvalid())
7147       return true;
7148     QualType FirstArgType = FirstArg.get()->getType();
7149     if (!FirstArgType->isAnyPointerType())
7150       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7151                << "first" << FirstArgType << Arg0->getSourceRange();
7152     TheCall->setArg(0, FirstArg.get());
7153 
7154     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7155     if (SecArg.isInvalid())
7156       return true;
7157     QualType SecArgType = SecArg.get()->getType();
7158     if (!SecArgType->isIntegerType())
7159       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7160                << "second" << SecArgType << Arg1->getSourceRange();
7161 
7162     // Derive the return type from the pointer argument.
7163     TheCall->setType(FirstArgType);
7164     return false;
7165   }
7166 
7167   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7168     if (checkArgCount(*this, TheCall, 2))
7169       return true;
7170 
7171     Expr *Arg0 = TheCall->getArg(0);
7172     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7173     if (FirstArg.isInvalid())
7174       return true;
7175     QualType FirstArgType = FirstArg.get()->getType();
7176     if (!FirstArgType->isAnyPointerType())
7177       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7178                << "first" << FirstArgType << Arg0->getSourceRange();
7179     TheCall->setArg(0, FirstArg.get());
7180 
7181     // Derive the return type from the pointer argument.
7182     TheCall->setType(FirstArgType);
7183 
7184     // Second arg must be an constant in range [0,15]
7185     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7186   }
7187 
7188   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7189     if (checkArgCount(*this, TheCall, 2))
7190       return true;
7191     Expr *Arg0 = TheCall->getArg(0);
7192     Expr *Arg1 = TheCall->getArg(1);
7193 
7194     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7195     if (FirstArg.isInvalid())
7196       return true;
7197     QualType FirstArgType = FirstArg.get()->getType();
7198     if (!FirstArgType->isAnyPointerType())
7199       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7200                << "first" << FirstArgType << Arg0->getSourceRange();
7201 
7202     QualType SecArgType = Arg1->getType();
7203     if (!SecArgType->isIntegerType())
7204       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7205                << "second" << SecArgType << Arg1->getSourceRange();
7206     TheCall->setType(Context.IntTy);
7207     return false;
7208   }
7209 
7210   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7211       BuiltinID == AArch64::BI__builtin_arm_stg) {
7212     if (checkArgCount(*this, TheCall, 1))
7213       return true;
7214     Expr *Arg0 = TheCall->getArg(0);
7215     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7216     if (FirstArg.isInvalid())
7217       return true;
7218 
7219     QualType FirstArgType = FirstArg.get()->getType();
7220     if (!FirstArgType->isAnyPointerType())
7221       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7222                << "first" << FirstArgType << Arg0->getSourceRange();
7223     TheCall->setArg(0, FirstArg.get());
7224 
7225     // Derive the return type from the pointer argument.
7226     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7227       TheCall->setType(FirstArgType);
7228     return false;
7229   }
7230 
7231   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7232     Expr *ArgA = TheCall->getArg(0);
7233     Expr *ArgB = TheCall->getArg(1);
7234 
7235     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7236     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7237 
7238     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7239       return true;
7240 
7241     QualType ArgTypeA = ArgExprA.get()->getType();
7242     QualType ArgTypeB = ArgExprB.get()->getType();
7243 
7244     auto isNull = [&] (Expr *E) -> bool {
7245       return E->isNullPointerConstant(
7246                         Context, Expr::NPC_ValueDependentIsNotNull); };
7247 
7248     // argument should be either a pointer or null
7249     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7250       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7251         << "first" << ArgTypeA << ArgA->getSourceRange();
7252 
7253     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7254       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7255         << "second" << ArgTypeB << ArgB->getSourceRange();
7256 
7257     // Ensure Pointee types are compatible
7258     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7259         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7260       QualType pointeeA = ArgTypeA->getPointeeType();
7261       QualType pointeeB = ArgTypeB->getPointeeType();
7262       if (!Context.typesAreCompatible(
7263              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7264              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7265         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7266           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7267           << ArgB->getSourceRange();
7268       }
7269     }
7270 
7271     // at least one argument should be pointer type
7272     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7273       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7274         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7275 
7276     if (isNull(ArgA)) // adopt type of the other pointer
7277       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7278 
7279     if (isNull(ArgB))
7280       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7281 
7282     TheCall->setArg(0, ArgExprA.get());
7283     TheCall->setArg(1, ArgExprB.get());
7284     TheCall->setType(Context.LongLongTy);
7285     return false;
7286   }
7287   assert(false && "Unhandled ARM MTE intrinsic");
7288   return true;
7289 }
7290 
7291 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7292 /// TheCall is an ARM/AArch64 special register string literal.
7293 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7294                                     int ArgNum, unsigned ExpectedFieldNum,
7295                                     bool AllowName) {
7296   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7297                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7298                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7299                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7300                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7301                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7302   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7303                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7304                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7305                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7306                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7307                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7308   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7309 
7310   // We can't check the value of a dependent argument.
7311   Expr *Arg = TheCall->getArg(ArgNum);
7312   if (Arg->isTypeDependent() || Arg->isValueDependent())
7313     return false;
7314 
7315   // Check if the argument is a string literal.
7316   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7317     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7318            << Arg->getSourceRange();
7319 
7320   // Check the type of special register given.
7321   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7322   SmallVector<StringRef, 6> Fields;
7323   Reg.split(Fields, ":");
7324 
7325   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7326     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7327            << Arg->getSourceRange();
7328 
7329   // If the string is the name of a register then we cannot check that it is
7330   // valid here but if the string is of one the forms described in ACLE then we
7331   // can check that the supplied fields are integers and within the valid
7332   // ranges.
7333   if (Fields.size() > 1) {
7334     bool FiveFields = Fields.size() == 5;
7335 
7336     bool ValidString = true;
7337     if (IsARMBuiltin) {
7338       ValidString &= Fields[0].startswith_insensitive("cp") ||
7339                      Fields[0].startswith_insensitive("p");
7340       if (ValidString)
7341         Fields[0] = Fields[0].drop_front(
7342             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7343 
7344       ValidString &= Fields[2].startswith_insensitive("c");
7345       if (ValidString)
7346         Fields[2] = Fields[2].drop_front(1);
7347 
7348       if (FiveFields) {
7349         ValidString &= Fields[3].startswith_insensitive("c");
7350         if (ValidString)
7351           Fields[3] = Fields[3].drop_front(1);
7352       }
7353     }
7354 
7355     SmallVector<int, 5> Ranges;
7356     if (FiveFields)
7357       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7358     else
7359       Ranges.append({15, 7, 15});
7360 
7361     for (unsigned i=0; i<Fields.size(); ++i) {
7362       int IntField;
7363       ValidString &= !Fields[i].getAsInteger(10, IntField);
7364       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7365     }
7366 
7367     if (!ValidString)
7368       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7369              << Arg->getSourceRange();
7370   } else if (IsAArch64Builtin && Fields.size() == 1) {
7371     // If the register name is one of those that appear in the condition below
7372     // and the special register builtin being used is one of the write builtins,
7373     // then we require that the argument provided for writing to the register
7374     // is an integer constant expression. This is because it will be lowered to
7375     // an MSR (immediate) instruction, so we need to know the immediate at
7376     // compile time.
7377     if (TheCall->getNumArgs() != 2)
7378       return false;
7379 
7380     std::string RegLower = Reg.lower();
7381     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7382         RegLower != "pan" && RegLower != "uao")
7383       return false;
7384 
7385     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7386   }
7387 
7388   return false;
7389 }
7390 
7391 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7392 /// Emit an error and return true on failure; return false on success.
7393 /// TypeStr is a string containing the type descriptor of the value returned by
7394 /// the builtin and the descriptors of the expected type of the arguments.
7395 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7396 
7397   assert((TypeStr[0] != '\0') &&
7398          "Invalid types in PPC MMA builtin declaration");
7399 
7400   unsigned Mask = 0;
7401   unsigned ArgNum = 0;
7402 
7403   // The first type in TypeStr is the type of the value returned by the
7404   // builtin. So we first read that type and change the type of TheCall.
7405   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7406   TheCall->setType(type);
7407 
7408   while (*TypeStr != '\0') {
7409     Mask = 0;
7410     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7411     if (ArgNum >= TheCall->getNumArgs()) {
7412       ArgNum++;
7413       break;
7414     }
7415 
7416     Expr *Arg = TheCall->getArg(ArgNum);
7417     QualType ArgType = Arg->getType();
7418 
7419     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7420         (!ExpectedType->isVoidPointerType() &&
7421            ArgType.getCanonicalType() != ExpectedType))
7422       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7423              << ArgType << ExpectedType << 1 << 0 << 0;
7424 
7425     // If the value of the Mask is not 0, we have a constraint in the size of
7426     // the integer argument so here we ensure the argument is a constant that
7427     // is in the valid range.
7428     if (Mask != 0 &&
7429         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7430       return true;
7431 
7432     ArgNum++;
7433   }
7434 
7435   // In case we exited early from the previous loop, there are other types to
7436   // read from TypeStr. So we need to read them all to ensure we have the right
7437   // number of arguments in TheCall and if it is not the case, to display a
7438   // better error message.
7439   while (*TypeStr != '\0') {
7440     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7441     ArgNum++;
7442   }
7443   if (checkArgCount(*this, TheCall, ArgNum))
7444     return true;
7445 
7446   return false;
7447 }
7448 
7449 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7450 /// This checks that the target supports __builtin_longjmp and
7451 /// that val is a constant 1.
7452 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7453   if (!Context.getTargetInfo().hasSjLjLowering())
7454     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7455            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7456 
7457   Expr *Arg = TheCall->getArg(1);
7458   llvm::APSInt Result;
7459 
7460   // TODO: This is less than ideal. Overload this to take a value.
7461   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7462     return true;
7463 
7464   if (Result != 1)
7465     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7466            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7467 
7468   return false;
7469 }
7470 
7471 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7472 /// This checks that the target supports __builtin_setjmp.
7473 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7474   if (!Context.getTargetInfo().hasSjLjLowering())
7475     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7476            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7477   return false;
7478 }
7479 
7480 namespace {
7481 
7482 class UncoveredArgHandler {
7483   enum { Unknown = -1, AllCovered = -2 };
7484 
7485   signed FirstUncoveredArg = Unknown;
7486   SmallVector<const Expr *, 4> DiagnosticExprs;
7487 
7488 public:
7489   UncoveredArgHandler() = default;
7490 
7491   bool hasUncoveredArg() const {
7492     return (FirstUncoveredArg >= 0);
7493   }
7494 
7495   unsigned getUncoveredArg() const {
7496     assert(hasUncoveredArg() && "no uncovered argument");
7497     return FirstUncoveredArg;
7498   }
7499 
7500   void setAllCovered() {
7501     // A string has been found with all arguments covered, so clear out
7502     // the diagnostics.
7503     DiagnosticExprs.clear();
7504     FirstUncoveredArg = AllCovered;
7505   }
7506 
7507   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7508     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7509 
7510     // Don't update if a previous string covers all arguments.
7511     if (FirstUncoveredArg == AllCovered)
7512       return;
7513 
7514     // UncoveredArgHandler tracks the highest uncovered argument index
7515     // and with it all the strings that match this index.
7516     if (NewFirstUncoveredArg == FirstUncoveredArg)
7517       DiagnosticExprs.push_back(StrExpr);
7518     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7519       DiagnosticExprs.clear();
7520       DiagnosticExprs.push_back(StrExpr);
7521       FirstUncoveredArg = NewFirstUncoveredArg;
7522     }
7523   }
7524 
7525   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7526 };
7527 
7528 enum StringLiteralCheckType {
7529   SLCT_NotALiteral,
7530   SLCT_UncheckedLiteral,
7531   SLCT_CheckedLiteral
7532 };
7533 
7534 } // namespace
7535 
7536 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7537                                      BinaryOperatorKind BinOpKind,
7538                                      bool AddendIsRight) {
7539   unsigned BitWidth = Offset.getBitWidth();
7540   unsigned AddendBitWidth = Addend.getBitWidth();
7541   // There might be negative interim results.
7542   if (Addend.isUnsigned()) {
7543     Addend = Addend.zext(++AddendBitWidth);
7544     Addend.setIsSigned(true);
7545   }
7546   // Adjust the bit width of the APSInts.
7547   if (AddendBitWidth > BitWidth) {
7548     Offset = Offset.sext(AddendBitWidth);
7549     BitWidth = AddendBitWidth;
7550   } else if (BitWidth > AddendBitWidth) {
7551     Addend = Addend.sext(BitWidth);
7552   }
7553 
7554   bool Ov = false;
7555   llvm::APSInt ResOffset = Offset;
7556   if (BinOpKind == BO_Add)
7557     ResOffset = Offset.sadd_ov(Addend, Ov);
7558   else {
7559     assert(AddendIsRight && BinOpKind == BO_Sub &&
7560            "operator must be add or sub with addend on the right");
7561     ResOffset = Offset.ssub_ov(Addend, Ov);
7562   }
7563 
7564   // We add an offset to a pointer here so we should support an offset as big as
7565   // possible.
7566   if (Ov) {
7567     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7568            "index (intermediate) result too big");
7569     Offset = Offset.sext(2 * BitWidth);
7570     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7571     return;
7572   }
7573 
7574   Offset = ResOffset;
7575 }
7576 
7577 namespace {
7578 
7579 // This is a wrapper class around StringLiteral to support offsetted string
7580 // literals as format strings. It takes the offset into account when returning
7581 // the string and its length or the source locations to display notes correctly.
7582 class FormatStringLiteral {
7583   const StringLiteral *FExpr;
7584   int64_t Offset;
7585 
7586  public:
7587   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7588       : FExpr(fexpr), Offset(Offset) {}
7589 
7590   StringRef getString() const {
7591     return FExpr->getString().drop_front(Offset);
7592   }
7593 
7594   unsigned getByteLength() const {
7595     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7596   }
7597 
7598   unsigned getLength() const { return FExpr->getLength() - Offset; }
7599   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7600 
7601   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7602 
7603   QualType getType() const { return FExpr->getType(); }
7604 
7605   bool isAscii() const { return FExpr->isAscii(); }
7606   bool isWide() const { return FExpr->isWide(); }
7607   bool isUTF8() const { return FExpr->isUTF8(); }
7608   bool isUTF16() const { return FExpr->isUTF16(); }
7609   bool isUTF32() const { return FExpr->isUTF32(); }
7610   bool isPascal() const { return FExpr->isPascal(); }
7611 
7612   SourceLocation getLocationOfByte(
7613       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7614       const TargetInfo &Target, unsigned *StartToken = nullptr,
7615       unsigned *StartTokenByteOffset = nullptr) const {
7616     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7617                                     StartToken, StartTokenByteOffset);
7618   }
7619 
7620   SourceLocation getBeginLoc() const LLVM_READONLY {
7621     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7622   }
7623 
7624   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7625 };
7626 
7627 }  // namespace
7628 
7629 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7630                               const Expr *OrigFormatExpr,
7631                               ArrayRef<const Expr *> Args,
7632                               bool HasVAListArg, unsigned format_idx,
7633                               unsigned firstDataArg,
7634                               Sema::FormatStringType Type,
7635                               bool inFunctionCall,
7636                               Sema::VariadicCallType CallType,
7637                               llvm::SmallBitVector &CheckedVarArgs,
7638                               UncoveredArgHandler &UncoveredArg,
7639                               bool IgnoreStringsWithoutSpecifiers);
7640 
7641 // Determine if an expression is a string literal or constant string.
7642 // If this function returns false on the arguments to a function expecting a
7643 // format string, we will usually need to emit a warning.
7644 // True string literals are then checked by CheckFormatString.
7645 static StringLiteralCheckType
7646 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7647                       bool HasVAListArg, unsigned format_idx,
7648                       unsigned firstDataArg, Sema::FormatStringType Type,
7649                       Sema::VariadicCallType CallType, bool InFunctionCall,
7650                       llvm::SmallBitVector &CheckedVarArgs,
7651                       UncoveredArgHandler &UncoveredArg,
7652                       llvm::APSInt Offset,
7653                       bool IgnoreStringsWithoutSpecifiers = false) {
7654   if (S.isConstantEvaluated())
7655     return SLCT_NotALiteral;
7656  tryAgain:
7657   assert(Offset.isSigned() && "invalid offset");
7658 
7659   if (E->isTypeDependent() || E->isValueDependent())
7660     return SLCT_NotALiteral;
7661 
7662   E = E->IgnoreParenCasts();
7663 
7664   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7665     // Technically -Wformat-nonliteral does not warn about this case.
7666     // The behavior of printf and friends in this case is implementation
7667     // dependent.  Ideally if the format string cannot be null then
7668     // it should have a 'nonnull' attribute in the function prototype.
7669     return SLCT_UncheckedLiteral;
7670 
7671   switch (E->getStmtClass()) {
7672   case Stmt::BinaryConditionalOperatorClass:
7673   case Stmt::ConditionalOperatorClass: {
7674     // The expression is a literal if both sub-expressions were, and it was
7675     // completely checked only if both sub-expressions were checked.
7676     const AbstractConditionalOperator *C =
7677         cast<AbstractConditionalOperator>(E);
7678 
7679     // Determine whether it is necessary to check both sub-expressions, for
7680     // example, because the condition expression is a constant that can be
7681     // evaluated at compile time.
7682     bool CheckLeft = true, CheckRight = true;
7683 
7684     bool Cond;
7685     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7686                                                  S.isConstantEvaluated())) {
7687       if (Cond)
7688         CheckRight = false;
7689       else
7690         CheckLeft = false;
7691     }
7692 
7693     // We need to maintain the offsets for the right and the left hand side
7694     // separately to check if every possible indexed expression is a valid
7695     // string literal. They might have different offsets for different string
7696     // literals in the end.
7697     StringLiteralCheckType Left;
7698     if (!CheckLeft)
7699       Left = SLCT_UncheckedLiteral;
7700     else {
7701       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7702                                    HasVAListArg, format_idx, firstDataArg,
7703                                    Type, CallType, InFunctionCall,
7704                                    CheckedVarArgs, UncoveredArg, Offset,
7705                                    IgnoreStringsWithoutSpecifiers);
7706       if (Left == SLCT_NotALiteral || !CheckRight) {
7707         return Left;
7708       }
7709     }
7710 
7711     StringLiteralCheckType Right = checkFormatStringExpr(
7712         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7713         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7714         IgnoreStringsWithoutSpecifiers);
7715 
7716     return (CheckLeft && Left < Right) ? Left : Right;
7717   }
7718 
7719   case Stmt::ImplicitCastExprClass:
7720     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7721     goto tryAgain;
7722 
7723   case Stmt::OpaqueValueExprClass:
7724     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7725       E = src;
7726       goto tryAgain;
7727     }
7728     return SLCT_NotALiteral;
7729 
7730   case Stmt::PredefinedExprClass:
7731     // While __func__, etc., are technically not string literals, they
7732     // cannot contain format specifiers and thus are not a security
7733     // liability.
7734     return SLCT_UncheckedLiteral;
7735 
7736   case Stmt::DeclRefExprClass: {
7737     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7738 
7739     // As an exception, do not flag errors for variables binding to
7740     // const string literals.
7741     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7742       bool isConstant = false;
7743       QualType T = DR->getType();
7744 
7745       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7746         isConstant = AT->getElementType().isConstant(S.Context);
7747       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7748         isConstant = T.isConstant(S.Context) &&
7749                      PT->getPointeeType().isConstant(S.Context);
7750       } else if (T->isObjCObjectPointerType()) {
7751         // In ObjC, there is usually no "const ObjectPointer" type,
7752         // so don't check if the pointee type is constant.
7753         isConstant = T.isConstant(S.Context);
7754       }
7755 
7756       if (isConstant) {
7757         if (const Expr *Init = VD->getAnyInitializer()) {
7758           // Look through initializers like const char c[] = { "foo" }
7759           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7760             if (InitList->isStringLiteralInit())
7761               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7762           }
7763           return checkFormatStringExpr(S, Init, Args,
7764                                        HasVAListArg, format_idx,
7765                                        firstDataArg, Type, CallType,
7766                                        /*InFunctionCall*/ false, CheckedVarArgs,
7767                                        UncoveredArg, Offset);
7768         }
7769       }
7770 
7771       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7772       // special check to see if the format string is a function parameter
7773       // of the function calling the printf function.  If the function
7774       // has an attribute indicating it is a printf-like function, then we
7775       // should suppress warnings concerning non-literals being used in a call
7776       // to a vprintf function.  For example:
7777       //
7778       // void
7779       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7780       //      va_list ap;
7781       //      va_start(ap, fmt);
7782       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7783       //      ...
7784       // }
7785       if (HasVAListArg) {
7786         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7787           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7788             int PVIndex = PV->getFunctionScopeIndex() + 1;
7789             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7790               // adjust for implicit parameter
7791               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7792                 if (MD->isInstance())
7793                   ++PVIndex;
7794               // We also check if the formats are compatible.
7795               // We can't pass a 'scanf' string to a 'printf' function.
7796               if (PVIndex == PVFormat->getFormatIdx() &&
7797                   Type == S.GetFormatStringType(PVFormat))
7798                 return SLCT_UncheckedLiteral;
7799             }
7800           }
7801         }
7802       }
7803     }
7804 
7805     return SLCT_NotALiteral;
7806   }
7807 
7808   case Stmt::CallExprClass:
7809   case Stmt::CXXMemberCallExprClass: {
7810     const CallExpr *CE = cast<CallExpr>(E);
7811     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7812       bool IsFirst = true;
7813       StringLiteralCheckType CommonResult;
7814       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7815         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7816         StringLiteralCheckType Result = checkFormatStringExpr(
7817             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7818             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7819             IgnoreStringsWithoutSpecifiers);
7820         if (IsFirst) {
7821           CommonResult = Result;
7822           IsFirst = false;
7823         }
7824       }
7825       if (!IsFirst)
7826         return CommonResult;
7827 
7828       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7829         unsigned BuiltinID = FD->getBuiltinID();
7830         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7831             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7832           const Expr *Arg = CE->getArg(0);
7833           return checkFormatStringExpr(S, Arg, Args,
7834                                        HasVAListArg, format_idx,
7835                                        firstDataArg, Type, CallType,
7836                                        InFunctionCall, CheckedVarArgs,
7837                                        UncoveredArg, Offset,
7838                                        IgnoreStringsWithoutSpecifiers);
7839         }
7840       }
7841     }
7842 
7843     return SLCT_NotALiteral;
7844   }
7845   case Stmt::ObjCMessageExprClass: {
7846     const auto *ME = cast<ObjCMessageExpr>(E);
7847     if (const auto *MD = ME->getMethodDecl()) {
7848       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7849         // As a special case heuristic, if we're using the method -[NSBundle
7850         // localizedStringForKey:value:table:], ignore any key strings that lack
7851         // format specifiers. The idea is that if the key doesn't have any
7852         // format specifiers then its probably just a key to map to the
7853         // localized strings. If it does have format specifiers though, then its
7854         // likely that the text of the key is the format string in the
7855         // programmer's language, and should be checked.
7856         const ObjCInterfaceDecl *IFace;
7857         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7858             IFace->getIdentifier()->isStr("NSBundle") &&
7859             MD->getSelector().isKeywordSelector(
7860                 {"localizedStringForKey", "value", "table"})) {
7861           IgnoreStringsWithoutSpecifiers = true;
7862         }
7863 
7864         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7865         return checkFormatStringExpr(
7866             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7867             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7868             IgnoreStringsWithoutSpecifiers);
7869       }
7870     }
7871 
7872     return SLCT_NotALiteral;
7873   }
7874   case Stmt::ObjCStringLiteralClass:
7875   case Stmt::StringLiteralClass: {
7876     const StringLiteral *StrE = nullptr;
7877 
7878     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7879       StrE = ObjCFExpr->getString();
7880     else
7881       StrE = cast<StringLiteral>(E);
7882 
7883     if (StrE) {
7884       if (Offset.isNegative() || Offset > StrE->getLength()) {
7885         // TODO: It would be better to have an explicit warning for out of
7886         // bounds literals.
7887         return SLCT_NotALiteral;
7888       }
7889       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7890       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7891                         firstDataArg, Type, InFunctionCall, CallType,
7892                         CheckedVarArgs, UncoveredArg,
7893                         IgnoreStringsWithoutSpecifiers);
7894       return SLCT_CheckedLiteral;
7895     }
7896 
7897     return SLCT_NotALiteral;
7898   }
7899   case Stmt::BinaryOperatorClass: {
7900     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7901 
7902     // A string literal + an int offset is still a string literal.
7903     if (BinOp->isAdditiveOp()) {
7904       Expr::EvalResult LResult, RResult;
7905 
7906       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7907           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7908       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7909           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7910 
7911       if (LIsInt != RIsInt) {
7912         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7913 
7914         if (LIsInt) {
7915           if (BinOpKind == BO_Add) {
7916             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7917             E = BinOp->getRHS();
7918             goto tryAgain;
7919           }
7920         } else {
7921           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7922           E = BinOp->getLHS();
7923           goto tryAgain;
7924         }
7925       }
7926     }
7927 
7928     return SLCT_NotALiteral;
7929   }
7930   case Stmt::UnaryOperatorClass: {
7931     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7932     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7933     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7934       Expr::EvalResult IndexResult;
7935       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7936                                        Expr::SE_NoSideEffects,
7937                                        S.isConstantEvaluated())) {
7938         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7939                    /*RHS is int*/ true);
7940         E = ASE->getBase();
7941         goto tryAgain;
7942       }
7943     }
7944 
7945     return SLCT_NotALiteral;
7946   }
7947 
7948   default:
7949     return SLCT_NotALiteral;
7950   }
7951 }
7952 
7953 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7954   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7955       .Case("scanf", FST_Scanf)
7956       .Cases("printf", "printf0", FST_Printf)
7957       .Cases("NSString", "CFString", FST_NSString)
7958       .Case("strftime", FST_Strftime)
7959       .Case("strfmon", FST_Strfmon)
7960       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7961       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7962       .Case("os_trace", FST_OSLog)
7963       .Case("os_log", FST_OSLog)
7964       .Default(FST_Unknown);
7965 }
7966 
7967 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7968 /// functions) for correct use of format strings.
7969 /// Returns true if a format string has been fully checked.
7970 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7971                                 ArrayRef<const Expr *> Args,
7972                                 bool IsCXXMember,
7973                                 VariadicCallType CallType,
7974                                 SourceLocation Loc, SourceRange Range,
7975                                 llvm::SmallBitVector &CheckedVarArgs) {
7976   FormatStringInfo FSI;
7977   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7978     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7979                                 FSI.FirstDataArg, GetFormatStringType(Format),
7980                                 CallType, Loc, Range, CheckedVarArgs);
7981   return false;
7982 }
7983 
7984 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7985                                 bool HasVAListArg, unsigned format_idx,
7986                                 unsigned firstDataArg, FormatStringType Type,
7987                                 VariadicCallType CallType,
7988                                 SourceLocation Loc, SourceRange Range,
7989                                 llvm::SmallBitVector &CheckedVarArgs) {
7990   // CHECK: printf/scanf-like function is called with no format string.
7991   if (format_idx >= Args.size()) {
7992     Diag(Loc, diag::warn_missing_format_string) << Range;
7993     return false;
7994   }
7995 
7996   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7997 
7998   // CHECK: format string is not a string literal.
7999   //
8000   // Dynamically generated format strings are difficult to
8001   // automatically vet at compile time.  Requiring that format strings
8002   // are string literals: (1) permits the checking of format strings by
8003   // the compiler and thereby (2) can practically remove the source of
8004   // many format string exploits.
8005 
8006   // Format string can be either ObjC string (e.g. @"%d") or
8007   // C string (e.g. "%d")
8008   // ObjC string uses the same format specifiers as C string, so we can use
8009   // the same format string checking logic for both ObjC and C strings.
8010   UncoveredArgHandler UncoveredArg;
8011   StringLiteralCheckType CT =
8012       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8013                             format_idx, firstDataArg, Type, CallType,
8014                             /*IsFunctionCall*/ true, CheckedVarArgs,
8015                             UncoveredArg,
8016                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8017 
8018   // Generate a diagnostic where an uncovered argument is detected.
8019   if (UncoveredArg.hasUncoveredArg()) {
8020     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8021     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8022     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8023   }
8024 
8025   if (CT != SLCT_NotALiteral)
8026     // Literal format string found, check done!
8027     return CT == SLCT_CheckedLiteral;
8028 
8029   // Strftime is particular as it always uses a single 'time' argument,
8030   // so it is safe to pass a non-literal string.
8031   if (Type == FST_Strftime)
8032     return false;
8033 
8034   // Do not emit diag when the string param is a macro expansion and the
8035   // format is either NSString or CFString. This is a hack to prevent
8036   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8037   // which are usually used in place of NS and CF string literals.
8038   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8039   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8040     return false;
8041 
8042   // If there are no arguments specified, warn with -Wformat-security, otherwise
8043   // warn only with -Wformat-nonliteral.
8044   if (Args.size() == firstDataArg) {
8045     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8046       << OrigFormatExpr->getSourceRange();
8047     switch (Type) {
8048     default:
8049       break;
8050     case FST_Kprintf:
8051     case FST_FreeBSDKPrintf:
8052     case FST_Printf:
8053       Diag(FormatLoc, diag::note_format_security_fixit)
8054         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8055       break;
8056     case FST_NSString:
8057       Diag(FormatLoc, diag::note_format_security_fixit)
8058         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8059       break;
8060     }
8061   } else {
8062     Diag(FormatLoc, diag::warn_format_nonliteral)
8063       << OrigFormatExpr->getSourceRange();
8064   }
8065   return false;
8066 }
8067 
8068 namespace {
8069 
8070 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8071 protected:
8072   Sema &S;
8073   const FormatStringLiteral *FExpr;
8074   const Expr *OrigFormatExpr;
8075   const Sema::FormatStringType FSType;
8076   const unsigned FirstDataArg;
8077   const unsigned NumDataArgs;
8078   const char *Beg; // Start of format string.
8079   const bool HasVAListArg;
8080   ArrayRef<const Expr *> Args;
8081   unsigned FormatIdx;
8082   llvm::SmallBitVector CoveredArgs;
8083   bool usesPositionalArgs = false;
8084   bool atFirstArg = true;
8085   bool inFunctionCall;
8086   Sema::VariadicCallType CallType;
8087   llvm::SmallBitVector &CheckedVarArgs;
8088   UncoveredArgHandler &UncoveredArg;
8089 
8090 public:
8091   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8092                      const Expr *origFormatExpr,
8093                      const Sema::FormatStringType type, unsigned firstDataArg,
8094                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8095                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8096                      bool inFunctionCall, Sema::VariadicCallType callType,
8097                      llvm::SmallBitVector &CheckedVarArgs,
8098                      UncoveredArgHandler &UncoveredArg)
8099       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8100         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8101         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8102         inFunctionCall(inFunctionCall), CallType(callType),
8103         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8104     CoveredArgs.resize(numDataArgs);
8105     CoveredArgs.reset();
8106   }
8107 
8108   void DoneProcessing();
8109 
8110   void HandleIncompleteSpecifier(const char *startSpecifier,
8111                                  unsigned specifierLen) override;
8112 
8113   void HandleInvalidLengthModifier(
8114                            const analyze_format_string::FormatSpecifier &FS,
8115                            const analyze_format_string::ConversionSpecifier &CS,
8116                            const char *startSpecifier, unsigned specifierLen,
8117                            unsigned DiagID);
8118 
8119   void HandleNonStandardLengthModifier(
8120                     const analyze_format_string::FormatSpecifier &FS,
8121                     const char *startSpecifier, unsigned specifierLen);
8122 
8123   void HandleNonStandardConversionSpecifier(
8124                     const analyze_format_string::ConversionSpecifier &CS,
8125                     const char *startSpecifier, unsigned specifierLen);
8126 
8127   void HandlePosition(const char *startPos, unsigned posLen) override;
8128 
8129   void HandleInvalidPosition(const char *startSpecifier,
8130                              unsigned specifierLen,
8131                              analyze_format_string::PositionContext p) override;
8132 
8133   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8134 
8135   void HandleNullChar(const char *nullCharacter) override;
8136 
8137   template <typename Range>
8138   static void
8139   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8140                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8141                        bool IsStringLocation, Range StringRange,
8142                        ArrayRef<FixItHint> Fixit = None);
8143 
8144 protected:
8145   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8146                                         const char *startSpec,
8147                                         unsigned specifierLen,
8148                                         const char *csStart, unsigned csLen);
8149 
8150   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8151                                          const char *startSpec,
8152                                          unsigned specifierLen);
8153 
8154   SourceRange getFormatStringRange();
8155   CharSourceRange getSpecifierRange(const char *startSpecifier,
8156                                     unsigned specifierLen);
8157   SourceLocation getLocationOfByte(const char *x);
8158 
8159   const Expr *getDataArg(unsigned i) const;
8160 
8161   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8162                     const analyze_format_string::ConversionSpecifier &CS,
8163                     const char *startSpecifier, unsigned specifierLen,
8164                     unsigned argIndex);
8165 
8166   template <typename Range>
8167   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8168                             bool IsStringLocation, Range StringRange,
8169                             ArrayRef<FixItHint> Fixit = None);
8170 };
8171 
8172 } // namespace
8173 
8174 SourceRange CheckFormatHandler::getFormatStringRange() {
8175   return OrigFormatExpr->getSourceRange();
8176 }
8177 
8178 CharSourceRange CheckFormatHandler::
8179 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8180   SourceLocation Start = getLocationOfByte(startSpecifier);
8181   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8182 
8183   // Advance the end SourceLocation by one due to half-open ranges.
8184   End = End.getLocWithOffset(1);
8185 
8186   return CharSourceRange::getCharRange(Start, End);
8187 }
8188 
8189 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8190   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8191                                   S.getLangOpts(), S.Context.getTargetInfo());
8192 }
8193 
8194 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8195                                                    unsigned specifierLen){
8196   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8197                        getLocationOfByte(startSpecifier),
8198                        /*IsStringLocation*/true,
8199                        getSpecifierRange(startSpecifier, specifierLen));
8200 }
8201 
8202 void CheckFormatHandler::HandleInvalidLengthModifier(
8203     const analyze_format_string::FormatSpecifier &FS,
8204     const analyze_format_string::ConversionSpecifier &CS,
8205     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8206   using namespace analyze_format_string;
8207 
8208   const LengthModifier &LM = FS.getLengthModifier();
8209   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8210 
8211   // See if we know how to fix this length modifier.
8212   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8213   if (FixedLM) {
8214     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8215                          getLocationOfByte(LM.getStart()),
8216                          /*IsStringLocation*/true,
8217                          getSpecifierRange(startSpecifier, specifierLen));
8218 
8219     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8220       << FixedLM->toString()
8221       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8222 
8223   } else {
8224     FixItHint Hint;
8225     if (DiagID == diag::warn_format_nonsensical_length)
8226       Hint = FixItHint::CreateRemoval(LMRange);
8227 
8228     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8229                          getLocationOfByte(LM.getStart()),
8230                          /*IsStringLocation*/true,
8231                          getSpecifierRange(startSpecifier, specifierLen),
8232                          Hint);
8233   }
8234 }
8235 
8236 void CheckFormatHandler::HandleNonStandardLengthModifier(
8237     const analyze_format_string::FormatSpecifier &FS,
8238     const char *startSpecifier, unsigned specifierLen) {
8239   using namespace analyze_format_string;
8240 
8241   const LengthModifier &LM = FS.getLengthModifier();
8242   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8243 
8244   // See if we know how to fix this length modifier.
8245   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8246   if (FixedLM) {
8247     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8248                            << LM.toString() << 0,
8249                          getLocationOfByte(LM.getStart()),
8250                          /*IsStringLocation*/true,
8251                          getSpecifierRange(startSpecifier, specifierLen));
8252 
8253     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8254       << FixedLM->toString()
8255       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8256 
8257   } else {
8258     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8259                            << LM.toString() << 0,
8260                          getLocationOfByte(LM.getStart()),
8261                          /*IsStringLocation*/true,
8262                          getSpecifierRange(startSpecifier, specifierLen));
8263   }
8264 }
8265 
8266 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8267     const analyze_format_string::ConversionSpecifier &CS,
8268     const char *startSpecifier, unsigned specifierLen) {
8269   using namespace analyze_format_string;
8270 
8271   // See if we know how to fix this conversion specifier.
8272   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8273   if (FixedCS) {
8274     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8275                           << CS.toString() << /*conversion specifier*/1,
8276                          getLocationOfByte(CS.getStart()),
8277                          /*IsStringLocation*/true,
8278                          getSpecifierRange(startSpecifier, specifierLen));
8279 
8280     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8281     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8282       << FixedCS->toString()
8283       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8284   } else {
8285     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8286                           << CS.toString() << /*conversion specifier*/1,
8287                          getLocationOfByte(CS.getStart()),
8288                          /*IsStringLocation*/true,
8289                          getSpecifierRange(startSpecifier, specifierLen));
8290   }
8291 }
8292 
8293 void CheckFormatHandler::HandlePosition(const char *startPos,
8294                                         unsigned posLen) {
8295   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8296                                getLocationOfByte(startPos),
8297                                /*IsStringLocation*/true,
8298                                getSpecifierRange(startPos, posLen));
8299 }
8300 
8301 void
8302 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8303                                      analyze_format_string::PositionContext p) {
8304   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8305                          << (unsigned) p,
8306                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8307                        getSpecifierRange(startPos, posLen));
8308 }
8309 
8310 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8311                                             unsigned posLen) {
8312   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8313                                getLocationOfByte(startPos),
8314                                /*IsStringLocation*/true,
8315                                getSpecifierRange(startPos, posLen));
8316 }
8317 
8318 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8319   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8320     // The presence of a null character is likely an error.
8321     EmitFormatDiagnostic(
8322       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8323       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8324       getFormatStringRange());
8325   }
8326 }
8327 
8328 // Note that this may return NULL if there was an error parsing or building
8329 // one of the argument expressions.
8330 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8331   return Args[FirstDataArg + i];
8332 }
8333 
8334 void CheckFormatHandler::DoneProcessing() {
8335   // Does the number of data arguments exceed the number of
8336   // format conversions in the format string?
8337   if (!HasVAListArg) {
8338       // Find any arguments that weren't covered.
8339     CoveredArgs.flip();
8340     signed notCoveredArg = CoveredArgs.find_first();
8341     if (notCoveredArg >= 0) {
8342       assert((unsigned)notCoveredArg < NumDataArgs);
8343       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8344     } else {
8345       UncoveredArg.setAllCovered();
8346     }
8347   }
8348 }
8349 
8350 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8351                                    const Expr *ArgExpr) {
8352   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8353          "Invalid state");
8354 
8355   if (!ArgExpr)
8356     return;
8357 
8358   SourceLocation Loc = ArgExpr->getBeginLoc();
8359 
8360   if (S.getSourceManager().isInSystemMacro(Loc))
8361     return;
8362 
8363   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8364   for (auto E : DiagnosticExprs)
8365     PDiag << E->getSourceRange();
8366 
8367   CheckFormatHandler::EmitFormatDiagnostic(
8368                                   S, IsFunctionCall, DiagnosticExprs[0],
8369                                   PDiag, Loc, /*IsStringLocation*/false,
8370                                   DiagnosticExprs[0]->getSourceRange());
8371 }
8372 
8373 bool
8374 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8375                                                      SourceLocation Loc,
8376                                                      const char *startSpec,
8377                                                      unsigned specifierLen,
8378                                                      const char *csStart,
8379                                                      unsigned csLen) {
8380   bool keepGoing = true;
8381   if (argIndex < NumDataArgs) {
8382     // Consider the argument coverered, even though the specifier doesn't
8383     // make sense.
8384     CoveredArgs.set(argIndex);
8385   }
8386   else {
8387     // If argIndex exceeds the number of data arguments we
8388     // don't issue a warning because that is just a cascade of warnings (and
8389     // they may have intended '%%' anyway). We don't want to continue processing
8390     // the format string after this point, however, as we will like just get
8391     // gibberish when trying to match arguments.
8392     keepGoing = false;
8393   }
8394 
8395   StringRef Specifier(csStart, csLen);
8396 
8397   // If the specifier in non-printable, it could be the first byte of a UTF-8
8398   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8399   // hex value.
8400   std::string CodePointStr;
8401   if (!llvm::sys::locale::isPrint(*csStart)) {
8402     llvm::UTF32 CodePoint;
8403     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8404     const llvm::UTF8 *E =
8405         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8406     llvm::ConversionResult Result =
8407         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8408 
8409     if (Result != llvm::conversionOK) {
8410       unsigned char FirstChar = *csStart;
8411       CodePoint = (llvm::UTF32)FirstChar;
8412     }
8413 
8414     llvm::raw_string_ostream OS(CodePointStr);
8415     if (CodePoint < 256)
8416       OS << "\\x" << llvm::format("%02x", CodePoint);
8417     else if (CodePoint <= 0xFFFF)
8418       OS << "\\u" << llvm::format("%04x", CodePoint);
8419     else
8420       OS << "\\U" << llvm::format("%08x", CodePoint);
8421     OS.flush();
8422     Specifier = CodePointStr;
8423   }
8424 
8425   EmitFormatDiagnostic(
8426       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8427       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8428 
8429   return keepGoing;
8430 }
8431 
8432 void
8433 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8434                                                       const char *startSpec,
8435                                                       unsigned specifierLen) {
8436   EmitFormatDiagnostic(
8437     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8438     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8439 }
8440 
8441 bool
8442 CheckFormatHandler::CheckNumArgs(
8443   const analyze_format_string::FormatSpecifier &FS,
8444   const analyze_format_string::ConversionSpecifier &CS,
8445   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8446 
8447   if (argIndex >= NumDataArgs) {
8448     PartialDiagnostic PDiag = FS.usesPositionalArg()
8449       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8450            << (argIndex+1) << NumDataArgs)
8451       : S.PDiag(diag::warn_printf_insufficient_data_args);
8452     EmitFormatDiagnostic(
8453       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8454       getSpecifierRange(startSpecifier, specifierLen));
8455 
8456     // Since more arguments than conversion tokens are given, by extension
8457     // all arguments are covered, so mark this as so.
8458     UncoveredArg.setAllCovered();
8459     return false;
8460   }
8461   return true;
8462 }
8463 
8464 template<typename Range>
8465 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8466                                               SourceLocation Loc,
8467                                               bool IsStringLocation,
8468                                               Range StringRange,
8469                                               ArrayRef<FixItHint> FixIt) {
8470   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8471                        Loc, IsStringLocation, StringRange, FixIt);
8472 }
8473 
8474 /// If the format string is not within the function call, emit a note
8475 /// so that the function call and string are in diagnostic messages.
8476 ///
8477 /// \param InFunctionCall if true, the format string is within the function
8478 /// call and only one diagnostic message will be produced.  Otherwise, an
8479 /// extra note will be emitted pointing to location of the format string.
8480 ///
8481 /// \param ArgumentExpr the expression that is passed as the format string
8482 /// argument in the function call.  Used for getting locations when two
8483 /// diagnostics are emitted.
8484 ///
8485 /// \param PDiag the callee should already have provided any strings for the
8486 /// diagnostic message.  This function only adds locations and fixits
8487 /// to diagnostics.
8488 ///
8489 /// \param Loc primary location for diagnostic.  If two diagnostics are
8490 /// required, one will be at Loc and a new SourceLocation will be created for
8491 /// the other one.
8492 ///
8493 /// \param IsStringLocation if true, Loc points to the format string should be
8494 /// used for the note.  Otherwise, Loc points to the argument list and will
8495 /// be used with PDiag.
8496 ///
8497 /// \param StringRange some or all of the string to highlight.  This is
8498 /// templated so it can accept either a CharSourceRange or a SourceRange.
8499 ///
8500 /// \param FixIt optional fix it hint for the format string.
8501 template <typename Range>
8502 void CheckFormatHandler::EmitFormatDiagnostic(
8503     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8504     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8505     Range StringRange, ArrayRef<FixItHint> FixIt) {
8506   if (InFunctionCall) {
8507     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8508     D << StringRange;
8509     D << FixIt;
8510   } else {
8511     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8512       << ArgumentExpr->getSourceRange();
8513 
8514     const Sema::SemaDiagnosticBuilder &Note =
8515       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8516              diag::note_format_string_defined);
8517 
8518     Note << StringRange;
8519     Note << FixIt;
8520   }
8521 }
8522 
8523 //===--- CHECK: Printf format string checking ------------------------------===//
8524 
8525 namespace {
8526 
8527 class CheckPrintfHandler : public CheckFormatHandler {
8528 public:
8529   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8530                      const Expr *origFormatExpr,
8531                      const Sema::FormatStringType type, unsigned firstDataArg,
8532                      unsigned numDataArgs, bool isObjC, const char *beg,
8533                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8534                      unsigned formatIdx, bool inFunctionCall,
8535                      Sema::VariadicCallType CallType,
8536                      llvm::SmallBitVector &CheckedVarArgs,
8537                      UncoveredArgHandler &UncoveredArg)
8538       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8539                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8540                            inFunctionCall, CallType, CheckedVarArgs,
8541                            UncoveredArg) {}
8542 
8543   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8544 
8545   /// Returns true if '%@' specifiers are allowed in the format string.
8546   bool allowsObjCArg() const {
8547     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8548            FSType == Sema::FST_OSTrace;
8549   }
8550 
8551   bool HandleInvalidPrintfConversionSpecifier(
8552                                       const analyze_printf::PrintfSpecifier &FS,
8553                                       const char *startSpecifier,
8554                                       unsigned specifierLen) override;
8555 
8556   void handleInvalidMaskType(StringRef MaskType) override;
8557 
8558   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8559                              const char *startSpecifier,
8560                              unsigned specifierLen) override;
8561   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8562                        const char *StartSpecifier,
8563                        unsigned SpecifierLen,
8564                        const Expr *E);
8565 
8566   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8567                     const char *startSpecifier, unsigned specifierLen);
8568   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8569                            const analyze_printf::OptionalAmount &Amt,
8570                            unsigned type,
8571                            const char *startSpecifier, unsigned specifierLen);
8572   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8573                   const analyze_printf::OptionalFlag &flag,
8574                   const char *startSpecifier, unsigned specifierLen);
8575   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8576                          const analyze_printf::OptionalFlag &ignoredFlag,
8577                          const analyze_printf::OptionalFlag &flag,
8578                          const char *startSpecifier, unsigned specifierLen);
8579   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8580                            const Expr *E);
8581 
8582   void HandleEmptyObjCModifierFlag(const char *startFlag,
8583                                    unsigned flagLen) override;
8584 
8585   void HandleInvalidObjCModifierFlag(const char *startFlag,
8586                                             unsigned flagLen) override;
8587 
8588   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8589                                            const char *flagsEnd,
8590                                            const char *conversionPosition)
8591                                              override;
8592 };
8593 
8594 } // namespace
8595 
8596 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8597                                       const analyze_printf::PrintfSpecifier &FS,
8598                                       const char *startSpecifier,
8599                                       unsigned specifierLen) {
8600   const analyze_printf::PrintfConversionSpecifier &CS =
8601     FS.getConversionSpecifier();
8602 
8603   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8604                                           getLocationOfByte(CS.getStart()),
8605                                           startSpecifier, specifierLen,
8606                                           CS.getStart(), CS.getLength());
8607 }
8608 
8609 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8610   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8611 }
8612 
8613 bool CheckPrintfHandler::HandleAmount(
8614                                const analyze_format_string::OptionalAmount &Amt,
8615                                unsigned k, const char *startSpecifier,
8616                                unsigned specifierLen) {
8617   if (Amt.hasDataArgument()) {
8618     if (!HasVAListArg) {
8619       unsigned argIndex = Amt.getArgIndex();
8620       if (argIndex >= NumDataArgs) {
8621         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8622                                << k,
8623                              getLocationOfByte(Amt.getStart()),
8624                              /*IsStringLocation*/true,
8625                              getSpecifierRange(startSpecifier, specifierLen));
8626         // Don't do any more checking.  We will just emit
8627         // spurious errors.
8628         return false;
8629       }
8630 
8631       // Type check the data argument.  It should be an 'int'.
8632       // Although not in conformance with C99, we also allow the argument to be
8633       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8634       // doesn't emit a warning for that case.
8635       CoveredArgs.set(argIndex);
8636       const Expr *Arg = getDataArg(argIndex);
8637       if (!Arg)
8638         return false;
8639 
8640       QualType T = Arg->getType();
8641 
8642       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8643       assert(AT.isValid());
8644 
8645       if (!AT.matchesType(S.Context, T)) {
8646         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8647                                << k << AT.getRepresentativeTypeName(S.Context)
8648                                << T << Arg->getSourceRange(),
8649                              getLocationOfByte(Amt.getStart()),
8650                              /*IsStringLocation*/true,
8651                              getSpecifierRange(startSpecifier, specifierLen));
8652         // Don't do any more checking.  We will just emit
8653         // spurious errors.
8654         return false;
8655       }
8656     }
8657   }
8658   return true;
8659 }
8660 
8661 void CheckPrintfHandler::HandleInvalidAmount(
8662                                       const analyze_printf::PrintfSpecifier &FS,
8663                                       const analyze_printf::OptionalAmount &Amt,
8664                                       unsigned type,
8665                                       const char *startSpecifier,
8666                                       unsigned specifierLen) {
8667   const analyze_printf::PrintfConversionSpecifier &CS =
8668     FS.getConversionSpecifier();
8669 
8670   FixItHint fixit =
8671     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8672       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8673                                  Amt.getConstantLength()))
8674       : FixItHint();
8675 
8676   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8677                          << type << CS.toString(),
8678                        getLocationOfByte(Amt.getStart()),
8679                        /*IsStringLocation*/true,
8680                        getSpecifierRange(startSpecifier, specifierLen),
8681                        fixit);
8682 }
8683 
8684 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8685                                     const analyze_printf::OptionalFlag &flag,
8686                                     const char *startSpecifier,
8687                                     unsigned specifierLen) {
8688   // Warn about pointless flag with a fixit removal.
8689   const analyze_printf::PrintfConversionSpecifier &CS =
8690     FS.getConversionSpecifier();
8691   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8692                          << flag.toString() << CS.toString(),
8693                        getLocationOfByte(flag.getPosition()),
8694                        /*IsStringLocation*/true,
8695                        getSpecifierRange(startSpecifier, specifierLen),
8696                        FixItHint::CreateRemoval(
8697                          getSpecifierRange(flag.getPosition(), 1)));
8698 }
8699 
8700 void CheckPrintfHandler::HandleIgnoredFlag(
8701                                 const analyze_printf::PrintfSpecifier &FS,
8702                                 const analyze_printf::OptionalFlag &ignoredFlag,
8703                                 const analyze_printf::OptionalFlag &flag,
8704                                 const char *startSpecifier,
8705                                 unsigned specifierLen) {
8706   // Warn about ignored flag with a fixit removal.
8707   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8708                          << ignoredFlag.toString() << flag.toString(),
8709                        getLocationOfByte(ignoredFlag.getPosition()),
8710                        /*IsStringLocation*/true,
8711                        getSpecifierRange(startSpecifier, specifierLen),
8712                        FixItHint::CreateRemoval(
8713                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8714 }
8715 
8716 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8717                                                      unsigned flagLen) {
8718   // Warn about an empty flag.
8719   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8720                        getLocationOfByte(startFlag),
8721                        /*IsStringLocation*/true,
8722                        getSpecifierRange(startFlag, flagLen));
8723 }
8724 
8725 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8726                                                        unsigned flagLen) {
8727   // Warn about an invalid flag.
8728   auto Range = getSpecifierRange(startFlag, flagLen);
8729   StringRef flag(startFlag, flagLen);
8730   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8731                       getLocationOfByte(startFlag),
8732                       /*IsStringLocation*/true,
8733                       Range, FixItHint::CreateRemoval(Range));
8734 }
8735 
8736 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8737     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8738     // Warn about using '[...]' without a '@' conversion.
8739     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8740     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8741     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8742                          getLocationOfByte(conversionPosition),
8743                          /*IsStringLocation*/true,
8744                          Range, FixItHint::CreateRemoval(Range));
8745 }
8746 
8747 // Determines if the specified is a C++ class or struct containing
8748 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8749 // "c_str()").
8750 template<typename MemberKind>
8751 static llvm::SmallPtrSet<MemberKind*, 1>
8752 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8753   const RecordType *RT = Ty->getAs<RecordType>();
8754   llvm::SmallPtrSet<MemberKind*, 1> Results;
8755 
8756   if (!RT)
8757     return Results;
8758   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8759   if (!RD || !RD->getDefinition())
8760     return Results;
8761 
8762   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8763                  Sema::LookupMemberName);
8764   R.suppressDiagnostics();
8765 
8766   // We just need to include all members of the right kind turned up by the
8767   // filter, at this point.
8768   if (S.LookupQualifiedName(R, RT->getDecl()))
8769     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8770       NamedDecl *decl = (*I)->getUnderlyingDecl();
8771       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8772         Results.insert(FK);
8773     }
8774   return Results;
8775 }
8776 
8777 /// Check if we could call '.c_str()' on an object.
8778 ///
8779 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8780 /// allow the call, or if it would be ambiguous).
8781 bool Sema::hasCStrMethod(const Expr *E) {
8782   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8783 
8784   MethodSet Results =
8785       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8786   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8787        MI != ME; ++MI)
8788     if ((*MI)->getMinRequiredArguments() == 0)
8789       return true;
8790   return false;
8791 }
8792 
8793 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8794 // better diagnostic if so. AT is assumed to be valid.
8795 // Returns true when a c_str() conversion method is found.
8796 bool CheckPrintfHandler::checkForCStrMembers(
8797     const analyze_printf::ArgType &AT, const Expr *E) {
8798   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8799 
8800   MethodSet Results =
8801       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8802 
8803   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8804        MI != ME; ++MI) {
8805     const CXXMethodDecl *Method = *MI;
8806     if (Method->getMinRequiredArguments() == 0 &&
8807         AT.matchesType(S.Context, Method->getReturnType())) {
8808       // FIXME: Suggest parens if the expression needs them.
8809       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8810       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8811           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8812       return true;
8813     }
8814   }
8815 
8816   return false;
8817 }
8818 
8819 bool
8820 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8821                                             &FS,
8822                                           const char *startSpecifier,
8823                                           unsigned specifierLen) {
8824   using namespace analyze_format_string;
8825   using namespace analyze_printf;
8826 
8827   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8828 
8829   if (FS.consumesDataArgument()) {
8830     if (atFirstArg) {
8831         atFirstArg = false;
8832         usesPositionalArgs = FS.usesPositionalArg();
8833     }
8834     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8835       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8836                                         startSpecifier, specifierLen);
8837       return false;
8838     }
8839   }
8840 
8841   // First check if the field width, precision, and conversion specifier
8842   // have matching data arguments.
8843   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8844                     startSpecifier, specifierLen)) {
8845     return false;
8846   }
8847 
8848   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8849                     startSpecifier, specifierLen)) {
8850     return false;
8851   }
8852 
8853   if (!CS.consumesDataArgument()) {
8854     // FIXME: Technically specifying a precision or field width here
8855     // makes no sense.  Worth issuing a warning at some point.
8856     return true;
8857   }
8858 
8859   // Consume the argument.
8860   unsigned argIndex = FS.getArgIndex();
8861   if (argIndex < NumDataArgs) {
8862     // The check to see if the argIndex is valid will come later.
8863     // We set the bit here because we may exit early from this
8864     // function if we encounter some other error.
8865     CoveredArgs.set(argIndex);
8866   }
8867 
8868   // FreeBSD kernel extensions.
8869   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8870       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8871     // We need at least two arguments.
8872     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8873       return false;
8874 
8875     // Claim the second argument.
8876     CoveredArgs.set(argIndex + 1);
8877 
8878     // Type check the first argument (int for %b, pointer for %D)
8879     const Expr *Ex = getDataArg(argIndex);
8880     const analyze_printf::ArgType &AT =
8881       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8882         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8883     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8884       EmitFormatDiagnostic(
8885           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8886               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8887               << false << Ex->getSourceRange(),
8888           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8889           getSpecifierRange(startSpecifier, specifierLen));
8890 
8891     // Type check the second argument (char * for both %b and %D)
8892     Ex = getDataArg(argIndex + 1);
8893     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8894     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8895       EmitFormatDiagnostic(
8896           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8897               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8898               << false << Ex->getSourceRange(),
8899           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8900           getSpecifierRange(startSpecifier, specifierLen));
8901 
8902      return true;
8903   }
8904 
8905   // Check for using an Objective-C specific conversion specifier
8906   // in a non-ObjC literal.
8907   if (!allowsObjCArg() && CS.isObjCArg()) {
8908     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8909                                                   specifierLen);
8910   }
8911 
8912   // %P can only be used with os_log.
8913   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8914     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8915                                                   specifierLen);
8916   }
8917 
8918   // %n is not allowed with os_log.
8919   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8920     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8921                          getLocationOfByte(CS.getStart()),
8922                          /*IsStringLocation*/ false,
8923                          getSpecifierRange(startSpecifier, specifierLen));
8924 
8925     return true;
8926   }
8927 
8928   // Only scalars are allowed for os_trace.
8929   if (FSType == Sema::FST_OSTrace &&
8930       (CS.getKind() == ConversionSpecifier::PArg ||
8931        CS.getKind() == ConversionSpecifier::sArg ||
8932        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8933     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8934                                                   specifierLen);
8935   }
8936 
8937   // Check for use of public/private annotation outside of os_log().
8938   if (FSType != Sema::FST_OSLog) {
8939     if (FS.isPublic().isSet()) {
8940       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8941                                << "public",
8942                            getLocationOfByte(FS.isPublic().getPosition()),
8943                            /*IsStringLocation*/ false,
8944                            getSpecifierRange(startSpecifier, specifierLen));
8945     }
8946     if (FS.isPrivate().isSet()) {
8947       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8948                                << "private",
8949                            getLocationOfByte(FS.isPrivate().getPosition()),
8950                            /*IsStringLocation*/ false,
8951                            getSpecifierRange(startSpecifier, specifierLen));
8952     }
8953   }
8954 
8955   // Check for invalid use of field width
8956   if (!FS.hasValidFieldWidth()) {
8957     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8958         startSpecifier, specifierLen);
8959   }
8960 
8961   // Check for invalid use of precision
8962   if (!FS.hasValidPrecision()) {
8963     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8964         startSpecifier, specifierLen);
8965   }
8966 
8967   // Precision is mandatory for %P specifier.
8968   if (CS.getKind() == ConversionSpecifier::PArg &&
8969       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8970     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8971                          getLocationOfByte(startSpecifier),
8972                          /*IsStringLocation*/ false,
8973                          getSpecifierRange(startSpecifier, specifierLen));
8974   }
8975 
8976   // Check each flag does not conflict with any other component.
8977   if (!FS.hasValidThousandsGroupingPrefix())
8978     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8979   if (!FS.hasValidLeadingZeros())
8980     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8981   if (!FS.hasValidPlusPrefix())
8982     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8983   if (!FS.hasValidSpacePrefix())
8984     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8985   if (!FS.hasValidAlternativeForm())
8986     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8987   if (!FS.hasValidLeftJustified())
8988     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8989 
8990   // Check that flags are not ignored by another flag
8991   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8992     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8993         startSpecifier, specifierLen);
8994   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8995     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8996             startSpecifier, specifierLen);
8997 
8998   // Check the length modifier is valid with the given conversion specifier.
8999   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9000                                  S.getLangOpts()))
9001     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9002                                 diag::warn_format_nonsensical_length);
9003   else if (!FS.hasStandardLengthModifier())
9004     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9005   else if (!FS.hasStandardLengthConversionCombination())
9006     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9007                                 diag::warn_format_non_standard_conversion_spec);
9008 
9009   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9010     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9011 
9012   // The remaining checks depend on the data arguments.
9013   if (HasVAListArg)
9014     return true;
9015 
9016   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9017     return false;
9018 
9019   const Expr *Arg = getDataArg(argIndex);
9020   if (!Arg)
9021     return true;
9022 
9023   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9024 }
9025 
9026 static bool requiresParensToAddCast(const Expr *E) {
9027   // FIXME: We should have a general way to reason about operator
9028   // precedence and whether parens are actually needed here.
9029   // Take care of a few common cases where they aren't.
9030   const Expr *Inside = E->IgnoreImpCasts();
9031   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9032     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9033 
9034   switch (Inside->getStmtClass()) {
9035   case Stmt::ArraySubscriptExprClass:
9036   case Stmt::CallExprClass:
9037   case Stmt::CharacterLiteralClass:
9038   case Stmt::CXXBoolLiteralExprClass:
9039   case Stmt::DeclRefExprClass:
9040   case Stmt::FloatingLiteralClass:
9041   case Stmt::IntegerLiteralClass:
9042   case Stmt::MemberExprClass:
9043   case Stmt::ObjCArrayLiteralClass:
9044   case Stmt::ObjCBoolLiteralExprClass:
9045   case Stmt::ObjCBoxedExprClass:
9046   case Stmt::ObjCDictionaryLiteralClass:
9047   case Stmt::ObjCEncodeExprClass:
9048   case Stmt::ObjCIvarRefExprClass:
9049   case Stmt::ObjCMessageExprClass:
9050   case Stmt::ObjCPropertyRefExprClass:
9051   case Stmt::ObjCStringLiteralClass:
9052   case Stmt::ObjCSubscriptRefExprClass:
9053   case Stmt::ParenExprClass:
9054   case Stmt::StringLiteralClass:
9055   case Stmt::UnaryOperatorClass:
9056     return false;
9057   default:
9058     return true;
9059   }
9060 }
9061 
9062 static std::pair<QualType, StringRef>
9063 shouldNotPrintDirectly(const ASTContext &Context,
9064                        QualType IntendedTy,
9065                        const Expr *E) {
9066   // Use a 'while' to peel off layers of typedefs.
9067   QualType TyTy = IntendedTy;
9068   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9069     StringRef Name = UserTy->getDecl()->getName();
9070     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9071       .Case("CFIndex", Context.getNSIntegerType())
9072       .Case("NSInteger", Context.getNSIntegerType())
9073       .Case("NSUInteger", Context.getNSUIntegerType())
9074       .Case("SInt32", Context.IntTy)
9075       .Case("UInt32", Context.UnsignedIntTy)
9076       .Default(QualType());
9077 
9078     if (!CastTy.isNull())
9079       return std::make_pair(CastTy, Name);
9080 
9081     TyTy = UserTy->desugar();
9082   }
9083 
9084   // Strip parens if necessary.
9085   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9086     return shouldNotPrintDirectly(Context,
9087                                   PE->getSubExpr()->getType(),
9088                                   PE->getSubExpr());
9089 
9090   // If this is a conditional expression, then its result type is constructed
9091   // via usual arithmetic conversions and thus there might be no necessary
9092   // typedef sugar there.  Recurse to operands to check for NSInteger &
9093   // Co. usage condition.
9094   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9095     QualType TrueTy, FalseTy;
9096     StringRef TrueName, FalseName;
9097 
9098     std::tie(TrueTy, TrueName) =
9099       shouldNotPrintDirectly(Context,
9100                              CO->getTrueExpr()->getType(),
9101                              CO->getTrueExpr());
9102     std::tie(FalseTy, FalseName) =
9103       shouldNotPrintDirectly(Context,
9104                              CO->getFalseExpr()->getType(),
9105                              CO->getFalseExpr());
9106 
9107     if (TrueTy == FalseTy)
9108       return std::make_pair(TrueTy, TrueName);
9109     else if (TrueTy.isNull())
9110       return std::make_pair(FalseTy, FalseName);
9111     else if (FalseTy.isNull())
9112       return std::make_pair(TrueTy, TrueName);
9113   }
9114 
9115   return std::make_pair(QualType(), StringRef());
9116 }
9117 
9118 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9119 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9120 /// type do not count.
9121 static bool
9122 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9123   QualType From = ICE->getSubExpr()->getType();
9124   QualType To = ICE->getType();
9125   // It's an integer promotion if the destination type is the promoted
9126   // source type.
9127   if (ICE->getCastKind() == CK_IntegralCast &&
9128       From->isPromotableIntegerType() &&
9129       S.Context.getPromotedIntegerType(From) == To)
9130     return true;
9131   // Look through vector types, since we do default argument promotion for
9132   // those in OpenCL.
9133   if (const auto *VecTy = From->getAs<ExtVectorType>())
9134     From = VecTy->getElementType();
9135   if (const auto *VecTy = To->getAs<ExtVectorType>())
9136     To = VecTy->getElementType();
9137   // It's a floating promotion if the source type is a lower rank.
9138   return ICE->getCastKind() == CK_FloatingCast &&
9139          S.Context.getFloatingTypeOrder(From, To) < 0;
9140 }
9141 
9142 bool
9143 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9144                                     const char *StartSpecifier,
9145                                     unsigned SpecifierLen,
9146                                     const Expr *E) {
9147   using namespace analyze_format_string;
9148   using namespace analyze_printf;
9149 
9150   // Now type check the data expression that matches the
9151   // format specifier.
9152   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9153   if (!AT.isValid())
9154     return true;
9155 
9156   QualType ExprTy = E->getType();
9157   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9158     ExprTy = TET->getUnderlyingExpr()->getType();
9159   }
9160 
9161   // Diagnose attempts to print a boolean value as a character. Unlike other
9162   // -Wformat diagnostics, this is fine from a type perspective, but it still
9163   // doesn't make sense.
9164   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9165       E->isKnownToHaveBooleanValue()) {
9166     const CharSourceRange &CSR =
9167         getSpecifierRange(StartSpecifier, SpecifierLen);
9168     SmallString<4> FSString;
9169     llvm::raw_svector_ostream os(FSString);
9170     FS.toString(os);
9171     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9172                              << FSString,
9173                          E->getExprLoc(), false, CSR);
9174     return true;
9175   }
9176 
9177   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9178   if (Match == analyze_printf::ArgType::Match)
9179     return true;
9180 
9181   // Look through argument promotions for our error message's reported type.
9182   // This includes the integral and floating promotions, but excludes array
9183   // and function pointer decay (seeing that an argument intended to be a
9184   // string has type 'char [6]' is probably more confusing than 'char *') and
9185   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9186   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9187     if (isArithmeticArgumentPromotion(S, ICE)) {
9188       E = ICE->getSubExpr();
9189       ExprTy = E->getType();
9190 
9191       // Check if we didn't match because of an implicit cast from a 'char'
9192       // or 'short' to an 'int'.  This is done because printf is a varargs
9193       // function.
9194       if (ICE->getType() == S.Context.IntTy ||
9195           ICE->getType() == S.Context.UnsignedIntTy) {
9196         // All further checking is done on the subexpression
9197         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9198             AT.matchesType(S.Context, ExprTy);
9199         if (ImplicitMatch == analyze_printf::ArgType::Match)
9200           return true;
9201         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9202             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9203           Match = ImplicitMatch;
9204       }
9205     }
9206   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9207     // Special case for 'a', which has type 'int' in C.
9208     // Note, however, that we do /not/ want to treat multibyte constants like
9209     // 'MooV' as characters! This form is deprecated but still exists. In
9210     // addition, don't treat expressions as of type 'char' if one byte length
9211     // modifier is provided.
9212     if (ExprTy == S.Context.IntTy &&
9213         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9214       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9215         ExprTy = S.Context.CharTy;
9216   }
9217 
9218   // Look through enums to their underlying type.
9219   bool IsEnum = false;
9220   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9221     ExprTy = EnumTy->getDecl()->getIntegerType();
9222     IsEnum = true;
9223   }
9224 
9225   // %C in an Objective-C context prints a unichar, not a wchar_t.
9226   // If the argument is an integer of some kind, believe the %C and suggest
9227   // a cast instead of changing the conversion specifier.
9228   QualType IntendedTy = ExprTy;
9229   if (isObjCContext() &&
9230       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9231     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9232         !ExprTy->isCharType()) {
9233       // 'unichar' is defined as a typedef of unsigned short, but we should
9234       // prefer using the typedef if it is visible.
9235       IntendedTy = S.Context.UnsignedShortTy;
9236 
9237       // While we are here, check if the value is an IntegerLiteral that happens
9238       // to be within the valid range.
9239       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9240         const llvm::APInt &V = IL->getValue();
9241         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9242           return true;
9243       }
9244 
9245       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9246                           Sema::LookupOrdinaryName);
9247       if (S.LookupName(Result, S.getCurScope())) {
9248         NamedDecl *ND = Result.getFoundDecl();
9249         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9250           if (TD->getUnderlyingType() == IntendedTy)
9251             IntendedTy = S.Context.getTypedefType(TD);
9252       }
9253     }
9254   }
9255 
9256   // Special-case some of Darwin's platform-independence types by suggesting
9257   // casts to primitive types that are known to be large enough.
9258   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9259   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9260     QualType CastTy;
9261     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9262     if (!CastTy.isNull()) {
9263       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9264       // (long in ASTContext). Only complain to pedants.
9265       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9266           (AT.isSizeT() || AT.isPtrdiffT()) &&
9267           AT.matchesType(S.Context, CastTy))
9268         Match = ArgType::NoMatchPedantic;
9269       IntendedTy = CastTy;
9270       ShouldNotPrintDirectly = true;
9271     }
9272   }
9273 
9274   // We may be able to offer a FixItHint if it is a supported type.
9275   PrintfSpecifier fixedFS = FS;
9276   bool Success =
9277       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9278 
9279   if (Success) {
9280     // Get the fix string from the fixed format specifier
9281     SmallString<16> buf;
9282     llvm::raw_svector_ostream os(buf);
9283     fixedFS.toString(os);
9284 
9285     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9286 
9287     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9288       unsigned Diag;
9289       switch (Match) {
9290       case ArgType::Match: llvm_unreachable("expected non-matching");
9291       case ArgType::NoMatchPedantic:
9292         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9293         break;
9294       case ArgType::NoMatchTypeConfusion:
9295         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9296         break;
9297       case ArgType::NoMatch:
9298         Diag = diag::warn_format_conversion_argument_type_mismatch;
9299         break;
9300       }
9301 
9302       // In this case, the specifier is wrong and should be changed to match
9303       // the argument.
9304       EmitFormatDiagnostic(S.PDiag(Diag)
9305                                << AT.getRepresentativeTypeName(S.Context)
9306                                << IntendedTy << IsEnum << E->getSourceRange(),
9307                            E->getBeginLoc(),
9308                            /*IsStringLocation*/ false, SpecRange,
9309                            FixItHint::CreateReplacement(SpecRange, os.str()));
9310     } else {
9311       // The canonical type for formatting this value is different from the
9312       // actual type of the expression. (This occurs, for example, with Darwin's
9313       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9314       // should be printed as 'long' for 64-bit compatibility.)
9315       // Rather than emitting a normal format/argument mismatch, we want to
9316       // add a cast to the recommended type (and correct the format string
9317       // if necessary).
9318       SmallString<16> CastBuf;
9319       llvm::raw_svector_ostream CastFix(CastBuf);
9320       CastFix << "(";
9321       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9322       CastFix << ")";
9323 
9324       SmallVector<FixItHint,4> Hints;
9325       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9326         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9327 
9328       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9329         // If there's already a cast present, just replace it.
9330         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9331         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9332 
9333       } else if (!requiresParensToAddCast(E)) {
9334         // If the expression has high enough precedence,
9335         // just write the C-style cast.
9336         Hints.push_back(
9337             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9338       } else {
9339         // Otherwise, add parens around the expression as well as the cast.
9340         CastFix << "(";
9341         Hints.push_back(
9342             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9343 
9344         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9345         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9346       }
9347 
9348       if (ShouldNotPrintDirectly) {
9349         // The expression has a type that should not be printed directly.
9350         // We extract the name from the typedef because we don't want to show
9351         // the underlying type in the diagnostic.
9352         StringRef Name;
9353         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9354           Name = TypedefTy->getDecl()->getName();
9355         else
9356           Name = CastTyName;
9357         unsigned Diag = Match == ArgType::NoMatchPedantic
9358                             ? diag::warn_format_argument_needs_cast_pedantic
9359                             : diag::warn_format_argument_needs_cast;
9360         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9361                                            << E->getSourceRange(),
9362                              E->getBeginLoc(), /*IsStringLocation=*/false,
9363                              SpecRange, Hints);
9364       } else {
9365         // In this case, the expression could be printed using a different
9366         // specifier, but we've decided that the specifier is probably correct
9367         // and we should cast instead. Just use the normal warning message.
9368         EmitFormatDiagnostic(
9369             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9370                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9371                 << E->getSourceRange(),
9372             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9373       }
9374     }
9375   } else {
9376     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9377                                                    SpecifierLen);
9378     // Since the warning for passing non-POD types to variadic functions
9379     // was deferred until now, we emit a warning for non-POD
9380     // arguments here.
9381     switch (S.isValidVarArgType(ExprTy)) {
9382     case Sema::VAK_Valid:
9383     case Sema::VAK_ValidInCXX11: {
9384       unsigned Diag;
9385       switch (Match) {
9386       case ArgType::Match: llvm_unreachable("expected non-matching");
9387       case ArgType::NoMatchPedantic:
9388         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9389         break;
9390       case ArgType::NoMatchTypeConfusion:
9391         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9392         break;
9393       case ArgType::NoMatch:
9394         Diag = diag::warn_format_conversion_argument_type_mismatch;
9395         break;
9396       }
9397 
9398       EmitFormatDiagnostic(
9399           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9400                         << IsEnum << CSR << E->getSourceRange(),
9401           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9402       break;
9403     }
9404     case Sema::VAK_Undefined:
9405     case Sema::VAK_MSVCUndefined:
9406       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9407                                << S.getLangOpts().CPlusPlus11 << ExprTy
9408                                << CallType
9409                                << AT.getRepresentativeTypeName(S.Context) << CSR
9410                                << E->getSourceRange(),
9411                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9412       checkForCStrMembers(AT, E);
9413       break;
9414 
9415     case Sema::VAK_Invalid:
9416       if (ExprTy->isObjCObjectType())
9417         EmitFormatDiagnostic(
9418             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9419                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9420                 << AT.getRepresentativeTypeName(S.Context) << CSR
9421                 << E->getSourceRange(),
9422             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9423       else
9424         // FIXME: If this is an initializer list, suggest removing the braces
9425         // or inserting a cast to the target type.
9426         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9427             << isa<InitListExpr>(E) << ExprTy << CallType
9428             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9429       break;
9430     }
9431 
9432     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9433            "format string specifier index out of range");
9434     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9435   }
9436 
9437   return true;
9438 }
9439 
9440 //===--- CHECK: Scanf format string checking ------------------------------===//
9441 
9442 namespace {
9443 
9444 class CheckScanfHandler : public CheckFormatHandler {
9445 public:
9446   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9447                     const Expr *origFormatExpr, Sema::FormatStringType type,
9448                     unsigned firstDataArg, unsigned numDataArgs,
9449                     const char *beg, bool hasVAListArg,
9450                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9451                     bool inFunctionCall, Sema::VariadicCallType CallType,
9452                     llvm::SmallBitVector &CheckedVarArgs,
9453                     UncoveredArgHandler &UncoveredArg)
9454       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9455                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9456                            inFunctionCall, CallType, CheckedVarArgs,
9457                            UncoveredArg) {}
9458 
9459   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9460                             const char *startSpecifier,
9461                             unsigned specifierLen) override;
9462 
9463   bool HandleInvalidScanfConversionSpecifier(
9464           const analyze_scanf::ScanfSpecifier &FS,
9465           const char *startSpecifier,
9466           unsigned specifierLen) override;
9467 
9468   void HandleIncompleteScanList(const char *start, const char *end) override;
9469 };
9470 
9471 } // namespace
9472 
9473 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9474                                                  const char *end) {
9475   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9476                        getLocationOfByte(end), /*IsStringLocation*/true,
9477                        getSpecifierRange(start, end - start));
9478 }
9479 
9480 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9481                                         const analyze_scanf::ScanfSpecifier &FS,
9482                                         const char *startSpecifier,
9483                                         unsigned specifierLen) {
9484   const analyze_scanf::ScanfConversionSpecifier &CS =
9485     FS.getConversionSpecifier();
9486 
9487   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9488                                           getLocationOfByte(CS.getStart()),
9489                                           startSpecifier, specifierLen,
9490                                           CS.getStart(), CS.getLength());
9491 }
9492 
9493 bool CheckScanfHandler::HandleScanfSpecifier(
9494                                        const analyze_scanf::ScanfSpecifier &FS,
9495                                        const char *startSpecifier,
9496                                        unsigned specifierLen) {
9497   using namespace analyze_scanf;
9498   using namespace analyze_format_string;
9499 
9500   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9501 
9502   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9503   // be used to decide if we are using positional arguments consistently.
9504   if (FS.consumesDataArgument()) {
9505     if (atFirstArg) {
9506       atFirstArg = false;
9507       usesPositionalArgs = FS.usesPositionalArg();
9508     }
9509     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9510       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9511                                         startSpecifier, specifierLen);
9512       return false;
9513     }
9514   }
9515 
9516   // Check if the field with is non-zero.
9517   const OptionalAmount &Amt = FS.getFieldWidth();
9518   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9519     if (Amt.getConstantAmount() == 0) {
9520       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9521                                                    Amt.getConstantLength());
9522       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9523                            getLocationOfByte(Amt.getStart()),
9524                            /*IsStringLocation*/true, R,
9525                            FixItHint::CreateRemoval(R));
9526     }
9527   }
9528 
9529   if (!FS.consumesDataArgument()) {
9530     // FIXME: Technically specifying a precision or field width here
9531     // makes no sense.  Worth issuing a warning at some point.
9532     return true;
9533   }
9534 
9535   // Consume the argument.
9536   unsigned argIndex = FS.getArgIndex();
9537   if (argIndex < NumDataArgs) {
9538       // The check to see if the argIndex is valid will come later.
9539       // We set the bit here because we may exit early from this
9540       // function if we encounter some other error.
9541     CoveredArgs.set(argIndex);
9542   }
9543 
9544   // Check the length modifier is valid with the given conversion specifier.
9545   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9546                                  S.getLangOpts()))
9547     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9548                                 diag::warn_format_nonsensical_length);
9549   else if (!FS.hasStandardLengthModifier())
9550     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9551   else if (!FS.hasStandardLengthConversionCombination())
9552     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9553                                 diag::warn_format_non_standard_conversion_spec);
9554 
9555   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9556     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9557 
9558   // The remaining checks depend on the data arguments.
9559   if (HasVAListArg)
9560     return true;
9561 
9562   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9563     return false;
9564 
9565   // Check that the argument type matches the format specifier.
9566   const Expr *Ex = getDataArg(argIndex);
9567   if (!Ex)
9568     return true;
9569 
9570   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9571 
9572   if (!AT.isValid()) {
9573     return true;
9574   }
9575 
9576   analyze_format_string::ArgType::MatchKind Match =
9577       AT.matchesType(S.Context, Ex->getType());
9578   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9579   if (Match == analyze_format_string::ArgType::Match)
9580     return true;
9581 
9582   ScanfSpecifier fixedFS = FS;
9583   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9584                                  S.getLangOpts(), S.Context);
9585 
9586   unsigned Diag =
9587       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9588                : diag::warn_format_conversion_argument_type_mismatch;
9589 
9590   if (Success) {
9591     // Get the fix string from the fixed format specifier.
9592     SmallString<128> buf;
9593     llvm::raw_svector_ostream os(buf);
9594     fixedFS.toString(os);
9595 
9596     EmitFormatDiagnostic(
9597         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9598                       << Ex->getType() << false << Ex->getSourceRange(),
9599         Ex->getBeginLoc(),
9600         /*IsStringLocation*/ false,
9601         getSpecifierRange(startSpecifier, specifierLen),
9602         FixItHint::CreateReplacement(
9603             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9604   } else {
9605     EmitFormatDiagnostic(S.PDiag(Diag)
9606                              << AT.getRepresentativeTypeName(S.Context)
9607                              << Ex->getType() << false << Ex->getSourceRange(),
9608                          Ex->getBeginLoc(),
9609                          /*IsStringLocation*/ false,
9610                          getSpecifierRange(startSpecifier, specifierLen));
9611   }
9612 
9613   return true;
9614 }
9615 
9616 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9617                               const Expr *OrigFormatExpr,
9618                               ArrayRef<const Expr *> Args,
9619                               bool HasVAListArg, unsigned format_idx,
9620                               unsigned firstDataArg,
9621                               Sema::FormatStringType Type,
9622                               bool inFunctionCall,
9623                               Sema::VariadicCallType CallType,
9624                               llvm::SmallBitVector &CheckedVarArgs,
9625                               UncoveredArgHandler &UncoveredArg,
9626                               bool IgnoreStringsWithoutSpecifiers) {
9627   // CHECK: is the format string a wide literal?
9628   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9629     CheckFormatHandler::EmitFormatDiagnostic(
9630         S, inFunctionCall, Args[format_idx],
9631         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9632         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9633     return;
9634   }
9635 
9636   // Str - The format string.  NOTE: this is NOT null-terminated!
9637   StringRef StrRef = FExpr->getString();
9638   const char *Str = StrRef.data();
9639   // Account for cases where the string literal is truncated in a declaration.
9640   const ConstantArrayType *T =
9641     S.Context.getAsConstantArrayType(FExpr->getType());
9642   assert(T && "String literal not of constant array type!");
9643   size_t TypeSize = T->getSize().getZExtValue();
9644   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9645   const unsigned numDataArgs = Args.size() - firstDataArg;
9646 
9647   if (IgnoreStringsWithoutSpecifiers &&
9648       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9649           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9650     return;
9651 
9652   // Emit a warning if the string literal is truncated and does not contain an
9653   // embedded null character.
9654   if (TypeSize <= StrRef.size() &&
9655       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9656     CheckFormatHandler::EmitFormatDiagnostic(
9657         S, inFunctionCall, Args[format_idx],
9658         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9659         FExpr->getBeginLoc(),
9660         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9661     return;
9662   }
9663 
9664   // CHECK: empty format string?
9665   if (StrLen == 0 && numDataArgs > 0) {
9666     CheckFormatHandler::EmitFormatDiagnostic(
9667         S, inFunctionCall, Args[format_idx],
9668         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9669         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9670     return;
9671   }
9672 
9673   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9674       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9675       Type == Sema::FST_OSTrace) {
9676     CheckPrintfHandler H(
9677         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9678         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9679         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9680         CheckedVarArgs, UncoveredArg);
9681 
9682     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9683                                                   S.getLangOpts(),
9684                                                   S.Context.getTargetInfo(),
9685                                             Type == Sema::FST_FreeBSDKPrintf))
9686       H.DoneProcessing();
9687   } else if (Type == Sema::FST_Scanf) {
9688     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9689                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9690                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9691 
9692     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9693                                                  S.getLangOpts(),
9694                                                  S.Context.getTargetInfo()))
9695       H.DoneProcessing();
9696   } // TODO: handle other formats
9697 }
9698 
9699 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9700   // Str - The format string.  NOTE: this is NOT null-terminated!
9701   StringRef StrRef = FExpr->getString();
9702   const char *Str = StrRef.data();
9703   // Account for cases where the string literal is truncated in a declaration.
9704   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9705   assert(T && "String literal not of constant array type!");
9706   size_t TypeSize = T->getSize().getZExtValue();
9707   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9708   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9709                                                          getLangOpts(),
9710                                                          Context.getTargetInfo());
9711 }
9712 
9713 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9714 
9715 // Returns the related absolute value function that is larger, of 0 if one
9716 // does not exist.
9717 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9718   switch (AbsFunction) {
9719   default:
9720     return 0;
9721 
9722   case Builtin::BI__builtin_abs:
9723     return Builtin::BI__builtin_labs;
9724   case Builtin::BI__builtin_labs:
9725     return Builtin::BI__builtin_llabs;
9726   case Builtin::BI__builtin_llabs:
9727     return 0;
9728 
9729   case Builtin::BI__builtin_fabsf:
9730     return Builtin::BI__builtin_fabs;
9731   case Builtin::BI__builtin_fabs:
9732     return Builtin::BI__builtin_fabsl;
9733   case Builtin::BI__builtin_fabsl:
9734     return 0;
9735 
9736   case Builtin::BI__builtin_cabsf:
9737     return Builtin::BI__builtin_cabs;
9738   case Builtin::BI__builtin_cabs:
9739     return Builtin::BI__builtin_cabsl;
9740   case Builtin::BI__builtin_cabsl:
9741     return 0;
9742 
9743   case Builtin::BIabs:
9744     return Builtin::BIlabs;
9745   case Builtin::BIlabs:
9746     return Builtin::BIllabs;
9747   case Builtin::BIllabs:
9748     return 0;
9749 
9750   case Builtin::BIfabsf:
9751     return Builtin::BIfabs;
9752   case Builtin::BIfabs:
9753     return Builtin::BIfabsl;
9754   case Builtin::BIfabsl:
9755     return 0;
9756 
9757   case Builtin::BIcabsf:
9758    return Builtin::BIcabs;
9759   case Builtin::BIcabs:
9760     return Builtin::BIcabsl;
9761   case Builtin::BIcabsl:
9762     return 0;
9763   }
9764 }
9765 
9766 // Returns the argument type of the absolute value function.
9767 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9768                                              unsigned AbsType) {
9769   if (AbsType == 0)
9770     return QualType();
9771 
9772   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9773   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9774   if (Error != ASTContext::GE_None)
9775     return QualType();
9776 
9777   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9778   if (!FT)
9779     return QualType();
9780 
9781   if (FT->getNumParams() != 1)
9782     return QualType();
9783 
9784   return FT->getParamType(0);
9785 }
9786 
9787 // Returns the best absolute value function, or zero, based on type and
9788 // current absolute value function.
9789 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9790                                    unsigned AbsFunctionKind) {
9791   unsigned BestKind = 0;
9792   uint64_t ArgSize = Context.getTypeSize(ArgType);
9793   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9794        Kind = getLargerAbsoluteValueFunction(Kind)) {
9795     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9796     if (Context.getTypeSize(ParamType) >= ArgSize) {
9797       if (BestKind == 0)
9798         BestKind = Kind;
9799       else if (Context.hasSameType(ParamType, ArgType)) {
9800         BestKind = Kind;
9801         break;
9802       }
9803     }
9804   }
9805   return BestKind;
9806 }
9807 
9808 enum AbsoluteValueKind {
9809   AVK_Integer,
9810   AVK_Floating,
9811   AVK_Complex
9812 };
9813 
9814 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9815   if (T->isIntegralOrEnumerationType())
9816     return AVK_Integer;
9817   if (T->isRealFloatingType())
9818     return AVK_Floating;
9819   if (T->isAnyComplexType())
9820     return AVK_Complex;
9821 
9822   llvm_unreachable("Type not integer, floating, or complex");
9823 }
9824 
9825 // Changes the absolute value function to a different type.  Preserves whether
9826 // the function is a builtin.
9827 static unsigned changeAbsFunction(unsigned AbsKind,
9828                                   AbsoluteValueKind ValueKind) {
9829   switch (ValueKind) {
9830   case AVK_Integer:
9831     switch (AbsKind) {
9832     default:
9833       return 0;
9834     case Builtin::BI__builtin_fabsf:
9835     case Builtin::BI__builtin_fabs:
9836     case Builtin::BI__builtin_fabsl:
9837     case Builtin::BI__builtin_cabsf:
9838     case Builtin::BI__builtin_cabs:
9839     case Builtin::BI__builtin_cabsl:
9840       return Builtin::BI__builtin_abs;
9841     case Builtin::BIfabsf:
9842     case Builtin::BIfabs:
9843     case Builtin::BIfabsl:
9844     case Builtin::BIcabsf:
9845     case Builtin::BIcabs:
9846     case Builtin::BIcabsl:
9847       return Builtin::BIabs;
9848     }
9849   case AVK_Floating:
9850     switch (AbsKind) {
9851     default:
9852       return 0;
9853     case Builtin::BI__builtin_abs:
9854     case Builtin::BI__builtin_labs:
9855     case Builtin::BI__builtin_llabs:
9856     case Builtin::BI__builtin_cabsf:
9857     case Builtin::BI__builtin_cabs:
9858     case Builtin::BI__builtin_cabsl:
9859       return Builtin::BI__builtin_fabsf;
9860     case Builtin::BIabs:
9861     case Builtin::BIlabs:
9862     case Builtin::BIllabs:
9863     case Builtin::BIcabsf:
9864     case Builtin::BIcabs:
9865     case Builtin::BIcabsl:
9866       return Builtin::BIfabsf;
9867     }
9868   case AVK_Complex:
9869     switch (AbsKind) {
9870     default:
9871       return 0;
9872     case Builtin::BI__builtin_abs:
9873     case Builtin::BI__builtin_labs:
9874     case Builtin::BI__builtin_llabs:
9875     case Builtin::BI__builtin_fabsf:
9876     case Builtin::BI__builtin_fabs:
9877     case Builtin::BI__builtin_fabsl:
9878       return Builtin::BI__builtin_cabsf;
9879     case Builtin::BIabs:
9880     case Builtin::BIlabs:
9881     case Builtin::BIllabs:
9882     case Builtin::BIfabsf:
9883     case Builtin::BIfabs:
9884     case Builtin::BIfabsl:
9885       return Builtin::BIcabsf;
9886     }
9887   }
9888   llvm_unreachable("Unable to convert function");
9889 }
9890 
9891 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9892   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9893   if (!FnInfo)
9894     return 0;
9895 
9896   switch (FDecl->getBuiltinID()) {
9897   default:
9898     return 0;
9899   case Builtin::BI__builtin_abs:
9900   case Builtin::BI__builtin_fabs:
9901   case Builtin::BI__builtin_fabsf:
9902   case Builtin::BI__builtin_fabsl:
9903   case Builtin::BI__builtin_labs:
9904   case Builtin::BI__builtin_llabs:
9905   case Builtin::BI__builtin_cabs:
9906   case Builtin::BI__builtin_cabsf:
9907   case Builtin::BI__builtin_cabsl:
9908   case Builtin::BIabs:
9909   case Builtin::BIlabs:
9910   case Builtin::BIllabs:
9911   case Builtin::BIfabs:
9912   case Builtin::BIfabsf:
9913   case Builtin::BIfabsl:
9914   case Builtin::BIcabs:
9915   case Builtin::BIcabsf:
9916   case Builtin::BIcabsl:
9917     return FDecl->getBuiltinID();
9918   }
9919   llvm_unreachable("Unknown Builtin type");
9920 }
9921 
9922 // If the replacement is valid, emit a note with replacement function.
9923 // Additionally, suggest including the proper header if not already included.
9924 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9925                             unsigned AbsKind, QualType ArgType) {
9926   bool EmitHeaderHint = true;
9927   const char *HeaderName = nullptr;
9928   const char *FunctionName = nullptr;
9929   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9930     FunctionName = "std::abs";
9931     if (ArgType->isIntegralOrEnumerationType()) {
9932       HeaderName = "cstdlib";
9933     } else if (ArgType->isRealFloatingType()) {
9934       HeaderName = "cmath";
9935     } else {
9936       llvm_unreachable("Invalid Type");
9937     }
9938 
9939     // Lookup all std::abs
9940     if (NamespaceDecl *Std = S.getStdNamespace()) {
9941       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9942       R.suppressDiagnostics();
9943       S.LookupQualifiedName(R, Std);
9944 
9945       for (const auto *I : R) {
9946         const FunctionDecl *FDecl = nullptr;
9947         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9948           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9949         } else {
9950           FDecl = dyn_cast<FunctionDecl>(I);
9951         }
9952         if (!FDecl)
9953           continue;
9954 
9955         // Found std::abs(), check that they are the right ones.
9956         if (FDecl->getNumParams() != 1)
9957           continue;
9958 
9959         // Check that the parameter type can handle the argument.
9960         QualType ParamType = FDecl->getParamDecl(0)->getType();
9961         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9962             S.Context.getTypeSize(ArgType) <=
9963                 S.Context.getTypeSize(ParamType)) {
9964           // Found a function, don't need the header hint.
9965           EmitHeaderHint = false;
9966           break;
9967         }
9968       }
9969     }
9970   } else {
9971     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9972     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9973 
9974     if (HeaderName) {
9975       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9976       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9977       R.suppressDiagnostics();
9978       S.LookupName(R, S.getCurScope());
9979 
9980       if (R.isSingleResult()) {
9981         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9982         if (FD && FD->getBuiltinID() == AbsKind) {
9983           EmitHeaderHint = false;
9984         } else {
9985           return;
9986         }
9987       } else if (!R.empty()) {
9988         return;
9989       }
9990     }
9991   }
9992 
9993   S.Diag(Loc, diag::note_replace_abs_function)
9994       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9995 
9996   if (!HeaderName)
9997     return;
9998 
9999   if (!EmitHeaderHint)
10000     return;
10001 
10002   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10003                                                     << FunctionName;
10004 }
10005 
10006 template <std::size_t StrLen>
10007 static bool IsStdFunction(const FunctionDecl *FDecl,
10008                           const char (&Str)[StrLen]) {
10009   if (!FDecl)
10010     return false;
10011   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10012     return false;
10013   if (!FDecl->isInStdNamespace())
10014     return false;
10015 
10016   return true;
10017 }
10018 
10019 // Warn when using the wrong abs() function.
10020 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10021                                       const FunctionDecl *FDecl) {
10022   if (Call->getNumArgs() != 1)
10023     return;
10024 
10025   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10026   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10027   if (AbsKind == 0 && !IsStdAbs)
10028     return;
10029 
10030   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10031   QualType ParamType = Call->getArg(0)->getType();
10032 
10033   // Unsigned types cannot be negative.  Suggest removing the absolute value
10034   // function call.
10035   if (ArgType->isUnsignedIntegerType()) {
10036     const char *FunctionName =
10037         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10038     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10039     Diag(Call->getExprLoc(), diag::note_remove_abs)
10040         << FunctionName
10041         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10042     return;
10043   }
10044 
10045   // Taking the absolute value of a pointer is very suspicious, they probably
10046   // wanted to index into an array, dereference a pointer, call a function, etc.
10047   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10048     unsigned DiagType = 0;
10049     if (ArgType->isFunctionType())
10050       DiagType = 1;
10051     else if (ArgType->isArrayType())
10052       DiagType = 2;
10053 
10054     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10055     return;
10056   }
10057 
10058   // std::abs has overloads which prevent most of the absolute value problems
10059   // from occurring.
10060   if (IsStdAbs)
10061     return;
10062 
10063   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10064   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10065 
10066   // The argument and parameter are the same kind.  Check if they are the right
10067   // size.
10068   if (ArgValueKind == ParamValueKind) {
10069     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10070       return;
10071 
10072     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10073     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10074         << FDecl << ArgType << ParamType;
10075 
10076     if (NewAbsKind == 0)
10077       return;
10078 
10079     emitReplacement(*this, Call->getExprLoc(),
10080                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10081     return;
10082   }
10083 
10084   // ArgValueKind != ParamValueKind
10085   // The wrong type of absolute value function was used.  Attempt to find the
10086   // proper one.
10087   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10088   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10089   if (NewAbsKind == 0)
10090     return;
10091 
10092   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10093       << FDecl << ParamValueKind << ArgValueKind;
10094 
10095   emitReplacement(*this, Call->getExprLoc(),
10096                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10097 }
10098 
10099 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10100 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10101                                 const FunctionDecl *FDecl) {
10102   if (!Call || !FDecl) return;
10103 
10104   // Ignore template specializations and macros.
10105   if (inTemplateInstantiation()) return;
10106   if (Call->getExprLoc().isMacroID()) return;
10107 
10108   // Only care about the one template argument, two function parameter std::max
10109   if (Call->getNumArgs() != 2) return;
10110   if (!IsStdFunction(FDecl, "max")) return;
10111   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10112   if (!ArgList) return;
10113   if (ArgList->size() != 1) return;
10114 
10115   // Check that template type argument is unsigned integer.
10116   const auto& TA = ArgList->get(0);
10117   if (TA.getKind() != TemplateArgument::Type) return;
10118   QualType ArgType = TA.getAsType();
10119   if (!ArgType->isUnsignedIntegerType()) return;
10120 
10121   // See if either argument is a literal zero.
10122   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10123     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10124     if (!MTE) return false;
10125     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10126     if (!Num) return false;
10127     if (Num->getValue() != 0) return false;
10128     return true;
10129   };
10130 
10131   const Expr *FirstArg = Call->getArg(0);
10132   const Expr *SecondArg = Call->getArg(1);
10133   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10134   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10135 
10136   // Only warn when exactly one argument is zero.
10137   if (IsFirstArgZero == IsSecondArgZero) return;
10138 
10139   SourceRange FirstRange = FirstArg->getSourceRange();
10140   SourceRange SecondRange = SecondArg->getSourceRange();
10141 
10142   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10143 
10144   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10145       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10146 
10147   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10148   SourceRange RemovalRange;
10149   if (IsFirstArgZero) {
10150     RemovalRange = SourceRange(FirstRange.getBegin(),
10151                                SecondRange.getBegin().getLocWithOffset(-1));
10152   } else {
10153     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10154                                SecondRange.getEnd());
10155   }
10156 
10157   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10158         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10159         << FixItHint::CreateRemoval(RemovalRange);
10160 }
10161 
10162 //===--- CHECK: Standard memory functions ---------------------------------===//
10163 
10164 /// Takes the expression passed to the size_t parameter of functions
10165 /// such as memcmp, strncat, etc and warns if it's a comparison.
10166 ///
10167 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10168 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10169                                            IdentifierInfo *FnName,
10170                                            SourceLocation FnLoc,
10171                                            SourceLocation RParenLoc) {
10172   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10173   if (!Size)
10174     return false;
10175 
10176   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10177   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10178     return false;
10179 
10180   SourceRange SizeRange = Size->getSourceRange();
10181   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10182       << SizeRange << FnName;
10183   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10184       << FnName
10185       << FixItHint::CreateInsertion(
10186              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10187       << FixItHint::CreateRemoval(RParenLoc);
10188   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10189       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10190       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10191                                     ")");
10192 
10193   return true;
10194 }
10195 
10196 /// Determine whether the given type is or contains a dynamic class type
10197 /// (e.g., whether it has a vtable).
10198 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10199                                                      bool &IsContained) {
10200   // Look through array types while ignoring qualifiers.
10201   const Type *Ty = T->getBaseElementTypeUnsafe();
10202   IsContained = false;
10203 
10204   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10205   RD = RD ? RD->getDefinition() : nullptr;
10206   if (!RD || RD->isInvalidDecl())
10207     return nullptr;
10208 
10209   if (RD->isDynamicClass())
10210     return RD;
10211 
10212   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10213   // It's impossible for a class to transitively contain itself by value, so
10214   // infinite recursion is impossible.
10215   for (auto *FD : RD->fields()) {
10216     bool SubContained;
10217     if (const CXXRecordDecl *ContainedRD =
10218             getContainedDynamicClass(FD->getType(), SubContained)) {
10219       IsContained = true;
10220       return ContainedRD;
10221     }
10222   }
10223 
10224   return nullptr;
10225 }
10226 
10227 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10228   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10229     if (Unary->getKind() == UETT_SizeOf)
10230       return Unary;
10231   return nullptr;
10232 }
10233 
10234 /// If E is a sizeof expression, returns its argument expression,
10235 /// otherwise returns NULL.
10236 static const Expr *getSizeOfExprArg(const Expr *E) {
10237   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10238     if (!SizeOf->isArgumentType())
10239       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10240   return nullptr;
10241 }
10242 
10243 /// If E is a sizeof expression, returns its argument type.
10244 static QualType getSizeOfArgType(const Expr *E) {
10245   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10246     return SizeOf->getTypeOfArgument();
10247   return QualType();
10248 }
10249 
10250 namespace {
10251 
10252 struct SearchNonTrivialToInitializeField
10253     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10254   using Super =
10255       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10256 
10257   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10258 
10259   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10260                      SourceLocation SL) {
10261     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10262       asDerived().visitArray(PDIK, AT, SL);
10263       return;
10264     }
10265 
10266     Super::visitWithKind(PDIK, FT, SL);
10267   }
10268 
10269   void visitARCStrong(QualType FT, SourceLocation SL) {
10270     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10271   }
10272   void visitARCWeak(QualType FT, SourceLocation SL) {
10273     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10274   }
10275   void visitStruct(QualType FT, SourceLocation SL) {
10276     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10277       visit(FD->getType(), FD->getLocation());
10278   }
10279   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10280                   const ArrayType *AT, SourceLocation SL) {
10281     visit(getContext().getBaseElementType(AT), SL);
10282   }
10283   void visitTrivial(QualType FT, SourceLocation SL) {}
10284 
10285   static void diag(QualType RT, const Expr *E, Sema &S) {
10286     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10287   }
10288 
10289   ASTContext &getContext() { return S.getASTContext(); }
10290 
10291   const Expr *E;
10292   Sema &S;
10293 };
10294 
10295 struct SearchNonTrivialToCopyField
10296     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10297   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10298 
10299   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10300 
10301   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10302                      SourceLocation SL) {
10303     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10304       asDerived().visitArray(PCK, AT, SL);
10305       return;
10306     }
10307 
10308     Super::visitWithKind(PCK, FT, SL);
10309   }
10310 
10311   void visitARCStrong(QualType FT, SourceLocation SL) {
10312     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10313   }
10314   void visitARCWeak(QualType FT, SourceLocation SL) {
10315     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10316   }
10317   void visitStruct(QualType FT, SourceLocation SL) {
10318     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10319       visit(FD->getType(), FD->getLocation());
10320   }
10321   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10322                   SourceLocation SL) {
10323     visit(getContext().getBaseElementType(AT), SL);
10324   }
10325   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10326                 SourceLocation SL) {}
10327   void visitTrivial(QualType FT, SourceLocation SL) {}
10328   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10329 
10330   static void diag(QualType RT, const Expr *E, Sema &S) {
10331     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10332   }
10333 
10334   ASTContext &getContext() { return S.getASTContext(); }
10335 
10336   const Expr *E;
10337   Sema &S;
10338 };
10339 
10340 }
10341 
10342 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10343 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10344   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10345 
10346   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10347     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10348       return false;
10349 
10350     return doesExprLikelyComputeSize(BO->getLHS()) ||
10351            doesExprLikelyComputeSize(BO->getRHS());
10352   }
10353 
10354   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10355 }
10356 
10357 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10358 ///
10359 /// \code
10360 ///   #define MACRO 0
10361 ///   foo(MACRO);
10362 ///   foo(0);
10363 /// \endcode
10364 ///
10365 /// This should return true for the first call to foo, but not for the second
10366 /// (regardless of whether foo is a macro or function).
10367 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10368                                         SourceLocation CallLoc,
10369                                         SourceLocation ArgLoc) {
10370   if (!CallLoc.isMacroID())
10371     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10372 
10373   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10374          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10375 }
10376 
10377 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10378 /// last two arguments transposed.
10379 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10380   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10381     return;
10382 
10383   const Expr *SizeArg =
10384     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10385 
10386   auto isLiteralZero = [](const Expr *E) {
10387     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10388   };
10389 
10390   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10391   SourceLocation CallLoc = Call->getRParenLoc();
10392   SourceManager &SM = S.getSourceManager();
10393   if (isLiteralZero(SizeArg) &&
10394       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10395 
10396     SourceLocation DiagLoc = SizeArg->getExprLoc();
10397 
10398     // Some platforms #define bzero to __builtin_memset. See if this is the
10399     // case, and if so, emit a better diagnostic.
10400     if (BId == Builtin::BIbzero ||
10401         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10402                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10403       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10404       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10405     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10406       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10407       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10408     }
10409     return;
10410   }
10411 
10412   // If the second argument to a memset is a sizeof expression and the third
10413   // isn't, this is also likely an error. This should catch
10414   // 'memset(buf, sizeof(buf), 0xff)'.
10415   if (BId == Builtin::BImemset &&
10416       doesExprLikelyComputeSize(Call->getArg(1)) &&
10417       !doesExprLikelyComputeSize(Call->getArg(2))) {
10418     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10419     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10420     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10421     return;
10422   }
10423 }
10424 
10425 /// Check for dangerous or invalid arguments to memset().
10426 ///
10427 /// This issues warnings on known problematic, dangerous or unspecified
10428 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10429 /// function calls.
10430 ///
10431 /// \param Call The call expression to diagnose.
10432 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10433                                    unsigned BId,
10434                                    IdentifierInfo *FnName) {
10435   assert(BId != 0);
10436 
10437   // It is possible to have a non-standard definition of memset.  Validate
10438   // we have enough arguments, and if not, abort further checking.
10439   unsigned ExpectedNumArgs =
10440       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10441   if (Call->getNumArgs() < ExpectedNumArgs)
10442     return;
10443 
10444   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10445                       BId == Builtin::BIstrndup ? 1 : 2);
10446   unsigned LenArg =
10447       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10448   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10449 
10450   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10451                                      Call->getBeginLoc(), Call->getRParenLoc()))
10452     return;
10453 
10454   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10455   CheckMemaccessSize(*this, BId, Call);
10456 
10457   // We have special checking when the length is a sizeof expression.
10458   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10459   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10460   llvm::FoldingSetNodeID SizeOfArgID;
10461 
10462   // Although widely used, 'bzero' is not a standard function. Be more strict
10463   // with the argument types before allowing diagnostics and only allow the
10464   // form bzero(ptr, sizeof(...)).
10465   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10466   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10467     return;
10468 
10469   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10470     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10471     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10472 
10473     QualType DestTy = Dest->getType();
10474     QualType PointeeTy;
10475     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10476       PointeeTy = DestPtrTy->getPointeeType();
10477 
10478       // Never warn about void type pointers. This can be used to suppress
10479       // false positives.
10480       if (PointeeTy->isVoidType())
10481         continue;
10482 
10483       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10484       // actually comparing the expressions for equality. Because computing the
10485       // expression IDs can be expensive, we only do this if the diagnostic is
10486       // enabled.
10487       if (SizeOfArg &&
10488           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10489                            SizeOfArg->getExprLoc())) {
10490         // We only compute IDs for expressions if the warning is enabled, and
10491         // cache the sizeof arg's ID.
10492         if (SizeOfArgID == llvm::FoldingSetNodeID())
10493           SizeOfArg->Profile(SizeOfArgID, Context, true);
10494         llvm::FoldingSetNodeID DestID;
10495         Dest->Profile(DestID, Context, true);
10496         if (DestID == SizeOfArgID) {
10497           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10498           //       over sizeof(src) as well.
10499           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10500           StringRef ReadableName = FnName->getName();
10501 
10502           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10503             if (UnaryOp->getOpcode() == UO_AddrOf)
10504               ActionIdx = 1; // If its an address-of operator, just remove it.
10505           if (!PointeeTy->isIncompleteType() &&
10506               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10507             ActionIdx = 2; // If the pointee's size is sizeof(char),
10508                            // suggest an explicit length.
10509 
10510           // If the function is defined as a builtin macro, do not show macro
10511           // expansion.
10512           SourceLocation SL = SizeOfArg->getExprLoc();
10513           SourceRange DSR = Dest->getSourceRange();
10514           SourceRange SSR = SizeOfArg->getSourceRange();
10515           SourceManager &SM = getSourceManager();
10516 
10517           if (SM.isMacroArgExpansion(SL)) {
10518             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10519             SL = SM.getSpellingLoc(SL);
10520             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10521                              SM.getSpellingLoc(DSR.getEnd()));
10522             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10523                              SM.getSpellingLoc(SSR.getEnd()));
10524           }
10525 
10526           DiagRuntimeBehavior(SL, SizeOfArg,
10527                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10528                                 << ReadableName
10529                                 << PointeeTy
10530                                 << DestTy
10531                                 << DSR
10532                                 << SSR);
10533           DiagRuntimeBehavior(SL, SizeOfArg,
10534                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10535                                 << ActionIdx
10536                                 << SSR);
10537 
10538           break;
10539         }
10540       }
10541 
10542       // Also check for cases where the sizeof argument is the exact same
10543       // type as the memory argument, and where it points to a user-defined
10544       // record type.
10545       if (SizeOfArgTy != QualType()) {
10546         if (PointeeTy->isRecordType() &&
10547             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10548           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10549                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10550                                 << FnName << SizeOfArgTy << ArgIdx
10551                                 << PointeeTy << Dest->getSourceRange()
10552                                 << LenExpr->getSourceRange());
10553           break;
10554         }
10555       }
10556     } else if (DestTy->isArrayType()) {
10557       PointeeTy = DestTy;
10558     }
10559 
10560     if (PointeeTy == QualType())
10561       continue;
10562 
10563     // Always complain about dynamic classes.
10564     bool IsContained;
10565     if (const CXXRecordDecl *ContainedRD =
10566             getContainedDynamicClass(PointeeTy, IsContained)) {
10567 
10568       unsigned OperationType = 0;
10569       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10570       // "overwritten" if we're warning about the destination for any call
10571       // but memcmp; otherwise a verb appropriate to the call.
10572       if (ArgIdx != 0 || IsCmp) {
10573         if (BId == Builtin::BImemcpy)
10574           OperationType = 1;
10575         else if(BId == Builtin::BImemmove)
10576           OperationType = 2;
10577         else if (IsCmp)
10578           OperationType = 3;
10579       }
10580 
10581       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10582                           PDiag(diag::warn_dyn_class_memaccess)
10583                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10584                               << IsContained << ContainedRD << OperationType
10585                               << Call->getCallee()->getSourceRange());
10586     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10587              BId != Builtin::BImemset)
10588       DiagRuntimeBehavior(
10589         Dest->getExprLoc(), Dest,
10590         PDiag(diag::warn_arc_object_memaccess)
10591           << ArgIdx << FnName << PointeeTy
10592           << Call->getCallee()->getSourceRange());
10593     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10594       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10595           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10596         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10597                             PDiag(diag::warn_cstruct_memaccess)
10598                                 << ArgIdx << FnName << PointeeTy << 0);
10599         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10600       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10601                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10602         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10603                             PDiag(diag::warn_cstruct_memaccess)
10604                                 << ArgIdx << FnName << PointeeTy << 1);
10605         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10606       } else {
10607         continue;
10608       }
10609     } else
10610       continue;
10611 
10612     DiagRuntimeBehavior(
10613       Dest->getExprLoc(), Dest,
10614       PDiag(diag::note_bad_memaccess_silence)
10615         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10616     break;
10617   }
10618 }
10619 
10620 // A little helper routine: ignore addition and subtraction of integer literals.
10621 // This intentionally does not ignore all integer constant expressions because
10622 // we don't want to remove sizeof().
10623 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10624   Ex = Ex->IgnoreParenCasts();
10625 
10626   while (true) {
10627     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10628     if (!BO || !BO->isAdditiveOp())
10629       break;
10630 
10631     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10632     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10633 
10634     if (isa<IntegerLiteral>(RHS))
10635       Ex = LHS;
10636     else if (isa<IntegerLiteral>(LHS))
10637       Ex = RHS;
10638     else
10639       break;
10640   }
10641 
10642   return Ex;
10643 }
10644 
10645 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10646                                                       ASTContext &Context) {
10647   // Only handle constant-sized or VLAs, but not flexible members.
10648   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10649     // Only issue the FIXIT for arrays of size > 1.
10650     if (CAT->getSize().getSExtValue() <= 1)
10651       return false;
10652   } else if (!Ty->isVariableArrayType()) {
10653     return false;
10654   }
10655   return true;
10656 }
10657 
10658 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10659 // be the size of the source, instead of the destination.
10660 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10661                                     IdentifierInfo *FnName) {
10662 
10663   // Don't crash if the user has the wrong number of arguments
10664   unsigned NumArgs = Call->getNumArgs();
10665   if ((NumArgs != 3) && (NumArgs != 4))
10666     return;
10667 
10668   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10669   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10670   const Expr *CompareWithSrc = nullptr;
10671 
10672   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10673                                      Call->getBeginLoc(), Call->getRParenLoc()))
10674     return;
10675 
10676   // Look for 'strlcpy(dst, x, sizeof(x))'
10677   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10678     CompareWithSrc = Ex;
10679   else {
10680     // Look for 'strlcpy(dst, x, strlen(x))'
10681     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10682       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10683           SizeCall->getNumArgs() == 1)
10684         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10685     }
10686   }
10687 
10688   if (!CompareWithSrc)
10689     return;
10690 
10691   // Determine if the argument to sizeof/strlen is equal to the source
10692   // argument.  In principle there's all kinds of things you could do
10693   // here, for instance creating an == expression and evaluating it with
10694   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10695   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10696   if (!SrcArgDRE)
10697     return;
10698 
10699   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10700   if (!CompareWithSrcDRE ||
10701       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10702     return;
10703 
10704   const Expr *OriginalSizeArg = Call->getArg(2);
10705   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10706       << OriginalSizeArg->getSourceRange() << FnName;
10707 
10708   // Output a FIXIT hint if the destination is an array (rather than a
10709   // pointer to an array).  This could be enhanced to handle some
10710   // pointers if we know the actual size, like if DstArg is 'array+2'
10711   // we could say 'sizeof(array)-2'.
10712   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10713   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10714     return;
10715 
10716   SmallString<128> sizeString;
10717   llvm::raw_svector_ostream OS(sizeString);
10718   OS << "sizeof(";
10719   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10720   OS << ")";
10721 
10722   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10723       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10724                                       OS.str());
10725 }
10726 
10727 /// Check if two expressions refer to the same declaration.
10728 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10729   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10730     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10731       return D1->getDecl() == D2->getDecl();
10732   return false;
10733 }
10734 
10735 static const Expr *getStrlenExprArg(const Expr *E) {
10736   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10737     const FunctionDecl *FD = CE->getDirectCallee();
10738     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10739       return nullptr;
10740     return CE->getArg(0)->IgnoreParenCasts();
10741   }
10742   return nullptr;
10743 }
10744 
10745 // Warn on anti-patterns as the 'size' argument to strncat.
10746 // The correct size argument should look like following:
10747 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10748 void Sema::CheckStrncatArguments(const CallExpr *CE,
10749                                  IdentifierInfo *FnName) {
10750   // Don't crash if the user has the wrong number of arguments.
10751   if (CE->getNumArgs() < 3)
10752     return;
10753   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10754   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10755   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10756 
10757   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10758                                      CE->getRParenLoc()))
10759     return;
10760 
10761   // Identify common expressions, which are wrongly used as the size argument
10762   // to strncat and may lead to buffer overflows.
10763   unsigned PatternType = 0;
10764   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10765     // - sizeof(dst)
10766     if (referToTheSameDecl(SizeOfArg, DstArg))
10767       PatternType = 1;
10768     // - sizeof(src)
10769     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10770       PatternType = 2;
10771   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10772     if (BE->getOpcode() == BO_Sub) {
10773       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10774       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10775       // - sizeof(dst) - strlen(dst)
10776       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10777           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10778         PatternType = 1;
10779       // - sizeof(src) - (anything)
10780       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10781         PatternType = 2;
10782     }
10783   }
10784 
10785   if (PatternType == 0)
10786     return;
10787 
10788   // Generate the diagnostic.
10789   SourceLocation SL = LenArg->getBeginLoc();
10790   SourceRange SR = LenArg->getSourceRange();
10791   SourceManager &SM = getSourceManager();
10792 
10793   // If the function is defined as a builtin macro, do not show macro expansion.
10794   if (SM.isMacroArgExpansion(SL)) {
10795     SL = SM.getSpellingLoc(SL);
10796     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10797                      SM.getSpellingLoc(SR.getEnd()));
10798   }
10799 
10800   // Check if the destination is an array (rather than a pointer to an array).
10801   QualType DstTy = DstArg->getType();
10802   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10803                                                                     Context);
10804   if (!isKnownSizeArray) {
10805     if (PatternType == 1)
10806       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10807     else
10808       Diag(SL, diag::warn_strncat_src_size) << SR;
10809     return;
10810   }
10811 
10812   if (PatternType == 1)
10813     Diag(SL, diag::warn_strncat_large_size) << SR;
10814   else
10815     Diag(SL, diag::warn_strncat_src_size) << SR;
10816 
10817   SmallString<128> sizeString;
10818   llvm::raw_svector_ostream OS(sizeString);
10819   OS << "sizeof(";
10820   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10821   OS << ") - ";
10822   OS << "strlen(";
10823   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10824   OS << ") - 1";
10825 
10826   Diag(SL, diag::note_strncat_wrong_size)
10827     << FixItHint::CreateReplacement(SR, OS.str());
10828 }
10829 
10830 namespace {
10831 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10832                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10833   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10834     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10835         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10836     return;
10837   }
10838 }
10839 
10840 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10841                                  const UnaryOperator *UnaryExpr) {
10842   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10843     const Decl *D = Lvalue->getDecl();
10844     if (isa<DeclaratorDecl>(D))
10845       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10846         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10847   }
10848 
10849   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10850     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10851                                       Lvalue->getMemberDecl());
10852 }
10853 
10854 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10855                             const UnaryOperator *UnaryExpr) {
10856   const auto *Lambda = dyn_cast<LambdaExpr>(
10857       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10858   if (!Lambda)
10859     return;
10860 
10861   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10862       << CalleeName << 2 /*object: lambda expression*/;
10863 }
10864 
10865 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10866                                   const DeclRefExpr *Lvalue) {
10867   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10868   if (Var == nullptr)
10869     return;
10870 
10871   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10872       << CalleeName << 0 /*object: */ << Var;
10873 }
10874 
10875 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10876                             const CastExpr *Cast) {
10877   SmallString<128> SizeString;
10878   llvm::raw_svector_ostream OS(SizeString);
10879 
10880   clang::CastKind Kind = Cast->getCastKind();
10881   if (Kind == clang::CK_BitCast &&
10882       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10883     return;
10884   if (Kind == clang::CK_IntegralToPointer &&
10885       !isa<IntegerLiteral>(
10886           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10887     return;
10888 
10889   switch (Cast->getCastKind()) {
10890   case clang::CK_BitCast:
10891   case clang::CK_IntegralToPointer:
10892   case clang::CK_FunctionToPointerDecay:
10893     OS << '\'';
10894     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10895     OS << '\'';
10896     break;
10897   default:
10898     return;
10899   }
10900 
10901   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10902       << CalleeName << 0 /*object: */ << OS.str();
10903 }
10904 } // namespace
10905 
10906 /// Alerts the user that they are attempting to free a non-malloc'd object.
10907 void Sema::CheckFreeArguments(const CallExpr *E) {
10908   const std::string CalleeName =
10909       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10910 
10911   { // Prefer something that doesn't involve a cast to make things simpler.
10912     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10913     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10914       switch (UnaryExpr->getOpcode()) {
10915       case UnaryOperator::Opcode::UO_AddrOf:
10916         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10917       case UnaryOperator::Opcode::UO_Plus:
10918         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10919       default:
10920         break;
10921       }
10922 
10923     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10924       if (Lvalue->getType()->isArrayType())
10925         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10926 
10927     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10928       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10929           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10930       return;
10931     }
10932 
10933     if (isa<BlockExpr>(Arg)) {
10934       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10935           << CalleeName << 1 /*object: block*/;
10936       return;
10937     }
10938   }
10939   // Maybe the cast was important, check after the other cases.
10940   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10941     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10942 }
10943 
10944 void
10945 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10946                          SourceLocation ReturnLoc,
10947                          bool isObjCMethod,
10948                          const AttrVec *Attrs,
10949                          const FunctionDecl *FD) {
10950   // Check if the return value is null but should not be.
10951   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10952        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10953       CheckNonNullExpr(*this, RetValExp))
10954     Diag(ReturnLoc, diag::warn_null_ret)
10955       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10956 
10957   // C++11 [basic.stc.dynamic.allocation]p4:
10958   //   If an allocation function declared with a non-throwing
10959   //   exception-specification fails to allocate storage, it shall return
10960   //   a null pointer. Any other allocation function that fails to allocate
10961   //   storage shall indicate failure only by throwing an exception [...]
10962   if (FD) {
10963     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10964     if (Op == OO_New || Op == OO_Array_New) {
10965       const FunctionProtoType *Proto
10966         = FD->getType()->castAs<FunctionProtoType>();
10967       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10968           CheckNonNullExpr(*this, RetValExp))
10969         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10970           << FD << getLangOpts().CPlusPlus11;
10971     }
10972   }
10973 
10974   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10975   // here prevent the user from using a PPC MMA type as trailing return type.
10976   if (Context.getTargetInfo().getTriple().isPPC64())
10977     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10978 }
10979 
10980 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10981 
10982 /// Check for comparisons of floating point operands using != and ==.
10983 /// Issue a warning if these are no self-comparisons, as they are not likely
10984 /// to do what the programmer intended.
10985 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10986   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10987   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10988 
10989   // Special case: check for x == x (which is OK).
10990   // Do not emit warnings for such cases.
10991   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10992     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10993       if (DRL->getDecl() == DRR->getDecl())
10994         return;
10995 
10996   // Special case: check for comparisons against literals that can be exactly
10997   //  represented by APFloat.  In such cases, do not emit a warning.  This
10998   //  is a heuristic: often comparison against such literals are used to
10999   //  detect if a value in a variable has not changed.  This clearly can
11000   //  lead to false negatives.
11001   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11002     if (FLL->isExact())
11003       return;
11004   } else
11005     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11006       if (FLR->isExact())
11007         return;
11008 
11009   // Check for comparisons with builtin types.
11010   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11011     if (CL->getBuiltinCallee())
11012       return;
11013 
11014   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11015     if (CR->getBuiltinCallee())
11016       return;
11017 
11018   // Emit the diagnostic.
11019   Diag(Loc, diag::warn_floatingpoint_eq)
11020     << LHS->getSourceRange() << RHS->getSourceRange();
11021 }
11022 
11023 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11024 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11025 
11026 namespace {
11027 
11028 /// Structure recording the 'active' range of an integer-valued
11029 /// expression.
11030 struct IntRange {
11031   /// The number of bits active in the int. Note that this includes exactly one
11032   /// sign bit if !NonNegative.
11033   unsigned Width;
11034 
11035   /// True if the int is known not to have negative values. If so, all leading
11036   /// bits before Width are known zero, otherwise they are known to be the
11037   /// same as the MSB within Width.
11038   bool NonNegative;
11039 
11040   IntRange(unsigned Width, bool NonNegative)
11041       : Width(Width), NonNegative(NonNegative) {}
11042 
11043   /// Number of bits excluding the sign bit.
11044   unsigned valueBits() const {
11045     return NonNegative ? Width : Width - 1;
11046   }
11047 
11048   /// Returns the range of the bool type.
11049   static IntRange forBoolType() {
11050     return IntRange(1, true);
11051   }
11052 
11053   /// Returns the range of an opaque value of the given integral type.
11054   static IntRange forValueOfType(ASTContext &C, QualType T) {
11055     return forValueOfCanonicalType(C,
11056                           T->getCanonicalTypeInternal().getTypePtr());
11057   }
11058 
11059   /// Returns the range of an opaque value of a canonical integral type.
11060   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11061     assert(T->isCanonicalUnqualified());
11062 
11063     if (const VectorType *VT = dyn_cast<VectorType>(T))
11064       T = VT->getElementType().getTypePtr();
11065     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11066       T = CT->getElementType().getTypePtr();
11067     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11068       T = AT->getValueType().getTypePtr();
11069 
11070     if (!C.getLangOpts().CPlusPlus) {
11071       // For enum types in C code, use the underlying datatype.
11072       if (const EnumType *ET = dyn_cast<EnumType>(T))
11073         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11074     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11075       // For enum types in C++, use the known bit width of the enumerators.
11076       EnumDecl *Enum = ET->getDecl();
11077       // In C++11, enums can have a fixed underlying type. Use this type to
11078       // compute the range.
11079       if (Enum->isFixed()) {
11080         return IntRange(C.getIntWidth(QualType(T, 0)),
11081                         !ET->isSignedIntegerOrEnumerationType());
11082       }
11083 
11084       unsigned NumPositive = Enum->getNumPositiveBits();
11085       unsigned NumNegative = Enum->getNumNegativeBits();
11086 
11087       if (NumNegative == 0)
11088         return IntRange(NumPositive, true/*NonNegative*/);
11089       else
11090         return IntRange(std::max(NumPositive + 1, NumNegative),
11091                         false/*NonNegative*/);
11092     }
11093 
11094     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11095       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11096 
11097     const BuiltinType *BT = cast<BuiltinType>(T);
11098     assert(BT->isInteger());
11099 
11100     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11101   }
11102 
11103   /// Returns the "target" range of a canonical integral type, i.e.
11104   /// the range of values expressible in the type.
11105   ///
11106   /// This matches forValueOfCanonicalType except that enums have the
11107   /// full range of their type, not the range of their enumerators.
11108   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11109     assert(T->isCanonicalUnqualified());
11110 
11111     if (const VectorType *VT = dyn_cast<VectorType>(T))
11112       T = VT->getElementType().getTypePtr();
11113     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11114       T = CT->getElementType().getTypePtr();
11115     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11116       T = AT->getValueType().getTypePtr();
11117     if (const EnumType *ET = dyn_cast<EnumType>(T))
11118       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11119 
11120     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11121       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11122 
11123     const BuiltinType *BT = cast<BuiltinType>(T);
11124     assert(BT->isInteger());
11125 
11126     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11127   }
11128 
11129   /// Returns the supremum of two ranges: i.e. their conservative merge.
11130   static IntRange join(IntRange L, IntRange R) {
11131     bool Unsigned = L.NonNegative && R.NonNegative;
11132     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11133                     L.NonNegative && R.NonNegative);
11134   }
11135 
11136   /// Return the range of a bitwise-AND of the two ranges.
11137   static IntRange bit_and(IntRange L, IntRange R) {
11138     unsigned Bits = std::max(L.Width, R.Width);
11139     bool NonNegative = false;
11140     if (L.NonNegative) {
11141       Bits = std::min(Bits, L.Width);
11142       NonNegative = true;
11143     }
11144     if (R.NonNegative) {
11145       Bits = std::min(Bits, R.Width);
11146       NonNegative = true;
11147     }
11148     return IntRange(Bits, NonNegative);
11149   }
11150 
11151   /// Return the range of a sum of the two ranges.
11152   static IntRange sum(IntRange L, IntRange R) {
11153     bool Unsigned = L.NonNegative && R.NonNegative;
11154     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11155                     Unsigned);
11156   }
11157 
11158   /// Return the range of a difference of the two ranges.
11159   static IntRange difference(IntRange L, IntRange R) {
11160     // We need a 1-bit-wider range if:
11161     //   1) LHS can be negative: least value can be reduced.
11162     //   2) RHS can be negative: greatest value can be increased.
11163     bool CanWiden = !L.NonNegative || !R.NonNegative;
11164     bool Unsigned = L.NonNegative && R.Width == 0;
11165     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11166                         !Unsigned,
11167                     Unsigned);
11168   }
11169 
11170   /// Return the range of a product of the two ranges.
11171   static IntRange product(IntRange L, IntRange R) {
11172     // If both LHS and RHS can be negative, we can form
11173     //   -2^L * -2^R = 2^(L + R)
11174     // which requires L + R + 1 value bits to represent.
11175     bool CanWiden = !L.NonNegative && !R.NonNegative;
11176     bool Unsigned = L.NonNegative && R.NonNegative;
11177     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11178                     Unsigned);
11179   }
11180 
11181   /// Return the range of a remainder operation between the two ranges.
11182   static IntRange rem(IntRange L, IntRange R) {
11183     // The result of a remainder can't be larger than the result of
11184     // either side. The sign of the result is the sign of the LHS.
11185     bool Unsigned = L.NonNegative;
11186     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11187                     Unsigned);
11188   }
11189 };
11190 
11191 } // namespace
11192 
11193 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11194                               unsigned MaxWidth) {
11195   if (value.isSigned() && value.isNegative())
11196     return IntRange(value.getMinSignedBits(), false);
11197 
11198   if (value.getBitWidth() > MaxWidth)
11199     value = value.trunc(MaxWidth);
11200 
11201   // isNonNegative() just checks the sign bit without considering
11202   // signedness.
11203   return IntRange(value.getActiveBits(), true);
11204 }
11205 
11206 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11207                               unsigned MaxWidth) {
11208   if (result.isInt())
11209     return GetValueRange(C, result.getInt(), MaxWidth);
11210 
11211   if (result.isVector()) {
11212     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11213     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11214       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11215       R = IntRange::join(R, El);
11216     }
11217     return R;
11218   }
11219 
11220   if (result.isComplexInt()) {
11221     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11222     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11223     return IntRange::join(R, I);
11224   }
11225 
11226   // This can happen with lossless casts to intptr_t of "based" lvalues.
11227   // Assume it might use arbitrary bits.
11228   // FIXME: The only reason we need to pass the type in here is to get
11229   // the sign right on this one case.  It would be nice if APValue
11230   // preserved this.
11231   assert(result.isLValue() || result.isAddrLabelDiff());
11232   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11233 }
11234 
11235 static QualType GetExprType(const Expr *E) {
11236   QualType Ty = E->getType();
11237   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11238     Ty = AtomicRHS->getValueType();
11239   return Ty;
11240 }
11241 
11242 /// Pseudo-evaluate the given integer expression, estimating the
11243 /// range of values it might take.
11244 ///
11245 /// \param MaxWidth The width to which the value will be truncated.
11246 /// \param Approximate If \c true, return a likely range for the result: in
11247 ///        particular, assume that aritmetic on narrower types doesn't leave
11248 ///        those types. If \c false, return a range including all possible
11249 ///        result values.
11250 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11251                              bool InConstantContext, bool Approximate) {
11252   E = E->IgnoreParens();
11253 
11254   // Try a full evaluation first.
11255   Expr::EvalResult result;
11256   if (E->EvaluateAsRValue(result, C, InConstantContext))
11257     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11258 
11259   // I think we only want to look through implicit casts here; if the
11260   // user has an explicit widening cast, we should treat the value as
11261   // being of the new, wider type.
11262   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11263     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11264       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11265                           Approximate);
11266 
11267     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11268 
11269     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11270                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11271 
11272     // Assume that non-integer casts can span the full range of the type.
11273     if (!isIntegerCast)
11274       return OutputTypeRange;
11275 
11276     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11277                                      std::min(MaxWidth, OutputTypeRange.Width),
11278                                      InConstantContext, Approximate);
11279 
11280     // Bail out if the subexpr's range is as wide as the cast type.
11281     if (SubRange.Width >= OutputTypeRange.Width)
11282       return OutputTypeRange;
11283 
11284     // Otherwise, we take the smaller width, and we're non-negative if
11285     // either the output type or the subexpr is.
11286     return IntRange(SubRange.Width,
11287                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11288   }
11289 
11290   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11291     // If we can fold the condition, just take that operand.
11292     bool CondResult;
11293     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11294       return GetExprRange(C,
11295                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11296                           MaxWidth, InConstantContext, Approximate);
11297 
11298     // Otherwise, conservatively merge.
11299     // GetExprRange requires an integer expression, but a throw expression
11300     // results in a void type.
11301     Expr *E = CO->getTrueExpr();
11302     IntRange L = E->getType()->isVoidType()
11303                      ? IntRange{0, true}
11304                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11305     E = CO->getFalseExpr();
11306     IntRange R = E->getType()->isVoidType()
11307                      ? IntRange{0, true}
11308                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11309     return IntRange::join(L, R);
11310   }
11311 
11312   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11313     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11314 
11315     switch (BO->getOpcode()) {
11316     case BO_Cmp:
11317       llvm_unreachable("builtin <=> should have class type");
11318 
11319     // Boolean-valued operations are single-bit and positive.
11320     case BO_LAnd:
11321     case BO_LOr:
11322     case BO_LT:
11323     case BO_GT:
11324     case BO_LE:
11325     case BO_GE:
11326     case BO_EQ:
11327     case BO_NE:
11328       return IntRange::forBoolType();
11329 
11330     // The type of the assignments is the type of the LHS, so the RHS
11331     // is not necessarily the same type.
11332     case BO_MulAssign:
11333     case BO_DivAssign:
11334     case BO_RemAssign:
11335     case BO_AddAssign:
11336     case BO_SubAssign:
11337     case BO_XorAssign:
11338     case BO_OrAssign:
11339       // TODO: bitfields?
11340       return IntRange::forValueOfType(C, GetExprType(E));
11341 
11342     // Simple assignments just pass through the RHS, which will have
11343     // been coerced to the LHS type.
11344     case BO_Assign:
11345       // TODO: bitfields?
11346       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11347                           Approximate);
11348 
11349     // Operations with opaque sources are black-listed.
11350     case BO_PtrMemD:
11351     case BO_PtrMemI:
11352       return IntRange::forValueOfType(C, GetExprType(E));
11353 
11354     // Bitwise-and uses the *infinum* of the two source ranges.
11355     case BO_And:
11356     case BO_AndAssign:
11357       Combine = IntRange::bit_and;
11358       break;
11359 
11360     // Left shift gets black-listed based on a judgement call.
11361     case BO_Shl:
11362       // ...except that we want to treat '1 << (blah)' as logically
11363       // positive.  It's an important idiom.
11364       if (IntegerLiteral *I
11365             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11366         if (I->getValue() == 1) {
11367           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11368           return IntRange(R.Width, /*NonNegative*/ true);
11369         }
11370       }
11371       LLVM_FALLTHROUGH;
11372 
11373     case BO_ShlAssign:
11374       return IntRange::forValueOfType(C, GetExprType(E));
11375 
11376     // Right shift by a constant can narrow its left argument.
11377     case BO_Shr:
11378     case BO_ShrAssign: {
11379       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11380                                 Approximate);
11381 
11382       // If the shift amount is a positive constant, drop the width by
11383       // that much.
11384       if (Optional<llvm::APSInt> shift =
11385               BO->getRHS()->getIntegerConstantExpr(C)) {
11386         if (shift->isNonNegative()) {
11387           unsigned zext = shift->getZExtValue();
11388           if (zext >= L.Width)
11389             L.Width = (L.NonNegative ? 0 : 1);
11390           else
11391             L.Width -= zext;
11392         }
11393       }
11394 
11395       return L;
11396     }
11397 
11398     // Comma acts as its right operand.
11399     case BO_Comma:
11400       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11401                           Approximate);
11402 
11403     case BO_Add:
11404       if (!Approximate)
11405         Combine = IntRange::sum;
11406       break;
11407 
11408     case BO_Sub:
11409       if (BO->getLHS()->getType()->isPointerType())
11410         return IntRange::forValueOfType(C, GetExprType(E));
11411       if (!Approximate)
11412         Combine = IntRange::difference;
11413       break;
11414 
11415     case BO_Mul:
11416       if (!Approximate)
11417         Combine = IntRange::product;
11418       break;
11419 
11420     // The width of a division result is mostly determined by the size
11421     // of the LHS.
11422     case BO_Div: {
11423       // Don't 'pre-truncate' the operands.
11424       unsigned opWidth = C.getIntWidth(GetExprType(E));
11425       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11426                                 Approximate);
11427 
11428       // If the divisor is constant, use that.
11429       if (Optional<llvm::APSInt> divisor =
11430               BO->getRHS()->getIntegerConstantExpr(C)) {
11431         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11432         if (log2 >= L.Width)
11433           L.Width = (L.NonNegative ? 0 : 1);
11434         else
11435           L.Width = std::min(L.Width - log2, MaxWidth);
11436         return L;
11437       }
11438 
11439       // Otherwise, just use the LHS's width.
11440       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11441       // could be -1.
11442       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11443                                 Approximate);
11444       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11445     }
11446 
11447     case BO_Rem:
11448       Combine = IntRange::rem;
11449       break;
11450 
11451     // The default behavior is okay for these.
11452     case BO_Xor:
11453     case BO_Or:
11454       break;
11455     }
11456 
11457     // Combine the two ranges, but limit the result to the type in which we
11458     // performed the computation.
11459     QualType T = GetExprType(E);
11460     unsigned opWidth = C.getIntWidth(T);
11461     IntRange L =
11462         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11463     IntRange R =
11464         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11465     IntRange C = Combine(L, R);
11466     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11467     C.Width = std::min(C.Width, MaxWidth);
11468     return C;
11469   }
11470 
11471   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11472     switch (UO->getOpcode()) {
11473     // Boolean-valued operations are white-listed.
11474     case UO_LNot:
11475       return IntRange::forBoolType();
11476 
11477     // Operations with opaque sources are black-listed.
11478     case UO_Deref:
11479     case UO_AddrOf: // should be impossible
11480       return IntRange::forValueOfType(C, GetExprType(E));
11481 
11482     default:
11483       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11484                           Approximate);
11485     }
11486   }
11487 
11488   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11489     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11490                         Approximate);
11491 
11492   if (const auto *BitField = E->getSourceBitField())
11493     return IntRange(BitField->getBitWidthValue(C),
11494                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11495 
11496   return IntRange::forValueOfType(C, GetExprType(E));
11497 }
11498 
11499 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11500                              bool InConstantContext, bool Approximate) {
11501   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11502                       Approximate);
11503 }
11504 
11505 /// Checks whether the given value, which currently has the given
11506 /// source semantics, has the same value when coerced through the
11507 /// target semantics.
11508 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11509                                  const llvm::fltSemantics &Src,
11510                                  const llvm::fltSemantics &Tgt) {
11511   llvm::APFloat truncated = value;
11512 
11513   bool ignored;
11514   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11515   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11516 
11517   return truncated.bitwiseIsEqual(value);
11518 }
11519 
11520 /// Checks whether the given value, which currently has the given
11521 /// source semantics, has the same value when coerced through the
11522 /// target semantics.
11523 ///
11524 /// The value might be a vector of floats (or a complex number).
11525 static bool IsSameFloatAfterCast(const APValue &value,
11526                                  const llvm::fltSemantics &Src,
11527                                  const llvm::fltSemantics &Tgt) {
11528   if (value.isFloat())
11529     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11530 
11531   if (value.isVector()) {
11532     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11533       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11534         return false;
11535     return true;
11536   }
11537 
11538   assert(value.isComplexFloat());
11539   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11540           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11541 }
11542 
11543 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11544                                        bool IsListInit = false);
11545 
11546 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11547   // Suppress cases where we are comparing against an enum constant.
11548   if (const DeclRefExpr *DR =
11549       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11550     if (isa<EnumConstantDecl>(DR->getDecl()))
11551       return true;
11552 
11553   // Suppress cases where the value is expanded from a macro, unless that macro
11554   // is how a language represents a boolean literal. This is the case in both C
11555   // and Objective-C.
11556   SourceLocation BeginLoc = E->getBeginLoc();
11557   if (BeginLoc.isMacroID()) {
11558     StringRef MacroName = Lexer::getImmediateMacroName(
11559         BeginLoc, S.getSourceManager(), S.getLangOpts());
11560     return MacroName != "YES" && MacroName != "NO" &&
11561            MacroName != "true" && MacroName != "false";
11562   }
11563 
11564   return false;
11565 }
11566 
11567 static bool isKnownToHaveUnsignedValue(Expr *E) {
11568   return E->getType()->isIntegerType() &&
11569          (!E->getType()->isSignedIntegerType() ||
11570           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11571 }
11572 
11573 namespace {
11574 /// The promoted range of values of a type. In general this has the
11575 /// following structure:
11576 ///
11577 ///     |-----------| . . . |-----------|
11578 ///     ^           ^       ^           ^
11579 ///    Min       HoleMin  HoleMax      Max
11580 ///
11581 /// ... where there is only a hole if a signed type is promoted to unsigned
11582 /// (in which case Min and Max are the smallest and largest representable
11583 /// values).
11584 struct PromotedRange {
11585   // Min, or HoleMax if there is a hole.
11586   llvm::APSInt PromotedMin;
11587   // Max, or HoleMin if there is a hole.
11588   llvm::APSInt PromotedMax;
11589 
11590   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11591     if (R.Width == 0)
11592       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11593     else if (R.Width >= BitWidth && !Unsigned) {
11594       // Promotion made the type *narrower*. This happens when promoting
11595       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11596       // Treat all values of 'signed int' as being in range for now.
11597       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11598       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11599     } else {
11600       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11601                         .extOrTrunc(BitWidth);
11602       PromotedMin.setIsUnsigned(Unsigned);
11603 
11604       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11605                         .extOrTrunc(BitWidth);
11606       PromotedMax.setIsUnsigned(Unsigned);
11607     }
11608   }
11609 
11610   // Determine whether this range is contiguous (has no hole).
11611   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11612 
11613   // Where a constant value is within the range.
11614   enum ComparisonResult {
11615     LT = 0x1,
11616     LE = 0x2,
11617     GT = 0x4,
11618     GE = 0x8,
11619     EQ = 0x10,
11620     NE = 0x20,
11621     InRangeFlag = 0x40,
11622 
11623     Less = LE | LT | NE,
11624     Min = LE | InRangeFlag,
11625     InRange = InRangeFlag,
11626     Max = GE | InRangeFlag,
11627     Greater = GE | GT | NE,
11628 
11629     OnlyValue = LE | GE | EQ | InRangeFlag,
11630     InHole = NE
11631   };
11632 
11633   ComparisonResult compare(const llvm::APSInt &Value) const {
11634     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11635            Value.isUnsigned() == PromotedMin.isUnsigned());
11636     if (!isContiguous()) {
11637       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11638       if (Value.isMinValue()) return Min;
11639       if (Value.isMaxValue()) return Max;
11640       if (Value >= PromotedMin) return InRange;
11641       if (Value <= PromotedMax) return InRange;
11642       return InHole;
11643     }
11644 
11645     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11646     case -1: return Less;
11647     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11648     case 1:
11649       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11650       case -1: return InRange;
11651       case 0: return Max;
11652       case 1: return Greater;
11653       }
11654     }
11655 
11656     llvm_unreachable("impossible compare result");
11657   }
11658 
11659   static llvm::Optional<StringRef>
11660   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11661     if (Op == BO_Cmp) {
11662       ComparisonResult LTFlag = LT, GTFlag = GT;
11663       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11664 
11665       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11666       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11667       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11668       return llvm::None;
11669     }
11670 
11671     ComparisonResult TrueFlag, FalseFlag;
11672     if (Op == BO_EQ) {
11673       TrueFlag = EQ;
11674       FalseFlag = NE;
11675     } else if (Op == BO_NE) {
11676       TrueFlag = NE;
11677       FalseFlag = EQ;
11678     } else {
11679       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11680         TrueFlag = LT;
11681         FalseFlag = GE;
11682       } else {
11683         TrueFlag = GT;
11684         FalseFlag = LE;
11685       }
11686       if (Op == BO_GE || Op == BO_LE)
11687         std::swap(TrueFlag, FalseFlag);
11688     }
11689     if (R & TrueFlag)
11690       return StringRef("true");
11691     if (R & FalseFlag)
11692       return StringRef("false");
11693     return llvm::None;
11694   }
11695 };
11696 }
11697 
11698 static bool HasEnumType(Expr *E) {
11699   // Strip off implicit integral promotions.
11700   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11701     if (ICE->getCastKind() != CK_IntegralCast &&
11702         ICE->getCastKind() != CK_NoOp)
11703       break;
11704     E = ICE->getSubExpr();
11705   }
11706 
11707   return E->getType()->isEnumeralType();
11708 }
11709 
11710 static int classifyConstantValue(Expr *Constant) {
11711   // The values of this enumeration are used in the diagnostics
11712   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11713   enum ConstantValueKind {
11714     Miscellaneous = 0,
11715     LiteralTrue,
11716     LiteralFalse
11717   };
11718   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11719     return BL->getValue() ? ConstantValueKind::LiteralTrue
11720                           : ConstantValueKind::LiteralFalse;
11721   return ConstantValueKind::Miscellaneous;
11722 }
11723 
11724 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11725                                         Expr *Constant, Expr *Other,
11726                                         const llvm::APSInt &Value,
11727                                         bool RhsConstant) {
11728   if (S.inTemplateInstantiation())
11729     return false;
11730 
11731   Expr *OriginalOther = Other;
11732 
11733   Constant = Constant->IgnoreParenImpCasts();
11734   Other = Other->IgnoreParenImpCasts();
11735 
11736   // Suppress warnings on tautological comparisons between values of the same
11737   // enumeration type. There are only two ways we could warn on this:
11738   //  - If the constant is outside the range of representable values of
11739   //    the enumeration. In such a case, we should warn about the cast
11740   //    to enumeration type, not about the comparison.
11741   //  - If the constant is the maximum / minimum in-range value. For an
11742   //    enumeratin type, such comparisons can be meaningful and useful.
11743   if (Constant->getType()->isEnumeralType() &&
11744       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11745     return false;
11746 
11747   IntRange OtherValueRange = GetExprRange(
11748       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11749 
11750   QualType OtherT = Other->getType();
11751   if (const auto *AT = OtherT->getAs<AtomicType>())
11752     OtherT = AT->getValueType();
11753   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11754 
11755   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11756   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11757   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11758                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11759                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11760 
11761   // Whether we're treating Other as being a bool because of the form of
11762   // expression despite it having another type (typically 'int' in C).
11763   bool OtherIsBooleanDespiteType =
11764       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11765   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11766     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11767 
11768   // Check if all values in the range of possible values of this expression
11769   // lead to the same comparison outcome.
11770   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11771                                         Value.isUnsigned());
11772   auto Cmp = OtherPromotedValueRange.compare(Value);
11773   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11774   if (!Result)
11775     return false;
11776 
11777   // Also consider the range determined by the type alone. This allows us to
11778   // classify the warning under the proper diagnostic group.
11779   bool TautologicalTypeCompare = false;
11780   {
11781     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11782                                          Value.isUnsigned());
11783     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11784     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11785                                                        RhsConstant)) {
11786       TautologicalTypeCompare = true;
11787       Cmp = TypeCmp;
11788       Result = TypeResult;
11789     }
11790   }
11791 
11792   // Don't warn if the non-constant operand actually always evaluates to the
11793   // same value.
11794   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11795     return false;
11796 
11797   // Suppress the diagnostic for an in-range comparison if the constant comes
11798   // from a macro or enumerator. We don't want to diagnose
11799   //
11800   //   some_long_value <= INT_MAX
11801   //
11802   // when sizeof(int) == sizeof(long).
11803   bool InRange = Cmp & PromotedRange::InRangeFlag;
11804   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11805     return false;
11806 
11807   // A comparison of an unsigned bit-field against 0 is really a type problem,
11808   // even though at the type level the bit-field might promote to 'signed int'.
11809   if (Other->refersToBitField() && InRange && Value == 0 &&
11810       Other->getType()->isUnsignedIntegerOrEnumerationType())
11811     TautologicalTypeCompare = true;
11812 
11813   // If this is a comparison to an enum constant, include that
11814   // constant in the diagnostic.
11815   const EnumConstantDecl *ED = nullptr;
11816   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11817     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11818 
11819   // Should be enough for uint128 (39 decimal digits)
11820   SmallString<64> PrettySourceValue;
11821   llvm::raw_svector_ostream OS(PrettySourceValue);
11822   if (ED) {
11823     OS << '\'' << *ED << "' (" << Value << ")";
11824   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11825                Constant->IgnoreParenImpCasts())) {
11826     OS << (BL->getValue() ? "YES" : "NO");
11827   } else {
11828     OS << Value;
11829   }
11830 
11831   if (!TautologicalTypeCompare) {
11832     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11833         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11834         << E->getOpcodeStr() << OS.str() << *Result
11835         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11836     return true;
11837   }
11838 
11839   if (IsObjCSignedCharBool) {
11840     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11841                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11842                               << OS.str() << *Result);
11843     return true;
11844   }
11845 
11846   // FIXME: We use a somewhat different formatting for the in-range cases and
11847   // cases involving boolean values for historical reasons. We should pick a
11848   // consistent way of presenting these diagnostics.
11849   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11850 
11851     S.DiagRuntimeBehavior(
11852         E->getOperatorLoc(), E,
11853         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11854                          : diag::warn_tautological_bool_compare)
11855             << OS.str() << classifyConstantValue(Constant) << OtherT
11856             << OtherIsBooleanDespiteType << *Result
11857             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11858   } else {
11859     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11860     unsigned Diag =
11861         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11862             ? (HasEnumType(OriginalOther)
11863                    ? diag::warn_unsigned_enum_always_true_comparison
11864                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11865                               : diag::warn_unsigned_always_true_comparison)
11866             : diag::warn_tautological_constant_compare;
11867 
11868     S.Diag(E->getOperatorLoc(), Diag)
11869         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11870         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11871   }
11872 
11873   return true;
11874 }
11875 
11876 /// Analyze the operands of the given comparison.  Implements the
11877 /// fallback case from AnalyzeComparison.
11878 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11879   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11880   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11881 }
11882 
11883 /// Implements -Wsign-compare.
11884 ///
11885 /// \param E the binary operator to check for warnings
11886 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11887   // The type the comparison is being performed in.
11888   QualType T = E->getLHS()->getType();
11889 
11890   // Only analyze comparison operators where both sides have been converted to
11891   // the same type.
11892   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11893     return AnalyzeImpConvsInComparison(S, E);
11894 
11895   // Don't analyze value-dependent comparisons directly.
11896   if (E->isValueDependent())
11897     return AnalyzeImpConvsInComparison(S, E);
11898 
11899   Expr *LHS = E->getLHS();
11900   Expr *RHS = E->getRHS();
11901 
11902   if (T->isIntegralType(S.Context)) {
11903     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11904     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11905 
11906     // We don't care about expressions whose result is a constant.
11907     if (RHSValue && LHSValue)
11908       return AnalyzeImpConvsInComparison(S, E);
11909 
11910     // We only care about expressions where just one side is literal
11911     if ((bool)RHSValue ^ (bool)LHSValue) {
11912       // Is the constant on the RHS or LHS?
11913       const bool RhsConstant = (bool)RHSValue;
11914       Expr *Const = RhsConstant ? RHS : LHS;
11915       Expr *Other = RhsConstant ? LHS : RHS;
11916       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11917 
11918       // Check whether an integer constant comparison results in a value
11919       // of 'true' or 'false'.
11920       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11921         return AnalyzeImpConvsInComparison(S, E);
11922     }
11923   }
11924 
11925   if (!T->hasUnsignedIntegerRepresentation()) {
11926     // We don't do anything special if this isn't an unsigned integral
11927     // comparison:  we're only interested in integral comparisons, and
11928     // signed comparisons only happen in cases we don't care to warn about.
11929     return AnalyzeImpConvsInComparison(S, E);
11930   }
11931 
11932   LHS = LHS->IgnoreParenImpCasts();
11933   RHS = RHS->IgnoreParenImpCasts();
11934 
11935   if (!S.getLangOpts().CPlusPlus) {
11936     // Avoid warning about comparison of integers with different signs when
11937     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11938     // the type of `E`.
11939     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11940       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11941     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11942       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11943   }
11944 
11945   // Check to see if one of the (unmodified) operands is of different
11946   // signedness.
11947   Expr *signedOperand, *unsignedOperand;
11948   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11949     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11950            "unsigned comparison between two signed integer expressions?");
11951     signedOperand = LHS;
11952     unsignedOperand = RHS;
11953   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11954     signedOperand = RHS;
11955     unsignedOperand = LHS;
11956   } else {
11957     return AnalyzeImpConvsInComparison(S, E);
11958   }
11959 
11960   // Otherwise, calculate the effective range of the signed operand.
11961   IntRange signedRange = GetExprRange(
11962       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11963 
11964   // Go ahead and analyze implicit conversions in the operands.  Note
11965   // that we skip the implicit conversions on both sides.
11966   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11967   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11968 
11969   // If the signed range is non-negative, -Wsign-compare won't fire.
11970   if (signedRange.NonNegative)
11971     return;
11972 
11973   // For (in)equality comparisons, if the unsigned operand is a
11974   // constant which cannot collide with a overflowed signed operand,
11975   // then reinterpreting the signed operand as unsigned will not
11976   // change the result of the comparison.
11977   if (E->isEqualityOp()) {
11978     unsigned comparisonWidth = S.Context.getIntWidth(T);
11979     IntRange unsignedRange =
11980         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11981                      /*Approximate*/ true);
11982 
11983     // We should never be unable to prove that the unsigned operand is
11984     // non-negative.
11985     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11986 
11987     if (unsignedRange.Width < comparisonWidth)
11988       return;
11989   }
11990 
11991   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11992                         S.PDiag(diag::warn_mixed_sign_comparison)
11993                             << LHS->getType() << RHS->getType()
11994                             << LHS->getSourceRange() << RHS->getSourceRange());
11995 }
11996 
11997 /// Analyzes an attempt to assign the given value to a bitfield.
11998 ///
11999 /// Returns true if there was something fishy about the attempt.
12000 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12001                                       SourceLocation InitLoc) {
12002   assert(Bitfield->isBitField());
12003   if (Bitfield->isInvalidDecl())
12004     return false;
12005 
12006   // White-list bool bitfields.
12007   QualType BitfieldType = Bitfield->getType();
12008   if (BitfieldType->isBooleanType())
12009      return false;
12010 
12011   if (BitfieldType->isEnumeralType()) {
12012     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12013     // If the underlying enum type was not explicitly specified as an unsigned
12014     // type and the enum contain only positive values, MSVC++ will cause an
12015     // inconsistency by storing this as a signed type.
12016     if (S.getLangOpts().CPlusPlus11 &&
12017         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12018         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12019         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12020       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12021           << BitfieldEnumDecl;
12022     }
12023   }
12024 
12025   if (Bitfield->getType()->isBooleanType())
12026     return false;
12027 
12028   // Ignore value- or type-dependent expressions.
12029   if (Bitfield->getBitWidth()->isValueDependent() ||
12030       Bitfield->getBitWidth()->isTypeDependent() ||
12031       Init->isValueDependent() ||
12032       Init->isTypeDependent())
12033     return false;
12034 
12035   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12036   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12037 
12038   Expr::EvalResult Result;
12039   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12040                                    Expr::SE_AllowSideEffects)) {
12041     // The RHS is not constant.  If the RHS has an enum type, make sure the
12042     // bitfield is wide enough to hold all the values of the enum without
12043     // truncation.
12044     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12045       EnumDecl *ED = EnumTy->getDecl();
12046       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12047 
12048       // Enum types are implicitly signed on Windows, so check if there are any
12049       // negative enumerators to see if the enum was intended to be signed or
12050       // not.
12051       bool SignedEnum = ED->getNumNegativeBits() > 0;
12052 
12053       // Check for surprising sign changes when assigning enum values to a
12054       // bitfield of different signedness.  If the bitfield is signed and we
12055       // have exactly the right number of bits to store this unsigned enum,
12056       // suggest changing the enum to an unsigned type. This typically happens
12057       // on Windows where unfixed enums always use an underlying type of 'int'.
12058       unsigned DiagID = 0;
12059       if (SignedEnum && !SignedBitfield) {
12060         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12061       } else if (SignedBitfield && !SignedEnum &&
12062                  ED->getNumPositiveBits() == FieldWidth) {
12063         DiagID = diag::warn_signed_bitfield_enum_conversion;
12064       }
12065 
12066       if (DiagID) {
12067         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12068         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12069         SourceRange TypeRange =
12070             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12071         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12072             << SignedEnum << TypeRange;
12073       }
12074 
12075       // Compute the required bitwidth. If the enum has negative values, we need
12076       // one more bit than the normal number of positive bits to represent the
12077       // sign bit.
12078       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12079                                                   ED->getNumNegativeBits())
12080                                        : ED->getNumPositiveBits();
12081 
12082       // Check the bitwidth.
12083       if (BitsNeeded > FieldWidth) {
12084         Expr *WidthExpr = Bitfield->getBitWidth();
12085         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12086             << Bitfield << ED;
12087         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12088             << BitsNeeded << ED << WidthExpr->getSourceRange();
12089       }
12090     }
12091 
12092     return false;
12093   }
12094 
12095   llvm::APSInt Value = Result.Val.getInt();
12096 
12097   unsigned OriginalWidth = Value.getBitWidth();
12098 
12099   if (!Value.isSigned() || Value.isNegative())
12100     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12101       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12102         OriginalWidth = Value.getMinSignedBits();
12103 
12104   if (OriginalWidth <= FieldWidth)
12105     return false;
12106 
12107   // Compute the value which the bitfield will contain.
12108   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12109   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12110 
12111   // Check whether the stored value is equal to the original value.
12112   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12113   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12114     return false;
12115 
12116   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12117   // therefore don't strictly fit into a signed bitfield of width 1.
12118   if (FieldWidth == 1 && Value == 1)
12119     return false;
12120 
12121   std::string PrettyValue = toString(Value, 10);
12122   std::string PrettyTrunc = toString(TruncatedValue, 10);
12123 
12124   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12125     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12126     << Init->getSourceRange();
12127 
12128   return true;
12129 }
12130 
12131 /// Analyze the given simple or compound assignment for warning-worthy
12132 /// operations.
12133 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12134   // Just recurse on the LHS.
12135   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12136 
12137   // We want to recurse on the RHS as normal unless we're assigning to
12138   // a bitfield.
12139   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12140     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12141                                   E->getOperatorLoc())) {
12142       // Recurse, ignoring any implicit conversions on the RHS.
12143       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12144                                         E->getOperatorLoc());
12145     }
12146   }
12147 
12148   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12149 
12150   // Diagnose implicitly sequentially-consistent atomic assignment.
12151   if (E->getLHS()->getType()->isAtomicType())
12152     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12153 }
12154 
12155 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12156 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12157                             SourceLocation CContext, unsigned diag,
12158                             bool pruneControlFlow = false) {
12159   if (pruneControlFlow) {
12160     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12161                           S.PDiag(diag)
12162                               << SourceType << T << E->getSourceRange()
12163                               << SourceRange(CContext));
12164     return;
12165   }
12166   S.Diag(E->getExprLoc(), diag)
12167     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12168 }
12169 
12170 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12171 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12172                             SourceLocation CContext,
12173                             unsigned diag, bool pruneControlFlow = false) {
12174   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12175 }
12176 
12177 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12178   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12179       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12180 }
12181 
12182 static void adornObjCBoolConversionDiagWithTernaryFixit(
12183     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12184   Expr *Ignored = SourceExpr->IgnoreImplicit();
12185   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12186     Ignored = OVE->getSourceExpr();
12187   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12188                      isa<BinaryOperator>(Ignored) ||
12189                      isa<CXXOperatorCallExpr>(Ignored);
12190   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12191   if (NeedsParens)
12192     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12193             << FixItHint::CreateInsertion(EndLoc, ")");
12194   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12195 }
12196 
12197 /// Diagnose an implicit cast from a floating point value to an integer value.
12198 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12199                                     SourceLocation CContext) {
12200   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12201   const bool PruneWarnings = S.inTemplateInstantiation();
12202 
12203   Expr *InnerE = E->IgnoreParenImpCasts();
12204   // We also want to warn on, e.g., "int i = -1.234"
12205   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12206     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12207       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12208 
12209   const bool IsLiteral =
12210       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12211 
12212   llvm::APFloat Value(0.0);
12213   bool IsConstant =
12214     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12215   if (!IsConstant) {
12216     if (isObjCSignedCharBool(S, T)) {
12217       return adornObjCBoolConversionDiagWithTernaryFixit(
12218           S, E,
12219           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12220               << E->getType());
12221     }
12222 
12223     return DiagnoseImpCast(S, E, T, CContext,
12224                            diag::warn_impcast_float_integer, PruneWarnings);
12225   }
12226 
12227   bool isExact = false;
12228 
12229   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12230                             T->hasUnsignedIntegerRepresentation());
12231   llvm::APFloat::opStatus Result = Value.convertToInteger(
12232       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12233 
12234   // FIXME: Force the precision of the source value down so we don't print
12235   // digits which are usually useless (we don't really care here if we
12236   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12237   // would automatically print the shortest representation, but it's a bit
12238   // tricky to implement.
12239   SmallString<16> PrettySourceValue;
12240   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12241   precision = (precision * 59 + 195) / 196;
12242   Value.toString(PrettySourceValue, precision);
12243 
12244   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12245     return adornObjCBoolConversionDiagWithTernaryFixit(
12246         S, E,
12247         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12248             << PrettySourceValue);
12249   }
12250 
12251   if (Result == llvm::APFloat::opOK && isExact) {
12252     if (IsLiteral) return;
12253     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12254                            PruneWarnings);
12255   }
12256 
12257   // Conversion of a floating-point value to a non-bool integer where the
12258   // integral part cannot be represented by the integer type is undefined.
12259   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12260     return DiagnoseImpCast(
12261         S, E, T, CContext,
12262         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12263                   : diag::warn_impcast_float_to_integer_out_of_range,
12264         PruneWarnings);
12265 
12266   unsigned DiagID = 0;
12267   if (IsLiteral) {
12268     // Warn on floating point literal to integer.
12269     DiagID = diag::warn_impcast_literal_float_to_integer;
12270   } else if (IntegerValue == 0) {
12271     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12272       return DiagnoseImpCast(S, E, T, CContext,
12273                              diag::warn_impcast_float_integer, PruneWarnings);
12274     }
12275     // Warn on non-zero to zero conversion.
12276     DiagID = diag::warn_impcast_float_to_integer_zero;
12277   } else {
12278     if (IntegerValue.isUnsigned()) {
12279       if (!IntegerValue.isMaxValue()) {
12280         return DiagnoseImpCast(S, E, T, CContext,
12281                                diag::warn_impcast_float_integer, PruneWarnings);
12282       }
12283     } else {  // IntegerValue.isSigned()
12284       if (!IntegerValue.isMaxSignedValue() &&
12285           !IntegerValue.isMinSignedValue()) {
12286         return DiagnoseImpCast(S, E, T, CContext,
12287                                diag::warn_impcast_float_integer, PruneWarnings);
12288       }
12289     }
12290     // Warn on evaluatable floating point expression to integer conversion.
12291     DiagID = diag::warn_impcast_float_to_integer;
12292   }
12293 
12294   SmallString<16> PrettyTargetValue;
12295   if (IsBool)
12296     PrettyTargetValue = Value.isZero() ? "false" : "true";
12297   else
12298     IntegerValue.toString(PrettyTargetValue);
12299 
12300   if (PruneWarnings) {
12301     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12302                           S.PDiag(DiagID)
12303                               << E->getType() << T.getUnqualifiedType()
12304                               << PrettySourceValue << PrettyTargetValue
12305                               << E->getSourceRange() << SourceRange(CContext));
12306   } else {
12307     S.Diag(E->getExprLoc(), DiagID)
12308         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12309         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12310   }
12311 }
12312 
12313 /// Analyze the given compound assignment for the possible losing of
12314 /// floating-point precision.
12315 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12316   assert(isa<CompoundAssignOperator>(E) &&
12317          "Must be compound assignment operation");
12318   // Recurse on the LHS and RHS in here
12319   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12320   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12321 
12322   if (E->getLHS()->getType()->isAtomicType())
12323     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12324 
12325   // Now check the outermost expression
12326   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12327   const auto *RBT = cast<CompoundAssignOperator>(E)
12328                         ->getComputationResultType()
12329                         ->getAs<BuiltinType>();
12330 
12331   // The below checks assume source is floating point.
12332   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12333 
12334   // If source is floating point but target is an integer.
12335   if (ResultBT->isInteger())
12336     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12337                            E->getExprLoc(), diag::warn_impcast_float_integer);
12338 
12339   if (!ResultBT->isFloatingPoint())
12340     return;
12341 
12342   // If both source and target are floating points, warn about losing precision.
12343   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12344       QualType(ResultBT, 0), QualType(RBT, 0));
12345   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12346     // warn about dropping FP rank.
12347     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12348                     diag::warn_impcast_float_result_precision);
12349 }
12350 
12351 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12352                                       IntRange Range) {
12353   if (!Range.Width) return "0";
12354 
12355   llvm::APSInt ValueInRange = Value;
12356   ValueInRange.setIsSigned(!Range.NonNegative);
12357   ValueInRange = ValueInRange.trunc(Range.Width);
12358   return toString(ValueInRange, 10);
12359 }
12360 
12361 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12362   if (!isa<ImplicitCastExpr>(Ex))
12363     return false;
12364 
12365   Expr *InnerE = Ex->IgnoreParenImpCasts();
12366   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12367   const Type *Source =
12368     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12369   if (Target->isDependentType())
12370     return false;
12371 
12372   const BuiltinType *FloatCandidateBT =
12373     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12374   const Type *BoolCandidateType = ToBool ? Target : Source;
12375 
12376   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12377           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12378 }
12379 
12380 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12381                                              SourceLocation CC) {
12382   unsigned NumArgs = TheCall->getNumArgs();
12383   for (unsigned i = 0; i < NumArgs; ++i) {
12384     Expr *CurrA = TheCall->getArg(i);
12385     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12386       continue;
12387 
12388     bool IsSwapped = ((i > 0) &&
12389         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12390     IsSwapped |= ((i < (NumArgs - 1)) &&
12391         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12392     if (IsSwapped) {
12393       // Warn on this floating-point to bool conversion.
12394       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12395                       CurrA->getType(), CC,
12396                       diag::warn_impcast_floating_point_to_bool);
12397     }
12398   }
12399 }
12400 
12401 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12402                                    SourceLocation CC) {
12403   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12404                         E->getExprLoc()))
12405     return;
12406 
12407   // Don't warn on functions which have return type nullptr_t.
12408   if (isa<CallExpr>(E))
12409     return;
12410 
12411   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12412   const Expr::NullPointerConstantKind NullKind =
12413       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12414   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12415     return;
12416 
12417   // Return if target type is a safe conversion.
12418   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12419       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12420     return;
12421 
12422   SourceLocation Loc = E->getSourceRange().getBegin();
12423 
12424   // Venture through the macro stacks to get to the source of macro arguments.
12425   // The new location is a better location than the complete location that was
12426   // passed in.
12427   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12428   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12429 
12430   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12431   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12432     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12433         Loc, S.SourceMgr, S.getLangOpts());
12434     if (MacroName == "NULL")
12435       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12436   }
12437 
12438   // Only warn if the null and context location are in the same macro expansion.
12439   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12440     return;
12441 
12442   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12443       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12444       << FixItHint::CreateReplacement(Loc,
12445                                       S.getFixItZeroLiteralForType(T, Loc));
12446 }
12447 
12448 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12449                                   ObjCArrayLiteral *ArrayLiteral);
12450 
12451 static void
12452 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12453                            ObjCDictionaryLiteral *DictionaryLiteral);
12454 
12455 /// Check a single element within a collection literal against the
12456 /// target element type.
12457 static void checkObjCCollectionLiteralElement(Sema &S,
12458                                               QualType TargetElementType,
12459                                               Expr *Element,
12460                                               unsigned ElementKind) {
12461   // Skip a bitcast to 'id' or qualified 'id'.
12462   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12463     if (ICE->getCastKind() == CK_BitCast &&
12464         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12465       Element = ICE->getSubExpr();
12466   }
12467 
12468   QualType ElementType = Element->getType();
12469   ExprResult ElementResult(Element);
12470   if (ElementType->getAs<ObjCObjectPointerType>() &&
12471       S.CheckSingleAssignmentConstraints(TargetElementType,
12472                                          ElementResult,
12473                                          false, false)
12474         != Sema::Compatible) {
12475     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12476         << ElementType << ElementKind << TargetElementType
12477         << Element->getSourceRange();
12478   }
12479 
12480   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12481     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12482   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12483     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12484 }
12485 
12486 /// Check an Objective-C array literal being converted to the given
12487 /// target type.
12488 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12489                                   ObjCArrayLiteral *ArrayLiteral) {
12490   if (!S.NSArrayDecl)
12491     return;
12492 
12493   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12494   if (!TargetObjCPtr)
12495     return;
12496 
12497   if (TargetObjCPtr->isUnspecialized() ||
12498       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12499         != S.NSArrayDecl->getCanonicalDecl())
12500     return;
12501 
12502   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12503   if (TypeArgs.size() != 1)
12504     return;
12505 
12506   QualType TargetElementType = TypeArgs[0];
12507   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12508     checkObjCCollectionLiteralElement(S, TargetElementType,
12509                                       ArrayLiteral->getElement(I),
12510                                       0);
12511   }
12512 }
12513 
12514 /// Check an Objective-C dictionary literal being converted to the given
12515 /// target type.
12516 static void
12517 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12518                            ObjCDictionaryLiteral *DictionaryLiteral) {
12519   if (!S.NSDictionaryDecl)
12520     return;
12521 
12522   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12523   if (!TargetObjCPtr)
12524     return;
12525 
12526   if (TargetObjCPtr->isUnspecialized() ||
12527       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12528         != S.NSDictionaryDecl->getCanonicalDecl())
12529     return;
12530 
12531   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12532   if (TypeArgs.size() != 2)
12533     return;
12534 
12535   QualType TargetKeyType = TypeArgs[0];
12536   QualType TargetObjectType = TypeArgs[1];
12537   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12538     auto Element = DictionaryLiteral->getKeyValueElement(I);
12539     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12540     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12541   }
12542 }
12543 
12544 // Helper function to filter out cases for constant width constant conversion.
12545 // Don't warn on char array initialization or for non-decimal values.
12546 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12547                                           SourceLocation CC) {
12548   // If initializing from a constant, and the constant starts with '0',
12549   // then it is a binary, octal, or hexadecimal.  Allow these constants
12550   // to fill all the bits, even if there is a sign change.
12551   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12552     const char FirstLiteralCharacter =
12553         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12554     if (FirstLiteralCharacter == '0')
12555       return false;
12556   }
12557 
12558   // If the CC location points to a '{', and the type is char, then assume
12559   // assume it is an array initialization.
12560   if (CC.isValid() && T->isCharType()) {
12561     const char FirstContextCharacter =
12562         S.getSourceManager().getCharacterData(CC)[0];
12563     if (FirstContextCharacter == '{')
12564       return false;
12565   }
12566 
12567   return true;
12568 }
12569 
12570 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12571   const auto *IL = dyn_cast<IntegerLiteral>(E);
12572   if (!IL) {
12573     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12574       if (UO->getOpcode() == UO_Minus)
12575         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12576     }
12577   }
12578 
12579   return IL;
12580 }
12581 
12582 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12583   E = E->IgnoreParenImpCasts();
12584   SourceLocation ExprLoc = E->getExprLoc();
12585 
12586   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12587     BinaryOperator::Opcode Opc = BO->getOpcode();
12588     Expr::EvalResult Result;
12589     // Do not diagnose unsigned shifts.
12590     if (Opc == BO_Shl) {
12591       const auto *LHS = getIntegerLiteral(BO->getLHS());
12592       const auto *RHS = getIntegerLiteral(BO->getRHS());
12593       if (LHS && LHS->getValue() == 0)
12594         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12595       else if (!E->isValueDependent() && LHS && RHS &&
12596                RHS->getValue().isNonNegative() &&
12597                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12598         S.Diag(ExprLoc, diag::warn_left_shift_always)
12599             << (Result.Val.getInt() != 0);
12600       else if (E->getType()->isSignedIntegerType())
12601         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12602     }
12603   }
12604 
12605   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12606     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12607     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12608     if (!LHS || !RHS)
12609       return;
12610     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12611         (RHS->getValue() == 0 || RHS->getValue() == 1))
12612       // Do not diagnose common idioms.
12613       return;
12614     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12615       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12616   }
12617 }
12618 
12619 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12620                                     SourceLocation CC,
12621                                     bool *ICContext = nullptr,
12622                                     bool IsListInit = false) {
12623   if (E->isTypeDependent() || E->isValueDependent()) return;
12624 
12625   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12626   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12627   if (Source == Target) return;
12628   if (Target->isDependentType()) return;
12629 
12630   // If the conversion context location is invalid don't complain. We also
12631   // don't want to emit a warning if the issue occurs from the expansion of
12632   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12633   // delay this check as long as possible. Once we detect we are in that
12634   // scenario, we just return.
12635   if (CC.isInvalid())
12636     return;
12637 
12638   if (Source->isAtomicType())
12639     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12640 
12641   // Diagnose implicit casts to bool.
12642   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12643     if (isa<StringLiteral>(E))
12644       // Warn on string literal to bool.  Checks for string literals in logical
12645       // and expressions, for instance, assert(0 && "error here"), are
12646       // prevented by a check in AnalyzeImplicitConversions().
12647       return DiagnoseImpCast(S, E, T, CC,
12648                              diag::warn_impcast_string_literal_to_bool);
12649     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12650         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12651       // This covers the literal expressions that evaluate to Objective-C
12652       // objects.
12653       return DiagnoseImpCast(S, E, T, CC,
12654                              diag::warn_impcast_objective_c_literal_to_bool);
12655     }
12656     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12657       // Warn on pointer to bool conversion that is always true.
12658       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12659                                      SourceRange(CC));
12660     }
12661   }
12662 
12663   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12664   // is a typedef for signed char (macOS), then that constant value has to be 1
12665   // or 0.
12666   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12667     Expr::EvalResult Result;
12668     if (E->EvaluateAsInt(Result, S.getASTContext(),
12669                          Expr::SE_AllowSideEffects)) {
12670       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12671         adornObjCBoolConversionDiagWithTernaryFixit(
12672             S, E,
12673             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12674                 << toString(Result.Val.getInt(), 10));
12675       }
12676       return;
12677     }
12678   }
12679 
12680   // Check implicit casts from Objective-C collection literals to specialized
12681   // collection types, e.g., NSArray<NSString *> *.
12682   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12683     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12684   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12685     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12686 
12687   // Strip vector types.
12688   if (isa<VectorType>(Source)) {
12689     if (Target->isVLSTBuiltinType() &&
12690         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12691                                          QualType(Source, 0)) ||
12692          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12693                                             QualType(Source, 0))))
12694       return;
12695 
12696     if (!isa<VectorType>(Target)) {
12697       if (S.SourceMgr.isInSystemMacro(CC))
12698         return;
12699       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12700     }
12701 
12702     // If the vector cast is cast between two vectors of the same size, it is
12703     // a bitcast, not a conversion.
12704     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12705       return;
12706 
12707     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12708     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12709   }
12710   if (auto VecTy = dyn_cast<VectorType>(Target))
12711     Target = VecTy->getElementType().getTypePtr();
12712 
12713   // Strip complex types.
12714   if (isa<ComplexType>(Source)) {
12715     if (!isa<ComplexType>(Target)) {
12716       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12717         return;
12718 
12719       return DiagnoseImpCast(S, E, T, CC,
12720                              S.getLangOpts().CPlusPlus
12721                                  ? diag::err_impcast_complex_scalar
12722                                  : diag::warn_impcast_complex_scalar);
12723     }
12724 
12725     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12726     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12727   }
12728 
12729   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12730   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12731 
12732   // If the source is floating point...
12733   if (SourceBT && SourceBT->isFloatingPoint()) {
12734     // ...and the target is floating point...
12735     if (TargetBT && TargetBT->isFloatingPoint()) {
12736       // ...then warn if we're dropping FP rank.
12737 
12738       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12739           QualType(SourceBT, 0), QualType(TargetBT, 0));
12740       if (Order > 0) {
12741         // Don't warn about float constants that are precisely
12742         // representable in the target type.
12743         Expr::EvalResult result;
12744         if (E->EvaluateAsRValue(result, S.Context)) {
12745           // Value might be a float, a float vector, or a float complex.
12746           if (IsSameFloatAfterCast(result.Val,
12747                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12748                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12749             return;
12750         }
12751 
12752         if (S.SourceMgr.isInSystemMacro(CC))
12753           return;
12754 
12755         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12756       }
12757       // ... or possibly if we're increasing rank, too
12758       else if (Order < 0) {
12759         if (S.SourceMgr.isInSystemMacro(CC))
12760           return;
12761 
12762         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12763       }
12764       return;
12765     }
12766 
12767     // If the target is integral, always warn.
12768     if (TargetBT && TargetBT->isInteger()) {
12769       if (S.SourceMgr.isInSystemMacro(CC))
12770         return;
12771 
12772       DiagnoseFloatingImpCast(S, E, T, CC);
12773     }
12774 
12775     // Detect the case where a call result is converted from floating-point to
12776     // to bool, and the final argument to the call is converted from bool, to
12777     // discover this typo:
12778     //
12779     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12780     //
12781     // FIXME: This is an incredibly special case; is there some more general
12782     // way to detect this class of misplaced-parentheses bug?
12783     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12784       // Check last argument of function call to see if it is an
12785       // implicit cast from a type matching the type the result
12786       // is being cast to.
12787       CallExpr *CEx = cast<CallExpr>(E);
12788       if (unsigned NumArgs = CEx->getNumArgs()) {
12789         Expr *LastA = CEx->getArg(NumArgs - 1);
12790         Expr *InnerE = LastA->IgnoreParenImpCasts();
12791         if (isa<ImplicitCastExpr>(LastA) &&
12792             InnerE->getType()->isBooleanType()) {
12793           // Warn on this floating-point to bool conversion
12794           DiagnoseImpCast(S, E, T, CC,
12795                           diag::warn_impcast_floating_point_to_bool);
12796         }
12797       }
12798     }
12799     return;
12800   }
12801 
12802   // Valid casts involving fixed point types should be accounted for here.
12803   if (Source->isFixedPointType()) {
12804     if (Target->isUnsaturatedFixedPointType()) {
12805       Expr::EvalResult Result;
12806       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12807                                   S.isConstantEvaluated())) {
12808         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12809         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12810         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12811         if (Value > MaxVal || Value < MinVal) {
12812           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12813                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12814                                     << Value.toString() << T
12815                                     << E->getSourceRange()
12816                                     << clang::SourceRange(CC));
12817           return;
12818         }
12819       }
12820     } else if (Target->isIntegerType()) {
12821       Expr::EvalResult Result;
12822       if (!S.isConstantEvaluated() &&
12823           E->EvaluateAsFixedPoint(Result, S.Context,
12824                                   Expr::SE_AllowSideEffects)) {
12825         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12826 
12827         bool Overflowed;
12828         llvm::APSInt IntResult = FXResult.convertToInt(
12829             S.Context.getIntWidth(T),
12830             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12831 
12832         if (Overflowed) {
12833           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12834                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12835                                     << FXResult.toString() << T
12836                                     << E->getSourceRange()
12837                                     << clang::SourceRange(CC));
12838           return;
12839         }
12840       }
12841     }
12842   } else if (Target->isUnsaturatedFixedPointType()) {
12843     if (Source->isIntegerType()) {
12844       Expr::EvalResult Result;
12845       if (!S.isConstantEvaluated() &&
12846           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12847         llvm::APSInt Value = Result.Val.getInt();
12848 
12849         bool Overflowed;
12850         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12851             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12852 
12853         if (Overflowed) {
12854           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12855                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12856                                     << toString(Value, /*Radix=*/10) << T
12857                                     << E->getSourceRange()
12858                                     << clang::SourceRange(CC));
12859           return;
12860         }
12861       }
12862     }
12863   }
12864 
12865   // If we are casting an integer type to a floating point type without
12866   // initialization-list syntax, we might lose accuracy if the floating
12867   // point type has a narrower significand than the integer type.
12868   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12869       TargetBT->isFloatingType() && !IsListInit) {
12870     // Determine the number of precision bits in the source integer type.
12871     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12872                                         /*Approximate*/ true);
12873     unsigned int SourcePrecision = SourceRange.Width;
12874 
12875     // Determine the number of precision bits in the
12876     // target floating point type.
12877     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12878         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12879 
12880     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12881         SourcePrecision > TargetPrecision) {
12882 
12883       if (Optional<llvm::APSInt> SourceInt =
12884               E->getIntegerConstantExpr(S.Context)) {
12885         // If the source integer is a constant, convert it to the target
12886         // floating point type. Issue a warning if the value changes
12887         // during the whole conversion.
12888         llvm::APFloat TargetFloatValue(
12889             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12890         llvm::APFloat::opStatus ConversionStatus =
12891             TargetFloatValue.convertFromAPInt(
12892                 *SourceInt, SourceBT->isSignedInteger(),
12893                 llvm::APFloat::rmNearestTiesToEven);
12894 
12895         if (ConversionStatus != llvm::APFloat::opOK) {
12896           SmallString<32> PrettySourceValue;
12897           SourceInt->toString(PrettySourceValue, 10);
12898           SmallString<32> PrettyTargetValue;
12899           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12900 
12901           S.DiagRuntimeBehavior(
12902               E->getExprLoc(), E,
12903               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12904                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12905                   << E->getSourceRange() << clang::SourceRange(CC));
12906         }
12907       } else {
12908         // Otherwise, the implicit conversion may lose precision.
12909         DiagnoseImpCast(S, E, T, CC,
12910                         diag::warn_impcast_integer_float_precision);
12911       }
12912     }
12913   }
12914 
12915   DiagnoseNullConversion(S, E, T, CC);
12916 
12917   S.DiscardMisalignedMemberAddress(Target, E);
12918 
12919   if (Target->isBooleanType())
12920     DiagnoseIntInBoolContext(S, E);
12921 
12922   if (!Source->isIntegerType() || !Target->isIntegerType())
12923     return;
12924 
12925   // TODO: remove this early return once the false positives for constant->bool
12926   // in templates, macros, etc, are reduced or removed.
12927   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12928     return;
12929 
12930   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12931       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12932     return adornObjCBoolConversionDiagWithTernaryFixit(
12933         S, E,
12934         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12935             << E->getType());
12936   }
12937 
12938   IntRange SourceTypeRange =
12939       IntRange::forTargetOfCanonicalType(S.Context, Source);
12940   IntRange LikelySourceRange =
12941       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12942   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12943 
12944   if (LikelySourceRange.Width > TargetRange.Width) {
12945     // If the source is a constant, use a default-on diagnostic.
12946     // TODO: this should happen for bitfield stores, too.
12947     Expr::EvalResult Result;
12948     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12949                          S.isConstantEvaluated())) {
12950       llvm::APSInt Value(32);
12951       Value = Result.Val.getInt();
12952 
12953       if (S.SourceMgr.isInSystemMacro(CC))
12954         return;
12955 
12956       std::string PrettySourceValue = toString(Value, 10);
12957       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12958 
12959       S.DiagRuntimeBehavior(
12960           E->getExprLoc(), E,
12961           S.PDiag(diag::warn_impcast_integer_precision_constant)
12962               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12963               << E->getSourceRange() << SourceRange(CC));
12964       return;
12965     }
12966 
12967     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12968     if (S.SourceMgr.isInSystemMacro(CC))
12969       return;
12970 
12971     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12972       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12973                              /* pruneControlFlow */ true);
12974     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12975   }
12976 
12977   if (TargetRange.Width > SourceTypeRange.Width) {
12978     if (auto *UO = dyn_cast<UnaryOperator>(E))
12979       if (UO->getOpcode() == UO_Minus)
12980         if (Source->isUnsignedIntegerType()) {
12981           if (Target->isUnsignedIntegerType())
12982             return DiagnoseImpCast(S, E, T, CC,
12983                                    diag::warn_impcast_high_order_zero_bits);
12984           if (Target->isSignedIntegerType())
12985             return DiagnoseImpCast(S, E, T, CC,
12986                                    diag::warn_impcast_nonnegative_result);
12987         }
12988   }
12989 
12990   if (TargetRange.Width == LikelySourceRange.Width &&
12991       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12992       Source->isSignedIntegerType()) {
12993     // Warn when doing a signed to signed conversion, warn if the positive
12994     // source value is exactly the width of the target type, which will
12995     // cause a negative value to be stored.
12996 
12997     Expr::EvalResult Result;
12998     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12999         !S.SourceMgr.isInSystemMacro(CC)) {
13000       llvm::APSInt Value = Result.Val.getInt();
13001       if (isSameWidthConstantConversion(S, E, T, CC)) {
13002         std::string PrettySourceValue = toString(Value, 10);
13003         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13004 
13005         S.DiagRuntimeBehavior(
13006             E->getExprLoc(), E,
13007             S.PDiag(diag::warn_impcast_integer_precision_constant)
13008                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13009                 << E->getSourceRange() << SourceRange(CC));
13010         return;
13011       }
13012     }
13013 
13014     // Fall through for non-constants to give a sign conversion warning.
13015   }
13016 
13017   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13018       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13019        LikelySourceRange.Width == TargetRange.Width)) {
13020     if (S.SourceMgr.isInSystemMacro(CC))
13021       return;
13022 
13023     unsigned DiagID = diag::warn_impcast_integer_sign;
13024 
13025     // Traditionally, gcc has warned about this under -Wsign-compare.
13026     // We also want to warn about it in -Wconversion.
13027     // So if -Wconversion is off, use a completely identical diagnostic
13028     // in the sign-compare group.
13029     // The conditional-checking code will
13030     if (ICContext) {
13031       DiagID = diag::warn_impcast_integer_sign_conditional;
13032       *ICContext = true;
13033     }
13034 
13035     return DiagnoseImpCast(S, E, T, CC, DiagID);
13036   }
13037 
13038   // Diagnose conversions between different enumeration types.
13039   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13040   // type, to give us better diagnostics.
13041   QualType SourceType = E->getType();
13042   if (!S.getLangOpts().CPlusPlus) {
13043     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13044       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13045         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13046         SourceType = S.Context.getTypeDeclType(Enum);
13047         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13048       }
13049   }
13050 
13051   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13052     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13053       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13054           TargetEnum->getDecl()->hasNameForLinkage() &&
13055           SourceEnum != TargetEnum) {
13056         if (S.SourceMgr.isInSystemMacro(CC))
13057           return;
13058 
13059         return DiagnoseImpCast(S, E, SourceType, T, CC,
13060                                diag::warn_impcast_different_enum_types);
13061       }
13062 }
13063 
13064 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13065                                      SourceLocation CC, QualType T);
13066 
13067 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13068                                     SourceLocation CC, bool &ICContext) {
13069   E = E->IgnoreParenImpCasts();
13070 
13071   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13072     return CheckConditionalOperator(S, CO, CC, T);
13073 
13074   AnalyzeImplicitConversions(S, E, CC);
13075   if (E->getType() != T)
13076     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13077 }
13078 
13079 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13080                                      SourceLocation CC, QualType T) {
13081   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13082 
13083   Expr *TrueExpr = E->getTrueExpr();
13084   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13085     TrueExpr = BCO->getCommon();
13086 
13087   bool Suspicious = false;
13088   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13089   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13090 
13091   if (T->isBooleanType())
13092     DiagnoseIntInBoolContext(S, E);
13093 
13094   // If -Wconversion would have warned about either of the candidates
13095   // for a signedness conversion to the context type...
13096   if (!Suspicious) return;
13097 
13098   // ...but it's currently ignored...
13099   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13100     return;
13101 
13102   // ...then check whether it would have warned about either of the
13103   // candidates for a signedness conversion to the condition type.
13104   if (E->getType() == T) return;
13105 
13106   Suspicious = false;
13107   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13108                           E->getType(), CC, &Suspicious);
13109   if (!Suspicious)
13110     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13111                             E->getType(), CC, &Suspicious);
13112 }
13113 
13114 /// Check conversion of given expression to boolean.
13115 /// Input argument E is a logical expression.
13116 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13117   if (S.getLangOpts().Bool)
13118     return;
13119   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13120     return;
13121   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13122 }
13123 
13124 namespace {
13125 struct AnalyzeImplicitConversionsWorkItem {
13126   Expr *E;
13127   SourceLocation CC;
13128   bool IsListInit;
13129 };
13130 }
13131 
13132 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13133 /// that should be visited are added to WorkList.
13134 static void AnalyzeImplicitConversions(
13135     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13136     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13137   Expr *OrigE = Item.E;
13138   SourceLocation CC = Item.CC;
13139 
13140   QualType T = OrigE->getType();
13141   Expr *E = OrigE->IgnoreParenImpCasts();
13142 
13143   // Propagate whether we are in a C++ list initialization expression.
13144   // If so, we do not issue warnings for implicit int-float conversion
13145   // precision loss, because C++11 narrowing already handles it.
13146   bool IsListInit = Item.IsListInit ||
13147                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13148 
13149   if (E->isTypeDependent() || E->isValueDependent())
13150     return;
13151 
13152   Expr *SourceExpr = E;
13153   // Examine, but don't traverse into the source expression of an
13154   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13155   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13156   // evaluate it in the context of checking the specific conversion to T though.
13157   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13158     if (auto *Src = OVE->getSourceExpr())
13159       SourceExpr = Src;
13160 
13161   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13162     if (UO->getOpcode() == UO_Not &&
13163         UO->getSubExpr()->isKnownToHaveBooleanValue())
13164       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13165           << OrigE->getSourceRange() << T->isBooleanType()
13166           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13167 
13168   // For conditional operators, we analyze the arguments as if they
13169   // were being fed directly into the output.
13170   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13171     CheckConditionalOperator(S, CO, CC, T);
13172     return;
13173   }
13174 
13175   // Check implicit argument conversions for function calls.
13176   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13177     CheckImplicitArgumentConversions(S, Call, CC);
13178 
13179   // Go ahead and check any implicit conversions we might have skipped.
13180   // The non-canonical typecheck is just an optimization;
13181   // CheckImplicitConversion will filter out dead implicit conversions.
13182   if (SourceExpr->getType() != T)
13183     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13184 
13185   // Now continue drilling into this expression.
13186 
13187   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13188     // The bound subexpressions in a PseudoObjectExpr are not reachable
13189     // as transitive children.
13190     // FIXME: Use a more uniform representation for this.
13191     for (auto *SE : POE->semantics())
13192       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13193         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13194   }
13195 
13196   // Skip past explicit casts.
13197   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13198     E = CE->getSubExpr()->IgnoreParenImpCasts();
13199     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13200       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13201     WorkList.push_back({E, CC, IsListInit});
13202     return;
13203   }
13204 
13205   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13206     // Do a somewhat different check with comparison operators.
13207     if (BO->isComparisonOp())
13208       return AnalyzeComparison(S, BO);
13209 
13210     // And with simple assignments.
13211     if (BO->getOpcode() == BO_Assign)
13212       return AnalyzeAssignment(S, BO);
13213     // And with compound assignments.
13214     if (BO->isAssignmentOp())
13215       return AnalyzeCompoundAssignment(S, BO);
13216   }
13217 
13218   // These break the otherwise-useful invariant below.  Fortunately,
13219   // we don't really need to recurse into them, because any internal
13220   // expressions should have been analyzed already when they were
13221   // built into statements.
13222   if (isa<StmtExpr>(E)) return;
13223 
13224   // Don't descend into unevaluated contexts.
13225   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13226 
13227   // Now just recurse over the expression's children.
13228   CC = E->getExprLoc();
13229   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13230   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13231   for (Stmt *SubStmt : E->children()) {
13232     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13233     if (!ChildExpr)
13234       continue;
13235 
13236     if (IsLogicalAndOperator &&
13237         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13238       // Ignore checking string literals that are in logical and operators.
13239       // This is a common pattern for asserts.
13240       continue;
13241     WorkList.push_back({ChildExpr, CC, IsListInit});
13242   }
13243 
13244   if (BO && BO->isLogicalOp()) {
13245     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13246     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13247       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13248 
13249     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13250     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13251       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13252   }
13253 
13254   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13255     if (U->getOpcode() == UO_LNot) {
13256       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13257     } else if (U->getOpcode() != UO_AddrOf) {
13258       if (U->getSubExpr()->getType()->isAtomicType())
13259         S.Diag(U->getSubExpr()->getBeginLoc(),
13260                diag::warn_atomic_implicit_seq_cst);
13261     }
13262   }
13263 }
13264 
13265 /// AnalyzeImplicitConversions - Find and report any interesting
13266 /// implicit conversions in the given expression.  There are a couple
13267 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13268 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13269                                        bool IsListInit/*= false*/) {
13270   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13271   WorkList.push_back({OrigE, CC, IsListInit});
13272   while (!WorkList.empty())
13273     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13274 }
13275 
13276 /// Diagnose integer type and any valid implicit conversion to it.
13277 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13278   // Taking into account implicit conversions,
13279   // allow any integer.
13280   if (!E->getType()->isIntegerType()) {
13281     S.Diag(E->getBeginLoc(),
13282            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13283     return true;
13284   }
13285   // Potentially emit standard warnings for implicit conversions if enabled
13286   // using -Wconversion.
13287   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13288   return false;
13289 }
13290 
13291 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13292 // Returns true when emitting a warning about taking the address of a reference.
13293 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13294                               const PartialDiagnostic &PD) {
13295   E = E->IgnoreParenImpCasts();
13296 
13297   const FunctionDecl *FD = nullptr;
13298 
13299   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13300     if (!DRE->getDecl()->getType()->isReferenceType())
13301       return false;
13302   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13303     if (!M->getMemberDecl()->getType()->isReferenceType())
13304       return false;
13305   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13306     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13307       return false;
13308     FD = Call->getDirectCallee();
13309   } else {
13310     return false;
13311   }
13312 
13313   SemaRef.Diag(E->getExprLoc(), PD);
13314 
13315   // If possible, point to location of function.
13316   if (FD) {
13317     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13318   }
13319 
13320   return true;
13321 }
13322 
13323 // Returns true if the SourceLocation is expanded from any macro body.
13324 // Returns false if the SourceLocation is invalid, is from not in a macro
13325 // expansion, or is from expanded from a top-level macro argument.
13326 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13327   if (Loc.isInvalid())
13328     return false;
13329 
13330   while (Loc.isMacroID()) {
13331     if (SM.isMacroBodyExpansion(Loc))
13332       return true;
13333     Loc = SM.getImmediateMacroCallerLoc(Loc);
13334   }
13335 
13336   return false;
13337 }
13338 
13339 /// Diagnose pointers that are always non-null.
13340 /// \param E the expression containing the pointer
13341 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13342 /// compared to a null pointer
13343 /// \param IsEqual True when the comparison is equal to a null pointer
13344 /// \param Range Extra SourceRange to highlight in the diagnostic
13345 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13346                                         Expr::NullPointerConstantKind NullKind,
13347                                         bool IsEqual, SourceRange Range) {
13348   if (!E)
13349     return;
13350 
13351   // Don't warn inside macros.
13352   if (E->getExprLoc().isMacroID()) {
13353     const SourceManager &SM = getSourceManager();
13354     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13355         IsInAnyMacroBody(SM, Range.getBegin()))
13356       return;
13357   }
13358   E = E->IgnoreImpCasts();
13359 
13360   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13361 
13362   if (isa<CXXThisExpr>(E)) {
13363     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13364                                 : diag::warn_this_bool_conversion;
13365     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13366     return;
13367   }
13368 
13369   bool IsAddressOf = false;
13370 
13371   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13372     if (UO->getOpcode() != UO_AddrOf)
13373       return;
13374     IsAddressOf = true;
13375     E = UO->getSubExpr();
13376   }
13377 
13378   if (IsAddressOf) {
13379     unsigned DiagID = IsCompare
13380                           ? diag::warn_address_of_reference_null_compare
13381                           : diag::warn_address_of_reference_bool_conversion;
13382     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13383                                          << IsEqual;
13384     if (CheckForReference(*this, E, PD)) {
13385       return;
13386     }
13387   }
13388 
13389   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13390     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13391     std::string Str;
13392     llvm::raw_string_ostream S(Str);
13393     E->printPretty(S, nullptr, getPrintingPolicy());
13394     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13395                                 : diag::warn_cast_nonnull_to_bool;
13396     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13397       << E->getSourceRange() << Range << IsEqual;
13398     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13399   };
13400 
13401   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13402   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13403     if (auto *Callee = Call->getDirectCallee()) {
13404       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13405         ComplainAboutNonnullParamOrCall(A);
13406         return;
13407       }
13408     }
13409   }
13410 
13411   // Expect to find a single Decl.  Skip anything more complicated.
13412   ValueDecl *D = nullptr;
13413   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13414     D = R->getDecl();
13415   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13416     D = M->getMemberDecl();
13417   }
13418 
13419   // Weak Decls can be null.
13420   if (!D || D->isWeak())
13421     return;
13422 
13423   // Check for parameter decl with nonnull attribute
13424   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13425     if (getCurFunction() &&
13426         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13427       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13428         ComplainAboutNonnullParamOrCall(A);
13429         return;
13430       }
13431 
13432       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13433         // Skip function template not specialized yet.
13434         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13435           return;
13436         auto ParamIter = llvm::find(FD->parameters(), PV);
13437         assert(ParamIter != FD->param_end());
13438         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13439 
13440         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13441           if (!NonNull->args_size()) {
13442               ComplainAboutNonnullParamOrCall(NonNull);
13443               return;
13444           }
13445 
13446           for (const ParamIdx &ArgNo : NonNull->args()) {
13447             if (ArgNo.getASTIndex() == ParamNo) {
13448               ComplainAboutNonnullParamOrCall(NonNull);
13449               return;
13450             }
13451           }
13452         }
13453       }
13454     }
13455   }
13456 
13457   QualType T = D->getType();
13458   const bool IsArray = T->isArrayType();
13459   const bool IsFunction = T->isFunctionType();
13460 
13461   // Address of function is used to silence the function warning.
13462   if (IsAddressOf && IsFunction) {
13463     return;
13464   }
13465 
13466   // Found nothing.
13467   if (!IsAddressOf && !IsFunction && !IsArray)
13468     return;
13469 
13470   // Pretty print the expression for the diagnostic.
13471   std::string Str;
13472   llvm::raw_string_ostream S(Str);
13473   E->printPretty(S, nullptr, getPrintingPolicy());
13474 
13475   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13476                               : diag::warn_impcast_pointer_to_bool;
13477   enum {
13478     AddressOf,
13479     FunctionPointer,
13480     ArrayPointer
13481   } DiagType;
13482   if (IsAddressOf)
13483     DiagType = AddressOf;
13484   else if (IsFunction)
13485     DiagType = FunctionPointer;
13486   else if (IsArray)
13487     DiagType = ArrayPointer;
13488   else
13489     llvm_unreachable("Could not determine diagnostic.");
13490   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13491                                 << Range << IsEqual;
13492 
13493   if (!IsFunction)
13494     return;
13495 
13496   // Suggest '&' to silence the function warning.
13497   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13498       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13499 
13500   // Check to see if '()' fixit should be emitted.
13501   QualType ReturnType;
13502   UnresolvedSet<4> NonTemplateOverloads;
13503   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13504   if (ReturnType.isNull())
13505     return;
13506 
13507   if (IsCompare) {
13508     // There are two cases here.  If there is null constant, the only suggest
13509     // for a pointer return type.  If the null is 0, then suggest if the return
13510     // type is a pointer or an integer type.
13511     if (!ReturnType->isPointerType()) {
13512       if (NullKind == Expr::NPCK_ZeroExpression ||
13513           NullKind == Expr::NPCK_ZeroLiteral) {
13514         if (!ReturnType->isIntegerType())
13515           return;
13516       } else {
13517         return;
13518       }
13519     }
13520   } else { // !IsCompare
13521     // For function to bool, only suggest if the function pointer has bool
13522     // return type.
13523     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13524       return;
13525   }
13526   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13527       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13528 }
13529 
13530 /// Diagnoses "dangerous" implicit conversions within the given
13531 /// expression (which is a full expression).  Implements -Wconversion
13532 /// and -Wsign-compare.
13533 ///
13534 /// \param CC the "context" location of the implicit conversion, i.e.
13535 ///   the most location of the syntactic entity requiring the implicit
13536 ///   conversion
13537 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13538   // Don't diagnose in unevaluated contexts.
13539   if (isUnevaluatedContext())
13540     return;
13541 
13542   // Don't diagnose for value- or type-dependent expressions.
13543   if (E->isTypeDependent() || E->isValueDependent())
13544     return;
13545 
13546   // Check for array bounds violations in cases where the check isn't triggered
13547   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13548   // ArraySubscriptExpr is on the RHS of a variable initialization.
13549   CheckArrayAccess(E);
13550 
13551   // This is not the right CC for (e.g.) a variable initialization.
13552   AnalyzeImplicitConversions(*this, E, CC);
13553 }
13554 
13555 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13556 /// Input argument E is a logical expression.
13557 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13558   ::CheckBoolLikeConversion(*this, E, CC);
13559 }
13560 
13561 /// Diagnose when expression is an integer constant expression and its evaluation
13562 /// results in integer overflow
13563 void Sema::CheckForIntOverflow (Expr *E) {
13564   // Use a work list to deal with nested struct initializers.
13565   SmallVector<Expr *, 2> Exprs(1, E);
13566 
13567   do {
13568     Expr *OriginalE = Exprs.pop_back_val();
13569     Expr *E = OriginalE->IgnoreParenCasts();
13570 
13571     if (isa<BinaryOperator>(E)) {
13572       E->EvaluateForOverflow(Context);
13573       continue;
13574     }
13575 
13576     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13577       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13578     else if (isa<ObjCBoxedExpr>(OriginalE))
13579       E->EvaluateForOverflow(Context);
13580     else if (auto Call = dyn_cast<CallExpr>(E))
13581       Exprs.append(Call->arg_begin(), Call->arg_end());
13582     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13583       Exprs.append(Message->arg_begin(), Message->arg_end());
13584   } while (!Exprs.empty());
13585 }
13586 
13587 namespace {
13588 
13589 /// Visitor for expressions which looks for unsequenced operations on the
13590 /// same object.
13591 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13592   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13593 
13594   /// A tree of sequenced regions within an expression. Two regions are
13595   /// unsequenced if one is an ancestor or a descendent of the other. When we
13596   /// finish processing an expression with sequencing, such as a comma
13597   /// expression, we fold its tree nodes into its parent, since they are
13598   /// unsequenced with respect to nodes we will visit later.
13599   class SequenceTree {
13600     struct Value {
13601       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13602       unsigned Parent : 31;
13603       unsigned Merged : 1;
13604     };
13605     SmallVector<Value, 8> Values;
13606 
13607   public:
13608     /// A region within an expression which may be sequenced with respect
13609     /// to some other region.
13610     class Seq {
13611       friend class SequenceTree;
13612 
13613       unsigned Index;
13614 
13615       explicit Seq(unsigned N) : Index(N) {}
13616 
13617     public:
13618       Seq() : Index(0) {}
13619     };
13620 
13621     SequenceTree() { Values.push_back(Value(0)); }
13622     Seq root() const { return Seq(0); }
13623 
13624     /// Create a new sequence of operations, which is an unsequenced
13625     /// subset of \p Parent. This sequence of operations is sequenced with
13626     /// respect to other children of \p Parent.
13627     Seq allocate(Seq Parent) {
13628       Values.push_back(Value(Parent.Index));
13629       return Seq(Values.size() - 1);
13630     }
13631 
13632     /// Merge a sequence of operations into its parent.
13633     void merge(Seq S) {
13634       Values[S.Index].Merged = true;
13635     }
13636 
13637     /// Determine whether two operations are unsequenced. This operation
13638     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13639     /// should have been merged into its parent as appropriate.
13640     bool isUnsequenced(Seq Cur, Seq Old) {
13641       unsigned C = representative(Cur.Index);
13642       unsigned Target = representative(Old.Index);
13643       while (C >= Target) {
13644         if (C == Target)
13645           return true;
13646         C = Values[C].Parent;
13647       }
13648       return false;
13649     }
13650 
13651   private:
13652     /// Pick a representative for a sequence.
13653     unsigned representative(unsigned K) {
13654       if (Values[K].Merged)
13655         // Perform path compression as we go.
13656         return Values[K].Parent = representative(Values[K].Parent);
13657       return K;
13658     }
13659   };
13660 
13661   /// An object for which we can track unsequenced uses.
13662   using Object = const NamedDecl *;
13663 
13664   /// Different flavors of object usage which we track. We only track the
13665   /// least-sequenced usage of each kind.
13666   enum UsageKind {
13667     /// A read of an object. Multiple unsequenced reads are OK.
13668     UK_Use,
13669 
13670     /// A modification of an object which is sequenced before the value
13671     /// computation of the expression, such as ++n in C++.
13672     UK_ModAsValue,
13673 
13674     /// A modification of an object which is not sequenced before the value
13675     /// computation of the expression, such as n++.
13676     UK_ModAsSideEffect,
13677 
13678     UK_Count = UK_ModAsSideEffect + 1
13679   };
13680 
13681   /// Bundle together a sequencing region and the expression corresponding
13682   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13683   struct Usage {
13684     const Expr *UsageExpr;
13685     SequenceTree::Seq Seq;
13686 
13687     Usage() : UsageExpr(nullptr), Seq() {}
13688   };
13689 
13690   struct UsageInfo {
13691     Usage Uses[UK_Count];
13692 
13693     /// Have we issued a diagnostic for this object already?
13694     bool Diagnosed;
13695 
13696     UsageInfo() : Uses(), Diagnosed(false) {}
13697   };
13698   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13699 
13700   Sema &SemaRef;
13701 
13702   /// Sequenced regions within the expression.
13703   SequenceTree Tree;
13704 
13705   /// Declaration modifications and references which we have seen.
13706   UsageInfoMap UsageMap;
13707 
13708   /// The region we are currently within.
13709   SequenceTree::Seq Region;
13710 
13711   /// Filled in with declarations which were modified as a side-effect
13712   /// (that is, post-increment operations).
13713   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13714 
13715   /// Expressions to check later. We defer checking these to reduce
13716   /// stack usage.
13717   SmallVectorImpl<const Expr *> &WorkList;
13718 
13719   /// RAII object wrapping the visitation of a sequenced subexpression of an
13720   /// expression. At the end of this process, the side-effects of the evaluation
13721   /// become sequenced with respect to the value computation of the result, so
13722   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13723   /// UK_ModAsValue.
13724   struct SequencedSubexpression {
13725     SequencedSubexpression(SequenceChecker &Self)
13726       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13727       Self.ModAsSideEffect = &ModAsSideEffect;
13728     }
13729 
13730     ~SequencedSubexpression() {
13731       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13732         // Add a new usage with usage kind UK_ModAsValue, and then restore
13733         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13734         // the previous one was empty).
13735         UsageInfo &UI = Self.UsageMap[M.first];
13736         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13737         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13738         SideEffectUsage = M.second;
13739       }
13740       Self.ModAsSideEffect = OldModAsSideEffect;
13741     }
13742 
13743     SequenceChecker &Self;
13744     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13745     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13746   };
13747 
13748   /// RAII object wrapping the visitation of a subexpression which we might
13749   /// choose to evaluate as a constant. If any subexpression is evaluated and
13750   /// found to be non-constant, this allows us to suppress the evaluation of
13751   /// the outer expression.
13752   class EvaluationTracker {
13753   public:
13754     EvaluationTracker(SequenceChecker &Self)
13755         : Self(Self), Prev(Self.EvalTracker) {
13756       Self.EvalTracker = this;
13757     }
13758 
13759     ~EvaluationTracker() {
13760       Self.EvalTracker = Prev;
13761       if (Prev)
13762         Prev->EvalOK &= EvalOK;
13763     }
13764 
13765     bool evaluate(const Expr *E, bool &Result) {
13766       if (!EvalOK || E->isValueDependent())
13767         return false;
13768       EvalOK = E->EvaluateAsBooleanCondition(
13769           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13770       return EvalOK;
13771     }
13772 
13773   private:
13774     SequenceChecker &Self;
13775     EvaluationTracker *Prev;
13776     bool EvalOK = true;
13777   } *EvalTracker = nullptr;
13778 
13779   /// Find the object which is produced by the specified expression,
13780   /// if any.
13781   Object getObject(const Expr *E, bool Mod) const {
13782     E = E->IgnoreParenCasts();
13783     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13784       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13785         return getObject(UO->getSubExpr(), Mod);
13786     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13787       if (BO->getOpcode() == BO_Comma)
13788         return getObject(BO->getRHS(), Mod);
13789       if (Mod && BO->isAssignmentOp())
13790         return getObject(BO->getLHS(), Mod);
13791     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13792       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13793       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13794         return ME->getMemberDecl();
13795     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13796       // FIXME: If this is a reference, map through to its value.
13797       return DRE->getDecl();
13798     return nullptr;
13799   }
13800 
13801   /// Note that an object \p O was modified or used by an expression
13802   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13803   /// the object \p O as obtained via the \p UsageMap.
13804   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13805     // Get the old usage for the given object and usage kind.
13806     Usage &U = UI.Uses[UK];
13807     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13808       // If we have a modification as side effect and are in a sequenced
13809       // subexpression, save the old Usage so that we can restore it later
13810       // in SequencedSubexpression::~SequencedSubexpression.
13811       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13812         ModAsSideEffect->push_back(std::make_pair(O, U));
13813       // Then record the new usage with the current sequencing region.
13814       U.UsageExpr = UsageExpr;
13815       U.Seq = Region;
13816     }
13817   }
13818 
13819   /// Check whether a modification or use of an object \p O in an expression
13820   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13821   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13822   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13823   /// usage and false we are checking for a mod-use unsequenced usage.
13824   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13825                   UsageKind OtherKind, bool IsModMod) {
13826     if (UI.Diagnosed)
13827       return;
13828 
13829     const Usage &U = UI.Uses[OtherKind];
13830     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13831       return;
13832 
13833     const Expr *Mod = U.UsageExpr;
13834     const Expr *ModOrUse = UsageExpr;
13835     if (OtherKind == UK_Use)
13836       std::swap(Mod, ModOrUse);
13837 
13838     SemaRef.DiagRuntimeBehavior(
13839         Mod->getExprLoc(), {Mod, ModOrUse},
13840         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13841                                : diag::warn_unsequenced_mod_use)
13842             << O << SourceRange(ModOrUse->getExprLoc()));
13843     UI.Diagnosed = true;
13844   }
13845 
13846   // A note on note{Pre, Post}{Use, Mod}:
13847   //
13848   // (It helps to follow the algorithm with an expression such as
13849   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13850   //  operations before C++17 and both are well-defined in C++17).
13851   //
13852   // When visiting a node which uses/modify an object we first call notePreUse
13853   // or notePreMod before visiting its sub-expression(s). At this point the
13854   // children of the current node have not yet been visited and so the eventual
13855   // uses/modifications resulting from the children of the current node have not
13856   // been recorded yet.
13857   //
13858   // We then visit the children of the current node. After that notePostUse or
13859   // notePostMod is called. These will 1) detect an unsequenced modification
13860   // as side effect (as in "k++ + k") and 2) add a new usage with the
13861   // appropriate usage kind.
13862   //
13863   // We also have to be careful that some operation sequences modification as
13864   // side effect as well (for example: || or ,). To account for this we wrap
13865   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13866   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13867   // which record usages which are modifications as side effect, and then
13868   // downgrade them (or more accurately restore the previous usage which was a
13869   // modification as side effect) when exiting the scope of the sequenced
13870   // subexpression.
13871 
13872   void notePreUse(Object O, const Expr *UseExpr) {
13873     UsageInfo &UI = UsageMap[O];
13874     // Uses conflict with other modifications.
13875     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13876   }
13877 
13878   void notePostUse(Object O, const Expr *UseExpr) {
13879     UsageInfo &UI = UsageMap[O];
13880     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13881                /*IsModMod=*/false);
13882     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13883   }
13884 
13885   void notePreMod(Object O, const Expr *ModExpr) {
13886     UsageInfo &UI = UsageMap[O];
13887     // Modifications conflict with other modifications and with uses.
13888     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13889     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13890   }
13891 
13892   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13893     UsageInfo &UI = UsageMap[O];
13894     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13895                /*IsModMod=*/true);
13896     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13897   }
13898 
13899 public:
13900   SequenceChecker(Sema &S, const Expr *E,
13901                   SmallVectorImpl<const Expr *> &WorkList)
13902       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13903     Visit(E);
13904     // Silence a -Wunused-private-field since WorkList is now unused.
13905     // TODO: Evaluate if it can be used, and if not remove it.
13906     (void)this->WorkList;
13907   }
13908 
13909   void VisitStmt(const Stmt *S) {
13910     // Skip all statements which aren't expressions for now.
13911   }
13912 
13913   void VisitExpr(const Expr *E) {
13914     // By default, just recurse to evaluated subexpressions.
13915     Base::VisitStmt(E);
13916   }
13917 
13918   void VisitCastExpr(const CastExpr *E) {
13919     Object O = Object();
13920     if (E->getCastKind() == CK_LValueToRValue)
13921       O = getObject(E->getSubExpr(), false);
13922 
13923     if (O)
13924       notePreUse(O, E);
13925     VisitExpr(E);
13926     if (O)
13927       notePostUse(O, E);
13928   }
13929 
13930   void VisitSequencedExpressions(const Expr *SequencedBefore,
13931                                  const Expr *SequencedAfter) {
13932     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13933     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13934     SequenceTree::Seq OldRegion = Region;
13935 
13936     {
13937       SequencedSubexpression SeqBefore(*this);
13938       Region = BeforeRegion;
13939       Visit(SequencedBefore);
13940     }
13941 
13942     Region = AfterRegion;
13943     Visit(SequencedAfter);
13944 
13945     Region = OldRegion;
13946 
13947     Tree.merge(BeforeRegion);
13948     Tree.merge(AfterRegion);
13949   }
13950 
13951   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13952     // C++17 [expr.sub]p1:
13953     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13954     //   expression E1 is sequenced before the expression E2.
13955     if (SemaRef.getLangOpts().CPlusPlus17)
13956       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13957     else {
13958       Visit(ASE->getLHS());
13959       Visit(ASE->getRHS());
13960     }
13961   }
13962 
13963   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13964   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13965   void VisitBinPtrMem(const BinaryOperator *BO) {
13966     // C++17 [expr.mptr.oper]p4:
13967     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13968     //  the expression E1 is sequenced before the expression E2.
13969     if (SemaRef.getLangOpts().CPlusPlus17)
13970       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13971     else {
13972       Visit(BO->getLHS());
13973       Visit(BO->getRHS());
13974     }
13975   }
13976 
13977   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13978   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13979   void VisitBinShlShr(const BinaryOperator *BO) {
13980     // C++17 [expr.shift]p4:
13981     //  The expression E1 is sequenced before the expression E2.
13982     if (SemaRef.getLangOpts().CPlusPlus17)
13983       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13984     else {
13985       Visit(BO->getLHS());
13986       Visit(BO->getRHS());
13987     }
13988   }
13989 
13990   void VisitBinComma(const BinaryOperator *BO) {
13991     // C++11 [expr.comma]p1:
13992     //   Every value computation and side effect associated with the left
13993     //   expression is sequenced before every value computation and side
13994     //   effect associated with the right expression.
13995     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13996   }
13997 
13998   void VisitBinAssign(const BinaryOperator *BO) {
13999     SequenceTree::Seq RHSRegion;
14000     SequenceTree::Seq LHSRegion;
14001     if (SemaRef.getLangOpts().CPlusPlus17) {
14002       RHSRegion = Tree.allocate(Region);
14003       LHSRegion = Tree.allocate(Region);
14004     } else {
14005       RHSRegion = Region;
14006       LHSRegion = Region;
14007     }
14008     SequenceTree::Seq OldRegion = Region;
14009 
14010     // C++11 [expr.ass]p1:
14011     //  [...] the assignment is sequenced after the value computation
14012     //  of the right and left operands, [...]
14013     //
14014     // so check it before inspecting the operands and update the
14015     // map afterwards.
14016     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14017     if (O)
14018       notePreMod(O, BO);
14019 
14020     if (SemaRef.getLangOpts().CPlusPlus17) {
14021       // C++17 [expr.ass]p1:
14022       //  [...] The right operand is sequenced before the left operand. [...]
14023       {
14024         SequencedSubexpression SeqBefore(*this);
14025         Region = RHSRegion;
14026         Visit(BO->getRHS());
14027       }
14028 
14029       Region = LHSRegion;
14030       Visit(BO->getLHS());
14031 
14032       if (O && isa<CompoundAssignOperator>(BO))
14033         notePostUse(O, BO);
14034 
14035     } else {
14036       // C++11 does not specify any sequencing between the LHS and RHS.
14037       Region = LHSRegion;
14038       Visit(BO->getLHS());
14039 
14040       if (O && isa<CompoundAssignOperator>(BO))
14041         notePostUse(O, BO);
14042 
14043       Region = RHSRegion;
14044       Visit(BO->getRHS());
14045     }
14046 
14047     // C++11 [expr.ass]p1:
14048     //  the assignment is sequenced [...] before the value computation of the
14049     //  assignment expression.
14050     // C11 6.5.16/3 has no such rule.
14051     Region = OldRegion;
14052     if (O)
14053       notePostMod(O, BO,
14054                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14055                                                   : UK_ModAsSideEffect);
14056     if (SemaRef.getLangOpts().CPlusPlus17) {
14057       Tree.merge(RHSRegion);
14058       Tree.merge(LHSRegion);
14059     }
14060   }
14061 
14062   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14063     VisitBinAssign(CAO);
14064   }
14065 
14066   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14067   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14068   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14069     Object O = getObject(UO->getSubExpr(), true);
14070     if (!O)
14071       return VisitExpr(UO);
14072 
14073     notePreMod(O, UO);
14074     Visit(UO->getSubExpr());
14075     // C++11 [expr.pre.incr]p1:
14076     //   the expression ++x is equivalent to x+=1
14077     notePostMod(O, UO,
14078                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14079                                                 : UK_ModAsSideEffect);
14080   }
14081 
14082   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14083   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14084   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14085     Object O = getObject(UO->getSubExpr(), true);
14086     if (!O)
14087       return VisitExpr(UO);
14088 
14089     notePreMod(O, UO);
14090     Visit(UO->getSubExpr());
14091     notePostMod(O, UO, UK_ModAsSideEffect);
14092   }
14093 
14094   void VisitBinLOr(const BinaryOperator *BO) {
14095     // C++11 [expr.log.or]p2:
14096     //  If the second expression is evaluated, every value computation and
14097     //  side effect associated with the first expression is sequenced before
14098     //  every value computation and side effect associated with the
14099     //  second expression.
14100     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14101     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14102     SequenceTree::Seq OldRegion = Region;
14103 
14104     EvaluationTracker Eval(*this);
14105     {
14106       SequencedSubexpression Sequenced(*this);
14107       Region = LHSRegion;
14108       Visit(BO->getLHS());
14109     }
14110 
14111     // C++11 [expr.log.or]p1:
14112     //  [...] the second operand is not evaluated if the first operand
14113     //  evaluates to true.
14114     bool EvalResult = false;
14115     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14116     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14117     if (ShouldVisitRHS) {
14118       Region = RHSRegion;
14119       Visit(BO->getRHS());
14120     }
14121 
14122     Region = OldRegion;
14123     Tree.merge(LHSRegion);
14124     Tree.merge(RHSRegion);
14125   }
14126 
14127   void VisitBinLAnd(const BinaryOperator *BO) {
14128     // C++11 [expr.log.and]p2:
14129     //  If the second expression is evaluated, every value computation and
14130     //  side effect associated with the first expression is sequenced before
14131     //  every value computation and side effect associated with the
14132     //  second expression.
14133     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14134     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14135     SequenceTree::Seq OldRegion = Region;
14136 
14137     EvaluationTracker Eval(*this);
14138     {
14139       SequencedSubexpression Sequenced(*this);
14140       Region = LHSRegion;
14141       Visit(BO->getLHS());
14142     }
14143 
14144     // C++11 [expr.log.and]p1:
14145     //  [...] the second operand is not evaluated if the first operand is false.
14146     bool EvalResult = false;
14147     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14148     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14149     if (ShouldVisitRHS) {
14150       Region = RHSRegion;
14151       Visit(BO->getRHS());
14152     }
14153 
14154     Region = OldRegion;
14155     Tree.merge(LHSRegion);
14156     Tree.merge(RHSRegion);
14157   }
14158 
14159   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14160     // C++11 [expr.cond]p1:
14161     //  [...] Every value computation and side effect associated with the first
14162     //  expression is sequenced before every value computation and side effect
14163     //  associated with the second or third expression.
14164     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14165 
14166     // No sequencing is specified between the true and false expression.
14167     // However since exactly one of both is going to be evaluated we can
14168     // consider them to be sequenced. This is needed to avoid warning on
14169     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14170     // both the true and false expressions because we can't evaluate x.
14171     // This will still allow us to detect an expression like (pre C++17)
14172     // "(x ? y += 1 : y += 2) = y".
14173     //
14174     // We don't wrap the visitation of the true and false expression with
14175     // SequencedSubexpression because we don't want to downgrade modifications
14176     // as side effect in the true and false expressions after the visition
14177     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14178     // not warn between the two "y++", but we should warn between the "y++"
14179     // and the "y".
14180     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14181     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14182     SequenceTree::Seq OldRegion = Region;
14183 
14184     EvaluationTracker Eval(*this);
14185     {
14186       SequencedSubexpression Sequenced(*this);
14187       Region = ConditionRegion;
14188       Visit(CO->getCond());
14189     }
14190 
14191     // C++11 [expr.cond]p1:
14192     // [...] The first expression is contextually converted to bool (Clause 4).
14193     // It is evaluated and if it is true, the result of the conditional
14194     // expression is the value of the second expression, otherwise that of the
14195     // third expression. Only one of the second and third expressions is
14196     // evaluated. [...]
14197     bool EvalResult = false;
14198     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14199     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14200     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14201     if (ShouldVisitTrueExpr) {
14202       Region = TrueRegion;
14203       Visit(CO->getTrueExpr());
14204     }
14205     if (ShouldVisitFalseExpr) {
14206       Region = FalseRegion;
14207       Visit(CO->getFalseExpr());
14208     }
14209 
14210     Region = OldRegion;
14211     Tree.merge(ConditionRegion);
14212     Tree.merge(TrueRegion);
14213     Tree.merge(FalseRegion);
14214   }
14215 
14216   void VisitCallExpr(const CallExpr *CE) {
14217     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14218 
14219     if (CE->isUnevaluatedBuiltinCall(Context))
14220       return;
14221 
14222     // C++11 [intro.execution]p15:
14223     //   When calling a function [...], every value computation and side effect
14224     //   associated with any argument expression, or with the postfix expression
14225     //   designating the called function, is sequenced before execution of every
14226     //   expression or statement in the body of the function [and thus before
14227     //   the value computation of its result].
14228     SequencedSubexpression Sequenced(*this);
14229     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14230       // C++17 [expr.call]p5
14231       //   The postfix-expression is sequenced before each expression in the
14232       //   expression-list and any default argument. [...]
14233       SequenceTree::Seq CalleeRegion;
14234       SequenceTree::Seq OtherRegion;
14235       if (SemaRef.getLangOpts().CPlusPlus17) {
14236         CalleeRegion = Tree.allocate(Region);
14237         OtherRegion = Tree.allocate(Region);
14238       } else {
14239         CalleeRegion = Region;
14240         OtherRegion = Region;
14241       }
14242       SequenceTree::Seq OldRegion = Region;
14243 
14244       // Visit the callee expression first.
14245       Region = CalleeRegion;
14246       if (SemaRef.getLangOpts().CPlusPlus17) {
14247         SequencedSubexpression Sequenced(*this);
14248         Visit(CE->getCallee());
14249       } else {
14250         Visit(CE->getCallee());
14251       }
14252 
14253       // Then visit the argument expressions.
14254       Region = OtherRegion;
14255       for (const Expr *Argument : CE->arguments())
14256         Visit(Argument);
14257 
14258       Region = OldRegion;
14259       if (SemaRef.getLangOpts().CPlusPlus17) {
14260         Tree.merge(CalleeRegion);
14261         Tree.merge(OtherRegion);
14262       }
14263     });
14264   }
14265 
14266   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14267     // C++17 [over.match.oper]p2:
14268     //   [...] the operator notation is first transformed to the equivalent
14269     //   function-call notation as summarized in Table 12 (where @ denotes one
14270     //   of the operators covered in the specified subclause). However, the
14271     //   operands are sequenced in the order prescribed for the built-in
14272     //   operator (Clause 8).
14273     //
14274     // From the above only overloaded binary operators and overloaded call
14275     // operators have sequencing rules in C++17 that we need to handle
14276     // separately.
14277     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14278         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14279       return VisitCallExpr(CXXOCE);
14280 
14281     enum {
14282       NoSequencing,
14283       LHSBeforeRHS,
14284       RHSBeforeLHS,
14285       LHSBeforeRest
14286     } SequencingKind;
14287     switch (CXXOCE->getOperator()) {
14288     case OO_Equal:
14289     case OO_PlusEqual:
14290     case OO_MinusEqual:
14291     case OO_StarEqual:
14292     case OO_SlashEqual:
14293     case OO_PercentEqual:
14294     case OO_CaretEqual:
14295     case OO_AmpEqual:
14296     case OO_PipeEqual:
14297     case OO_LessLessEqual:
14298     case OO_GreaterGreaterEqual:
14299       SequencingKind = RHSBeforeLHS;
14300       break;
14301 
14302     case OO_LessLess:
14303     case OO_GreaterGreater:
14304     case OO_AmpAmp:
14305     case OO_PipePipe:
14306     case OO_Comma:
14307     case OO_ArrowStar:
14308     case OO_Subscript:
14309       SequencingKind = LHSBeforeRHS;
14310       break;
14311 
14312     case OO_Call:
14313       SequencingKind = LHSBeforeRest;
14314       break;
14315 
14316     default:
14317       SequencingKind = NoSequencing;
14318       break;
14319     }
14320 
14321     if (SequencingKind == NoSequencing)
14322       return VisitCallExpr(CXXOCE);
14323 
14324     // This is a call, so all subexpressions are sequenced before the result.
14325     SequencedSubexpression Sequenced(*this);
14326 
14327     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14328       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14329              "Should only get there with C++17 and above!");
14330       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14331              "Should only get there with an overloaded binary operator"
14332              " or an overloaded call operator!");
14333 
14334       if (SequencingKind == LHSBeforeRest) {
14335         assert(CXXOCE->getOperator() == OO_Call &&
14336                "We should only have an overloaded call operator here!");
14337 
14338         // This is very similar to VisitCallExpr, except that we only have the
14339         // C++17 case. The postfix-expression is the first argument of the
14340         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14341         // are in the following arguments.
14342         //
14343         // Note that we intentionally do not visit the callee expression since
14344         // it is just a decayed reference to a function.
14345         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14346         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14347         SequenceTree::Seq OldRegion = Region;
14348 
14349         assert(CXXOCE->getNumArgs() >= 1 &&
14350                "An overloaded call operator must have at least one argument"
14351                " for the postfix-expression!");
14352         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14353         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14354                                           CXXOCE->getNumArgs() - 1);
14355 
14356         // Visit the postfix-expression first.
14357         {
14358           Region = PostfixExprRegion;
14359           SequencedSubexpression Sequenced(*this);
14360           Visit(PostfixExpr);
14361         }
14362 
14363         // Then visit the argument expressions.
14364         Region = ArgsRegion;
14365         for (const Expr *Arg : Args)
14366           Visit(Arg);
14367 
14368         Region = OldRegion;
14369         Tree.merge(PostfixExprRegion);
14370         Tree.merge(ArgsRegion);
14371       } else {
14372         assert(CXXOCE->getNumArgs() == 2 &&
14373                "Should only have two arguments here!");
14374         assert((SequencingKind == LHSBeforeRHS ||
14375                 SequencingKind == RHSBeforeLHS) &&
14376                "Unexpected sequencing kind!");
14377 
14378         // We do not visit the callee expression since it is just a decayed
14379         // reference to a function.
14380         const Expr *E1 = CXXOCE->getArg(0);
14381         const Expr *E2 = CXXOCE->getArg(1);
14382         if (SequencingKind == RHSBeforeLHS)
14383           std::swap(E1, E2);
14384 
14385         return VisitSequencedExpressions(E1, E2);
14386       }
14387     });
14388   }
14389 
14390   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14391     // This is a call, so all subexpressions are sequenced before the result.
14392     SequencedSubexpression Sequenced(*this);
14393 
14394     if (!CCE->isListInitialization())
14395       return VisitExpr(CCE);
14396 
14397     // In C++11, list initializations are sequenced.
14398     SmallVector<SequenceTree::Seq, 32> Elts;
14399     SequenceTree::Seq Parent = Region;
14400     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14401                                               E = CCE->arg_end();
14402          I != E; ++I) {
14403       Region = Tree.allocate(Parent);
14404       Elts.push_back(Region);
14405       Visit(*I);
14406     }
14407 
14408     // Forget that the initializers are sequenced.
14409     Region = Parent;
14410     for (unsigned I = 0; I < Elts.size(); ++I)
14411       Tree.merge(Elts[I]);
14412   }
14413 
14414   void VisitInitListExpr(const InitListExpr *ILE) {
14415     if (!SemaRef.getLangOpts().CPlusPlus11)
14416       return VisitExpr(ILE);
14417 
14418     // In C++11, list initializations are sequenced.
14419     SmallVector<SequenceTree::Seq, 32> Elts;
14420     SequenceTree::Seq Parent = Region;
14421     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14422       const Expr *E = ILE->getInit(I);
14423       if (!E)
14424         continue;
14425       Region = Tree.allocate(Parent);
14426       Elts.push_back(Region);
14427       Visit(E);
14428     }
14429 
14430     // Forget that the initializers are sequenced.
14431     Region = Parent;
14432     for (unsigned I = 0; I < Elts.size(); ++I)
14433       Tree.merge(Elts[I]);
14434   }
14435 };
14436 
14437 } // namespace
14438 
14439 void Sema::CheckUnsequencedOperations(const Expr *E) {
14440   SmallVector<const Expr *, 8> WorkList;
14441   WorkList.push_back(E);
14442   while (!WorkList.empty()) {
14443     const Expr *Item = WorkList.pop_back_val();
14444     SequenceChecker(*this, Item, WorkList);
14445   }
14446 }
14447 
14448 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14449                               bool IsConstexpr) {
14450   llvm::SaveAndRestore<bool> ConstantContext(
14451       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14452   CheckImplicitConversions(E, CheckLoc);
14453   if (!E->isInstantiationDependent())
14454     CheckUnsequencedOperations(E);
14455   if (!IsConstexpr && !E->isValueDependent())
14456     CheckForIntOverflow(E);
14457   DiagnoseMisalignedMembers();
14458 }
14459 
14460 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14461                                        FieldDecl *BitField,
14462                                        Expr *Init) {
14463   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14464 }
14465 
14466 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14467                                          SourceLocation Loc) {
14468   if (!PType->isVariablyModifiedType())
14469     return;
14470   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14471     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14472     return;
14473   }
14474   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14475     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14476     return;
14477   }
14478   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14479     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14480     return;
14481   }
14482 
14483   const ArrayType *AT = S.Context.getAsArrayType(PType);
14484   if (!AT)
14485     return;
14486 
14487   if (AT->getSizeModifier() != ArrayType::Star) {
14488     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14489     return;
14490   }
14491 
14492   S.Diag(Loc, diag::err_array_star_in_function_definition);
14493 }
14494 
14495 /// CheckParmsForFunctionDef - Check that the parameters of the given
14496 /// function are appropriate for the definition of a function. This
14497 /// takes care of any checks that cannot be performed on the
14498 /// declaration itself, e.g., that the types of each of the function
14499 /// parameters are complete.
14500 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14501                                     bool CheckParameterNames) {
14502   bool HasInvalidParm = false;
14503   for (ParmVarDecl *Param : Parameters) {
14504     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14505     // function declarator that is part of a function definition of
14506     // that function shall not have incomplete type.
14507     //
14508     // This is also C++ [dcl.fct]p6.
14509     if (!Param->isInvalidDecl() &&
14510         RequireCompleteType(Param->getLocation(), Param->getType(),
14511                             diag::err_typecheck_decl_incomplete_type)) {
14512       Param->setInvalidDecl();
14513       HasInvalidParm = true;
14514     }
14515 
14516     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14517     // declaration of each parameter shall include an identifier.
14518     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14519         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14520       // Diagnose this as an extension in C17 and earlier.
14521       if (!getLangOpts().C2x)
14522         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14523     }
14524 
14525     // C99 6.7.5.3p12:
14526     //   If the function declarator is not part of a definition of that
14527     //   function, parameters may have incomplete type and may use the [*]
14528     //   notation in their sequences of declarator specifiers to specify
14529     //   variable length array types.
14530     QualType PType = Param->getOriginalType();
14531     // FIXME: This diagnostic should point the '[*]' if source-location
14532     // information is added for it.
14533     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14534 
14535     // If the parameter is a c++ class type and it has to be destructed in the
14536     // callee function, declare the destructor so that it can be called by the
14537     // callee function. Do not perform any direct access check on the dtor here.
14538     if (!Param->isInvalidDecl()) {
14539       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14540         if (!ClassDecl->isInvalidDecl() &&
14541             !ClassDecl->hasIrrelevantDestructor() &&
14542             !ClassDecl->isDependentContext() &&
14543             ClassDecl->isParamDestroyedInCallee()) {
14544           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14545           MarkFunctionReferenced(Param->getLocation(), Destructor);
14546           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14547         }
14548       }
14549     }
14550 
14551     // Parameters with the pass_object_size attribute only need to be marked
14552     // constant at function definitions. Because we lack information about
14553     // whether we're on a declaration or definition when we're instantiating the
14554     // attribute, we need to check for constness here.
14555     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14556       if (!Param->getType().isConstQualified())
14557         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14558             << Attr->getSpelling() << 1;
14559 
14560     // Check for parameter names shadowing fields from the class.
14561     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14562       // The owning context for the parameter should be the function, but we
14563       // want to see if this function's declaration context is a record.
14564       DeclContext *DC = Param->getDeclContext();
14565       if (DC && DC->isFunctionOrMethod()) {
14566         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14567           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14568                                      RD, /*DeclIsField*/ false);
14569       }
14570     }
14571   }
14572 
14573   return HasInvalidParm;
14574 }
14575 
14576 Optional<std::pair<CharUnits, CharUnits>>
14577 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14578 
14579 /// Compute the alignment and offset of the base class object given the
14580 /// derived-to-base cast expression and the alignment and offset of the derived
14581 /// class object.
14582 static std::pair<CharUnits, CharUnits>
14583 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14584                                    CharUnits BaseAlignment, CharUnits Offset,
14585                                    ASTContext &Ctx) {
14586   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14587        ++PathI) {
14588     const CXXBaseSpecifier *Base = *PathI;
14589     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14590     if (Base->isVirtual()) {
14591       // The complete object may have a lower alignment than the non-virtual
14592       // alignment of the base, in which case the base may be misaligned. Choose
14593       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14594       // conservative lower bound of the complete object alignment.
14595       CharUnits NonVirtualAlignment =
14596           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14597       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14598       Offset = CharUnits::Zero();
14599     } else {
14600       const ASTRecordLayout &RL =
14601           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14602       Offset += RL.getBaseClassOffset(BaseDecl);
14603     }
14604     DerivedType = Base->getType();
14605   }
14606 
14607   return std::make_pair(BaseAlignment, Offset);
14608 }
14609 
14610 /// Compute the alignment and offset of a binary additive operator.
14611 static Optional<std::pair<CharUnits, CharUnits>>
14612 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14613                                      bool IsSub, ASTContext &Ctx) {
14614   QualType PointeeType = PtrE->getType()->getPointeeType();
14615 
14616   if (!PointeeType->isConstantSizeType())
14617     return llvm::None;
14618 
14619   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14620 
14621   if (!P)
14622     return llvm::None;
14623 
14624   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14625   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14626     CharUnits Offset = EltSize * IdxRes->getExtValue();
14627     if (IsSub)
14628       Offset = -Offset;
14629     return std::make_pair(P->first, P->second + Offset);
14630   }
14631 
14632   // If the integer expression isn't a constant expression, compute the lower
14633   // bound of the alignment using the alignment and offset of the pointer
14634   // expression and the element size.
14635   return std::make_pair(
14636       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14637       CharUnits::Zero());
14638 }
14639 
14640 /// This helper function takes an lvalue expression and returns the alignment of
14641 /// a VarDecl and a constant offset from the VarDecl.
14642 Optional<std::pair<CharUnits, CharUnits>>
14643 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14644   E = E->IgnoreParens();
14645   switch (E->getStmtClass()) {
14646   default:
14647     break;
14648   case Stmt::CStyleCastExprClass:
14649   case Stmt::CXXStaticCastExprClass:
14650   case Stmt::ImplicitCastExprClass: {
14651     auto *CE = cast<CastExpr>(E);
14652     const Expr *From = CE->getSubExpr();
14653     switch (CE->getCastKind()) {
14654     default:
14655       break;
14656     case CK_NoOp:
14657       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14658     case CK_UncheckedDerivedToBase:
14659     case CK_DerivedToBase: {
14660       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14661       if (!P)
14662         break;
14663       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14664                                                 P->second, Ctx);
14665     }
14666     }
14667     break;
14668   }
14669   case Stmt::ArraySubscriptExprClass: {
14670     auto *ASE = cast<ArraySubscriptExpr>(E);
14671     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14672                                                 false, Ctx);
14673   }
14674   case Stmt::DeclRefExprClass: {
14675     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14676       // FIXME: If VD is captured by copy or is an escaping __block variable,
14677       // use the alignment of VD's type.
14678       if (!VD->getType()->isReferenceType())
14679         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14680       if (VD->hasInit())
14681         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14682     }
14683     break;
14684   }
14685   case Stmt::MemberExprClass: {
14686     auto *ME = cast<MemberExpr>(E);
14687     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14688     if (!FD || FD->getType()->isReferenceType() ||
14689         FD->getParent()->isInvalidDecl())
14690       break;
14691     Optional<std::pair<CharUnits, CharUnits>> P;
14692     if (ME->isArrow())
14693       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14694     else
14695       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14696     if (!P)
14697       break;
14698     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14699     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14700     return std::make_pair(P->first,
14701                           P->second + CharUnits::fromQuantity(Offset));
14702   }
14703   case Stmt::UnaryOperatorClass: {
14704     auto *UO = cast<UnaryOperator>(E);
14705     switch (UO->getOpcode()) {
14706     default:
14707       break;
14708     case UO_Deref:
14709       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14710     }
14711     break;
14712   }
14713   case Stmt::BinaryOperatorClass: {
14714     auto *BO = cast<BinaryOperator>(E);
14715     auto Opcode = BO->getOpcode();
14716     switch (Opcode) {
14717     default:
14718       break;
14719     case BO_Comma:
14720       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14721     }
14722     break;
14723   }
14724   }
14725   return llvm::None;
14726 }
14727 
14728 /// This helper function takes a pointer expression and returns the alignment of
14729 /// a VarDecl and a constant offset from the VarDecl.
14730 Optional<std::pair<CharUnits, CharUnits>>
14731 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14732   E = E->IgnoreParens();
14733   switch (E->getStmtClass()) {
14734   default:
14735     break;
14736   case Stmt::CStyleCastExprClass:
14737   case Stmt::CXXStaticCastExprClass:
14738   case Stmt::ImplicitCastExprClass: {
14739     auto *CE = cast<CastExpr>(E);
14740     const Expr *From = CE->getSubExpr();
14741     switch (CE->getCastKind()) {
14742     default:
14743       break;
14744     case CK_NoOp:
14745       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14746     case CK_ArrayToPointerDecay:
14747       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14748     case CK_UncheckedDerivedToBase:
14749     case CK_DerivedToBase: {
14750       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14751       if (!P)
14752         break;
14753       return getDerivedToBaseAlignmentAndOffset(
14754           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14755     }
14756     }
14757     break;
14758   }
14759   case Stmt::CXXThisExprClass: {
14760     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14761     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14762     return std::make_pair(Alignment, CharUnits::Zero());
14763   }
14764   case Stmt::UnaryOperatorClass: {
14765     auto *UO = cast<UnaryOperator>(E);
14766     if (UO->getOpcode() == UO_AddrOf)
14767       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14768     break;
14769   }
14770   case Stmt::BinaryOperatorClass: {
14771     auto *BO = cast<BinaryOperator>(E);
14772     auto Opcode = BO->getOpcode();
14773     switch (Opcode) {
14774     default:
14775       break;
14776     case BO_Add:
14777     case BO_Sub: {
14778       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14779       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14780         std::swap(LHS, RHS);
14781       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14782                                                   Ctx);
14783     }
14784     case BO_Comma:
14785       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14786     }
14787     break;
14788   }
14789   }
14790   return llvm::None;
14791 }
14792 
14793 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14794   // See if we can compute the alignment of a VarDecl and an offset from it.
14795   Optional<std::pair<CharUnits, CharUnits>> P =
14796       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14797 
14798   if (P)
14799     return P->first.alignmentAtOffset(P->second);
14800 
14801   // If that failed, return the type's alignment.
14802   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14803 }
14804 
14805 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14806 /// pointer cast increases the alignment requirements.
14807 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14808   // This is actually a lot of work to potentially be doing on every
14809   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14810   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14811     return;
14812 
14813   // Ignore dependent types.
14814   if (T->isDependentType() || Op->getType()->isDependentType())
14815     return;
14816 
14817   // Require that the destination be a pointer type.
14818   const PointerType *DestPtr = T->getAs<PointerType>();
14819   if (!DestPtr) return;
14820 
14821   // If the destination has alignment 1, we're done.
14822   QualType DestPointee = DestPtr->getPointeeType();
14823   if (DestPointee->isIncompleteType()) return;
14824   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14825   if (DestAlign.isOne()) return;
14826 
14827   // Require that the source be a pointer type.
14828   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14829   if (!SrcPtr) return;
14830   QualType SrcPointee = SrcPtr->getPointeeType();
14831 
14832   // Explicitly allow casts from cv void*.  We already implicitly
14833   // allowed casts to cv void*, since they have alignment 1.
14834   // Also allow casts involving incomplete types, which implicitly
14835   // includes 'void'.
14836   if (SrcPointee->isIncompleteType()) return;
14837 
14838   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14839 
14840   if (SrcAlign >= DestAlign) return;
14841 
14842   Diag(TRange.getBegin(), diag::warn_cast_align)
14843     << Op->getType() << T
14844     << static_cast<unsigned>(SrcAlign.getQuantity())
14845     << static_cast<unsigned>(DestAlign.getQuantity())
14846     << TRange << Op->getSourceRange();
14847 }
14848 
14849 /// Check whether this array fits the idiom of a size-one tail padded
14850 /// array member of a struct.
14851 ///
14852 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14853 /// commonly used to emulate flexible arrays in C89 code.
14854 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14855                                     const NamedDecl *ND) {
14856   if (Size != 1 || !ND) return false;
14857 
14858   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14859   if (!FD) return false;
14860 
14861   // Don't consider sizes resulting from macro expansions or template argument
14862   // substitution to form C89 tail-padded arrays.
14863 
14864   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14865   while (TInfo) {
14866     TypeLoc TL = TInfo->getTypeLoc();
14867     // Look through typedefs.
14868     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14869       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14870       TInfo = TDL->getTypeSourceInfo();
14871       continue;
14872     }
14873     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14874       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14875       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14876         return false;
14877     }
14878     break;
14879   }
14880 
14881   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14882   if (!RD) return false;
14883   if (RD->isUnion()) return false;
14884   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14885     if (!CRD->isStandardLayout()) return false;
14886   }
14887 
14888   // See if this is the last field decl in the record.
14889   const Decl *D = FD;
14890   while ((D = D->getNextDeclInContext()))
14891     if (isa<FieldDecl>(D))
14892       return false;
14893   return true;
14894 }
14895 
14896 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14897                             const ArraySubscriptExpr *ASE,
14898                             bool AllowOnePastEnd, bool IndexNegated) {
14899   // Already diagnosed by the constant evaluator.
14900   if (isConstantEvaluated())
14901     return;
14902 
14903   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14904   if (IndexExpr->isValueDependent())
14905     return;
14906 
14907   const Type *EffectiveType =
14908       BaseExpr->getType()->getPointeeOrArrayElementType();
14909   BaseExpr = BaseExpr->IgnoreParenCasts();
14910   const ConstantArrayType *ArrayTy =
14911       Context.getAsConstantArrayType(BaseExpr->getType());
14912 
14913   const Type *BaseType =
14914       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14915   bool IsUnboundedArray = (BaseType == nullptr);
14916   if (EffectiveType->isDependentType() ||
14917       (!IsUnboundedArray && BaseType->isDependentType()))
14918     return;
14919 
14920   Expr::EvalResult Result;
14921   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14922     return;
14923 
14924   llvm::APSInt index = Result.Val.getInt();
14925   if (IndexNegated) {
14926     index.setIsUnsigned(false);
14927     index = -index;
14928   }
14929 
14930   const NamedDecl *ND = nullptr;
14931   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14932     ND = DRE->getDecl();
14933   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14934     ND = ME->getMemberDecl();
14935 
14936   if (IsUnboundedArray) {
14937     if (index.isUnsigned() || !index.isNegative()) {
14938       const auto &ASTC = getASTContext();
14939       unsigned AddrBits =
14940           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14941               EffectiveType->getCanonicalTypeInternal()));
14942       if (index.getBitWidth() < AddrBits)
14943         index = index.zext(AddrBits);
14944       Optional<CharUnits> ElemCharUnits =
14945           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14946       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14947       // pointer) bounds-checking isn't meaningful.
14948       if (!ElemCharUnits)
14949         return;
14950       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14951       // If index has more active bits than address space, we already know
14952       // we have a bounds violation to warn about.  Otherwise, compute
14953       // address of (index + 1)th element, and warn about bounds violation
14954       // only if that address exceeds address space.
14955       if (index.getActiveBits() <= AddrBits) {
14956         bool Overflow;
14957         llvm::APInt Product(index);
14958         Product += 1;
14959         Product = Product.umul_ov(ElemBytes, Overflow);
14960         if (!Overflow && Product.getActiveBits() <= AddrBits)
14961           return;
14962       }
14963 
14964       // Need to compute max possible elements in address space, since that
14965       // is included in diag message.
14966       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14967       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14968       MaxElems += 1;
14969       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14970       MaxElems = MaxElems.udiv(ElemBytes);
14971 
14972       unsigned DiagID =
14973           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14974               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14975 
14976       // Diag message shows element size in bits and in "bytes" (platform-
14977       // dependent CharUnits)
14978       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14979                           PDiag(DiagID)
14980                               << toString(index, 10, true) << AddrBits
14981                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14982                               << toString(ElemBytes, 10, false)
14983                               << toString(MaxElems, 10, false)
14984                               << (unsigned)MaxElems.getLimitedValue(~0U)
14985                               << IndexExpr->getSourceRange());
14986 
14987       if (!ND) {
14988         // Try harder to find a NamedDecl to point at in the note.
14989         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14990           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14991         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14992           ND = DRE->getDecl();
14993         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14994           ND = ME->getMemberDecl();
14995       }
14996 
14997       if (ND)
14998         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14999                             PDiag(diag::note_array_declared_here) << ND);
15000     }
15001     return;
15002   }
15003 
15004   if (index.isUnsigned() || !index.isNegative()) {
15005     // It is possible that the type of the base expression after
15006     // IgnoreParenCasts is incomplete, even though the type of the base
15007     // expression before IgnoreParenCasts is complete (see PR39746 for an
15008     // example). In this case we have no information about whether the array
15009     // access exceeds the array bounds. However we can still diagnose an array
15010     // access which precedes the array bounds.
15011     if (BaseType->isIncompleteType())
15012       return;
15013 
15014     llvm::APInt size = ArrayTy->getSize();
15015     if (!size.isStrictlyPositive())
15016       return;
15017 
15018     if (BaseType != EffectiveType) {
15019       // Make sure we're comparing apples to apples when comparing index to size
15020       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15021       uint64_t array_typesize = Context.getTypeSize(BaseType);
15022       // Handle ptrarith_typesize being zero, such as when casting to void*
15023       if (!ptrarith_typesize) ptrarith_typesize = 1;
15024       if (ptrarith_typesize != array_typesize) {
15025         // There's a cast to a different size type involved
15026         uint64_t ratio = array_typesize / ptrarith_typesize;
15027         // TODO: Be smarter about handling cases where array_typesize is not a
15028         // multiple of ptrarith_typesize
15029         if (ptrarith_typesize * ratio == array_typesize)
15030           size *= llvm::APInt(size.getBitWidth(), ratio);
15031       }
15032     }
15033 
15034     if (size.getBitWidth() > index.getBitWidth())
15035       index = index.zext(size.getBitWidth());
15036     else if (size.getBitWidth() < index.getBitWidth())
15037       size = size.zext(index.getBitWidth());
15038 
15039     // For array subscripting the index must be less than size, but for pointer
15040     // arithmetic also allow the index (offset) to be equal to size since
15041     // computing the next address after the end of the array is legal and
15042     // commonly done e.g. in C++ iterators and range-based for loops.
15043     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15044       return;
15045 
15046     // Also don't warn for arrays of size 1 which are members of some
15047     // structure. These are often used to approximate flexible arrays in C89
15048     // code.
15049     if (IsTailPaddedMemberArray(*this, size, ND))
15050       return;
15051 
15052     // Suppress the warning if the subscript expression (as identified by the
15053     // ']' location) and the index expression are both from macro expansions
15054     // within a system header.
15055     if (ASE) {
15056       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15057           ASE->getRBracketLoc());
15058       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15059         SourceLocation IndexLoc =
15060             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15061         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15062           return;
15063       }
15064     }
15065 
15066     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15067                           : diag::warn_ptr_arith_exceeds_bounds;
15068 
15069     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15070                         PDiag(DiagID) << toString(index, 10, true)
15071                                       << toString(size, 10, true)
15072                                       << (unsigned)size.getLimitedValue(~0U)
15073                                       << IndexExpr->getSourceRange());
15074   } else {
15075     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15076     if (!ASE) {
15077       DiagID = diag::warn_ptr_arith_precedes_bounds;
15078       if (index.isNegative()) index = -index;
15079     }
15080 
15081     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15082                         PDiag(DiagID) << toString(index, 10, true)
15083                                       << IndexExpr->getSourceRange());
15084   }
15085 
15086   if (!ND) {
15087     // Try harder to find a NamedDecl to point at in the note.
15088     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15089       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15090     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15091       ND = DRE->getDecl();
15092     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15093       ND = ME->getMemberDecl();
15094   }
15095 
15096   if (ND)
15097     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15098                         PDiag(diag::note_array_declared_here) << ND);
15099 }
15100 
15101 void Sema::CheckArrayAccess(const Expr *expr) {
15102   int AllowOnePastEnd = 0;
15103   while (expr) {
15104     expr = expr->IgnoreParenImpCasts();
15105     switch (expr->getStmtClass()) {
15106       case Stmt::ArraySubscriptExprClass: {
15107         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15108         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15109                          AllowOnePastEnd > 0);
15110         expr = ASE->getBase();
15111         break;
15112       }
15113       case Stmt::MemberExprClass: {
15114         expr = cast<MemberExpr>(expr)->getBase();
15115         break;
15116       }
15117       case Stmt::OMPArraySectionExprClass: {
15118         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15119         if (ASE->getLowerBound())
15120           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15121                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15122         return;
15123       }
15124       case Stmt::UnaryOperatorClass: {
15125         // Only unwrap the * and & unary operators
15126         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15127         expr = UO->getSubExpr();
15128         switch (UO->getOpcode()) {
15129           case UO_AddrOf:
15130             AllowOnePastEnd++;
15131             break;
15132           case UO_Deref:
15133             AllowOnePastEnd--;
15134             break;
15135           default:
15136             return;
15137         }
15138         break;
15139       }
15140       case Stmt::ConditionalOperatorClass: {
15141         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15142         if (const Expr *lhs = cond->getLHS())
15143           CheckArrayAccess(lhs);
15144         if (const Expr *rhs = cond->getRHS())
15145           CheckArrayAccess(rhs);
15146         return;
15147       }
15148       case Stmt::CXXOperatorCallExprClass: {
15149         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15150         for (const auto *Arg : OCE->arguments())
15151           CheckArrayAccess(Arg);
15152         return;
15153       }
15154       default:
15155         return;
15156     }
15157   }
15158 }
15159 
15160 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15161 
15162 namespace {
15163 
15164 struct RetainCycleOwner {
15165   VarDecl *Variable = nullptr;
15166   SourceRange Range;
15167   SourceLocation Loc;
15168   bool Indirect = false;
15169 
15170   RetainCycleOwner() = default;
15171 
15172   void setLocsFrom(Expr *e) {
15173     Loc = e->getExprLoc();
15174     Range = e->getSourceRange();
15175   }
15176 };
15177 
15178 } // namespace
15179 
15180 /// Consider whether capturing the given variable can possibly lead to
15181 /// a retain cycle.
15182 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15183   // In ARC, it's captured strongly iff the variable has __strong
15184   // lifetime.  In MRR, it's captured strongly if the variable is
15185   // __block and has an appropriate type.
15186   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15187     return false;
15188 
15189   owner.Variable = var;
15190   if (ref)
15191     owner.setLocsFrom(ref);
15192   return true;
15193 }
15194 
15195 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15196   while (true) {
15197     e = e->IgnoreParens();
15198     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15199       switch (cast->getCastKind()) {
15200       case CK_BitCast:
15201       case CK_LValueBitCast:
15202       case CK_LValueToRValue:
15203       case CK_ARCReclaimReturnedObject:
15204         e = cast->getSubExpr();
15205         continue;
15206 
15207       default:
15208         return false;
15209       }
15210     }
15211 
15212     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15213       ObjCIvarDecl *ivar = ref->getDecl();
15214       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15215         return false;
15216 
15217       // Try to find a retain cycle in the base.
15218       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15219         return false;
15220 
15221       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15222       owner.Indirect = true;
15223       return true;
15224     }
15225 
15226     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15227       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15228       if (!var) return false;
15229       return considerVariable(var, ref, owner);
15230     }
15231 
15232     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15233       if (member->isArrow()) return false;
15234 
15235       // Don't count this as an indirect ownership.
15236       e = member->getBase();
15237       continue;
15238     }
15239 
15240     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15241       // Only pay attention to pseudo-objects on property references.
15242       ObjCPropertyRefExpr *pre
15243         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15244                                               ->IgnoreParens());
15245       if (!pre) return false;
15246       if (pre->isImplicitProperty()) return false;
15247       ObjCPropertyDecl *property = pre->getExplicitProperty();
15248       if (!property->isRetaining() &&
15249           !(property->getPropertyIvarDecl() &&
15250             property->getPropertyIvarDecl()->getType()
15251               .getObjCLifetime() == Qualifiers::OCL_Strong))
15252           return false;
15253 
15254       owner.Indirect = true;
15255       if (pre->isSuperReceiver()) {
15256         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15257         if (!owner.Variable)
15258           return false;
15259         owner.Loc = pre->getLocation();
15260         owner.Range = pre->getSourceRange();
15261         return true;
15262       }
15263       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15264                               ->getSourceExpr());
15265       continue;
15266     }
15267 
15268     // Array ivars?
15269 
15270     return false;
15271   }
15272 }
15273 
15274 namespace {
15275 
15276   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15277     ASTContext &Context;
15278     VarDecl *Variable;
15279     Expr *Capturer = nullptr;
15280     bool VarWillBeReased = false;
15281 
15282     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15283         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15284           Context(Context), Variable(variable) {}
15285 
15286     void VisitDeclRefExpr(DeclRefExpr *ref) {
15287       if (ref->getDecl() == Variable && !Capturer)
15288         Capturer = ref;
15289     }
15290 
15291     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15292       if (Capturer) return;
15293       Visit(ref->getBase());
15294       if (Capturer && ref->isFreeIvar())
15295         Capturer = ref;
15296     }
15297 
15298     void VisitBlockExpr(BlockExpr *block) {
15299       // Look inside nested blocks
15300       if (block->getBlockDecl()->capturesVariable(Variable))
15301         Visit(block->getBlockDecl()->getBody());
15302     }
15303 
15304     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15305       if (Capturer) return;
15306       if (OVE->getSourceExpr())
15307         Visit(OVE->getSourceExpr());
15308     }
15309 
15310     void VisitBinaryOperator(BinaryOperator *BinOp) {
15311       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15312         return;
15313       Expr *LHS = BinOp->getLHS();
15314       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15315         if (DRE->getDecl() != Variable)
15316           return;
15317         if (Expr *RHS = BinOp->getRHS()) {
15318           RHS = RHS->IgnoreParenCasts();
15319           Optional<llvm::APSInt> Value;
15320           VarWillBeReased =
15321               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15322                *Value == 0);
15323         }
15324       }
15325     }
15326   };
15327 
15328 } // namespace
15329 
15330 /// Check whether the given argument is a block which captures a
15331 /// variable.
15332 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15333   assert(owner.Variable && owner.Loc.isValid());
15334 
15335   e = e->IgnoreParenCasts();
15336 
15337   // Look through [^{...} copy] and Block_copy(^{...}).
15338   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15339     Selector Cmd = ME->getSelector();
15340     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15341       e = ME->getInstanceReceiver();
15342       if (!e)
15343         return nullptr;
15344       e = e->IgnoreParenCasts();
15345     }
15346   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15347     if (CE->getNumArgs() == 1) {
15348       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15349       if (Fn) {
15350         const IdentifierInfo *FnI = Fn->getIdentifier();
15351         if (FnI && FnI->isStr("_Block_copy")) {
15352           e = CE->getArg(0)->IgnoreParenCasts();
15353         }
15354       }
15355     }
15356   }
15357 
15358   BlockExpr *block = dyn_cast<BlockExpr>(e);
15359   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15360     return nullptr;
15361 
15362   FindCaptureVisitor visitor(S.Context, owner.Variable);
15363   visitor.Visit(block->getBlockDecl()->getBody());
15364   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15365 }
15366 
15367 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15368                                 RetainCycleOwner &owner) {
15369   assert(capturer);
15370   assert(owner.Variable && owner.Loc.isValid());
15371 
15372   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15373     << owner.Variable << capturer->getSourceRange();
15374   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15375     << owner.Indirect << owner.Range;
15376 }
15377 
15378 /// Check for a keyword selector that starts with the word 'add' or
15379 /// 'set'.
15380 static bool isSetterLikeSelector(Selector sel) {
15381   if (sel.isUnarySelector()) return false;
15382 
15383   StringRef str = sel.getNameForSlot(0);
15384   while (!str.empty() && str.front() == '_') str = str.substr(1);
15385   if (str.startswith("set"))
15386     str = str.substr(3);
15387   else if (str.startswith("add")) {
15388     // Specially allow 'addOperationWithBlock:'.
15389     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15390       return false;
15391     str = str.substr(3);
15392   }
15393   else
15394     return false;
15395 
15396   if (str.empty()) return true;
15397   return !isLowercase(str.front());
15398 }
15399 
15400 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15401                                                     ObjCMessageExpr *Message) {
15402   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15403                                                 Message->getReceiverInterface(),
15404                                                 NSAPI::ClassId_NSMutableArray);
15405   if (!IsMutableArray) {
15406     return None;
15407   }
15408 
15409   Selector Sel = Message->getSelector();
15410 
15411   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15412     S.NSAPIObj->getNSArrayMethodKind(Sel);
15413   if (!MKOpt) {
15414     return None;
15415   }
15416 
15417   NSAPI::NSArrayMethodKind MK = *MKOpt;
15418 
15419   switch (MK) {
15420     case NSAPI::NSMutableArr_addObject:
15421     case NSAPI::NSMutableArr_insertObjectAtIndex:
15422     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15423       return 0;
15424     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15425       return 1;
15426 
15427     default:
15428       return None;
15429   }
15430 
15431   return None;
15432 }
15433 
15434 static
15435 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15436                                                   ObjCMessageExpr *Message) {
15437   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15438                                             Message->getReceiverInterface(),
15439                                             NSAPI::ClassId_NSMutableDictionary);
15440   if (!IsMutableDictionary) {
15441     return None;
15442   }
15443 
15444   Selector Sel = Message->getSelector();
15445 
15446   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15447     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15448   if (!MKOpt) {
15449     return None;
15450   }
15451 
15452   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15453 
15454   switch (MK) {
15455     case NSAPI::NSMutableDict_setObjectForKey:
15456     case NSAPI::NSMutableDict_setValueForKey:
15457     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15458       return 0;
15459 
15460     default:
15461       return None;
15462   }
15463 
15464   return None;
15465 }
15466 
15467 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15468   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15469                                                 Message->getReceiverInterface(),
15470                                                 NSAPI::ClassId_NSMutableSet);
15471 
15472   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15473                                             Message->getReceiverInterface(),
15474                                             NSAPI::ClassId_NSMutableOrderedSet);
15475   if (!IsMutableSet && !IsMutableOrderedSet) {
15476     return None;
15477   }
15478 
15479   Selector Sel = Message->getSelector();
15480 
15481   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15482   if (!MKOpt) {
15483     return None;
15484   }
15485 
15486   NSAPI::NSSetMethodKind MK = *MKOpt;
15487 
15488   switch (MK) {
15489     case NSAPI::NSMutableSet_addObject:
15490     case NSAPI::NSOrderedSet_setObjectAtIndex:
15491     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15492     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15493       return 0;
15494     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15495       return 1;
15496   }
15497 
15498   return None;
15499 }
15500 
15501 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15502   if (!Message->isInstanceMessage()) {
15503     return;
15504   }
15505 
15506   Optional<int> ArgOpt;
15507 
15508   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15509       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15510       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15511     return;
15512   }
15513 
15514   int ArgIndex = *ArgOpt;
15515 
15516   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15517   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15518     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15519   }
15520 
15521   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15522     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15523       if (ArgRE->isObjCSelfExpr()) {
15524         Diag(Message->getSourceRange().getBegin(),
15525              diag::warn_objc_circular_container)
15526           << ArgRE->getDecl() << StringRef("'super'");
15527       }
15528     }
15529   } else {
15530     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15531 
15532     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15533       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15534     }
15535 
15536     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15537       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15538         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15539           ValueDecl *Decl = ReceiverRE->getDecl();
15540           Diag(Message->getSourceRange().getBegin(),
15541                diag::warn_objc_circular_container)
15542             << Decl << Decl;
15543           if (!ArgRE->isObjCSelfExpr()) {
15544             Diag(Decl->getLocation(),
15545                  diag::note_objc_circular_container_declared_here)
15546               << Decl;
15547           }
15548         }
15549       }
15550     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15551       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15552         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15553           ObjCIvarDecl *Decl = IvarRE->getDecl();
15554           Diag(Message->getSourceRange().getBegin(),
15555                diag::warn_objc_circular_container)
15556             << Decl << Decl;
15557           Diag(Decl->getLocation(),
15558                diag::note_objc_circular_container_declared_here)
15559             << Decl;
15560         }
15561       }
15562     }
15563   }
15564 }
15565 
15566 /// Check a message send to see if it's likely to cause a retain cycle.
15567 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15568   // Only check instance methods whose selector looks like a setter.
15569   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15570     return;
15571 
15572   // Try to find a variable that the receiver is strongly owned by.
15573   RetainCycleOwner owner;
15574   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15575     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15576       return;
15577   } else {
15578     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15579     owner.Variable = getCurMethodDecl()->getSelfDecl();
15580     owner.Loc = msg->getSuperLoc();
15581     owner.Range = msg->getSuperLoc();
15582   }
15583 
15584   // Check whether the receiver is captured by any of the arguments.
15585   const ObjCMethodDecl *MD = msg->getMethodDecl();
15586   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15587     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15588       // noescape blocks should not be retained by the method.
15589       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15590         continue;
15591       return diagnoseRetainCycle(*this, capturer, owner);
15592     }
15593   }
15594 }
15595 
15596 /// Check a property assign to see if it's likely to cause a retain cycle.
15597 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15598   RetainCycleOwner owner;
15599   if (!findRetainCycleOwner(*this, receiver, owner))
15600     return;
15601 
15602   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15603     diagnoseRetainCycle(*this, capturer, owner);
15604 }
15605 
15606 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15607   RetainCycleOwner Owner;
15608   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15609     return;
15610 
15611   // Because we don't have an expression for the variable, we have to set the
15612   // location explicitly here.
15613   Owner.Loc = Var->getLocation();
15614   Owner.Range = Var->getSourceRange();
15615 
15616   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15617     diagnoseRetainCycle(*this, Capturer, Owner);
15618 }
15619 
15620 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15621                                      Expr *RHS, bool isProperty) {
15622   // Check if RHS is an Objective-C object literal, which also can get
15623   // immediately zapped in a weak reference.  Note that we explicitly
15624   // allow ObjCStringLiterals, since those are designed to never really die.
15625   RHS = RHS->IgnoreParenImpCasts();
15626 
15627   // This enum needs to match with the 'select' in
15628   // warn_objc_arc_literal_assign (off-by-1).
15629   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15630   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15631     return false;
15632 
15633   S.Diag(Loc, diag::warn_arc_literal_assign)
15634     << (unsigned) Kind
15635     << (isProperty ? 0 : 1)
15636     << RHS->getSourceRange();
15637 
15638   return true;
15639 }
15640 
15641 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15642                                     Qualifiers::ObjCLifetime LT,
15643                                     Expr *RHS, bool isProperty) {
15644   // Strip off any implicit cast added to get to the one ARC-specific.
15645   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15646     if (cast->getCastKind() == CK_ARCConsumeObject) {
15647       S.Diag(Loc, diag::warn_arc_retained_assign)
15648         << (LT == Qualifiers::OCL_ExplicitNone)
15649         << (isProperty ? 0 : 1)
15650         << RHS->getSourceRange();
15651       return true;
15652     }
15653     RHS = cast->getSubExpr();
15654   }
15655 
15656   if (LT == Qualifiers::OCL_Weak &&
15657       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15658     return true;
15659 
15660   return false;
15661 }
15662 
15663 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15664                               QualType LHS, Expr *RHS) {
15665   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15666 
15667   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15668     return false;
15669 
15670   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15671     return true;
15672 
15673   return false;
15674 }
15675 
15676 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15677                               Expr *LHS, Expr *RHS) {
15678   QualType LHSType;
15679   // PropertyRef on LHS type need be directly obtained from
15680   // its declaration as it has a PseudoType.
15681   ObjCPropertyRefExpr *PRE
15682     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15683   if (PRE && !PRE->isImplicitProperty()) {
15684     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15685     if (PD)
15686       LHSType = PD->getType();
15687   }
15688 
15689   if (LHSType.isNull())
15690     LHSType = LHS->getType();
15691 
15692   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15693 
15694   if (LT == Qualifiers::OCL_Weak) {
15695     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15696       getCurFunction()->markSafeWeakUse(LHS);
15697   }
15698 
15699   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15700     return;
15701 
15702   // FIXME. Check for other life times.
15703   if (LT != Qualifiers::OCL_None)
15704     return;
15705 
15706   if (PRE) {
15707     if (PRE->isImplicitProperty())
15708       return;
15709     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15710     if (!PD)
15711       return;
15712 
15713     unsigned Attributes = PD->getPropertyAttributes();
15714     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15715       // when 'assign' attribute was not explicitly specified
15716       // by user, ignore it and rely on property type itself
15717       // for lifetime info.
15718       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15719       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15720           LHSType->isObjCRetainableType())
15721         return;
15722 
15723       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15724         if (cast->getCastKind() == CK_ARCConsumeObject) {
15725           Diag(Loc, diag::warn_arc_retained_property_assign)
15726           << RHS->getSourceRange();
15727           return;
15728         }
15729         RHS = cast->getSubExpr();
15730       }
15731     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15732       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15733         return;
15734     }
15735   }
15736 }
15737 
15738 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15739 
15740 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15741                                         SourceLocation StmtLoc,
15742                                         const NullStmt *Body) {
15743   // Do not warn if the body is a macro that expands to nothing, e.g:
15744   //
15745   // #define CALL(x)
15746   // if (condition)
15747   //   CALL(0);
15748   if (Body->hasLeadingEmptyMacro())
15749     return false;
15750 
15751   // Get line numbers of statement and body.
15752   bool StmtLineInvalid;
15753   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15754                                                       &StmtLineInvalid);
15755   if (StmtLineInvalid)
15756     return false;
15757 
15758   bool BodyLineInvalid;
15759   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15760                                                       &BodyLineInvalid);
15761   if (BodyLineInvalid)
15762     return false;
15763 
15764   // Warn if null statement and body are on the same line.
15765   if (StmtLine != BodyLine)
15766     return false;
15767 
15768   return true;
15769 }
15770 
15771 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15772                                  const Stmt *Body,
15773                                  unsigned DiagID) {
15774   // Since this is a syntactic check, don't emit diagnostic for template
15775   // instantiations, this just adds noise.
15776   if (CurrentInstantiationScope)
15777     return;
15778 
15779   // The body should be a null statement.
15780   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15781   if (!NBody)
15782     return;
15783 
15784   // Do the usual checks.
15785   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15786     return;
15787 
15788   Diag(NBody->getSemiLoc(), DiagID);
15789   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15790 }
15791 
15792 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15793                                  const Stmt *PossibleBody) {
15794   assert(!CurrentInstantiationScope); // Ensured by caller
15795 
15796   SourceLocation StmtLoc;
15797   const Stmt *Body;
15798   unsigned DiagID;
15799   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15800     StmtLoc = FS->getRParenLoc();
15801     Body = FS->getBody();
15802     DiagID = diag::warn_empty_for_body;
15803   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15804     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15805     Body = WS->getBody();
15806     DiagID = diag::warn_empty_while_body;
15807   } else
15808     return; // Neither `for' nor `while'.
15809 
15810   // The body should be a null statement.
15811   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15812   if (!NBody)
15813     return;
15814 
15815   // Skip expensive checks if diagnostic is disabled.
15816   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15817     return;
15818 
15819   // Do the usual checks.
15820   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15821     return;
15822 
15823   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15824   // noise level low, emit diagnostics only if for/while is followed by a
15825   // CompoundStmt, e.g.:
15826   //    for (int i = 0; i < n; i++);
15827   //    {
15828   //      a(i);
15829   //    }
15830   // or if for/while is followed by a statement with more indentation
15831   // than for/while itself:
15832   //    for (int i = 0; i < n; i++);
15833   //      a(i);
15834   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15835   if (!ProbableTypo) {
15836     bool BodyColInvalid;
15837     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15838         PossibleBody->getBeginLoc(), &BodyColInvalid);
15839     if (BodyColInvalid)
15840       return;
15841 
15842     bool StmtColInvalid;
15843     unsigned StmtCol =
15844         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15845     if (StmtColInvalid)
15846       return;
15847 
15848     if (BodyCol > StmtCol)
15849       ProbableTypo = true;
15850   }
15851 
15852   if (ProbableTypo) {
15853     Diag(NBody->getSemiLoc(), DiagID);
15854     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15855   }
15856 }
15857 
15858 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15859 
15860 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15861 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15862                              SourceLocation OpLoc) {
15863   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15864     return;
15865 
15866   if (inTemplateInstantiation())
15867     return;
15868 
15869   // Strip parens and casts away.
15870   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15871   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15872 
15873   // Check for a call expression
15874   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15875   if (!CE || CE->getNumArgs() != 1)
15876     return;
15877 
15878   // Check for a call to std::move
15879   if (!CE->isCallToStdMove())
15880     return;
15881 
15882   // Get argument from std::move
15883   RHSExpr = CE->getArg(0);
15884 
15885   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15886   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15887 
15888   // Two DeclRefExpr's, check that the decls are the same.
15889   if (LHSDeclRef && RHSDeclRef) {
15890     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15891       return;
15892     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15893         RHSDeclRef->getDecl()->getCanonicalDecl())
15894       return;
15895 
15896     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15897                                         << LHSExpr->getSourceRange()
15898                                         << RHSExpr->getSourceRange();
15899     return;
15900   }
15901 
15902   // Member variables require a different approach to check for self moves.
15903   // MemberExpr's are the same if every nested MemberExpr refers to the same
15904   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15905   // the base Expr's are CXXThisExpr's.
15906   const Expr *LHSBase = LHSExpr;
15907   const Expr *RHSBase = RHSExpr;
15908   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15909   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15910   if (!LHSME || !RHSME)
15911     return;
15912 
15913   while (LHSME && RHSME) {
15914     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15915         RHSME->getMemberDecl()->getCanonicalDecl())
15916       return;
15917 
15918     LHSBase = LHSME->getBase();
15919     RHSBase = RHSME->getBase();
15920     LHSME = dyn_cast<MemberExpr>(LHSBase);
15921     RHSME = dyn_cast<MemberExpr>(RHSBase);
15922   }
15923 
15924   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15925   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15926   if (LHSDeclRef && RHSDeclRef) {
15927     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15928       return;
15929     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15930         RHSDeclRef->getDecl()->getCanonicalDecl())
15931       return;
15932 
15933     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15934                                         << LHSExpr->getSourceRange()
15935                                         << RHSExpr->getSourceRange();
15936     return;
15937   }
15938 
15939   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15940     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15941                                         << LHSExpr->getSourceRange()
15942                                         << RHSExpr->getSourceRange();
15943 }
15944 
15945 //===--- Layout compatibility ----------------------------------------------//
15946 
15947 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15948 
15949 /// Check if two enumeration types are layout-compatible.
15950 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15951   // C++11 [dcl.enum] p8:
15952   // Two enumeration types are layout-compatible if they have the same
15953   // underlying type.
15954   return ED1->isComplete() && ED2->isComplete() &&
15955          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15956 }
15957 
15958 /// Check if two fields are layout-compatible.
15959 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15960                                FieldDecl *Field2) {
15961   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15962     return false;
15963 
15964   if (Field1->isBitField() != Field2->isBitField())
15965     return false;
15966 
15967   if (Field1->isBitField()) {
15968     // Make sure that the bit-fields are the same length.
15969     unsigned Bits1 = Field1->getBitWidthValue(C);
15970     unsigned Bits2 = Field2->getBitWidthValue(C);
15971 
15972     if (Bits1 != Bits2)
15973       return false;
15974   }
15975 
15976   return true;
15977 }
15978 
15979 /// Check if two standard-layout structs are layout-compatible.
15980 /// (C++11 [class.mem] p17)
15981 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15982                                      RecordDecl *RD2) {
15983   // If both records are C++ classes, check that base classes match.
15984   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15985     // If one of records is a CXXRecordDecl we are in C++ mode,
15986     // thus the other one is a CXXRecordDecl, too.
15987     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15988     // Check number of base classes.
15989     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15990       return false;
15991 
15992     // Check the base classes.
15993     for (CXXRecordDecl::base_class_const_iterator
15994                Base1 = D1CXX->bases_begin(),
15995            BaseEnd1 = D1CXX->bases_end(),
15996               Base2 = D2CXX->bases_begin();
15997          Base1 != BaseEnd1;
15998          ++Base1, ++Base2) {
15999       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16000         return false;
16001     }
16002   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16003     // If only RD2 is a C++ class, it should have zero base classes.
16004     if (D2CXX->getNumBases() > 0)
16005       return false;
16006   }
16007 
16008   // Check the fields.
16009   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16010                              Field2End = RD2->field_end(),
16011                              Field1 = RD1->field_begin(),
16012                              Field1End = RD1->field_end();
16013   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16014     if (!isLayoutCompatible(C, *Field1, *Field2))
16015       return false;
16016   }
16017   if (Field1 != Field1End || Field2 != Field2End)
16018     return false;
16019 
16020   return true;
16021 }
16022 
16023 /// Check if two standard-layout unions are layout-compatible.
16024 /// (C++11 [class.mem] p18)
16025 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16026                                     RecordDecl *RD2) {
16027   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16028   for (auto *Field2 : RD2->fields())
16029     UnmatchedFields.insert(Field2);
16030 
16031   for (auto *Field1 : RD1->fields()) {
16032     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16033         I = UnmatchedFields.begin(),
16034         E = UnmatchedFields.end();
16035 
16036     for ( ; I != E; ++I) {
16037       if (isLayoutCompatible(C, Field1, *I)) {
16038         bool Result = UnmatchedFields.erase(*I);
16039         (void) Result;
16040         assert(Result);
16041         break;
16042       }
16043     }
16044     if (I == E)
16045       return false;
16046   }
16047 
16048   return UnmatchedFields.empty();
16049 }
16050 
16051 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16052                                RecordDecl *RD2) {
16053   if (RD1->isUnion() != RD2->isUnion())
16054     return false;
16055 
16056   if (RD1->isUnion())
16057     return isLayoutCompatibleUnion(C, RD1, RD2);
16058   else
16059     return isLayoutCompatibleStruct(C, RD1, RD2);
16060 }
16061 
16062 /// Check if two types are layout-compatible in C++11 sense.
16063 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16064   if (T1.isNull() || T2.isNull())
16065     return false;
16066 
16067   // C++11 [basic.types] p11:
16068   // If two types T1 and T2 are the same type, then T1 and T2 are
16069   // layout-compatible types.
16070   if (C.hasSameType(T1, T2))
16071     return true;
16072 
16073   T1 = T1.getCanonicalType().getUnqualifiedType();
16074   T2 = T2.getCanonicalType().getUnqualifiedType();
16075 
16076   const Type::TypeClass TC1 = T1->getTypeClass();
16077   const Type::TypeClass TC2 = T2->getTypeClass();
16078 
16079   if (TC1 != TC2)
16080     return false;
16081 
16082   if (TC1 == Type::Enum) {
16083     return isLayoutCompatible(C,
16084                               cast<EnumType>(T1)->getDecl(),
16085                               cast<EnumType>(T2)->getDecl());
16086   } else if (TC1 == Type::Record) {
16087     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16088       return false;
16089 
16090     return isLayoutCompatible(C,
16091                               cast<RecordType>(T1)->getDecl(),
16092                               cast<RecordType>(T2)->getDecl());
16093   }
16094 
16095   return false;
16096 }
16097 
16098 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16099 
16100 /// Given a type tag expression find the type tag itself.
16101 ///
16102 /// \param TypeExpr Type tag expression, as it appears in user's code.
16103 ///
16104 /// \param VD Declaration of an identifier that appears in a type tag.
16105 ///
16106 /// \param MagicValue Type tag magic value.
16107 ///
16108 /// \param isConstantEvaluated whether the evalaution should be performed in
16109 
16110 /// constant context.
16111 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16112                             const ValueDecl **VD, uint64_t *MagicValue,
16113                             bool isConstantEvaluated) {
16114   while(true) {
16115     if (!TypeExpr)
16116       return false;
16117 
16118     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16119 
16120     switch (TypeExpr->getStmtClass()) {
16121     case Stmt::UnaryOperatorClass: {
16122       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16123       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16124         TypeExpr = UO->getSubExpr();
16125         continue;
16126       }
16127       return false;
16128     }
16129 
16130     case Stmt::DeclRefExprClass: {
16131       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16132       *VD = DRE->getDecl();
16133       return true;
16134     }
16135 
16136     case Stmt::IntegerLiteralClass: {
16137       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16138       llvm::APInt MagicValueAPInt = IL->getValue();
16139       if (MagicValueAPInt.getActiveBits() <= 64) {
16140         *MagicValue = MagicValueAPInt.getZExtValue();
16141         return true;
16142       } else
16143         return false;
16144     }
16145 
16146     case Stmt::BinaryConditionalOperatorClass:
16147     case Stmt::ConditionalOperatorClass: {
16148       const AbstractConditionalOperator *ACO =
16149           cast<AbstractConditionalOperator>(TypeExpr);
16150       bool Result;
16151       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16152                                                      isConstantEvaluated)) {
16153         if (Result)
16154           TypeExpr = ACO->getTrueExpr();
16155         else
16156           TypeExpr = ACO->getFalseExpr();
16157         continue;
16158       }
16159       return false;
16160     }
16161 
16162     case Stmt::BinaryOperatorClass: {
16163       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16164       if (BO->getOpcode() == BO_Comma) {
16165         TypeExpr = BO->getRHS();
16166         continue;
16167       }
16168       return false;
16169     }
16170 
16171     default:
16172       return false;
16173     }
16174   }
16175 }
16176 
16177 /// Retrieve the C type corresponding to type tag TypeExpr.
16178 ///
16179 /// \param TypeExpr Expression that specifies a type tag.
16180 ///
16181 /// \param MagicValues Registered magic values.
16182 ///
16183 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16184 ///        kind.
16185 ///
16186 /// \param TypeInfo Information about the corresponding C type.
16187 ///
16188 /// \param isConstantEvaluated whether the evalaution should be performed in
16189 /// constant context.
16190 ///
16191 /// \returns true if the corresponding C type was found.
16192 static bool GetMatchingCType(
16193     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16194     const ASTContext &Ctx,
16195     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16196         *MagicValues,
16197     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16198     bool isConstantEvaluated) {
16199   FoundWrongKind = false;
16200 
16201   // Variable declaration that has type_tag_for_datatype attribute.
16202   const ValueDecl *VD = nullptr;
16203 
16204   uint64_t MagicValue;
16205 
16206   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16207     return false;
16208 
16209   if (VD) {
16210     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16211       if (I->getArgumentKind() != ArgumentKind) {
16212         FoundWrongKind = true;
16213         return false;
16214       }
16215       TypeInfo.Type = I->getMatchingCType();
16216       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16217       TypeInfo.MustBeNull = I->getMustBeNull();
16218       return true;
16219     }
16220     return false;
16221   }
16222 
16223   if (!MagicValues)
16224     return false;
16225 
16226   llvm::DenseMap<Sema::TypeTagMagicValue,
16227                  Sema::TypeTagData>::const_iterator I =
16228       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16229   if (I == MagicValues->end())
16230     return false;
16231 
16232   TypeInfo = I->second;
16233   return true;
16234 }
16235 
16236 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16237                                       uint64_t MagicValue, QualType Type,
16238                                       bool LayoutCompatible,
16239                                       bool MustBeNull) {
16240   if (!TypeTagForDatatypeMagicValues)
16241     TypeTagForDatatypeMagicValues.reset(
16242         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16243 
16244   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16245   (*TypeTagForDatatypeMagicValues)[Magic] =
16246       TypeTagData(Type, LayoutCompatible, MustBeNull);
16247 }
16248 
16249 static bool IsSameCharType(QualType T1, QualType T2) {
16250   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16251   if (!BT1)
16252     return false;
16253 
16254   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16255   if (!BT2)
16256     return false;
16257 
16258   BuiltinType::Kind T1Kind = BT1->getKind();
16259   BuiltinType::Kind T2Kind = BT2->getKind();
16260 
16261   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16262          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16263          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16264          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16265 }
16266 
16267 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16268                                     const ArrayRef<const Expr *> ExprArgs,
16269                                     SourceLocation CallSiteLoc) {
16270   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16271   bool IsPointerAttr = Attr->getIsPointer();
16272 
16273   // Retrieve the argument representing the 'type_tag'.
16274   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16275   if (TypeTagIdxAST >= ExprArgs.size()) {
16276     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16277         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16278     return;
16279   }
16280   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16281   bool FoundWrongKind;
16282   TypeTagData TypeInfo;
16283   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16284                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16285                         TypeInfo, isConstantEvaluated())) {
16286     if (FoundWrongKind)
16287       Diag(TypeTagExpr->getExprLoc(),
16288            diag::warn_type_tag_for_datatype_wrong_kind)
16289         << TypeTagExpr->getSourceRange();
16290     return;
16291   }
16292 
16293   // Retrieve the argument representing the 'arg_idx'.
16294   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16295   if (ArgumentIdxAST >= ExprArgs.size()) {
16296     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16297         << 1 << Attr->getArgumentIdx().getSourceIndex();
16298     return;
16299   }
16300   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16301   if (IsPointerAttr) {
16302     // Skip implicit cast of pointer to `void *' (as a function argument).
16303     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16304       if (ICE->getType()->isVoidPointerType() &&
16305           ICE->getCastKind() == CK_BitCast)
16306         ArgumentExpr = ICE->getSubExpr();
16307   }
16308   QualType ArgumentType = ArgumentExpr->getType();
16309 
16310   // Passing a `void*' pointer shouldn't trigger a warning.
16311   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16312     return;
16313 
16314   if (TypeInfo.MustBeNull) {
16315     // Type tag with matching void type requires a null pointer.
16316     if (!ArgumentExpr->isNullPointerConstant(Context,
16317                                              Expr::NPC_ValueDependentIsNotNull)) {
16318       Diag(ArgumentExpr->getExprLoc(),
16319            diag::warn_type_safety_null_pointer_required)
16320           << ArgumentKind->getName()
16321           << ArgumentExpr->getSourceRange()
16322           << TypeTagExpr->getSourceRange();
16323     }
16324     return;
16325   }
16326 
16327   QualType RequiredType = TypeInfo.Type;
16328   if (IsPointerAttr)
16329     RequiredType = Context.getPointerType(RequiredType);
16330 
16331   bool mismatch = false;
16332   if (!TypeInfo.LayoutCompatible) {
16333     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16334 
16335     // C++11 [basic.fundamental] p1:
16336     // Plain char, signed char, and unsigned char are three distinct types.
16337     //
16338     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16339     // char' depending on the current char signedness mode.
16340     if (mismatch)
16341       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16342                                            RequiredType->getPointeeType())) ||
16343           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16344         mismatch = false;
16345   } else
16346     if (IsPointerAttr)
16347       mismatch = !isLayoutCompatible(Context,
16348                                      ArgumentType->getPointeeType(),
16349                                      RequiredType->getPointeeType());
16350     else
16351       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16352 
16353   if (mismatch)
16354     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16355         << ArgumentType << ArgumentKind
16356         << TypeInfo.LayoutCompatible << RequiredType
16357         << ArgumentExpr->getSourceRange()
16358         << TypeTagExpr->getSourceRange();
16359 }
16360 
16361 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16362                                          CharUnits Alignment) {
16363   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16364 }
16365 
16366 void Sema::DiagnoseMisalignedMembers() {
16367   for (MisalignedMember &m : MisalignedMembers) {
16368     const NamedDecl *ND = m.RD;
16369     if (ND->getName().empty()) {
16370       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16371         ND = TD;
16372     }
16373     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16374         << m.MD << ND << m.E->getSourceRange();
16375   }
16376   MisalignedMembers.clear();
16377 }
16378 
16379 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16380   E = E->IgnoreParens();
16381   if (!T->isPointerType() && !T->isIntegerType())
16382     return;
16383   if (isa<UnaryOperator>(E) &&
16384       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16385     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16386     if (isa<MemberExpr>(Op)) {
16387       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16388       if (MA != MisalignedMembers.end() &&
16389           (T->isIntegerType() ||
16390            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16391                                    Context.getTypeAlignInChars(
16392                                        T->getPointeeType()) <= MA->Alignment))))
16393         MisalignedMembers.erase(MA);
16394     }
16395   }
16396 }
16397 
16398 void Sema::RefersToMemberWithReducedAlignment(
16399     Expr *E,
16400     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16401         Action) {
16402   const auto *ME = dyn_cast<MemberExpr>(E);
16403   if (!ME)
16404     return;
16405 
16406   // No need to check expressions with an __unaligned-qualified type.
16407   if (E->getType().getQualifiers().hasUnaligned())
16408     return;
16409 
16410   // For a chain of MemberExpr like "a.b.c.d" this list
16411   // will keep FieldDecl's like [d, c, b].
16412   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16413   const MemberExpr *TopME = nullptr;
16414   bool AnyIsPacked = false;
16415   do {
16416     QualType BaseType = ME->getBase()->getType();
16417     if (BaseType->isDependentType())
16418       return;
16419     if (ME->isArrow())
16420       BaseType = BaseType->getPointeeType();
16421     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16422     if (RD->isInvalidDecl())
16423       return;
16424 
16425     ValueDecl *MD = ME->getMemberDecl();
16426     auto *FD = dyn_cast<FieldDecl>(MD);
16427     // We do not care about non-data members.
16428     if (!FD || FD->isInvalidDecl())
16429       return;
16430 
16431     AnyIsPacked =
16432         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16433     ReverseMemberChain.push_back(FD);
16434 
16435     TopME = ME;
16436     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16437   } while (ME);
16438   assert(TopME && "We did not compute a topmost MemberExpr!");
16439 
16440   // Not the scope of this diagnostic.
16441   if (!AnyIsPacked)
16442     return;
16443 
16444   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16445   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16446   // TODO: The innermost base of the member expression may be too complicated.
16447   // For now, just disregard these cases. This is left for future
16448   // improvement.
16449   if (!DRE && !isa<CXXThisExpr>(TopBase))
16450       return;
16451 
16452   // Alignment expected by the whole expression.
16453   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16454 
16455   // No need to do anything else with this case.
16456   if (ExpectedAlignment.isOne())
16457     return;
16458 
16459   // Synthesize offset of the whole access.
16460   CharUnits Offset;
16461   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16462        I++) {
16463     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16464   }
16465 
16466   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16467   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16468       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16469 
16470   // The base expression of the innermost MemberExpr may give
16471   // stronger guarantees than the class containing the member.
16472   if (DRE && !TopME->isArrow()) {
16473     const ValueDecl *VD = DRE->getDecl();
16474     if (!VD->getType()->isReferenceType())
16475       CompleteObjectAlignment =
16476           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16477   }
16478 
16479   // Check if the synthesized offset fulfills the alignment.
16480   if (Offset % ExpectedAlignment != 0 ||
16481       // It may fulfill the offset it but the effective alignment may still be
16482       // lower than the expected expression alignment.
16483       CompleteObjectAlignment < ExpectedAlignment) {
16484     // If this happens, we want to determine a sensible culprit of this.
16485     // Intuitively, watching the chain of member expressions from right to
16486     // left, we start with the required alignment (as required by the field
16487     // type) but some packed attribute in that chain has reduced the alignment.
16488     // It may happen that another packed structure increases it again. But if
16489     // we are here such increase has not been enough. So pointing the first
16490     // FieldDecl that either is packed or else its RecordDecl is,
16491     // seems reasonable.
16492     FieldDecl *FD = nullptr;
16493     CharUnits Alignment;
16494     for (FieldDecl *FDI : ReverseMemberChain) {
16495       if (FDI->hasAttr<PackedAttr>() ||
16496           FDI->getParent()->hasAttr<PackedAttr>()) {
16497         FD = FDI;
16498         Alignment = std::min(
16499             Context.getTypeAlignInChars(FD->getType()),
16500             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16501         break;
16502       }
16503     }
16504     assert(FD && "We did not find a packed FieldDecl!");
16505     Action(E, FD->getParent(), FD, Alignment);
16506   }
16507 }
16508 
16509 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16510   using namespace std::placeholders;
16511 
16512   RefersToMemberWithReducedAlignment(
16513       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16514                      _2, _3, _4));
16515 }
16516 
16517 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16518                                             ExprResult CallResult) {
16519   if (checkArgCount(*this, TheCall, 1))
16520     return ExprError();
16521 
16522   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16523   if (MatrixArg.isInvalid())
16524     return MatrixArg;
16525   Expr *Matrix = MatrixArg.get();
16526 
16527   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16528   if (!MType) {
16529     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16530     return ExprError();
16531   }
16532 
16533   // Create returned matrix type by swapping rows and columns of the argument
16534   // matrix type.
16535   QualType ResultType = Context.getConstantMatrixType(
16536       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16537 
16538   // Change the return type to the type of the returned matrix.
16539   TheCall->setType(ResultType);
16540 
16541   // Update call argument to use the possibly converted matrix argument.
16542   TheCall->setArg(0, Matrix);
16543   return CallResult;
16544 }
16545 
16546 // Get and verify the matrix dimensions.
16547 static llvm::Optional<unsigned>
16548 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16549   SourceLocation ErrorPos;
16550   Optional<llvm::APSInt> Value =
16551       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16552   if (!Value) {
16553     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16554         << Name;
16555     return {};
16556   }
16557   uint64_t Dim = Value->getZExtValue();
16558   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16559     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16560         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16561     return {};
16562   }
16563   return Dim;
16564 }
16565 
16566 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16567                                                   ExprResult CallResult) {
16568   if (!getLangOpts().MatrixTypes) {
16569     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16570     return ExprError();
16571   }
16572 
16573   if (checkArgCount(*this, TheCall, 4))
16574     return ExprError();
16575 
16576   unsigned PtrArgIdx = 0;
16577   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16578   Expr *RowsExpr = TheCall->getArg(1);
16579   Expr *ColumnsExpr = TheCall->getArg(2);
16580   Expr *StrideExpr = TheCall->getArg(3);
16581 
16582   bool ArgError = false;
16583 
16584   // Check pointer argument.
16585   {
16586     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16587     if (PtrConv.isInvalid())
16588       return PtrConv;
16589     PtrExpr = PtrConv.get();
16590     TheCall->setArg(0, PtrExpr);
16591     if (PtrExpr->isTypeDependent()) {
16592       TheCall->setType(Context.DependentTy);
16593       return TheCall;
16594     }
16595   }
16596 
16597   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16598   QualType ElementTy;
16599   if (!PtrTy) {
16600     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16601         << PtrArgIdx + 1;
16602     ArgError = true;
16603   } else {
16604     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16605 
16606     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16607       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16608           << PtrArgIdx + 1;
16609       ArgError = true;
16610     }
16611   }
16612 
16613   // Apply default Lvalue conversions and convert the expression to size_t.
16614   auto ApplyArgumentConversions = [this](Expr *E) {
16615     ExprResult Conv = DefaultLvalueConversion(E);
16616     if (Conv.isInvalid())
16617       return Conv;
16618 
16619     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16620   };
16621 
16622   // Apply conversion to row and column expressions.
16623   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16624   if (!RowsConv.isInvalid()) {
16625     RowsExpr = RowsConv.get();
16626     TheCall->setArg(1, RowsExpr);
16627   } else
16628     RowsExpr = nullptr;
16629 
16630   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16631   if (!ColumnsConv.isInvalid()) {
16632     ColumnsExpr = ColumnsConv.get();
16633     TheCall->setArg(2, ColumnsExpr);
16634   } else
16635     ColumnsExpr = nullptr;
16636 
16637   // If any any part of the result matrix type is still pending, just use
16638   // Context.DependentTy, until all parts are resolved.
16639   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16640       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16641     TheCall->setType(Context.DependentTy);
16642     return CallResult;
16643   }
16644 
16645   // Check row and column dimenions.
16646   llvm::Optional<unsigned> MaybeRows;
16647   if (RowsExpr)
16648     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16649 
16650   llvm::Optional<unsigned> MaybeColumns;
16651   if (ColumnsExpr)
16652     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16653 
16654   // Check stride argument.
16655   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16656   if (StrideConv.isInvalid())
16657     return ExprError();
16658   StrideExpr = StrideConv.get();
16659   TheCall->setArg(3, StrideExpr);
16660 
16661   if (MaybeRows) {
16662     if (Optional<llvm::APSInt> Value =
16663             StrideExpr->getIntegerConstantExpr(Context)) {
16664       uint64_t Stride = Value->getZExtValue();
16665       if (Stride < *MaybeRows) {
16666         Diag(StrideExpr->getBeginLoc(),
16667              diag::err_builtin_matrix_stride_too_small);
16668         ArgError = true;
16669       }
16670     }
16671   }
16672 
16673   if (ArgError || !MaybeRows || !MaybeColumns)
16674     return ExprError();
16675 
16676   TheCall->setType(
16677       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16678   return CallResult;
16679 }
16680 
16681 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16682                                                    ExprResult CallResult) {
16683   if (checkArgCount(*this, TheCall, 3))
16684     return ExprError();
16685 
16686   unsigned PtrArgIdx = 1;
16687   Expr *MatrixExpr = TheCall->getArg(0);
16688   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16689   Expr *StrideExpr = TheCall->getArg(2);
16690 
16691   bool ArgError = false;
16692 
16693   {
16694     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16695     if (MatrixConv.isInvalid())
16696       return MatrixConv;
16697     MatrixExpr = MatrixConv.get();
16698     TheCall->setArg(0, MatrixExpr);
16699   }
16700   if (MatrixExpr->isTypeDependent()) {
16701     TheCall->setType(Context.DependentTy);
16702     return TheCall;
16703   }
16704 
16705   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16706   if (!MatrixTy) {
16707     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16708     ArgError = true;
16709   }
16710 
16711   {
16712     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16713     if (PtrConv.isInvalid())
16714       return PtrConv;
16715     PtrExpr = PtrConv.get();
16716     TheCall->setArg(1, PtrExpr);
16717     if (PtrExpr->isTypeDependent()) {
16718       TheCall->setType(Context.DependentTy);
16719       return TheCall;
16720     }
16721   }
16722 
16723   // Check pointer argument.
16724   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16725   if (!PtrTy) {
16726     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16727         << PtrArgIdx + 1;
16728     ArgError = true;
16729   } else {
16730     QualType ElementTy = PtrTy->getPointeeType();
16731     if (ElementTy.isConstQualified()) {
16732       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16733       ArgError = true;
16734     }
16735     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16736     if (MatrixTy &&
16737         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16738       Diag(PtrExpr->getBeginLoc(),
16739            diag::err_builtin_matrix_pointer_arg_mismatch)
16740           << ElementTy << MatrixTy->getElementType();
16741       ArgError = true;
16742     }
16743   }
16744 
16745   // Apply default Lvalue conversions and convert the stride expression to
16746   // size_t.
16747   {
16748     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16749     if (StrideConv.isInvalid())
16750       return StrideConv;
16751 
16752     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16753     if (StrideConv.isInvalid())
16754       return StrideConv;
16755     StrideExpr = StrideConv.get();
16756     TheCall->setArg(2, StrideExpr);
16757   }
16758 
16759   // Check stride argument.
16760   if (MatrixTy) {
16761     if (Optional<llvm::APSInt> Value =
16762             StrideExpr->getIntegerConstantExpr(Context)) {
16763       uint64_t Stride = Value->getZExtValue();
16764       if (Stride < MatrixTy->getNumRows()) {
16765         Diag(StrideExpr->getBeginLoc(),
16766              diag::err_builtin_matrix_stride_too_small);
16767         ArgError = true;
16768       }
16769     }
16770   }
16771 
16772   if (ArgError)
16773     return ExprError();
16774 
16775   return CallResult;
16776 }
16777 
16778 /// \brief Enforce the bounds of a TCB
16779 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16780 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16781 /// and enforce_tcb_leaf attributes.
16782 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16783                                const FunctionDecl *Callee) {
16784   const FunctionDecl *Caller = getCurFunctionDecl();
16785 
16786   // Calls to builtins are not enforced.
16787   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16788       Callee->getBuiltinID() != 0)
16789     return;
16790 
16791   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16792   // all TCBs the callee is a part of.
16793   llvm::StringSet<> CalleeTCBs;
16794   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16795            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16796   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16797            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16798 
16799   // Go through the TCBs the caller is a part of and emit warnings if Caller
16800   // is in a TCB that the Callee is not.
16801   for_each(
16802       Caller->specific_attrs<EnforceTCBAttr>(),
16803       [&](const auto *A) {
16804         StringRef CallerTCB = A->getTCBName();
16805         if (CalleeTCBs.count(CallerTCB) == 0) {
16806           this->Diag(TheCall->getExprLoc(),
16807                      diag::warn_tcb_enforcement_violation) << Callee
16808                                                            << CallerTCB;
16809         }
16810       });
16811 }
16812