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           << MaxValue.toString(10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
776                           << UsedSize.getValue().toString(/*Radix=*/10));
777 }
778 
779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_subgroups",
842                                               S.getLangOpts())) {
843     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
844         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
845     return true;
846   }
847   return false;
848 }
849 
850 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
851   if (checkArgCount(S, TheCall, 2))
852     return true;
853 
854   if (checkOpenCLSubgroupExt(S, TheCall))
855     return true;
856 
857   // First argument is an ndrange_t type.
858   Expr *NDRangeArg = TheCall->getArg(0);
859   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
860     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
861         << TheCall->getDirectCallee() << "'ndrange_t'";
862     return true;
863   }
864 
865   Expr *BlockArg = TheCall->getArg(1);
866   if (!isBlockPointer(BlockArg)) {
867     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
868         << TheCall->getDirectCallee() << "block";
869     return true;
870   }
871   return checkOpenCLBlockArgs(S, BlockArg);
872 }
873 
874 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
875 /// get_kernel_work_group_size
876 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
877 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
878   if (checkArgCount(S, TheCall, 1))
879     return true;
880 
881   Expr *BlockArg = TheCall->getArg(0);
882   if (!isBlockPointer(BlockArg)) {
883     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
884         << TheCall->getDirectCallee() << "block";
885     return true;
886   }
887   return checkOpenCLBlockArgs(S, BlockArg);
888 }
889 
890 /// Diagnose integer type and any valid implicit conversion to it.
891 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
892                                       const QualType &IntType);
893 
894 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
895                                             unsigned Start, unsigned End) {
896   bool IllegalParams = false;
897   for (unsigned I = Start; I <= End; ++I)
898     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
899                                               S.Context.getSizeType());
900   return IllegalParams;
901 }
902 
903 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
904 /// 'local void*' parameter of passed block.
905 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
906                                            Expr *BlockArg,
907                                            unsigned NumNonVarArgs) {
908   const BlockPointerType *BPT =
909       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
910   unsigned NumBlockParams =
911       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
912   unsigned TotalNumArgs = TheCall->getNumArgs();
913 
914   // For each argument passed to the block, a corresponding uint needs to
915   // be passed to describe the size of the local memory.
916   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
917     S.Diag(TheCall->getBeginLoc(),
918            diag::err_opencl_enqueue_kernel_local_size_args);
919     return true;
920   }
921 
922   // Check that the sizes of the local memory are specified by integers.
923   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
924                                          TotalNumArgs - 1);
925 }
926 
927 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
928 /// overload formats specified in Table 6.13.17.1.
929 /// int enqueue_kernel(queue_t queue,
930 ///                    kernel_enqueue_flags_t flags,
931 ///                    const ndrange_t ndrange,
932 ///                    void (^block)(void))
933 /// int enqueue_kernel(queue_t queue,
934 ///                    kernel_enqueue_flags_t flags,
935 ///                    const ndrange_t ndrange,
936 ///                    uint num_events_in_wait_list,
937 ///                    clk_event_t *event_wait_list,
938 ///                    clk_event_t *event_ret,
939 ///                    void (^block)(void))
940 /// int enqueue_kernel(queue_t queue,
941 ///                    kernel_enqueue_flags_t flags,
942 ///                    const ndrange_t ndrange,
943 ///                    void (^block)(local void*, ...),
944 ///                    uint size0, ...)
945 /// int enqueue_kernel(queue_t queue,
946 ///                    kernel_enqueue_flags_t flags,
947 ///                    const ndrange_t ndrange,
948 ///                    uint num_events_in_wait_list,
949 ///                    clk_event_t *event_wait_list,
950 ///                    clk_event_t *event_ret,
951 ///                    void (^block)(local void*, ...),
952 ///                    uint size0, ...)
953 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
954   unsigned NumArgs = TheCall->getNumArgs();
955 
956   if (NumArgs < 4) {
957     S.Diag(TheCall->getBeginLoc(),
958            diag::err_typecheck_call_too_few_args_at_least)
959         << 0 << 4 << NumArgs;
960     return true;
961   }
962 
963   Expr *Arg0 = TheCall->getArg(0);
964   Expr *Arg1 = TheCall->getArg(1);
965   Expr *Arg2 = TheCall->getArg(2);
966   Expr *Arg3 = TheCall->getArg(3);
967 
968   // First argument always needs to be a queue_t type.
969   if (!Arg0->getType()->isQueueT()) {
970     S.Diag(TheCall->getArg(0)->getBeginLoc(),
971            diag::err_opencl_builtin_expected_type)
972         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
973     return true;
974   }
975 
976   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
977   if (!Arg1->getType()->isIntegerType()) {
978     S.Diag(TheCall->getArg(1)->getBeginLoc(),
979            diag::err_opencl_builtin_expected_type)
980         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
981     return true;
982   }
983 
984   // Third argument is always an ndrange_t type.
985   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
986     S.Diag(TheCall->getArg(2)->getBeginLoc(),
987            diag::err_opencl_builtin_expected_type)
988         << TheCall->getDirectCallee() << "'ndrange_t'";
989     return true;
990   }
991 
992   // With four arguments, there is only one form that the function could be
993   // called in: no events and no variable arguments.
994   if (NumArgs == 4) {
995     // check that the last argument is the right block type.
996     if (!isBlockPointer(Arg3)) {
997       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
998           << TheCall->getDirectCallee() << "block";
999       return true;
1000     }
1001     // we have a block type, check the prototype
1002     const BlockPointerType *BPT =
1003         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1004     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1005       S.Diag(Arg3->getBeginLoc(),
1006              diag::err_opencl_enqueue_kernel_blocks_no_args);
1007       return true;
1008     }
1009     return false;
1010   }
1011   // we can have block + varargs.
1012   if (isBlockPointer(Arg3))
1013     return (checkOpenCLBlockArgs(S, Arg3) ||
1014             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1015   // last two cases with either exactly 7 args or 7 args and varargs.
1016   if (NumArgs >= 7) {
1017     // check common block argument.
1018     Expr *Arg6 = TheCall->getArg(6);
1019     if (!isBlockPointer(Arg6)) {
1020       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1021           << TheCall->getDirectCallee() << "block";
1022       return true;
1023     }
1024     if (checkOpenCLBlockArgs(S, Arg6))
1025       return true;
1026 
1027     // Forth argument has to be any integer type.
1028     if (!Arg3->getType()->isIntegerType()) {
1029       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1030              diag::err_opencl_builtin_expected_type)
1031           << TheCall->getDirectCallee() << "integer";
1032       return true;
1033     }
1034     // check remaining common arguments.
1035     Expr *Arg4 = TheCall->getArg(4);
1036     Expr *Arg5 = TheCall->getArg(5);
1037 
1038     // Fifth argument is always passed as a pointer to clk_event_t.
1039     if (!Arg4->isNullPointerConstant(S.Context,
1040                                      Expr::NPC_ValueDependentIsNotNull) &&
1041         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1042       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee()
1045           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1046       return true;
1047     }
1048 
1049     // Sixth argument is always passed as a pointer to clk_event_t.
1050     if (!Arg5->isNullPointerConstant(S.Context,
1051                                      Expr::NPC_ValueDependentIsNotNull) &&
1052         !(Arg5->getType()->isPointerType() &&
1053           Arg5->getType()->getPointeeType()->isClkEventT())) {
1054       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1055              diag::err_opencl_builtin_expected_type)
1056           << TheCall->getDirectCallee()
1057           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1058       return true;
1059     }
1060 
1061     if (NumArgs == 7)
1062       return false;
1063 
1064     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1065   }
1066 
1067   // None of the specific case has been detected, give generic error
1068   S.Diag(TheCall->getBeginLoc(),
1069          diag::err_opencl_enqueue_kernel_incorrect_args);
1070   return true;
1071 }
1072 
1073 /// Returns OpenCL access qual.
1074 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1075     return D->getAttr<OpenCLAccessAttr>();
1076 }
1077 
1078 /// Returns true if pipe element type is different from the pointer.
1079 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1080   const Expr *Arg0 = Call->getArg(0);
1081   // First argument type should always be pipe.
1082   if (!Arg0->getType()->isPipeType()) {
1083     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1084         << Call->getDirectCallee() << Arg0->getSourceRange();
1085     return true;
1086   }
1087   OpenCLAccessAttr *AccessQual =
1088       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1089   // Validates the access qualifier is compatible with the call.
1090   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1091   // read_only and write_only, and assumed to be read_only if no qualifier is
1092   // specified.
1093   switch (Call->getDirectCallee()->getBuiltinID()) {
1094   case Builtin::BIread_pipe:
1095   case Builtin::BIreserve_read_pipe:
1096   case Builtin::BIcommit_read_pipe:
1097   case Builtin::BIwork_group_reserve_read_pipe:
1098   case Builtin::BIsub_group_reserve_read_pipe:
1099   case Builtin::BIwork_group_commit_read_pipe:
1100   case Builtin::BIsub_group_commit_read_pipe:
1101     if (!(!AccessQual || AccessQual->isReadOnly())) {
1102       S.Diag(Arg0->getBeginLoc(),
1103              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1104           << "read_only" << Arg0->getSourceRange();
1105       return true;
1106     }
1107     break;
1108   case Builtin::BIwrite_pipe:
1109   case Builtin::BIreserve_write_pipe:
1110   case Builtin::BIcommit_write_pipe:
1111   case Builtin::BIwork_group_reserve_write_pipe:
1112   case Builtin::BIsub_group_reserve_write_pipe:
1113   case Builtin::BIwork_group_commit_write_pipe:
1114   case Builtin::BIsub_group_commit_write_pipe:
1115     if (!(AccessQual && AccessQual->isWriteOnly())) {
1116       S.Diag(Arg0->getBeginLoc(),
1117              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1118           << "write_only" << Arg0->getSourceRange();
1119       return true;
1120     }
1121     break;
1122   default:
1123     break;
1124   }
1125   return false;
1126 }
1127 
1128 /// Returns true if pipe element type is different from the pointer.
1129 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1130   const Expr *Arg0 = Call->getArg(0);
1131   const Expr *ArgIdx = Call->getArg(Idx);
1132   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1133   const QualType EltTy = PipeTy->getElementType();
1134   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1135   // The Idx argument should be a pointer and the type of the pointer and
1136   // the type of pipe element should also be the same.
1137   if (!ArgTy ||
1138       !S.Context.hasSameType(
1139           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1140     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1141         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1142         << ArgIdx->getType() << ArgIdx->getSourceRange();
1143     return true;
1144   }
1145   return false;
1146 }
1147 
1148 // Performs semantic analysis for the read/write_pipe call.
1149 // \param S Reference to the semantic analyzer.
1150 // \param Call A pointer to the builtin call.
1151 // \return True if a semantic error has been found, false otherwise.
1152 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1153   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1154   // functions have two forms.
1155   switch (Call->getNumArgs()) {
1156   case 2:
1157     if (checkOpenCLPipeArg(S, Call))
1158       return true;
1159     // The call with 2 arguments should be
1160     // read/write_pipe(pipe T, T*).
1161     // Check packet type T.
1162     if (checkOpenCLPipePacketType(S, Call, 1))
1163       return true;
1164     break;
1165 
1166   case 4: {
1167     if (checkOpenCLPipeArg(S, Call))
1168       return true;
1169     // The call with 4 arguments should be
1170     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1171     // Check reserve_id_t.
1172     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1173       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1174           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1175           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1176       return true;
1177     }
1178 
1179     // Check the index.
1180     const Expr *Arg2 = Call->getArg(2);
1181     if (!Arg2->getType()->isIntegerType() &&
1182         !Arg2->getType()->isUnsignedIntegerType()) {
1183       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1184           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1185           << Arg2->getType() << Arg2->getSourceRange();
1186       return true;
1187     }
1188 
1189     // Check packet type T.
1190     if (checkOpenCLPipePacketType(S, Call, 3))
1191       return true;
1192   } break;
1193   default:
1194     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1195         << Call->getDirectCallee() << Call->getSourceRange();
1196     return true;
1197   }
1198 
1199   return false;
1200 }
1201 
1202 // Performs a semantic analysis on the {work_group_/sub_group_
1203 //        /_}reserve_{read/write}_pipe
1204 // \param S Reference to the semantic analyzer.
1205 // \param Call The call to the builtin function to be analyzed.
1206 // \return True if a semantic error was found, false otherwise.
1207 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1208   if (checkArgCount(S, Call, 2))
1209     return true;
1210 
1211   if (checkOpenCLPipeArg(S, Call))
1212     return true;
1213 
1214   // Check the reserve size.
1215   if (!Call->getArg(1)->getType()->isIntegerType() &&
1216       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1217     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1218         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1219         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1220     return true;
1221   }
1222 
1223   // Since return type of reserve_read/write_pipe built-in function is
1224   // reserve_id_t, which is not defined in the builtin def file , we used int
1225   // as return type and need to override the return type of these functions.
1226   Call->setType(S.Context.OCLReserveIDTy);
1227 
1228   return false;
1229 }
1230 
1231 // Performs a semantic analysis on {work_group_/sub_group_
1232 //        /_}commit_{read/write}_pipe
1233 // \param S Reference to the semantic analyzer.
1234 // \param Call The call to the builtin function to be analyzed.
1235 // \return True if a semantic error was found, false otherwise.
1236 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1237   if (checkArgCount(S, Call, 2))
1238     return true;
1239 
1240   if (checkOpenCLPipeArg(S, Call))
1241     return true;
1242 
1243   // Check reserve_id_t.
1244   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1245     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1246         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1247         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1248     return true;
1249   }
1250 
1251   return false;
1252 }
1253 
1254 // Performs a semantic analysis on the call to built-in Pipe
1255 //        Query Functions.
1256 // \param S Reference to the semantic analyzer.
1257 // \param Call The call to the builtin function to be analyzed.
1258 // \return True if a semantic error was found, false otherwise.
1259 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1260   if (checkArgCount(S, Call, 1))
1261     return true;
1262 
1263   if (!Call->getArg(0)->getType()->isPipeType()) {
1264     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1265         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1266     return true;
1267   }
1268 
1269   return false;
1270 }
1271 
1272 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1273 // Performs semantic analysis for the to_global/local/private call.
1274 // \param S Reference to the semantic analyzer.
1275 // \param BuiltinID ID of the builtin function.
1276 // \param Call A pointer to the builtin call.
1277 // \return True if a semantic error has been found, false otherwise.
1278 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1279                                     CallExpr *Call) {
1280   if (checkArgCount(S, Call, 1))
1281     return true;
1282 
1283   auto RT = Call->getArg(0)->getType();
1284   if (!RT->isPointerType() || RT->getPointeeType()
1285       .getAddressSpace() == LangAS::opencl_constant) {
1286     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1287         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1288     return true;
1289   }
1290 
1291   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1292     S.Diag(Call->getArg(0)->getBeginLoc(),
1293            diag::warn_opencl_generic_address_space_arg)
1294         << Call->getDirectCallee()->getNameInfo().getAsString()
1295         << Call->getArg(0)->getSourceRange();
1296   }
1297 
1298   RT = RT->getPointeeType();
1299   auto Qual = RT.getQualifiers();
1300   switch (BuiltinID) {
1301   case Builtin::BIto_global:
1302     Qual.setAddressSpace(LangAS::opencl_global);
1303     break;
1304   case Builtin::BIto_local:
1305     Qual.setAddressSpace(LangAS::opencl_local);
1306     break;
1307   case Builtin::BIto_private:
1308     Qual.setAddressSpace(LangAS::opencl_private);
1309     break;
1310   default:
1311     llvm_unreachable("Invalid builtin function");
1312   }
1313   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1314       RT.getUnqualifiedType(), Qual)));
1315 
1316   return false;
1317 }
1318 
1319 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1320   if (checkArgCount(S, TheCall, 1))
1321     return ExprError();
1322 
1323   // Compute __builtin_launder's parameter type from the argument.
1324   // The parameter type is:
1325   //  * The type of the argument if it's not an array or function type,
1326   //  Otherwise,
1327   //  * The decayed argument type.
1328   QualType ParamTy = [&]() {
1329     QualType ArgTy = TheCall->getArg(0)->getType();
1330     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1331       return S.Context.getPointerType(Ty->getElementType());
1332     if (ArgTy->isFunctionType()) {
1333       return S.Context.getPointerType(ArgTy);
1334     }
1335     return ArgTy;
1336   }();
1337 
1338   TheCall->setType(ParamTy);
1339 
1340   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1341     if (!ParamTy->isPointerType())
1342       return 0;
1343     if (ParamTy->isFunctionPointerType())
1344       return 1;
1345     if (ParamTy->isVoidPointerType())
1346       return 2;
1347     return llvm::Optional<unsigned>{};
1348   }();
1349   if (DiagSelect.hasValue()) {
1350     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1351         << DiagSelect.getValue() << TheCall->getSourceRange();
1352     return ExprError();
1353   }
1354 
1355   // We either have an incomplete class type, or we have a class template
1356   // whose instantiation has not been forced. Example:
1357   //
1358   //   template <class T> struct Foo { T value; };
1359   //   Foo<int> *p = nullptr;
1360   //   auto *d = __builtin_launder(p);
1361   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1362                             diag::err_incomplete_type))
1363     return ExprError();
1364 
1365   assert(ParamTy->getPointeeType()->isObjectType() &&
1366          "Unhandled non-object pointer case");
1367 
1368   InitializedEntity Entity =
1369       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1370   ExprResult Arg =
1371       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1372   if (Arg.isInvalid())
1373     return ExprError();
1374   TheCall->setArg(0, Arg.get());
1375 
1376   return TheCall;
1377 }
1378 
1379 // Emit an error and return true if the current architecture is not in the list
1380 // of supported architectures.
1381 static bool
1382 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1383                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1384   llvm::Triple::ArchType CurArch =
1385       S.getASTContext().getTargetInfo().getTriple().getArch();
1386   if (llvm::is_contained(SupportedArchs, CurArch))
1387     return false;
1388   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1389       << TheCall->getSourceRange();
1390   return true;
1391 }
1392 
1393 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1394                                  SourceLocation CallSiteLoc);
1395 
1396 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1397                                       CallExpr *TheCall) {
1398   switch (TI.getTriple().getArch()) {
1399   default:
1400     // Some builtins don't require additional checking, so just consider these
1401     // acceptable.
1402     return false;
1403   case llvm::Triple::arm:
1404   case llvm::Triple::armeb:
1405   case llvm::Triple::thumb:
1406   case llvm::Triple::thumbeb:
1407     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1408   case llvm::Triple::aarch64:
1409   case llvm::Triple::aarch64_32:
1410   case llvm::Triple::aarch64_be:
1411     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1412   case llvm::Triple::bpfeb:
1413   case llvm::Triple::bpfel:
1414     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1415   case llvm::Triple::hexagon:
1416     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1417   case llvm::Triple::mips:
1418   case llvm::Triple::mipsel:
1419   case llvm::Triple::mips64:
1420   case llvm::Triple::mips64el:
1421     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1422   case llvm::Triple::systemz:
1423     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1424   case llvm::Triple::x86:
1425   case llvm::Triple::x86_64:
1426     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1427   case llvm::Triple::ppc:
1428   case llvm::Triple::ppcle:
1429   case llvm::Triple::ppc64:
1430   case llvm::Triple::ppc64le:
1431     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1432   case llvm::Triple::amdgcn:
1433     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1434   case llvm::Triple::riscv32:
1435   case llvm::Triple::riscv64:
1436     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1437   }
1438 }
1439 
1440 ExprResult
1441 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1442                                CallExpr *TheCall) {
1443   ExprResult TheCallResult(TheCall);
1444 
1445   // Find out if any arguments are required to be integer constant expressions.
1446   unsigned ICEArguments = 0;
1447   ASTContext::GetBuiltinTypeError Error;
1448   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1449   if (Error != ASTContext::GE_None)
1450     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1451 
1452   // If any arguments are required to be ICE's, check and diagnose.
1453   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1454     // Skip arguments not required to be ICE's.
1455     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1456 
1457     llvm::APSInt Result;
1458     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1459       return true;
1460     ICEArguments &= ~(1 << ArgNo);
1461   }
1462 
1463   switch (BuiltinID) {
1464   case Builtin::BI__builtin___CFStringMakeConstantString:
1465     assert(TheCall->getNumArgs() == 1 &&
1466            "Wrong # arguments to builtin CFStringMakeConstantString");
1467     if (CheckObjCString(TheCall->getArg(0)))
1468       return ExprError();
1469     break;
1470   case Builtin::BI__builtin_ms_va_start:
1471   case Builtin::BI__builtin_stdarg_start:
1472   case Builtin::BI__builtin_va_start:
1473     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1474       return ExprError();
1475     break;
1476   case Builtin::BI__va_start: {
1477     switch (Context.getTargetInfo().getTriple().getArch()) {
1478     case llvm::Triple::aarch64:
1479     case llvm::Triple::arm:
1480     case llvm::Triple::thumb:
1481       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1482         return ExprError();
1483       break;
1484     default:
1485       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1486         return ExprError();
1487       break;
1488     }
1489     break;
1490   }
1491 
1492   // The acquire, release, and no fence variants are ARM and AArch64 only.
1493   case Builtin::BI_interlockedbittestandset_acq:
1494   case Builtin::BI_interlockedbittestandset_rel:
1495   case Builtin::BI_interlockedbittestandset_nf:
1496   case Builtin::BI_interlockedbittestandreset_acq:
1497   case Builtin::BI_interlockedbittestandreset_rel:
1498   case Builtin::BI_interlockedbittestandreset_nf:
1499     if (CheckBuiltinTargetSupport(
1500             *this, BuiltinID, TheCall,
1501             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1502       return ExprError();
1503     break;
1504 
1505   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1506   case Builtin::BI_bittest64:
1507   case Builtin::BI_bittestandcomplement64:
1508   case Builtin::BI_bittestandreset64:
1509   case Builtin::BI_bittestandset64:
1510   case Builtin::BI_interlockedbittestandreset64:
1511   case Builtin::BI_interlockedbittestandset64:
1512     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1513                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1514                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   case Builtin::BI__builtin_isgreater:
1519   case Builtin::BI__builtin_isgreaterequal:
1520   case Builtin::BI__builtin_isless:
1521   case Builtin::BI__builtin_islessequal:
1522   case Builtin::BI__builtin_islessgreater:
1523   case Builtin::BI__builtin_isunordered:
1524     if (SemaBuiltinUnorderedCompare(TheCall))
1525       return ExprError();
1526     break;
1527   case Builtin::BI__builtin_fpclassify:
1528     if (SemaBuiltinFPClassification(TheCall, 6))
1529       return ExprError();
1530     break;
1531   case Builtin::BI__builtin_isfinite:
1532   case Builtin::BI__builtin_isinf:
1533   case Builtin::BI__builtin_isinf_sign:
1534   case Builtin::BI__builtin_isnan:
1535   case Builtin::BI__builtin_isnormal:
1536   case Builtin::BI__builtin_signbit:
1537   case Builtin::BI__builtin_signbitf:
1538   case Builtin::BI__builtin_signbitl:
1539     if (SemaBuiltinFPClassification(TheCall, 1))
1540       return ExprError();
1541     break;
1542   case Builtin::BI__builtin_shufflevector:
1543     return SemaBuiltinShuffleVector(TheCall);
1544     // TheCall will be freed by the smart pointer here, but that's fine, since
1545     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1546   case Builtin::BI__builtin_prefetch:
1547     if (SemaBuiltinPrefetch(TheCall))
1548       return ExprError();
1549     break;
1550   case Builtin::BI__builtin_alloca_with_align:
1551     if (SemaBuiltinAllocaWithAlign(TheCall))
1552       return ExprError();
1553     LLVM_FALLTHROUGH;
1554   case Builtin::BI__builtin_alloca:
1555     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1556         << TheCall->getDirectCallee();
1557     break;
1558   case Builtin::BI__assume:
1559   case Builtin::BI__builtin_assume:
1560     if (SemaBuiltinAssume(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_assume_aligned:
1564     if (SemaBuiltinAssumeAligned(TheCall))
1565       return ExprError();
1566     break;
1567   case Builtin::BI__builtin_dynamic_object_size:
1568   case Builtin::BI__builtin_object_size:
1569     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1570       return ExprError();
1571     break;
1572   case Builtin::BI__builtin_longjmp:
1573     if (SemaBuiltinLongjmp(TheCall))
1574       return ExprError();
1575     break;
1576   case Builtin::BI__builtin_setjmp:
1577     if (SemaBuiltinSetjmp(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_classify_type:
1581     if (checkArgCount(*this, TheCall, 1)) return true;
1582     TheCall->setType(Context.IntTy);
1583     break;
1584   case Builtin::BI__builtin_complex:
1585     if (SemaBuiltinComplex(TheCall))
1586       return ExprError();
1587     break;
1588   case Builtin::BI__builtin_constant_p: {
1589     if (checkArgCount(*this, TheCall, 1)) return true;
1590     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1591     if (Arg.isInvalid()) return true;
1592     TheCall->setArg(0, Arg.get());
1593     TheCall->setType(Context.IntTy);
1594     break;
1595   }
1596   case Builtin::BI__builtin_launder:
1597     return SemaBuiltinLaunder(*this, TheCall);
1598   case Builtin::BI__sync_fetch_and_add:
1599   case Builtin::BI__sync_fetch_and_add_1:
1600   case Builtin::BI__sync_fetch_and_add_2:
1601   case Builtin::BI__sync_fetch_and_add_4:
1602   case Builtin::BI__sync_fetch_and_add_8:
1603   case Builtin::BI__sync_fetch_and_add_16:
1604   case Builtin::BI__sync_fetch_and_sub:
1605   case Builtin::BI__sync_fetch_and_sub_1:
1606   case Builtin::BI__sync_fetch_and_sub_2:
1607   case Builtin::BI__sync_fetch_and_sub_4:
1608   case Builtin::BI__sync_fetch_and_sub_8:
1609   case Builtin::BI__sync_fetch_and_sub_16:
1610   case Builtin::BI__sync_fetch_and_or:
1611   case Builtin::BI__sync_fetch_and_or_1:
1612   case Builtin::BI__sync_fetch_and_or_2:
1613   case Builtin::BI__sync_fetch_and_or_4:
1614   case Builtin::BI__sync_fetch_and_or_8:
1615   case Builtin::BI__sync_fetch_and_or_16:
1616   case Builtin::BI__sync_fetch_and_and:
1617   case Builtin::BI__sync_fetch_and_and_1:
1618   case Builtin::BI__sync_fetch_and_and_2:
1619   case Builtin::BI__sync_fetch_and_and_4:
1620   case Builtin::BI__sync_fetch_and_and_8:
1621   case Builtin::BI__sync_fetch_and_and_16:
1622   case Builtin::BI__sync_fetch_and_xor:
1623   case Builtin::BI__sync_fetch_and_xor_1:
1624   case Builtin::BI__sync_fetch_and_xor_2:
1625   case Builtin::BI__sync_fetch_and_xor_4:
1626   case Builtin::BI__sync_fetch_and_xor_8:
1627   case Builtin::BI__sync_fetch_and_xor_16:
1628   case Builtin::BI__sync_fetch_and_nand:
1629   case Builtin::BI__sync_fetch_and_nand_1:
1630   case Builtin::BI__sync_fetch_and_nand_2:
1631   case Builtin::BI__sync_fetch_and_nand_4:
1632   case Builtin::BI__sync_fetch_and_nand_8:
1633   case Builtin::BI__sync_fetch_and_nand_16:
1634   case Builtin::BI__sync_add_and_fetch:
1635   case Builtin::BI__sync_add_and_fetch_1:
1636   case Builtin::BI__sync_add_and_fetch_2:
1637   case Builtin::BI__sync_add_and_fetch_4:
1638   case Builtin::BI__sync_add_and_fetch_8:
1639   case Builtin::BI__sync_add_and_fetch_16:
1640   case Builtin::BI__sync_sub_and_fetch:
1641   case Builtin::BI__sync_sub_and_fetch_1:
1642   case Builtin::BI__sync_sub_and_fetch_2:
1643   case Builtin::BI__sync_sub_and_fetch_4:
1644   case Builtin::BI__sync_sub_and_fetch_8:
1645   case Builtin::BI__sync_sub_and_fetch_16:
1646   case Builtin::BI__sync_and_and_fetch:
1647   case Builtin::BI__sync_and_and_fetch_1:
1648   case Builtin::BI__sync_and_and_fetch_2:
1649   case Builtin::BI__sync_and_and_fetch_4:
1650   case Builtin::BI__sync_and_and_fetch_8:
1651   case Builtin::BI__sync_and_and_fetch_16:
1652   case Builtin::BI__sync_or_and_fetch:
1653   case Builtin::BI__sync_or_and_fetch_1:
1654   case Builtin::BI__sync_or_and_fetch_2:
1655   case Builtin::BI__sync_or_and_fetch_4:
1656   case Builtin::BI__sync_or_and_fetch_8:
1657   case Builtin::BI__sync_or_and_fetch_16:
1658   case Builtin::BI__sync_xor_and_fetch:
1659   case Builtin::BI__sync_xor_and_fetch_1:
1660   case Builtin::BI__sync_xor_and_fetch_2:
1661   case Builtin::BI__sync_xor_and_fetch_4:
1662   case Builtin::BI__sync_xor_and_fetch_8:
1663   case Builtin::BI__sync_xor_and_fetch_16:
1664   case Builtin::BI__sync_nand_and_fetch:
1665   case Builtin::BI__sync_nand_and_fetch_1:
1666   case Builtin::BI__sync_nand_and_fetch_2:
1667   case Builtin::BI__sync_nand_and_fetch_4:
1668   case Builtin::BI__sync_nand_and_fetch_8:
1669   case Builtin::BI__sync_nand_and_fetch_16:
1670   case Builtin::BI__sync_val_compare_and_swap:
1671   case Builtin::BI__sync_val_compare_and_swap_1:
1672   case Builtin::BI__sync_val_compare_and_swap_2:
1673   case Builtin::BI__sync_val_compare_and_swap_4:
1674   case Builtin::BI__sync_val_compare_and_swap_8:
1675   case Builtin::BI__sync_val_compare_and_swap_16:
1676   case Builtin::BI__sync_bool_compare_and_swap:
1677   case Builtin::BI__sync_bool_compare_and_swap_1:
1678   case Builtin::BI__sync_bool_compare_and_swap_2:
1679   case Builtin::BI__sync_bool_compare_and_swap_4:
1680   case Builtin::BI__sync_bool_compare_and_swap_8:
1681   case Builtin::BI__sync_bool_compare_and_swap_16:
1682   case Builtin::BI__sync_lock_test_and_set:
1683   case Builtin::BI__sync_lock_test_and_set_1:
1684   case Builtin::BI__sync_lock_test_and_set_2:
1685   case Builtin::BI__sync_lock_test_and_set_4:
1686   case Builtin::BI__sync_lock_test_and_set_8:
1687   case Builtin::BI__sync_lock_test_and_set_16:
1688   case Builtin::BI__sync_lock_release:
1689   case Builtin::BI__sync_lock_release_1:
1690   case Builtin::BI__sync_lock_release_2:
1691   case Builtin::BI__sync_lock_release_4:
1692   case Builtin::BI__sync_lock_release_8:
1693   case Builtin::BI__sync_lock_release_16:
1694   case Builtin::BI__sync_swap:
1695   case Builtin::BI__sync_swap_1:
1696   case Builtin::BI__sync_swap_2:
1697   case Builtin::BI__sync_swap_4:
1698   case Builtin::BI__sync_swap_8:
1699   case Builtin::BI__sync_swap_16:
1700     return SemaBuiltinAtomicOverloaded(TheCallResult);
1701   case Builtin::BI__sync_synchronize:
1702     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1703         << TheCall->getCallee()->getSourceRange();
1704     break;
1705   case Builtin::BI__builtin_nontemporal_load:
1706   case Builtin::BI__builtin_nontemporal_store:
1707     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1708   case Builtin::BI__builtin_memcpy_inline: {
1709     clang::Expr *SizeOp = TheCall->getArg(2);
1710     // We warn about copying to or from `nullptr` pointers when `size` is
1711     // greater than 0. When `size` is value dependent we cannot evaluate its
1712     // value so we bail out.
1713     if (SizeOp->isValueDependent())
1714       break;
1715     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1716       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1717       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1718     }
1719     break;
1720   }
1721 #define BUILTIN(ID, TYPE, ATTRS)
1722 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1723   case Builtin::BI##ID: \
1724     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1725 #include "clang/Basic/Builtins.def"
1726   case Builtin::BI__annotation:
1727     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1728       return ExprError();
1729     break;
1730   case Builtin::BI__builtin_annotation:
1731     if (SemaBuiltinAnnotation(*this, TheCall))
1732       return ExprError();
1733     break;
1734   case Builtin::BI__builtin_addressof:
1735     if (SemaBuiltinAddressof(*this, TheCall))
1736       return ExprError();
1737     break;
1738   case Builtin::BI__builtin_is_aligned:
1739   case Builtin::BI__builtin_align_up:
1740   case Builtin::BI__builtin_align_down:
1741     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1742       return ExprError();
1743     break;
1744   case Builtin::BI__builtin_add_overflow:
1745   case Builtin::BI__builtin_sub_overflow:
1746   case Builtin::BI__builtin_mul_overflow:
1747     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1748       return ExprError();
1749     break;
1750   case Builtin::BI__builtin_operator_new:
1751   case Builtin::BI__builtin_operator_delete: {
1752     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1753     ExprResult Res =
1754         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1755     if (Res.isInvalid())
1756       CorrectDelayedTyposInExpr(TheCallResult.get());
1757     return Res;
1758   }
1759   case Builtin::BI__builtin_dump_struct: {
1760     // We first want to ensure we are called with 2 arguments
1761     if (checkArgCount(*this, TheCall, 2))
1762       return ExprError();
1763     // Ensure that the first argument is of type 'struct XX *'
1764     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1765     const QualType PtrArgType = PtrArg->getType();
1766     if (!PtrArgType->isPointerType() ||
1767         !PtrArgType->getPointeeType()->isRecordType()) {
1768       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1769           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1770           << "structure pointer";
1771       return ExprError();
1772     }
1773 
1774     // Ensure that the second argument is of type 'FunctionType'
1775     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1776     const QualType FnPtrArgType = FnPtrArg->getType();
1777     if (!FnPtrArgType->isPointerType()) {
1778       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1779           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1780           << FnPtrArgType << "'int (*)(const char *, ...)'";
1781       return ExprError();
1782     }
1783 
1784     const auto *FuncType =
1785         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1786 
1787     if (!FuncType) {
1788       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1789           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1790           << FnPtrArgType << "'int (*)(const char *, ...)'";
1791       return ExprError();
1792     }
1793 
1794     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1795       if (!FT->getNumParams()) {
1796         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1797             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1798             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1799         return ExprError();
1800       }
1801       QualType PT = FT->getParamType(0);
1802       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1803           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1804           !PT->getPointeeType().isConstQualified()) {
1805         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1806             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1807             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1808         return ExprError();
1809       }
1810     }
1811 
1812     TheCall->setType(Context.IntTy);
1813     break;
1814   }
1815   case Builtin::BI__builtin_expect_with_probability: {
1816     // We first want to ensure we are called with 3 arguments
1817     if (checkArgCount(*this, TheCall, 3))
1818       return ExprError();
1819     // then check probability is constant float in range [0.0, 1.0]
1820     const Expr *ProbArg = TheCall->getArg(2);
1821     SmallVector<PartialDiagnosticAt, 8> Notes;
1822     Expr::EvalResult Eval;
1823     Eval.Diag = &Notes;
1824     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1825         !Eval.Val.isFloat()) {
1826       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1827           << ProbArg->getSourceRange();
1828       for (const PartialDiagnosticAt &PDiag : Notes)
1829         Diag(PDiag.first, PDiag.second);
1830       return ExprError();
1831     }
1832     llvm::APFloat Probability = Eval.Val.getFloat();
1833     bool LoseInfo = false;
1834     Probability.convert(llvm::APFloat::IEEEdouble(),
1835                         llvm::RoundingMode::Dynamic, &LoseInfo);
1836     if (!(Probability >= llvm::APFloat(0.0) &&
1837           Probability <= llvm::APFloat(1.0))) {
1838       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1839           << ProbArg->getSourceRange();
1840       return ExprError();
1841     }
1842     break;
1843   }
1844   case Builtin::BI__builtin_preserve_access_index:
1845     if (SemaBuiltinPreserveAI(*this, TheCall))
1846       return ExprError();
1847     break;
1848   case Builtin::BI__builtin_call_with_static_chain:
1849     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1850       return ExprError();
1851     break;
1852   case Builtin::BI__exception_code:
1853   case Builtin::BI_exception_code:
1854     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1855                                  diag::err_seh___except_block))
1856       return ExprError();
1857     break;
1858   case Builtin::BI__exception_info:
1859   case Builtin::BI_exception_info:
1860     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1861                                  diag::err_seh___except_filter))
1862       return ExprError();
1863     break;
1864   case Builtin::BI__GetExceptionInfo:
1865     if (checkArgCount(*this, TheCall, 1))
1866       return ExprError();
1867 
1868     if (CheckCXXThrowOperand(
1869             TheCall->getBeginLoc(),
1870             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1871             TheCall))
1872       return ExprError();
1873 
1874     TheCall->setType(Context.VoidPtrTy);
1875     break;
1876   // OpenCL v2.0, s6.13.16 - Pipe functions
1877   case Builtin::BIread_pipe:
1878   case Builtin::BIwrite_pipe:
1879     // Since those two functions are declared with var args, we need a semantic
1880     // check for the argument.
1881     if (SemaBuiltinRWPipe(*this, TheCall))
1882       return ExprError();
1883     break;
1884   case Builtin::BIreserve_read_pipe:
1885   case Builtin::BIreserve_write_pipe:
1886   case Builtin::BIwork_group_reserve_read_pipe:
1887   case Builtin::BIwork_group_reserve_write_pipe:
1888     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1889       return ExprError();
1890     break;
1891   case Builtin::BIsub_group_reserve_read_pipe:
1892   case Builtin::BIsub_group_reserve_write_pipe:
1893     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1894         SemaBuiltinReserveRWPipe(*this, TheCall))
1895       return ExprError();
1896     break;
1897   case Builtin::BIcommit_read_pipe:
1898   case Builtin::BIcommit_write_pipe:
1899   case Builtin::BIwork_group_commit_read_pipe:
1900   case Builtin::BIwork_group_commit_write_pipe:
1901     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1902       return ExprError();
1903     break;
1904   case Builtin::BIsub_group_commit_read_pipe:
1905   case Builtin::BIsub_group_commit_write_pipe:
1906     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1907         SemaBuiltinCommitRWPipe(*this, TheCall))
1908       return ExprError();
1909     break;
1910   case Builtin::BIget_pipe_num_packets:
1911   case Builtin::BIget_pipe_max_packets:
1912     if (SemaBuiltinPipePackets(*this, TheCall))
1913       return ExprError();
1914     break;
1915   case Builtin::BIto_global:
1916   case Builtin::BIto_local:
1917   case Builtin::BIto_private:
1918     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1919       return ExprError();
1920     break;
1921   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1922   case Builtin::BIenqueue_kernel:
1923     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1924       return ExprError();
1925     break;
1926   case Builtin::BIget_kernel_work_group_size:
1927   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1928     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1929       return ExprError();
1930     break;
1931   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1932   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1933     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1934       return ExprError();
1935     break;
1936   case Builtin::BI__builtin_os_log_format:
1937     Cleanup.setExprNeedsCleanups(true);
1938     LLVM_FALLTHROUGH;
1939   case Builtin::BI__builtin_os_log_format_buffer_size:
1940     if (SemaBuiltinOSLogFormat(TheCall))
1941       return ExprError();
1942     break;
1943   case Builtin::BI__builtin_frame_address:
1944   case Builtin::BI__builtin_return_address: {
1945     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1946       return ExprError();
1947 
1948     // -Wframe-address warning if non-zero passed to builtin
1949     // return/frame address.
1950     Expr::EvalResult Result;
1951     if (!TheCall->getArg(0)->isValueDependent() &&
1952         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1953         Result.Val.getInt() != 0)
1954       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1955           << ((BuiltinID == Builtin::BI__builtin_return_address)
1956                   ? "__builtin_return_address"
1957                   : "__builtin_frame_address")
1958           << TheCall->getSourceRange();
1959     break;
1960   }
1961 
1962   case Builtin::BI__builtin_matrix_transpose:
1963     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1964 
1965   case Builtin::BI__builtin_matrix_column_major_load:
1966     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1967 
1968   case Builtin::BI__builtin_matrix_column_major_store:
1969     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1970 
1971   case Builtin::BI__builtin_get_device_side_mangled_name: {
1972     auto Check = [](CallExpr *TheCall) {
1973       if (TheCall->getNumArgs() != 1)
1974         return false;
1975       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1976       if (!DRE)
1977         return false;
1978       auto *D = DRE->getDecl();
1979       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1980         return false;
1981       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1982              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1983     };
1984     if (!Check(TheCall)) {
1985       Diag(TheCall->getBeginLoc(),
1986            diag::err_hip_invalid_args_builtin_mangled_name);
1987       return ExprError();
1988     }
1989   }
1990   }
1991 
1992   // Since the target specific builtins for each arch overlap, only check those
1993   // of the arch we are compiling for.
1994   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1995     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1996       assert(Context.getAuxTargetInfo() &&
1997              "Aux Target Builtin, but not an aux target?");
1998 
1999       if (CheckTSBuiltinFunctionCall(
2000               *Context.getAuxTargetInfo(),
2001               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2002         return ExprError();
2003     } else {
2004       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2005                                      TheCall))
2006         return ExprError();
2007     }
2008   }
2009 
2010   return TheCallResult;
2011 }
2012 
2013 // Get the valid immediate range for the specified NEON type code.
2014 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2015   NeonTypeFlags Type(t);
2016   int IsQuad = ForceQuad ? true : Type.isQuad();
2017   switch (Type.getEltType()) {
2018   case NeonTypeFlags::Int8:
2019   case NeonTypeFlags::Poly8:
2020     return shift ? 7 : (8 << IsQuad) - 1;
2021   case NeonTypeFlags::Int16:
2022   case NeonTypeFlags::Poly16:
2023     return shift ? 15 : (4 << IsQuad) - 1;
2024   case NeonTypeFlags::Int32:
2025     return shift ? 31 : (2 << IsQuad) - 1;
2026   case NeonTypeFlags::Int64:
2027   case NeonTypeFlags::Poly64:
2028     return shift ? 63 : (1 << IsQuad) - 1;
2029   case NeonTypeFlags::Poly128:
2030     return shift ? 127 : (1 << IsQuad) - 1;
2031   case NeonTypeFlags::Float16:
2032     assert(!shift && "cannot shift float types!");
2033     return (4 << IsQuad) - 1;
2034   case NeonTypeFlags::Float32:
2035     assert(!shift && "cannot shift float types!");
2036     return (2 << IsQuad) - 1;
2037   case NeonTypeFlags::Float64:
2038     assert(!shift && "cannot shift float types!");
2039     return (1 << IsQuad) - 1;
2040   case NeonTypeFlags::BFloat16:
2041     assert(!shift && "cannot shift float types!");
2042     return (4 << IsQuad) - 1;
2043   }
2044   llvm_unreachable("Invalid NeonTypeFlag!");
2045 }
2046 
2047 /// getNeonEltType - Return the QualType corresponding to the elements of
2048 /// the vector type specified by the NeonTypeFlags.  This is used to check
2049 /// the pointer arguments for Neon load/store intrinsics.
2050 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2051                                bool IsPolyUnsigned, bool IsInt64Long) {
2052   switch (Flags.getEltType()) {
2053   case NeonTypeFlags::Int8:
2054     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2055   case NeonTypeFlags::Int16:
2056     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2057   case NeonTypeFlags::Int32:
2058     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2059   case NeonTypeFlags::Int64:
2060     if (IsInt64Long)
2061       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2062     else
2063       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2064                                 : Context.LongLongTy;
2065   case NeonTypeFlags::Poly8:
2066     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2067   case NeonTypeFlags::Poly16:
2068     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2069   case NeonTypeFlags::Poly64:
2070     if (IsInt64Long)
2071       return Context.UnsignedLongTy;
2072     else
2073       return Context.UnsignedLongLongTy;
2074   case NeonTypeFlags::Poly128:
2075     break;
2076   case NeonTypeFlags::Float16:
2077     return Context.HalfTy;
2078   case NeonTypeFlags::Float32:
2079     return Context.FloatTy;
2080   case NeonTypeFlags::Float64:
2081     return Context.DoubleTy;
2082   case NeonTypeFlags::BFloat16:
2083     return Context.BFloat16Ty;
2084   }
2085   llvm_unreachable("Invalid NeonTypeFlag!");
2086 }
2087 
2088 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2089   // Range check SVE intrinsics that take immediate values.
2090   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2091 
2092   switch (BuiltinID) {
2093   default:
2094     return false;
2095 #define GET_SVE_IMMEDIATE_CHECK
2096 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2097 #undef GET_SVE_IMMEDIATE_CHECK
2098   }
2099 
2100   // Perform all the immediate checks for this builtin call.
2101   bool HasError = false;
2102   for (auto &I : ImmChecks) {
2103     int ArgNum, CheckTy, ElementSizeInBits;
2104     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2105 
2106     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2107 
2108     // Function that checks whether the operand (ArgNum) is an immediate
2109     // that is one of the predefined values.
2110     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2111                                    int ErrDiag) -> bool {
2112       // We can't check the value of a dependent argument.
2113       Expr *Arg = TheCall->getArg(ArgNum);
2114       if (Arg->isTypeDependent() || Arg->isValueDependent())
2115         return false;
2116 
2117       // Check constant-ness first.
2118       llvm::APSInt Imm;
2119       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2120         return true;
2121 
2122       if (!CheckImm(Imm.getSExtValue()))
2123         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2124       return false;
2125     };
2126 
2127     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2128     case SVETypeFlags::ImmCheck0_31:
2129       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2130         HasError = true;
2131       break;
2132     case SVETypeFlags::ImmCheck0_13:
2133       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2134         HasError = true;
2135       break;
2136     case SVETypeFlags::ImmCheck1_16:
2137       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2138         HasError = true;
2139       break;
2140     case SVETypeFlags::ImmCheck0_7:
2141       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2142         HasError = true;
2143       break;
2144     case SVETypeFlags::ImmCheckExtract:
2145       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2146                                       (2048 / ElementSizeInBits) - 1))
2147         HasError = true;
2148       break;
2149     case SVETypeFlags::ImmCheckShiftRight:
2150       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2151         HasError = true;
2152       break;
2153     case SVETypeFlags::ImmCheckShiftRightNarrow:
2154       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2155                                       ElementSizeInBits / 2))
2156         HasError = true;
2157       break;
2158     case SVETypeFlags::ImmCheckShiftLeft:
2159       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2160                                       ElementSizeInBits - 1))
2161         HasError = true;
2162       break;
2163     case SVETypeFlags::ImmCheckLaneIndex:
2164       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2165                                       (128 / (1 * ElementSizeInBits)) - 1))
2166         HasError = true;
2167       break;
2168     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2169       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2170                                       (128 / (2 * ElementSizeInBits)) - 1))
2171         HasError = true;
2172       break;
2173     case SVETypeFlags::ImmCheckLaneIndexDot:
2174       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2175                                       (128 / (4 * ElementSizeInBits)) - 1))
2176         HasError = true;
2177       break;
2178     case SVETypeFlags::ImmCheckComplexRot90_270:
2179       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2180                               diag::err_rotation_argument_to_cadd))
2181         HasError = true;
2182       break;
2183     case SVETypeFlags::ImmCheckComplexRotAll90:
2184       if (CheckImmediateInSet(
2185               [](int64_t V) {
2186                 return V == 0 || V == 90 || V == 180 || V == 270;
2187               },
2188               diag::err_rotation_argument_to_cmla))
2189         HasError = true;
2190       break;
2191     case SVETypeFlags::ImmCheck0_1:
2192       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2193         HasError = true;
2194       break;
2195     case SVETypeFlags::ImmCheck0_2:
2196       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2197         HasError = true;
2198       break;
2199     case SVETypeFlags::ImmCheck0_3:
2200       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2201         HasError = true;
2202       break;
2203     }
2204   }
2205 
2206   return HasError;
2207 }
2208 
2209 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2210                                         unsigned BuiltinID, CallExpr *TheCall) {
2211   llvm::APSInt Result;
2212   uint64_t mask = 0;
2213   unsigned TV = 0;
2214   int PtrArgNum = -1;
2215   bool HasConstPtr = false;
2216   switch (BuiltinID) {
2217 #define GET_NEON_OVERLOAD_CHECK
2218 #include "clang/Basic/arm_neon.inc"
2219 #include "clang/Basic/arm_fp16.inc"
2220 #undef GET_NEON_OVERLOAD_CHECK
2221   }
2222 
2223   // For NEON intrinsics which are overloaded on vector element type, validate
2224   // the immediate which specifies which variant to emit.
2225   unsigned ImmArg = TheCall->getNumArgs()-1;
2226   if (mask) {
2227     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2228       return true;
2229 
2230     TV = Result.getLimitedValue(64);
2231     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2232       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2233              << TheCall->getArg(ImmArg)->getSourceRange();
2234   }
2235 
2236   if (PtrArgNum >= 0) {
2237     // Check that pointer arguments have the specified type.
2238     Expr *Arg = TheCall->getArg(PtrArgNum);
2239     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2240       Arg = ICE->getSubExpr();
2241     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2242     QualType RHSTy = RHS.get()->getType();
2243 
2244     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2245     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2246                           Arch == llvm::Triple::aarch64_32 ||
2247                           Arch == llvm::Triple::aarch64_be;
2248     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2249     QualType EltTy =
2250         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2251     if (HasConstPtr)
2252       EltTy = EltTy.withConst();
2253     QualType LHSTy = Context.getPointerType(EltTy);
2254     AssignConvertType ConvTy;
2255     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2256     if (RHS.isInvalid())
2257       return true;
2258     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2259                                  RHS.get(), AA_Assigning))
2260       return true;
2261   }
2262 
2263   // For NEON intrinsics which take an immediate value as part of the
2264   // instruction, range check them here.
2265   unsigned i = 0, l = 0, u = 0;
2266   switch (BuiltinID) {
2267   default:
2268     return false;
2269   #define GET_NEON_IMMEDIATE_CHECK
2270   #include "clang/Basic/arm_neon.inc"
2271   #include "clang/Basic/arm_fp16.inc"
2272   #undef GET_NEON_IMMEDIATE_CHECK
2273   }
2274 
2275   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2276 }
2277 
2278 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2279   switch (BuiltinID) {
2280   default:
2281     return false;
2282   #include "clang/Basic/arm_mve_builtin_sema.inc"
2283   }
2284 }
2285 
2286 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2287                                        CallExpr *TheCall) {
2288   bool Err = false;
2289   switch (BuiltinID) {
2290   default:
2291     return false;
2292 #include "clang/Basic/arm_cde_builtin_sema.inc"
2293   }
2294 
2295   if (Err)
2296     return true;
2297 
2298   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2299 }
2300 
2301 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2302                                         const Expr *CoprocArg, bool WantCDE) {
2303   if (isConstantEvaluated())
2304     return false;
2305 
2306   // We can't check the value of a dependent argument.
2307   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2308     return false;
2309 
2310   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2311   int64_t CoprocNo = CoprocNoAP.getExtValue();
2312   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2313 
2314   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2315   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2316 
2317   if (IsCDECoproc != WantCDE)
2318     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2319            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2320 
2321   return false;
2322 }
2323 
2324 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2325                                         unsigned MaxWidth) {
2326   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2327           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2328           BuiltinID == ARM::BI__builtin_arm_strex ||
2329           BuiltinID == ARM::BI__builtin_arm_stlex ||
2330           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2331           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2332           BuiltinID == AArch64::BI__builtin_arm_strex ||
2333           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2334          "unexpected ARM builtin");
2335   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2336                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2337                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2338                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2339 
2340   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2341 
2342   // Ensure that we have the proper number of arguments.
2343   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2344     return true;
2345 
2346   // Inspect the pointer argument of the atomic builtin.  This should always be
2347   // a pointer type, whose element is an integral scalar or pointer type.
2348   // Because it is a pointer type, we don't have to worry about any implicit
2349   // casts here.
2350   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2351   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2352   if (PointerArgRes.isInvalid())
2353     return true;
2354   PointerArg = PointerArgRes.get();
2355 
2356   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2357   if (!pointerType) {
2358     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2359         << PointerArg->getType() << PointerArg->getSourceRange();
2360     return true;
2361   }
2362 
2363   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2364   // task is to insert the appropriate casts into the AST. First work out just
2365   // what the appropriate type is.
2366   QualType ValType = pointerType->getPointeeType();
2367   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2368   if (IsLdrex)
2369     AddrType.addConst();
2370 
2371   // Issue a warning if the cast is dodgy.
2372   CastKind CastNeeded = CK_NoOp;
2373   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2374     CastNeeded = CK_BitCast;
2375     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2376         << PointerArg->getType() << Context.getPointerType(AddrType)
2377         << AA_Passing << PointerArg->getSourceRange();
2378   }
2379 
2380   // Finally, do the cast and replace the argument with the corrected version.
2381   AddrType = Context.getPointerType(AddrType);
2382   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2383   if (PointerArgRes.isInvalid())
2384     return true;
2385   PointerArg = PointerArgRes.get();
2386 
2387   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2388 
2389   // In general, we allow ints, floats and pointers to be loaded and stored.
2390   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2391       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2392     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2393         << PointerArg->getType() << PointerArg->getSourceRange();
2394     return true;
2395   }
2396 
2397   // But ARM doesn't have instructions to deal with 128-bit versions.
2398   if (Context.getTypeSize(ValType) > MaxWidth) {
2399     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2400     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2401         << PointerArg->getType() << PointerArg->getSourceRange();
2402     return true;
2403   }
2404 
2405   switch (ValType.getObjCLifetime()) {
2406   case Qualifiers::OCL_None:
2407   case Qualifiers::OCL_ExplicitNone:
2408     // okay
2409     break;
2410 
2411   case Qualifiers::OCL_Weak:
2412   case Qualifiers::OCL_Strong:
2413   case Qualifiers::OCL_Autoreleasing:
2414     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2415         << ValType << PointerArg->getSourceRange();
2416     return true;
2417   }
2418 
2419   if (IsLdrex) {
2420     TheCall->setType(ValType);
2421     return false;
2422   }
2423 
2424   // Initialize the argument to be stored.
2425   ExprResult ValArg = TheCall->getArg(0);
2426   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2427       Context, ValType, /*consume*/ false);
2428   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2429   if (ValArg.isInvalid())
2430     return true;
2431   TheCall->setArg(0, ValArg.get());
2432 
2433   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2434   // but the custom checker bypasses all default analysis.
2435   TheCall->setType(Context.IntTy);
2436   return false;
2437 }
2438 
2439 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2440                                        CallExpr *TheCall) {
2441   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2442       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2443       BuiltinID == ARM::BI__builtin_arm_strex ||
2444       BuiltinID == ARM::BI__builtin_arm_stlex) {
2445     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2446   }
2447 
2448   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2449     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2450       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2451   }
2452 
2453   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2454       BuiltinID == ARM::BI__builtin_arm_wsr64)
2455     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2456 
2457   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2458       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2459       BuiltinID == ARM::BI__builtin_arm_wsr ||
2460       BuiltinID == ARM::BI__builtin_arm_wsrp)
2461     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2462 
2463   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2464     return true;
2465   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2466     return true;
2467   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2468     return true;
2469 
2470   // For intrinsics which take an immediate value as part of the instruction,
2471   // range check them here.
2472   // FIXME: VFP Intrinsics should error if VFP not present.
2473   switch (BuiltinID) {
2474   default: return false;
2475   case ARM::BI__builtin_arm_ssat:
2476     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2477   case ARM::BI__builtin_arm_usat:
2478     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2479   case ARM::BI__builtin_arm_ssat16:
2480     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2481   case ARM::BI__builtin_arm_usat16:
2482     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2483   case ARM::BI__builtin_arm_vcvtr_f:
2484   case ARM::BI__builtin_arm_vcvtr_d:
2485     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2486   case ARM::BI__builtin_arm_dmb:
2487   case ARM::BI__builtin_arm_dsb:
2488   case ARM::BI__builtin_arm_isb:
2489   case ARM::BI__builtin_arm_dbg:
2490     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2491   case ARM::BI__builtin_arm_cdp:
2492   case ARM::BI__builtin_arm_cdp2:
2493   case ARM::BI__builtin_arm_mcr:
2494   case ARM::BI__builtin_arm_mcr2:
2495   case ARM::BI__builtin_arm_mrc:
2496   case ARM::BI__builtin_arm_mrc2:
2497   case ARM::BI__builtin_arm_mcrr:
2498   case ARM::BI__builtin_arm_mcrr2:
2499   case ARM::BI__builtin_arm_mrrc:
2500   case ARM::BI__builtin_arm_mrrc2:
2501   case ARM::BI__builtin_arm_ldc:
2502   case ARM::BI__builtin_arm_ldcl:
2503   case ARM::BI__builtin_arm_ldc2:
2504   case ARM::BI__builtin_arm_ldc2l:
2505   case ARM::BI__builtin_arm_stc:
2506   case ARM::BI__builtin_arm_stcl:
2507   case ARM::BI__builtin_arm_stc2:
2508   case ARM::BI__builtin_arm_stc2l:
2509     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2510            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2511                                         /*WantCDE*/ false);
2512   }
2513 }
2514 
2515 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2516                                            unsigned BuiltinID,
2517                                            CallExpr *TheCall) {
2518   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2519       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2520       BuiltinID == AArch64::BI__builtin_arm_strex ||
2521       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2522     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2523   }
2524 
2525   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2526     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2527       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2528       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2529       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2530   }
2531 
2532   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2533       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2534     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2535 
2536   // Memory Tagging Extensions (MTE) Intrinsics
2537   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2538       BuiltinID == AArch64::BI__builtin_arm_addg ||
2539       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2540       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2541       BuiltinID == AArch64::BI__builtin_arm_stg ||
2542       BuiltinID == AArch64::BI__builtin_arm_subp) {
2543     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2544   }
2545 
2546   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2547       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2548       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2549       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2550     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2551 
2552   // Only check the valid encoding range. Any constant in this range would be
2553   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2554   // an exception for incorrect registers. This matches MSVC behavior.
2555   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2556       BuiltinID == AArch64::BI_WriteStatusReg)
2557     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2558 
2559   if (BuiltinID == AArch64::BI__getReg)
2560     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2561 
2562   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2563     return true;
2564 
2565   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2566     return true;
2567 
2568   // For intrinsics which take an immediate value as part of the instruction,
2569   // range check them here.
2570   unsigned i = 0, l = 0, u = 0;
2571   switch (BuiltinID) {
2572   default: return false;
2573   case AArch64::BI__builtin_arm_dmb:
2574   case AArch64::BI__builtin_arm_dsb:
2575   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2576   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2577   }
2578 
2579   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2580 }
2581 
2582 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2583   if (Arg->getType()->getAsPlaceholderType())
2584     return false;
2585 
2586   // The first argument needs to be a record field access.
2587   // If it is an array element access, we delay decision
2588   // to BPF backend to check whether the access is a
2589   // field access or not.
2590   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2591           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2592           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2593 }
2594 
2595 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2596                             QualType VectorTy, QualType EltTy) {
2597   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2598   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2599     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2600         << Call->getSourceRange() << VectorEltTy << EltTy;
2601     return false;
2602   }
2603   return true;
2604 }
2605 
2606 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2607   QualType ArgType = Arg->getType();
2608   if (ArgType->getAsPlaceholderType())
2609     return false;
2610 
2611   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2612   // format:
2613   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2614   //   2. <type> var;
2615   //      __builtin_preserve_type_info(var, flag);
2616   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2617       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2618     return false;
2619 
2620   // Typedef type.
2621   if (ArgType->getAs<TypedefType>())
2622     return true;
2623 
2624   // Record type or Enum type.
2625   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2626   if (const auto *RT = Ty->getAs<RecordType>()) {
2627     if (!RT->getDecl()->getDeclName().isEmpty())
2628       return true;
2629   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2630     if (!ET->getDecl()->getDeclName().isEmpty())
2631       return true;
2632   }
2633 
2634   return false;
2635 }
2636 
2637 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2638   QualType ArgType = Arg->getType();
2639   if (ArgType->getAsPlaceholderType())
2640     return false;
2641 
2642   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2643   // format:
2644   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2645   //                                 flag);
2646   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2647   if (!UO)
2648     return false;
2649 
2650   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2651   if (!CE)
2652     return false;
2653   if (CE->getCastKind() != CK_IntegralToPointer &&
2654       CE->getCastKind() != CK_NullToPointer)
2655     return false;
2656 
2657   // The integer must be from an EnumConstantDecl.
2658   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2659   if (!DR)
2660     return false;
2661 
2662   const EnumConstantDecl *Enumerator =
2663       dyn_cast<EnumConstantDecl>(DR->getDecl());
2664   if (!Enumerator)
2665     return false;
2666 
2667   // The type must be EnumType.
2668   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2669   const auto *ET = Ty->getAs<EnumType>();
2670   if (!ET)
2671     return false;
2672 
2673   // The enum value must be supported.
2674   for (auto *EDI : ET->getDecl()->enumerators()) {
2675     if (EDI == Enumerator)
2676       return true;
2677   }
2678 
2679   return false;
2680 }
2681 
2682 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2683                                        CallExpr *TheCall) {
2684   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2685           BuiltinID == BPF::BI__builtin_btf_type_id ||
2686           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2687           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2688          "unexpected BPF builtin");
2689 
2690   if (checkArgCount(*this, TheCall, 2))
2691     return true;
2692 
2693   // The second argument needs to be a constant int
2694   Expr *Arg = TheCall->getArg(1);
2695   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2696   diag::kind kind;
2697   if (!Value) {
2698     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2699       kind = diag::err_preserve_field_info_not_const;
2700     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2701       kind = diag::err_btf_type_id_not_const;
2702     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2703       kind = diag::err_preserve_type_info_not_const;
2704     else
2705       kind = diag::err_preserve_enum_value_not_const;
2706     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2707     return true;
2708   }
2709 
2710   // The first argument
2711   Arg = TheCall->getArg(0);
2712   bool InvalidArg = false;
2713   bool ReturnUnsignedInt = true;
2714   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2715     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2716       InvalidArg = true;
2717       kind = diag::err_preserve_field_info_not_field;
2718     }
2719   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2720     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2721       InvalidArg = true;
2722       kind = diag::err_preserve_type_info_invalid;
2723     }
2724   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2725     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2726       InvalidArg = true;
2727       kind = diag::err_preserve_enum_value_invalid;
2728     }
2729     ReturnUnsignedInt = false;
2730   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2731     ReturnUnsignedInt = false;
2732   }
2733 
2734   if (InvalidArg) {
2735     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2736     return true;
2737   }
2738 
2739   if (ReturnUnsignedInt)
2740     TheCall->setType(Context.UnsignedIntTy);
2741   else
2742     TheCall->setType(Context.UnsignedLongTy);
2743   return false;
2744 }
2745 
2746 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2747   struct ArgInfo {
2748     uint8_t OpNum;
2749     bool IsSigned;
2750     uint8_t BitWidth;
2751     uint8_t Align;
2752   };
2753   struct BuiltinInfo {
2754     unsigned BuiltinID;
2755     ArgInfo Infos[2];
2756   };
2757 
2758   static BuiltinInfo Infos[] = {
2759     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2760     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2761     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2762     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2763     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2764     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2765     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2766     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2767     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2768     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2769     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2770 
2771     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2776     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2782 
2783     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2835                                                       {{ 1, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2843                                                       {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2850                                                        { 2, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2852                                                        { 2, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2854                                                        { 3, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2856                                                        { 3, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2873                                                       {{ 2, false, 4,  0 },
2874                                                        { 3, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2876                                                       {{ 2, false, 4,  0 },
2877                                                        { 3, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2879                                                       {{ 2, false, 4,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2882                                                       {{ 2, false, 4,  0 },
2883                                                        { 3, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2895                                                        { 2, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2897                                                        { 2, false, 6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2907                                                       {{ 1, false, 4,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2910                                                       {{ 1, false, 4,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2931                                                       {{ 3, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2936                                                       {{ 3, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2941                                                       {{ 3, false, 1,  0 }} },
2942   };
2943 
2944   // Use a dynamically initialized static to sort the table exactly once on
2945   // first run.
2946   static const bool SortOnce =
2947       (llvm::sort(Infos,
2948                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2949                    return LHS.BuiltinID < RHS.BuiltinID;
2950                  }),
2951        true);
2952   (void)SortOnce;
2953 
2954   const BuiltinInfo *F = llvm::partition_point(
2955       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2956   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2957     return false;
2958 
2959   bool Error = false;
2960 
2961   for (const ArgInfo &A : F->Infos) {
2962     // Ignore empty ArgInfo elements.
2963     if (A.BitWidth == 0)
2964       continue;
2965 
2966     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2967     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2968     if (!A.Align) {
2969       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2970     } else {
2971       unsigned M = 1 << A.Align;
2972       Min *= M;
2973       Max *= M;
2974       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2975                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2976     }
2977   }
2978   return Error;
2979 }
2980 
2981 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2982                                            CallExpr *TheCall) {
2983   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2984 }
2985 
2986 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2987                                         unsigned BuiltinID, CallExpr *TheCall) {
2988   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2989          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2990 }
2991 
2992 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2993                                CallExpr *TheCall) {
2994 
2995   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2996       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2997     if (!TI.hasFeature("dsp"))
2998       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2999   }
3000 
3001   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3002       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3003     if (!TI.hasFeature("dspr2"))
3004       return Diag(TheCall->getBeginLoc(),
3005                   diag::err_mips_builtin_requires_dspr2);
3006   }
3007 
3008   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3009       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3010     if (!TI.hasFeature("msa"))
3011       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3012   }
3013 
3014   return false;
3015 }
3016 
3017 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3018 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3019 // ordering for DSP is unspecified. MSA is ordered by the data format used
3020 // by the underlying instruction i.e., df/m, df/n and then by size.
3021 //
3022 // FIXME: The size tests here should instead be tablegen'd along with the
3023 //        definitions from include/clang/Basic/BuiltinsMips.def.
3024 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3025 //        be too.
3026 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3027   unsigned i = 0, l = 0, u = 0, m = 0;
3028   switch (BuiltinID) {
3029   default: return false;
3030   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3031   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3032   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3033   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3034   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3035   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3036   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3037   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3038   // df/m field.
3039   // These intrinsics take an unsigned 3 bit immediate.
3040   case Mips::BI__builtin_msa_bclri_b:
3041   case Mips::BI__builtin_msa_bnegi_b:
3042   case Mips::BI__builtin_msa_bseti_b:
3043   case Mips::BI__builtin_msa_sat_s_b:
3044   case Mips::BI__builtin_msa_sat_u_b:
3045   case Mips::BI__builtin_msa_slli_b:
3046   case Mips::BI__builtin_msa_srai_b:
3047   case Mips::BI__builtin_msa_srari_b:
3048   case Mips::BI__builtin_msa_srli_b:
3049   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3050   case Mips::BI__builtin_msa_binsli_b:
3051   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3052   // These intrinsics take an unsigned 4 bit immediate.
3053   case Mips::BI__builtin_msa_bclri_h:
3054   case Mips::BI__builtin_msa_bnegi_h:
3055   case Mips::BI__builtin_msa_bseti_h:
3056   case Mips::BI__builtin_msa_sat_s_h:
3057   case Mips::BI__builtin_msa_sat_u_h:
3058   case Mips::BI__builtin_msa_slli_h:
3059   case Mips::BI__builtin_msa_srai_h:
3060   case Mips::BI__builtin_msa_srari_h:
3061   case Mips::BI__builtin_msa_srli_h:
3062   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3063   case Mips::BI__builtin_msa_binsli_h:
3064   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3065   // These intrinsics take an unsigned 5 bit immediate.
3066   // The first block of intrinsics actually have an unsigned 5 bit field,
3067   // not a df/n field.
3068   case Mips::BI__builtin_msa_cfcmsa:
3069   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3070   case Mips::BI__builtin_msa_clei_u_b:
3071   case Mips::BI__builtin_msa_clei_u_h:
3072   case Mips::BI__builtin_msa_clei_u_w:
3073   case Mips::BI__builtin_msa_clei_u_d:
3074   case Mips::BI__builtin_msa_clti_u_b:
3075   case Mips::BI__builtin_msa_clti_u_h:
3076   case Mips::BI__builtin_msa_clti_u_w:
3077   case Mips::BI__builtin_msa_clti_u_d:
3078   case Mips::BI__builtin_msa_maxi_u_b:
3079   case Mips::BI__builtin_msa_maxi_u_h:
3080   case Mips::BI__builtin_msa_maxi_u_w:
3081   case Mips::BI__builtin_msa_maxi_u_d:
3082   case Mips::BI__builtin_msa_mini_u_b:
3083   case Mips::BI__builtin_msa_mini_u_h:
3084   case Mips::BI__builtin_msa_mini_u_w:
3085   case Mips::BI__builtin_msa_mini_u_d:
3086   case Mips::BI__builtin_msa_addvi_b:
3087   case Mips::BI__builtin_msa_addvi_h:
3088   case Mips::BI__builtin_msa_addvi_w:
3089   case Mips::BI__builtin_msa_addvi_d:
3090   case Mips::BI__builtin_msa_bclri_w:
3091   case Mips::BI__builtin_msa_bnegi_w:
3092   case Mips::BI__builtin_msa_bseti_w:
3093   case Mips::BI__builtin_msa_sat_s_w:
3094   case Mips::BI__builtin_msa_sat_u_w:
3095   case Mips::BI__builtin_msa_slli_w:
3096   case Mips::BI__builtin_msa_srai_w:
3097   case Mips::BI__builtin_msa_srari_w:
3098   case Mips::BI__builtin_msa_srli_w:
3099   case Mips::BI__builtin_msa_srlri_w:
3100   case Mips::BI__builtin_msa_subvi_b:
3101   case Mips::BI__builtin_msa_subvi_h:
3102   case Mips::BI__builtin_msa_subvi_w:
3103   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3104   case Mips::BI__builtin_msa_binsli_w:
3105   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3106   // These intrinsics take an unsigned 6 bit immediate.
3107   case Mips::BI__builtin_msa_bclri_d:
3108   case Mips::BI__builtin_msa_bnegi_d:
3109   case Mips::BI__builtin_msa_bseti_d:
3110   case Mips::BI__builtin_msa_sat_s_d:
3111   case Mips::BI__builtin_msa_sat_u_d:
3112   case Mips::BI__builtin_msa_slli_d:
3113   case Mips::BI__builtin_msa_srai_d:
3114   case Mips::BI__builtin_msa_srari_d:
3115   case Mips::BI__builtin_msa_srli_d:
3116   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3117   case Mips::BI__builtin_msa_binsli_d:
3118   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3119   // These intrinsics take a signed 5 bit immediate.
3120   case Mips::BI__builtin_msa_ceqi_b:
3121   case Mips::BI__builtin_msa_ceqi_h:
3122   case Mips::BI__builtin_msa_ceqi_w:
3123   case Mips::BI__builtin_msa_ceqi_d:
3124   case Mips::BI__builtin_msa_clti_s_b:
3125   case Mips::BI__builtin_msa_clti_s_h:
3126   case Mips::BI__builtin_msa_clti_s_w:
3127   case Mips::BI__builtin_msa_clti_s_d:
3128   case Mips::BI__builtin_msa_clei_s_b:
3129   case Mips::BI__builtin_msa_clei_s_h:
3130   case Mips::BI__builtin_msa_clei_s_w:
3131   case Mips::BI__builtin_msa_clei_s_d:
3132   case Mips::BI__builtin_msa_maxi_s_b:
3133   case Mips::BI__builtin_msa_maxi_s_h:
3134   case Mips::BI__builtin_msa_maxi_s_w:
3135   case Mips::BI__builtin_msa_maxi_s_d:
3136   case Mips::BI__builtin_msa_mini_s_b:
3137   case Mips::BI__builtin_msa_mini_s_h:
3138   case Mips::BI__builtin_msa_mini_s_w:
3139   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3140   // These intrinsics take an unsigned 8 bit immediate.
3141   case Mips::BI__builtin_msa_andi_b:
3142   case Mips::BI__builtin_msa_nori_b:
3143   case Mips::BI__builtin_msa_ori_b:
3144   case Mips::BI__builtin_msa_shf_b:
3145   case Mips::BI__builtin_msa_shf_h:
3146   case Mips::BI__builtin_msa_shf_w:
3147   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3148   case Mips::BI__builtin_msa_bseli_b:
3149   case Mips::BI__builtin_msa_bmnzi_b:
3150   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3151   // df/n format
3152   // These intrinsics take an unsigned 4 bit immediate.
3153   case Mips::BI__builtin_msa_copy_s_b:
3154   case Mips::BI__builtin_msa_copy_u_b:
3155   case Mips::BI__builtin_msa_insve_b:
3156   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3157   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3158   // These intrinsics take an unsigned 3 bit immediate.
3159   case Mips::BI__builtin_msa_copy_s_h:
3160   case Mips::BI__builtin_msa_copy_u_h:
3161   case Mips::BI__builtin_msa_insve_h:
3162   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3163   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3164   // These intrinsics take an unsigned 2 bit immediate.
3165   case Mips::BI__builtin_msa_copy_s_w:
3166   case Mips::BI__builtin_msa_copy_u_w:
3167   case Mips::BI__builtin_msa_insve_w:
3168   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3169   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3170   // These intrinsics take an unsigned 1 bit immediate.
3171   case Mips::BI__builtin_msa_copy_s_d:
3172   case Mips::BI__builtin_msa_copy_u_d:
3173   case Mips::BI__builtin_msa_insve_d:
3174   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3175   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3176   // Memory offsets and immediate loads.
3177   // These intrinsics take a signed 10 bit immediate.
3178   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3179   case Mips::BI__builtin_msa_ldi_h:
3180   case Mips::BI__builtin_msa_ldi_w:
3181   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3182   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3183   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3184   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3185   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3186   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3187   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3188   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3189   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3190   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3191   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3192   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3193   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3194   }
3195 
3196   if (!m)
3197     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3198 
3199   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3200          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3201 }
3202 
3203 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3204 /// advancing the pointer over the consumed characters. The decoded type is
3205 /// returned. If the decoded type represents a constant integer with a
3206 /// constraint on its value then Mask is set to that value. The type descriptors
3207 /// used in Str are specific to PPC MMA builtins and are documented in the file
3208 /// defining the PPC builtins.
3209 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3210                                         unsigned &Mask) {
3211   bool RequireICE = false;
3212   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3213   switch (*Str++) {
3214   case 'V':
3215     return Context.getVectorType(Context.UnsignedCharTy, 16,
3216                                  VectorType::VectorKind::AltiVecVector);
3217   case 'i': {
3218     char *End;
3219     unsigned size = strtoul(Str, &End, 10);
3220     assert(End != Str && "Missing constant parameter constraint");
3221     Str = End;
3222     Mask = size;
3223     return Context.IntTy;
3224   }
3225   case 'W': {
3226     char *End;
3227     unsigned size = strtoul(Str, &End, 10);
3228     assert(End != Str && "Missing PowerPC MMA type size");
3229     Str = End;
3230     QualType Type;
3231     switch (size) {
3232   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3233     case size: Type = Context.Id##Ty; break;
3234   #include "clang/Basic/PPCTypes.def"
3235     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3236     }
3237     bool CheckVectorArgs = false;
3238     while (!CheckVectorArgs) {
3239       switch (*Str++) {
3240       case '*':
3241         Type = Context.getPointerType(Type);
3242         break;
3243       case 'C':
3244         Type = Type.withConst();
3245         break;
3246       default:
3247         CheckVectorArgs = true;
3248         --Str;
3249         break;
3250       }
3251     }
3252     return Type;
3253   }
3254   default:
3255     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3256   }
3257 }
3258 
3259 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3260                                        CallExpr *TheCall) {
3261   unsigned i = 0, l = 0, u = 0;
3262   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3263                       BuiltinID == PPC::BI__builtin_divdeu ||
3264                       BuiltinID == PPC::BI__builtin_bpermd;
3265   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3266   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3267                        BuiltinID == PPC::BI__builtin_divweu ||
3268                        BuiltinID == PPC::BI__builtin_divde ||
3269                        BuiltinID == PPC::BI__builtin_divdeu;
3270 
3271   if (Is64BitBltin && !IsTarget64Bit)
3272     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3273            << TheCall->getSourceRange();
3274 
3275   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3276       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3277     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3278            << TheCall->getSourceRange();
3279 
3280   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3281     if (!TI.hasFeature("vsx"))
3282       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3283              << TheCall->getSourceRange();
3284     return false;
3285   };
3286 
3287   switch (BuiltinID) {
3288   default: return false;
3289   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3290   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3291     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3292            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3293   case PPC::BI__builtin_altivec_dss:
3294     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3295   case PPC::BI__builtin_tbegin:
3296   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3297   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3298   case PPC::BI__builtin_tabortwc:
3299   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3300   case PPC::BI__builtin_tabortwci:
3301   case PPC::BI__builtin_tabortdci:
3302     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3303            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3304   case PPC::BI__builtin_altivec_dst:
3305   case PPC::BI__builtin_altivec_dstt:
3306   case PPC::BI__builtin_altivec_dstst:
3307   case PPC::BI__builtin_altivec_dststt:
3308     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3309   case PPC::BI__builtin_vsx_xxpermdi:
3310   case PPC::BI__builtin_vsx_xxsldwi:
3311     return SemaBuiltinVSX(TheCall);
3312   case PPC::BI__builtin_unpack_vector_int128:
3313     return SemaVSXCheck(TheCall) ||
3314            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3315   case PPC::BI__builtin_pack_vector_int128:
3316     return SemaVSXCheck(TheCall);
3317   case PPC::BI__builtin_altivec_vgnb:
3318      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3319   case PPC::BI__builtin_altivec_vec_replace_elt:
3320   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3321     QualType VecTy = TheCall->getArg(0)->getType();
3322     QualType EltTy = TheCall->getArg(1)->getType();
3323     unsigned Width = Context.getIntWidth(EltTy);
3324     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3325            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3326   }
3327   case PPC::BI__builtin_vsx_xxeval:
3328      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3329   case PPC::BI__builtin_altivec_vsldbi:
3330      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3331   case PPC::BI__builtin_altivec_vsrdbi:
3332      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3333   case PPC::BI__builtin_vsx_xxpermx:
3334      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3335 #define CUSTOM_BUILTIN(Name, Types, Acc) \
3336   case PPC::BI__builtin_##Name: \
3337     return SemaBuiltinPPCMMACall(TheCall, Types);
3338 #include "clang/Basic/BuiltinsPPC.def"
3339   }
3340   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3341 }
3342 
3343 // Check if the given type is a non-pointer PPC MMA type. This function is used
3344 // in Sema to prevent invalid uses of restricted PPC MMA types.
3345 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3346   if (Type->isPointerType() || Type->isArrayType())
3347     return false;
3348 
3349   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3350 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3351   if (false
3352 #include "clang/Basic/PPCTypes.def"
3353      ) {
3354     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3355     return true;
3356   }
3357   return false;
3358 }
3359 
3360 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3361                                           CallExpr *TheCall) {
3362   // position of memory order and scope arguments in the builtin
3363   unsigned OrderIndex, ScopeIndex;
3364   switch (BuiltinID) {
3365   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3366   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3367   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3368   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3369     OrderIndex = 2;
3370     ScopeIndex = 3;
3371     break;
3372   case AMDGPU::BI__builtin_amdgcn_fence:
3373     OrderIndex = 0;
3374     ScopeIndex = 1;
3375     break;
3376   default:
3377     return false;
3378   }
3379 
3380   ExprResult Arg = TheCall->getArg(OrderIndex);
3381   auto ArgExpr = Arg.get();
3382   Expr::EvalResult ArgResult;
3383 
3384   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3385     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3386            << ArgExpr->getType();
3387   int ord = ArgResult.Val.getInt().getZExtValue();
3388 
3389   // Check valididty of memory ordering as per C11 / C++11's memody model.
3390   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3391   case llvm::AtomicOrderingCABI::acquire:
3392   case llvm::AtomicOrderingCABI::release:
3393   case llvm::AtomicOrderingCABI::acq_rel:
3394   case llvm::AtomicOrderingCABI::seq_cst:
3395     break;
3396   default: {
3397     return Diag(ArgExpr->getBeginLoc(),
3398                 diag::warn_atomic_op_has_invalid_memory_order)
3399            << ArgExpr->getSourceRange();
3400   }
3401   }
3402 
3403   Arg = TheCall->getArg(ScopeIndex);
3404   ArgExpr = Arg.get();
3405   Expr::EvalResult ArgResult1;
3406   // Check that sync scope is a constant literal
3407   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3408     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3409            << ArgExpr->getType();
3410 
3411   return false;
3412 }
3413 
3414 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3415                                          unsigned BuiltinID,
3416                                          CallExpr *TheCall) {
3417   // CodeGenFunction can also detect this, but this gives a better error
3418   // message.
3419   bool FeatureMissing = false;
3420   SmallVector<StringRef> ReqFeatures;
3421   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3422   Features.split(ReqFeatures, ',');
3423 
3424   // Check if each required feature is included
3425   for (auto &I : ReqFeatures) {
3426     if (TI.hasFeature(I))
3427       continue;
3428     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3429     I.consume_front("experimental-");
3430     std::string FeatureStr = I.str();
3431     FeatureStr[0] = std::toupper(FeatureStr[0]);
3432 
3433     // Error message
3434     FeatureMissing = true;
3435     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3436         << TheCall->getSourceRange() << StringRef(FeatureStr);
3437   }
3438 
3439   return FeatureMissing;
3440 }
3441 
3442 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3443                                            CallExpr *TheCall) {
3444   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3445     Expr *Arg = TheCall->getArg(0);
3446     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3447       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3448         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3449                << Arg->getSourceRange();
3450   }
3451 
3452   // For intrinsics which take an immediate value as part of the instruction,
3453   // range check them here.
3454   unsigned i = 0, l = 0, u = 0;
3455   switch (BuiltinID) {
3456   default: return false;
3457   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3458   case SystemZ::BI__builtin_s390_verimb:
3459   case SystemZ::BI__builtin_s390_verimh:
3460   case SystemZ::BI__builtin_s390_verimf:
3461   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3462   case SystemZ::BI__builtin_s390_vfaeb:
3463   case SystemZ::BI__builtin_s390_vfaeh:
3464   case SystemZ::BI__builtin_s390_vfaef:
3465   case SystemZ::BI__builtin_s390_vfaebs:
3466   case SystemZ::BI__builtin_s390_vfaehs:
3467   case SystemZ::BI__builtin_s390_vfaefs:
3468   case SystemZ::BI__builtin_s390_vfaezb:
3469   case SystemZ::BI__builtin_s390_vfaezh:
3470   case SystemZ::BI__builtin_s390_vfaezf:
3471   case SystemZ::BI__builtin_s390_vfaezbs:
3472   case SystemZ::BI__builtin_s390_vfaezhs:
3473   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3474   case SystemZ::BI__builtin_s390_vfisb:
3475   case SystemZ::BI__builtin_s390_vfidb:
3476     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3477            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3478   case SystemZ::BI__builtin_s390_vftcisb:
3479   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3480   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3481   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3482   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3483   case SystemZ::BI__builtin_s390_vstrcb:
3484   case SystemZ::BI__builtin_s390_vstrch:
3485   case SystemZ::BI__builtin_s390_vstrcf:
3486   case SystemZ::BI__builtin_s390_vstrczb:
3487   case SystemZ::BI__builtin_s390_vstrczh:
3488   case SystemZ::BI__builtin_s390_vstrczf:
3489   case SystemZ::BI__builtin_s390_vstrcbs:
3490   case SystemZ::BI__builtin_s390_vstrchs:
3491   case SystemZ::BI__builtin_s390_vstrcfs:
3492   case SystemZ::BI__builtin_s390_vstrczbs:
3493   case SystemZ::BI__builtin_s390_vstrczhs:
3494   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3495   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3496   case SystemZ::BI__builtin_s390_vfminsb:
3497   case SystemZ::BI__builtin_s390_vfmaxsb:
3498   case SystemZ::BI__builtin_s390_vfmindb:
3499   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3500   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3501   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3502   }
3503   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3504 }
3505 
3506 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3507 /// This checks that the target supports __builtin_cpu_supports and
3508 /// that the string argument is constant and valid.
3509 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3510                                    CallExpr *TheCall) {
3511   Expr *Arg = TheCall->getArg(0);
3512 
3513   // Check if the argument is a string literal.
3514   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3515     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3516            << Arg->getSourceRange();
3517 
3518   // Check the contents of the string.
3519   StringRef Feature =
3520       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3521   if (!TI.validateCpuSupports(Feature))
3522     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3523            << Arg->getSourceRange();
3524   return false;
3525 }
3526 
3527 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3528 /// This checks that the target supports __builtin_cpu_is and
3529 /// that the string argument is constant and valid.
3530 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3531   Expr *Arg = TheCall->getArg(0);
3532 
3533   // Check if the argument is a string literal.
3534   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3535     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3536            << Arg->getSourceRange();
3537 
3538   // Check the contents of the string.
3539   StringRef Feature =
3540       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3541   if (!TI.validateCpuIs(Feature))
3542     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3543            << Arg->getSourceRange();
3544   return false;
3545 }
3546 
3547 // Check if the rounding mode is legal.
3548 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3549   // Indicates if this instruction has rounding control or just SAE.
3550   bool HasRC = false;
3551 
3552   unsigned ArgNum = 0;
3553   switch (BuiltinID) {
3554   default:
3555     return false;
3556   case X86::BI__builtin_ia32_vcvttsd2si32:
3557   case X86::BI__builtin_ia32_vcvttsd2si64:
3558   case X86::BI__builtin_ia32_vcvttsd2usi32:
3559   case X86::BI__builtin_ia32_vcvttsd2usi64:
3560   case X86::BI__builtin_ia32_vcvttss2si32:
3561   case X86::BI__builtin_ia32_vcvttss2si64:
3562   case X86::BI__builtin_ia32_vcvttss2usi32:
3563   case X86::BI__builtin_ia32_vcvttss2usi64:
3564     ArgNum = 1;
3565     break;
3566   case X86::BI__builtin_ia32_maxpd512:
3567   case X86::BI__builtin_ia32_maxps512:
3568   case X86::BI__builtin_ia32_minpd512:
3569   case X86::BI__builtin_ia32_minps512:
3570     ArgNum = 2;
3571     break;
3572   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3573   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3574   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3575   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3576   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3577   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3578   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3579   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3580   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3581   case X86::BI__builtin_ia32_exp2pd_mask:
3582   case X86::BI__builtin_ia32_exp2ps_mask:
3583   case X86::BI__builtin_ia32_getexppd512_mask:
3584   case X86::BI__builtin_ia32_getexpps512_mask:
3585   case X86::BI__builtin_ia32_rcp28pd_mask:
3586   case X86::BI__builtin_ia32_rcp28ps_mask:
3587   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3588   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3589   case X86::BI__builtin_ia32_vcomisd:
3590   case X86::BI__builtin_ia32_vcomiss:
3591   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3592     ArgNum = 3;
3593     break;
3594   case X86::BI__builtin_ia32_cmppd512_mask:
3595   case X86::BI__builtin_ia32_cmpps512_mask:
3596   case X86::BI__builtin_ia32_cmpsd_mask:
3597   case X86::BI__builtin_ia32_cmpss_mask:
3598   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3599   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3600   case X86::BI__builtin_ia32_getexpss128_round_mask:
3601   case X86::BI__builtin_ia32_getmantpd512_mask:
3602   case X86::BI__builtin_ia32_getmantps512_mask:
3603   case X86::BI__builtin_ia32_maxsd_round_mask:
3604   case X86::BI__builtin_ia32_maxss_round_mask:
3605   case X86::BI__builtin_ia32_minsd_round_mask:
3606   case X86::BI__builtin_ia32_minss_round_mask:
3607   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3608   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3609   case X86::BI__builtin_ia32_reducepd512_mask:
3610   case X86::BI__builtin_ia32_reduceps512_mask:
3611   case X86::BI__builtin_ia32_rndscalepd_mask:
3612   case X86::BI__builtin_ia32_rndscaleps_mask:
3613   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3614   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3615     ArgNum = 4;
3616     break;
3617   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3618   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3619   case X86::BI__builtin_ia32_fixupimmps512_mask:
3620   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3621   case X86::BI__builtin_ia32_fixupimmsd_mask:
3622   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3623   case X86::BI__builtin_ia32_fixupimmss_mask:
3624   case X86::BI__builtin_ia32_fixupimmss_maskz:
3625   case X86::BI__builtin_ia32_getmantsd_round_mask:
3626   case X86::BI__builtin_ia32_getmantss_round_mask:
3627   case X86::BI__builtin_ia32_rangepd512_mask:
3628   case X86::BI__builtin_ia32_rangeps512_mask:
3629   case X86::BI__builtin_ia32_rangesd128_round_mask:
3630   case X86::BI__builtin_ia32_rangess128_round_mask:
3631   case X86::BI__builtin_ia32_reducesd_mask:
3632   case X86::BI__builtin_ia32_reducess_mask:
3633   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3634   case X86::BI__builtin_ia32_rndscaless_round_mask:
3635     ArgNum = 5;
3636     break;
3637   case X86::BI__builtin_ia32_vcvtsd2si64:
3638   case X86::BI__builtin_ia32_vcvtsd2si32:
3639   case X86::BI__builtin_ia32_vcvtsd2usi32:
3640   case X86::BI__builtin_ia32_vcvtsd2usi64:
3641   case X86::BI__builtin_ia32_vcvtss2si32:
3642   case X86::BI__builtin_ia32_vcvtss2si64:
3643   case X86::BI__builtin_ia32_vcvtss2usi32:
3644   case X86::BI__builtin_ia32_vcvtss2usi64:
3645   case X86::BI__builtin_ia32_sqrtpd512:
3646   case X86::BI__builtin_ia32_sqrtps512:
3647     ArgNum = 1;
3648     HasRC = true;
3649     break;
3650   case X86::BI__builtin_ia32_addpd512:
3651   case X86::BI__builtin_ia32_addps512:
3652   case X86::BI__builtin_ia32_divpd512:
3653   case X86::BI__builtin_ia32_divps512:
3654   case X86::BI__builtin_ia32_mulpd512:
3655   case X86::BI__builtin_ia32_mulps512:
3656   case X86::BI__builtin_ia32_subpd512:
3657   case X86::BI__builtin_ia32_subps512:
3658   case X86::BI__builtin_ia32_cvtsi2sd64:
3659   case X86::BI__builtin_ia32_cvtsi2ss32:
3660   case X86::BI__builtin_ia32_cvtsi2ss64:
3661   case X86::BI__builtin_ia32_cvtusi2sd64:
3662   case X86::BI__builtin_ia32_cvtusi2ss32:
3663   case X86::BI__builtin_ia32_cvtusi2ss64:
3664     ArgNum = 2;
3665     HasRC = true;
3666     break;
3667   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3668   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3669   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3670   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3671   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3672   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3673   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3674   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3675   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3676   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3677   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3678   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3679   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3680   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3681   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3682     ArgNum = 3;
3683     HasRC = true;
3684     break;
3685   case X86::BI__builtin_ia32_addss_round_mask:
3686   case X86::BI__builtin_ia32_addsd_round_mask:
3687   case X86::BI__builtin_ia32_divss_round_mask:
3688   case X86::BI__builtin_ia32_divsd_round_mask:
3689   case X86::BI__builtin_ia32_mulss_round_mask:
3690   case X86::BI__builtin_ia32_mulsd_round_mask:
3691   case X86::BI__builtin_ia32_subss_round_mask:
3692   case X86::BI__builtin_ia32_subsd_round_mask:
3693   case X86::BI__builtin_ia32_scalefpd512_mask:
3694   case X86::BI__builtin_ia32_scalefps512_mask:
3695   case X86::BI__builtin_ia32_scalefsd_round_mask:
3696   case X86::BI__builtin_ia32_scalefss_round_mask:
3697   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3698   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3699   case X86::BI__builtin_ia32_sqrtss_round_mask:
3700   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3701   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3702   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3703   case X86::BI__builtin_ia32_vfmaddss3_mask:
3704   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3705   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3706   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3707   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3708   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3709   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3710   case X86::BI__builtin_ia32_vfmaddps512_mask:
3711   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3712   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3713   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3714   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3715   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3716   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3717   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3718   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3719   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3720   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3721   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3722     ArgNum = 4;
3723     HasRC = true;
3724     break;
3725   }
3726 
3727   llvm::APSInt Result;
3728 
3729   // We can't check the value of a dependent argument.
3730   Expr *Arg = TheCall->getArg(ArgNum);
3731   if (Arg->isTypeDependent() || Arg->isValueDependent())
3732     return false;
3733 
3734   // Check constant-ness first.
3735   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3736     return true;
3737 
3738   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3739   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3740   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3741   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3742   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3743       Result == 8/*ROUND_NO_EXC*/ ||
3744       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3745       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3746     return false;
3747 
3748   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3749          << Arg->getSourceRange();
3750 }
3751 
3752 // Check if the gather/scatter scale is legal.
3753 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3754                                              CallExpr *TheCall) {
3755   unsigned ArgNum = 0;
3756   switch (BuiltinID) {
3757   default:
3758     return false;
3759   case X86::BI__builtin_ia32_gatherpfdpd:
3760   case X86::BI__builtin_ia32_gatherpfdps:
3761   case X86::BI__builtin_ia32_gatherpfqpd:
3762   case X86::BI__builtin_ia32_gatherpfqps:
3763   case X86::BI__builtin_ia32_scatterpfdpd:
3764   case X86::BI__builtin_ia32_scatterpfdps:
3765   case X86::BI__builtin_ia32_scatterpfqpd:
3766   case X86::BI__builtin_ia32_scatterpfqps:
3767     ArgNum = 3;
3768     break;
3769   case X86::BI__builtin_ia32_gatherd_pd:
3770   case X86::BI__builtin_ia32_gatherd_pd256:
3771   case X86::BI__builtin_ia32_gatherq_pd:
3772   case X86::BI__builtin_ia32_gatherq_pd256:
3773   case X86::BI__builtin_ia32_gatherd_ps:
3774   case X86::BI__builtin_ia32_gatherd_ps256:
3775   case X86::BI__builtin_ia32_gatherq_ps:
3776   case X86::BI__builtin_ia32_gatherq_ps256:
3777   case X86::BI__builtin_ia32_gatherd_q:
3778   case X86::BI__builtin_ia32_gatherd_q256:
3779   case X86::BI__builtin_ia32_gatherq_q:
3780   case X86::BI__builtin_ia32_gatherq_q256:
3781   case X86::BI__builtin_ia32_gatherd_d:
3782   case X86::BI__builtin_ia32_gatherd_d256:
3783   case X86::BI__builtin_ia32_gatherq_d:
3784   case X86::BI__builtin_ia32_gatherq_d256:
3785   case X86::BI__builtin_ia32_gather3div2df:
3786   case X86::BI__builtin_ia32_gather3div2di:
3787   case X86::BI__builtin_ia32_gather3div4df:
3788   case X86::BI__builtin_ia32_gather3div4di:
3789   case X86::BI__builtin_ia32_gather3div4sf:
3790   case X86::BI__builtin_ia32_gather3div4si:
3791   case X86::BI__builtin_ia32_gather3div8sf:
3792   case X86::BI__builtin_ia32_gather3div8si:
3793   case X86::BI__builtin_ia32_gather3siv2df:
3794   case X86::BI__builtin_ia32_gather3siv2di:
3795   case X86::BI__builtin_ia32_gather3siv4df:
3796   case X86::BI__builtin_ia32_gather3siv4di:
3797   case X86::BI__builtin_ia32_gather3siv4sf:
3798   case X86::BI__builtin_ia32_gather3siv4si:
3799   case X86::BI__builtin_ia32_gather3siv8sf:
3800   case X86::BI__builtin_ia32_gather3siv8si:
3801   case X86::BI__builtin_ia32_gathersiv8df:
3802   case X86::BI__builtin_ia32_gathersiv16sf:
3803   case X86::BI__builtin_ia32_gatherdiv8df:
3804   case X86::BI__builtin_ia32_gatherdiv16sf:
3805   case X86::BI__builtin_ia32_gathersiv8di:
3806   case X86::BI__builtin_ia32_gathersiv16si:
3807   case X86::BI__builtin_ia32_gatherdiv8di:
3808   case X86::BI__builtin_ia32_gatherdiv16si:
3809   case X86::BI__builtin_ia32_scatterdiv2df:
3810   case X86::BI__builtin_ia32_scatterdiv2di:
3811   case X86::BI__builtin_ia32_scatterdiv4df:
3812   case X86::BI__builtin_ia32_scatterdiv4di:
3813   case X86::BI__builtin_ia32_scatterdiv4sf:
3814   case X86::BI__builtin_ia32_scatterdiv4si:
3815   case X86::BI__builtin_ia32_scatterdiv8sf:
3816   case X86::BI__builtin_ia32_scatterdiv8si:
3817   case X86::BI__builtin_ia32_scattersiv2df:
3818   case X86::BI__builtin_ia32_scattersiv2di:
3819   case X86::BI__builtin_ia32_scattersiv4df:
3820   case X86::BI__builtin_ia32_scattersiv4di:
3821   case X86::BI__builtin_ia32_scattersiv4sf:
3822   case X86::BI__builtin_ia32_scattersiv4si:
3823   case X86::BI__builtin_ia32_scattersiv8sf:
3824   case X86::BI__builtin_ia32_scattersiv8si:
3825   case X86::BI__builtin_ia32_scattersiv8df:
3826   case X86::BI__builtin_ia32_scattersiv16sf:
3827   case X86::BI__builtin_ia32_scatterdiv8df:
3828   case X86::BI__builtin_ia32_scatterdiv16sf:
3829   case X86::BI__builtin_ia32_scattersiv8di:
3830   case X86::BI__builtin_ia32_scattersiv16si:
3831   case X86::BI__builtin_ia32_scatterdiv8di:
3832   case X86::BI__builtin_ia32_scatterdiv16si:
3833     ArgNum = 4;
3834     break;
3835   }
3836 
3837   llvm::APSInt Result;
3838 
3839   // We can't check the value of a dependent argument.
3840   Expr *Arg = TheCall->getArg(ArgNum);
3841   if (Arg->isTypeDependent() || Arg->isValueDependent())
3842     return false;
3843 
3844   // Check constant-ness first.
3845   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3846     return true;
3847 
3848   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3849     return false;
3850 
3851   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3852          << Arg->getSourceRange();
3853 }
3854 
3855 enum { TileRegLow = 0, TileRegHigh = 7 };
3856 
3857 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3858                                              ArrayRef<int> ArgNums) {
3859   for (int ArgNum : ArgNums) {
3860     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3861       return true;
3862   }
3863   return false;
3864 }
3865 
3866 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3867                                         ArrayRef<int> ArgNums) {
3868   // Because the max number of tile register is TileRegHigh + 1, so here we use
3869   // each bit to represent the usage of them in bitset.
3870   std::bitset<TileRegHigh + 1> ArgValues;
3871   for (int ArgNum : ArgNums) {
3872     Expr *Arg = TheCall->getArg(ArgNum);
3873     if (Arg->isTypeDependent() || Arg->isValueDependent())
3874       continue;
3875 
3876     llvm::APSInt Result;
3877     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3878       return true;
3879     int ArgExtValue = Result.getExtValue();
3880     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3881            "Incorrect tile register num.");
3882     if (ArgValues.test(ArgExtValue))
3883       return Diag(TheCall->getBeginLoc(),
3884                   diag::err_x86_builtin_tile_arg_duplicate)
3885              << TheCall->getArg(ArgNum)->getSourceRange();
3886     ArgValues.set(ArgExtValue);
3887   }
3888   return false;
3889 }
3890 
3891 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3892                                                 ArrayRef<int> ArgNums) {
3893   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3894          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3895 }
3896 
3897 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3898   switch (BuiltinID) {
3899   default:
3900     return false;
3901   case X86::BI__builtin_ia32_tileloadd64:
3902   case X86::BI__builtin_ia32_tileloaddt164:
3903   case X86::BI__builtin_ia32_tilestored64:
3904   case X86::BI__builtin_ia32_tilezero:
3905     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3906   case X86::BI__builtin_ia32_tdpbssd:
3907   case X86::BI__builtin_ia32_tdpbsud:
3908   case X86::BI__builtin_ia32_tdpbusd:
3909   case X86::BI__builtin_ia32_tdpbuud:
3910   case X86::BI__builtin_ia32_tdpbf16ps:
3911     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3912   }
3913 }
3914 static bool isX86_32Builtin(unsigned BuiltinID) {
3915   // These builtins only work on x86-32 targets.
3916   switch (BuiltinID) {
3917   case X86::BI__builtin_ia32_readeflags_u32:
3918   case X86::BI__builtin_ia32_writeeflags_u32:
3919     return true;
3920   }
3921 
3922   return false;
3923 }
3924 
3925 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3926                                        CallExpr *TheCall) {
3927   if (BuiltinID == X86::BI__builtin_cpu_supports)
3928     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3929 
3930   if (BuiltinID == X86::BI__builtin_cpu_is)
3931     return SemaBuiltinCpuIs(*this, TI, TheCall);
3932 
3933   // Check for 32-bit only builtins on a 64-bit target.
3934   const llvm::Triple &TT = TI.getTriple();
3935   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3936     return Diag(TheCall->getCallee()->getBeginLoc(),
3937                 diag::err_32_bit_builtin_64_bit_tgt);
3938 
3939   // If the intrinsic has rounding or SAE make sure its valid.
3940   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3941     return true;
3942 
3943   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3944   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3945     return true;
3946 
3947   // If the intrinsic has a tile arguments, make sure they are valid.
3948   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3949     return true;
3950 
3951   // For intrinsics which take an immediate value as part of the instruction,
3952   // range check them here.
3953   int i = 0, l = 0, u = 0;
3954   switch (BuiltinID) {
3955   default:
3956     return false;
3957   case X86::BI__builtin_ia32_vec_ext_v2si:
3958   case X86::BI__builtin_ia32_vec_ext_v2di:
3959   case X86::BI__builtin_ia32_vextractf128_pd256:
3960   case X86::BI__builtin_ia32_vextractf128_ps256:
3961   case X86::BI__builtin_ia32_vextractf128_si256:
3962   case X86::BI__builtin_ia32_extract128i256:
3963   case X86::BI__builtin_ia32_extractf64x4_mask:
3964   case X86::BI__builtin_ia32_extracti64x4_mask:
3965   case X86::BI__builtin_ia32_extractf32x8_mask:
3966   case X86::BI__builtin_ia32_extracti32x8_mask:
3967   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3968   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3969   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3970   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3971     i = 1; l = 0; u = 1;
3972     break;
3973   case X86::BI__builtin_ia32_vec_set_v2di:
3974   case X86::BI__builtin_ia32_vinsertf128_pd256:
3975   case X86::BI__builtin_ia32_vinsertf128_ps256:
3976   case X86::BI__builtin_ia32_vinsertf128_si256:
3977   case X86::BI__builtin_ia32_insert128i256:
3978   case X86::BI__builtin_ia32_insertf32x8:
3979   case X86::BI__builtin_ia32_inserti32x8:
3980   case X86::BI__builtin_ia32_insertf64x4:
3981   case X86::BI__builtin_ia32_inserti64x4:
3982   case X86::BI__builtin_ia32_insertf64x2_256:
3983   case X86::BI__builtin_ia32_inserti64x2_256:
3984   case X86::BI__builtin_ia32_insertf32x4_256:
3985   case X86::BI__builtin_ia32_inserti32x4_256:
3986     i = 2; l = 0; u = 1;
3987     break;
3988   case X86::BI__builtin_ia32_vpermilpd:
3989   case X86::BI__builtin_ia32_vec_ext_v4hi:
3990   case X86::BI__builtin_ia32_vec_ext_v4si:
3991   case X86::BI__builtin_ia32_vec_ext_v4sf:
3992   case X86::BI__builtin_ia32_vec_ext_v4di:
3993   case X86::BI__builtin_ia32_extractf32x4_mask:
3994   case X86::BI__builtin_ia32_extracti32x4_mask:
3995   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3996   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3997     i = 1; l = 0; u = 3;
3998     break;
3999   case X86::BI_mm_prefetch:
4000   case X86::BI__builtin_ia32_vec_ext_v8hi:
4001   case X86::BI__builtin_ia32_vec_ext_v8si:
4002     i = 1; l = 0; u = 7;
4003     break;
4004   case X86::BI__builtin_ia32_sha1rnds4:
4005   case X86::BI__builtin_ia32_blendpd:
4006   case X86::BI__builtin_ia32_shufpd:
4007   case X86::BI__builtin_ia32_vec_set_v4hi:
4008   case X86::BI__builtin_ia32_vec_set_v4si:
4009   case X86::BI__builtin_ia32_vec_set_v4di:
4010   case X86::BI__builtin_ia32_shuf_f32x4_256:
4011   case X86::BI__builtin_ia32_shuf_f64x2_256:
4012   case X86::BI__builtin_ia32_shuf_i32x4_256:
4013   case X86::BI__builtin_ia32_shuf_i64x2_256:
4014   case X86::BI__builtin_ia32_insertf64x2_512:
4015   case X86::BI__builtin_ia32_inserti64x2_512:
4016   case X86::BI__builtin_ia32_insertf32x4:
4017   case X86::BI__builtin_ia32_inserti32x4:
4018     i = 2; l = 0; u = 3;
4019     break;
4020   case X86::BI__builtin_ia32_vpermil2pd:
4021   case X86::BI__builtin_ia32_vpermil2pd256:
4022   case X86::BI__builtin_ia32_vpermil2ps:
4023   case X86::BI__builtin_ia32_vpermil2ps256:
4024     i = 3; l = 0; u = 3;
4025     break;
4026   case X86::BI__builtin_ia32_cmpb128_mask:
4027   case X86::BI__builtin_ia32_cmpw128_mask:
4028   case X86::BI__builtin_ia32_cmpd128_mask:
4029   case X86::BI__builtin_ia32_cmpq128_mask:
4030   case X86::BI__builtin_ia32_cmpb256_mask:
4031   case X86::BI__builtin_ia32_cmpw256_mask:
4032   case X86::BI__builtin_ia32_cmpd256_mask:
4033   case X86::BI__builtin_ia32_cmpq256_mask:
4034   case X86::BI__builtin_ia32_cmpb512_mask:
4035   case X86::BI__builtin_ia32_cmpw512_mask:
4036   case X86::BI__builtin_ia32_cmpd512_mask:
4037   case X86::BI__builtin_ia32_cmpq512_mask:
4038   case X86::BI__builtin_ia32_ucmpb128_mask:
4039   case X86::BI__builtin_ia32_ucmpw128_mask:
4040   case X86::BI__builtin_ia32_ucmpd128_mask:
4041   case X86::BI__builtin_ia32_ucmpq128_mask:
4042   case X86::BI__builtin_ia32_ucmpb256_mask:
4043   case X86::BI__builtin_ia32_ucmpw256_mask:
4044   case X86::BI__builtin_ia32_ucmpd256_mask:
4045   case X86::BI__builtin_ia32_ucmpq256_mask:
4046   case X86::BI__builtin_ia32_ucmpb512_mask:
4047   case X86::BI__builtin_ia32_ucmpw512_mask:
4048   case X86::BI__builtin_ia32_ucmpd512_mask:
4049   case X86::BI__builtin_ia32_ucmpq512_mask:
4050   case X86::BI__builtin_ia32_vpcomub:
4051   case X86::BI__builtin_ia32_vpcomuw:
4052   case X86::BI__builtin_ia32_vpcomud:
4053   case X86::BI__builtin_ia32_vpcomuq:
4054   case X86::BI__builtin_ia32_vpcomb:
4055   case X86::BI__builtin_ia32_vpcomw:
4056   case X86::BI__builtin_ia32_vpcomd:
4057   case X86::BI__builtin_ia32_vpcomq:
4058   case X86::BI__builtin_ia32_vec_set_v8hi:
4059   case X86::BI__builtin_ia32_vec_set_v8si:
4060     i = 2; l = 0; u = 7;
4061     break;
4062   case X86::BI__builtin_ia32_vpermilpd256:
4063   case X86::BI__builtin_ia32_roundps:
4064   case X86::BI__builtin_ia32_roundpd:
4065   case X86::BI__builtin_ia32_roundps256:
4066   case X86::BI__builtin_ia32_roundpd256:
4067   case X86::BI__builtin_ia32_getmantpd128_mask:
4068   case X86::BI__builtin_ia32_getmantpd256_mask:
4069   case X86::BI__builtin_ia32_getmantps128_mask:
4070   case X86::BI__builtin_ia32_getmantps256_mask:
4071   case X86::BI__builtin_ia32_getmantpd512_mask:
4072   case X86::BI__builtin_ia32_getmantps512_mask:
4073   case X86::BI__builtin_ia32_vec_ext_v16qi:
4074   case X86::BI__builtin_ia32_vec_ext_v16hi:
4075     i = 1; l = 0; u = 15;
4076     break;
4077   case X86::BI__builtin_ia32_pblendd128:
4078   case X86::BI__builtin_ia32_blendps:
4079   case X86::BI__builtin_ia32_blendpd256:
4080   case X86::BI__builtin_ia32_shufpd256:
4081   case X86::BI__builtin_ia32_roundss:
4082   case X86::BI__builtin_ia32_roundsd:
4083   case X86::BI__builtin_ia32_rangepd128_mask:
4084   case X86::BI__builtin_ia32_rangepd256_mask:
4085   case X86::BI__builtin_ia32_rangepd512_mask:
4086   case X86::BI__builtin_ia32_rangeps128_mask:
4087   case X86::BI__builtin_ia32_rangeps256_mask:
4088   case X86::BI__builtin_ia32_rangeps512_mask:
4089   case X86::BI__builtin_ia32_getmantsd_round_mask:
4090   case X86::BI__builtin_ia32_getmantss_round_mask:
4091   case X86::BI__builtin_ia32_vec_set_v16qi:
4092   case X86::BI__builtin_ia32_vec_set_v16hi:
4093     i = 2; l = 0; u = 15;
4094     break;
4095   case X86::BI__builtin_ia32_vec_ext_v32qi:
4096     i = 1; l = 0; u = 31;
4097     break;
4098   case X86::BI__builtin_ia32_cmpps:
4099   case X86::BI__builtin_ia32_cmpss:
4100   case X86::BI__builtin_ia32_cmppd:
4101   case X86::BI__builtin_ia32_cmpsd:
4102   case X86::BI__builtin_ia32_cmpps256:
4103   case X86::BI__builtin_ia32_cmppd256:
4104   case X86::BI__builtin_ia32_cmpps128_mask:
4105   case X86::BI__builtin_ia32_cmppd128_mask:
4106   case X86::BI__builtin_ia32_cmpps256_mask:
4107   case X86::BI__builtin_ia32_cmppd256_mask:
4108   case X86::BI__builtin_ia32_cmpps512_mask:
4109   case X86::BI__builtin_ia32_cmppd512_mask:
4110   case X86::BI__builtin_ia32_cmpsd_mask:
4111   case X86::BI__builtin_ia32_cmpss_mask:
4112   case X86::BI__builtin_ia32_vec_set_v32qi:
4113     i = 2; l = 0; u = 31;
4114     break;
4115   case X86::BI__builtin_ia32_permdf256:
4116   case X86::BI__builtin_ia32_permdi256:
4117   case X86::BI__builtin_ia32_permdf512:
4118   case X86::BI__builtin_ia32_permdi512:
4119   case X86::BI__builtin_ia32_vpermilps:
4120   case X86::BI__builtin_ia32_vpermilps256:
4121   case X86::BI__builtin_ia32_vpermilpd512:
4122   case X86::BI__builtin_ia32_vpermilps512:
4123   case X86::BI__builtin_ia32_pshufd:
4124   case X86::BI__builtin_ia32_pshufd256:
4125   case X86::BI__builtin_ia32_pshufd512:
4126   case X86::BI__builtin_ia32_pshufhw:
4127   case X86::BI__builtin_ia32_pshufhw256:
4128   case X86::BI__builtin_ia32_pshufhw512:
4129   case X86::BI__builtin_ia32_pshuflw:
4130   case X86::BI__builtin_ia32_pshuflw256:
4131   case X86::BI__builtin_ia32_pshuflw512:
4132   case X86::BI__builtin_ia32_vcvtps2ph:
4133   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4134   case X86::BI__builtin_ia32_vcvtps2ph256:
4135   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4136   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4137   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4138   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4139   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4140   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4141   case X86::BI__builtin_ia32_rndscaleps_mask:
4142   case X86::BI__builtin_ia32_rndscalepd_mask:
4143   case X86::BI__builtin_ia32_reducepd128_mask:
4144   case X86::BI__builtin_ia32_reducepd256_mask:
4145   case X86::BI__builtin_ia32_reducepd512_mask:
4146   case X86::BI__builtin_ia32_reduceps128_mask:
4147   case X86::BI__builtin_ia32_reduceps256_mask:
4148   case X86::BI__builtin_ia32_reduceps512_mask:
4149   case X86::BI__builtin_ia32_prold512:
4150   case X86::BI__builtin_ia32_prolq512:
4151   case X86::BI__builtin_ia32_prold128:
4152   case X86::BI__builtin_ia32_prold256:
4153   case X86::BI__builtin_ia32_prolq128:
4154   case X86::BI__builtin_ia32_prolq256:
4155   case X86::BI__builtin_ia32_prord512:
4156   case X86::BI__builtin_ia32_prorq512:
4157   case X86::BI__builtin_ia32_prord128:
4158   case X86::BI__builtin_ia32_prord256:
4159   case X86::BI__builtin_ia32_prorq128:
4160   case X86::BI__builtin_ia32_prorq256:
4161   case X86::BI__builtin_ia32_fpclasspd128_mask:
4162   case X86::BI__builtin_ia32_fpclasspd256_mask:
4163   case X86::BI__builtin_ia32_fpclassps128_mask:
4164   case X86::BI__builtin_ia32_fpclassps256_mask:
4165   case X86::BI__builtin_ia32_fpclassps512_mask:
4166   case X86::BI__builtin_ia32_fpclasspd512_mask:
4167   case X86::BI__builtin_ia32_fpclasssd_mask:
4168   case X86::BI__builtin_ia32_fpclassss_mask:
4169   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4170   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4171   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4172   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4173   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4174   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4175   case X86::BI__builtin_ia32_kshiftliqi:
4176   case X86::BI__builtin_ia32_kshiftlihi:
4177   case X86::BI__builtin_ia32_kshiftlisi:
4178   case X86::BI__builtin_ia32_kshiftlidi:
4179   case X86::BI__builtin_ia32_kshiftriqi:
4180   case X86::BI__builtin_ia32_kshiftrihi:
4181   case X86::BI__builtin_ia32_kshiftrisi:
4182   case X86::BI__builtin_ia32_kshiftridi:
4183     i = 1; l = 0; u = 255;
4184     break;
4185   case X86::BI__builtin_ia32_vperm2f128_pd256:
4186   case X86::BI__builtin_ia32_vperm2f128_ps256:
4187   case X86::BI__builtin_ia32_vperm2f128_si256:
4188   case X86::BI__builtin_ia32_permti256:
4189   case X86::BI__builtin_ia32_pblendw128:
4190   case X86::BI__builtin_ia32_pblendw256:
4191   case X86::BI__builtin_ia32_blendps256:
4192   case X86::BI__builtin_ia32_pblendd256:
4193   case X86::BI__builtin_ia32_palignr128:
4194   case X86::BI__builtin_ia32_palignr256:
4195   case X86::BI__builtin_ia32_palignr512:
4196   case X86::BI__builtin_ia32_alignq512:
4197   case X86::BI__builtin_ia32_alignd512:
4198   case X86::BI__builtin_ia32_alignd128:
4199   case X86::BI__builtin_ia32_alignd256:
4200   case X86::BI__builtin_ia32_alignq128:
4201   case X86::BI__builtin_ia32_alignq256:
4202   case X86::BI__builtin_ia32_vcomisd:
4203   case X86::BI__builtin_ia32_vcomiss:
4204   case X86::BI__builtin_ia32_shuf_f32x4:
4205   case X86::BI__builtin_ia32_shuf_f64x2:
4206   case X86::BI__builtin_ia32_shuf_i32x4:
4207   case X86::BI__builtin_ia32_shuf_i64x2:
4208   case X86::BI__builtin_ia32_shufpd512:
4209   case X86::BI__builtin_ia32_shufps:
4210   case X86::BI__builtin_ia32_shufps256:
4211   case X86::BI__builtin_ia32_shufps512:
4212   case X86::BI__builtin_ia32_dbpsadbw128:
4213   case X86::BI__builtin_ia32_dbpsadbw256:
4214   case X86::BI__builtin_ia32_dbpsadbw512:
4215   case X86::BI__builtin_ia32_vpshldd128:
4216   case X86::BI__builtin_ia32_vpshldd256:
4217   case X86::BI__builtin_ia32_vpshldd512:
4218   case X86::BI__builtin_ia32_vpshldq128:
4219   case X86::BI__builtin_ia32_vpshldq256:
4220   case X86::BI__builtin_ia32_vpshldq512:
4221   case X86::BI__builtin_ia32_vpshldw128:
4222   case X86::BI__builtin_ia32_vpshldw256:
4223   case X86::BI__builtin_ia32_vpshldw512:
4224   case X86::BI__builtin_ia32_vpshrdd128:
4225   case X86::BI__builtin_ia32_vpshrdd256:
4226   case X86::BI__builtin_ia32_vpshrdd512:
4227   case X86::BI__builtin_ia32_vpshrdq128:
4228   case X86::BI__builtin_ia32_vpshrdq256:
4229   case X86::BI__builtin_ia32_vpshrdq512:
4230   case X86::BI__builtin_ia32_vpshrdw128:
4231   case X86::BI__builtin_ia32_vpshrdw256:
4232   case X86::BI__builtin_ia32_vpshrdw512:
4233     i = 2; l = 0; u = 255;
4234     break;
4235   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4236   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4237   case X86::BI__builtin_ia32_fixupimmps512_mask:
4238   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4239   case X86::BI__builtin_ia32_fixupimmsd_mask:
4240   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4241   case X86::BI__builtin_ia32_fixupimmss_mask:
4242   case X86::BI__builtin_ia32_fixupimmss_maskz:
4243   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4244   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4245   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4246   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4247   case X86::BI__builtin_ia32_fixupimmps128_mask:
4248   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4249   case X86::BI__builtin_ia32_fixupimmps256_mask:
4250   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4251   case X86::BI__builtin_ia32_pternlogd512_mask:
4252   case X86::BI__builtin_ia32_pternlogd512_maskz:
4253   case X86::BI__builtin_ia32_pternlogq512_mask:
4254   case X86::BI__builtin_ia32_pternlogq512_maskz:
4255   case X86::BI__builtin_ia32_pternlogd128_mask:
4256   case X86::BI__builtin_ia32_pternlogd128_maskz:
4257   case X86::BI__builtin_ia32_pternlogd256_mask:
4258   case X86::BI__builtin_ia32_pternlogd256_maskz:
4259   case X86::BI__builtin_ia32_pternlogq128_mask:
4260   case X86::BI__builtin_ia32_pternlogq128_maskz:
4261   case X86::BI__builtin_ia32_pternlogq256_mask:
4262   case X86::BI__builtin_ia32_pternlogq256_maskz:
4263     i = 3; l = 0; u = 255;
4264     break;
4265   case X86::BI__builtin_ia32_gatherpfdpd:
4266   case X86::BI__builtin_ia32_gatherpfdps:
4267   case X86::BI__builtin_ia32_gatherpfqpd:
4268   case X86::BI__builtin_ia32_gatherpfqps:
4269   case X86::BI__builtin_ia32_scatterpfdpd:
4270   case X86::BI__builtin_ia32_scatterpfdps:
4271   case X86::BI__builtin_ia32_scatterpfqpd:
4272   case X86::BI__builtin_ia32_scatterpfqps:
4273     i = 4; l = 2; u = 3;
4274     break;
4275   case X86::BI__builtin_ia32_reducesd_mask:
4276   case X86::BI__builtin_ia32_reducess_mask:
4277   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4278   case X86::BI__builtin_ia32_rndscaless_round_mask:
4279     i = 4; l = 0; u = 255;
4280     break;
4281   }
4282 
4283   // Note that we don't force a hard error on the range check here, allowing
4284   // template-generated or macro-generated dead code to potentially have out-of-
4285   // range values. These need to code generate, but don't need to necessarily
4286   // make any sense. We use a warning that defaults to an error.
4287   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4288 }
4289 
4290 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4291 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4292 /// Returns true when the format fits the function and the FormatStringInfo has
4293 /// been populated.
4294 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4295                                FormatStringInfo *FSI) {
4296   FSI->HasVAListArg = Format->getFirstArg() == 0;
4297   FSI->FormatIdx = Format->getFormatIdx() - 1;
4298   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4299 
4300   // The way the format attribute works in GCC, the implicit this argument
4301   // of member functions is counted. However, it doesn't appear in our own
4302   // lists, so decrement format_idx in that case.
4303   if (IsCXXMember) {
4304     if(FSI->FormatIdx == 0)
4305       return false;
4306     --FSI->FormatIdx;
4307     if (FSI->FirstDataArg != 0)
4308       --FSI->FirstDataArg;
4309   }
4310   return true;
4311 }
4312 
4313 /// Checks if a the given expression evaluates to null.
4314 ///
4315 /// Returns true if the value evaluates to null.
4316 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4317   // If the expression has non-null type, it doesn't evaluate to null.
4318   if (auto nullability
4319         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4320     if (*nullability == NullabilityKind::NonNull)
4321       return false;
4322   }
4323 
4324   // As a special case, transparent unions initialized with zero are
4325   // considered null for the purposes of the nonnull attribute.
4326   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4327     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4328       if (const CompoundLiteralExpr *CLE =
4329           dyn_cast<CompoundLiteralExpr>(Expr))
4330         if (const InitListExpr *ILE =
4331             dyn_cast<InitListExpr>(CLE->getInitializer()))
4332           Expr = ILE->getInit(0);
4333   }
4334 
4335   bool Result;
4336   return (!Expr->isValueDependent() &&
4337           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4338           !Result);
4339 }
4340 
4341 static void CheckNonNullArgument(Sema &S,
4342                                  const Expr *ArgExpr,
4343                                  SourceLocation CallSiteLoc) {
4344   if (CheckNonNullExpr(S, ArgExpr))
4345     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4346                           S.PDiag(diag::warn_null_arg)
4347                               << ArgExpr->getSourceRange());
4348 }
4349 
4350 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4351   FormatStringInfo FSI;
4352   if ((GetFormatStringType(Format) == FST_NSString) &&
4353       getFormatStringInfo(Format, false, &FSI)) {
4354     Idx = FSI.FormatIdx;
4355     return true;
4356   }
4357   return false;
4358 }
4359 
4360 /// Diagnose use of %s directive in an NSString which is being passed
4361 /// as formatting string to formatting method.
4362 static void
4363 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4364                                         const NamedDecl *FDecl,
4365                                         Expr **Args,
4366                                         unsigned NumArgs) {
4367   unsigned Idx = 0;
4368   bool Format = false;
4369   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4370   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4371     Idx = 2;
4372     Format = true;
4373   }
4374   else
4375     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4376       if (S.GetFormatNSStringIdx(I, Idx)) {
4377         Format = true;
4378         break;
4379       }
4380     }
4381   if (!Format || NumArgs <= Idx)
4382     return;
4383   const Expr *FormatExpr = Args[Idx];
4384   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4385     FormatExpr = CSCE->getSubExpr();
4386   const StringLiteral *FormatString;
4387   if (const ObjCStringLiteral *OSL =
4388       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4389     FormatString = OSL->getString();
4390   else
4391     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4392   if (!FormatString)
4393     return;
4394   if (S.FormatStringHasSArg(FormatString)) {
4395     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4396       << "%s" << 1 << 1;
4397     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4398       << FDecl->getDeclName();
4399   }
4400 }
4401 
4402 /// Determine whether the given type has a non-null nullability annotation.
4403 static bool isNonNullType(ASTContext &ctx, QualType type) {
4404   if (auto nullability = type->getNullability(ctx))
4405     return *nullability == NullabilityKind::NonNull;
4406 
4407   return false;
4408 }
4409 
4410 static void CheckNonNullArguments(Sema &S,
4411                                   const NamedDecl *FDecl,
4412                                   const FunctionProtoType *Proto,
4413                                   ArrayRef<const Expr *> Args,
4414                                   SourceLocation CallSiteLoc) {
4415   assert((FDecl || Proto) && "Need a function declaration or prototype");
4416 
4417   // Already checked by by constant evaluator.
4418   if (S.isConstantEvaluated())
4419     return;
4420   // Check the attributes attached to the method/function itself.
4421   llvm::SmallBitVector NonNullArgs;
4422   if (FDecl) {
4423     // Handle the nonnull attribute on the function/method declaration itself.
4424     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4425       if (!NonNull->args_size()) {
4426         // Easy case: all pointer arguments are nonnull.
4427         for (const auto *Arg : Args)
4428           if (S.isValidPointerAttrType(Arg->getType()))
4429             CheckNonNullArgument(S, Arg, CallSiteLoc);
4430         return;
4431       }
4432 
4433       for (const ParamIdx &Idx : NonNull->args()) {
4434         unsigned IdxAST = Idx.getASTIndex();
4435         if (IdxAST >= Args.size())
4436           continue;
4437         if (NonNullArgs.empty())
4438           NonNullArgs.resize(Args.size());
4439         NonNullArgs.set(IdxAST);
4440       }
4441     }
4442   }
4443 
4444   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4445     // Handle the nonnull attribute on the parameters of the
4446     // function/method.
4447     ArrayRef<ParmVarDecl*> parms;
4448     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4449       parms = FD->parameters();
4450     else
4451       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4452 
4453     unsigned ParamIndex = 0;
4454     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4455          I != E; ++I, ++ParamIndex) {
4456       const ParmVarDecl *PVD = *I;
4457       if (PVD->hasAttr<NonNullAttr>() ||
4458           isNonNullType(S.Context, PVD->getType())) {
4459         if (NonNullArgs.empty())
4460           NonNullArgs.resize(Args.size());
4461 
4462         NonNullArgs.set(ParamIndex);
4463       }
4464     }
4465   } else {
4466     // If we have a non-function, non-method declaration but no
4467     // function prototype, try to dig out the function prototype.
4468     if (!Proto) {
4469       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4470         QualType type = VD->getType().getNonReferenceType();
4471         if (auto pointerType = type->getAs<PointerType>())
4472           type = pointerType->getPointeeType();
4473         else if (auto blockType = type->getAs<BlockPointerType>())
4474           type = blockType->getPointeeType();
4475         // FIXME: data member pointers?
4476 
4477         // Dig out the function prototype, if there is one.
4478         Proto = type->getAs<FunctionProtoType>();
4479       }
4480     }
4481 
4482     // Fill in non-null argument information from the nullability
4483     // information on the parameter types (if we have them).
4484     if (Proto) {
4485       unsigned Index = 0;
4486       for (auto paramType : Proto->getParamTypes()) {
4487         if (isNonNullType(S.Context, paramType)) {
4488           if (NonNullArgs.empty())
4489             NonNullArgs.resize(Args.size());
4490 
4491           NonNullArgs.set(Index);
4492         }
4493 
4494         ++Index;
4495       }
4496     }
4497   }
4498 
4499   // Check for non-null arguments.
4500   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4501        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4502     if (NonNullArgs[ArgIndex])
4503       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4504   }
4505 }
4506 
4507 /// Warn if a pointer or reference argument passed to a function points to an
4508 /// object that is less aligned than the parameter. This can happen when
4509 /// creating a typedef with a lower alignment than the original type and then
4510 /// calling functions defined in terms of the original type.
4511 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4512                              StringRef ParamName, QualType ArgTy,
4513                              QualType ParamTy) {
4514 
4515   // If a function accepts a pointer or reference type
4516   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4517     return;
4518 
4519   // If the parameter is a pointer type, get the pointee type for the
4520   // argument too. If the parameter is a reference type, don't try to get
4521   // the pointee type for the argument.
4522   if (ParamTy->isPointerType())
4523     ArgTy = ArgTy->getPointeeType();
4524 
4525   // Remove reference or pointer
4526   ParamTy = ParamTy->getPointeeType();
4527 
4528   // Find expected alignment, and the actual alignment of the passed object.
4529   // getTypeAlignInChars requires complete types
4530   if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4531       ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4532     return;
4533 
4534   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4535   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4536 
4537   // If the argument is less aligned than the parameter, there is a
4538   // potential alignment issue.
4539   if (ArgAlign < ParamAlign)
4540     Diag(Loc, diag::warn_param_mismatched_alignment)
4541         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4542         << ParamName << FDecl;
4543 }
4544 
4545 /// Handles the checks for format strings, non-POD arguments to vararg
4546 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4547 /// attributes.
4548 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4549                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4550                      bool IsMemberFunction, SourceLocation Loc,
4551                      SourceRange Range, VariadicCallType CallType) {
4552   // FIXME: We should check as much as we can in the template definition.
4553   if (CurContext->isDependentContext())
4554     return;
4555 
4556   // Printf and scanf checking.
4557   llvm::SmallBitVector CheckedVarArgs;
4558   if (FDecl) {
4559     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4560       // Only create vector if there are format attributes.
4561       CheckedVarArgs.resize(Args.size());
4562 
4563       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4564                            CheckedVarArgs);
4565     }
4566   }
4567 
4568   // Refuse POD arguments that weren't caught by the format string
4569   // checks above.
4570   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4571   if (CallType != VariadicDoesNotApply &&
4572       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4573     unsigned NumParams = Proto ? Proto->getNumParams()
4574                        : FDecl && isa<FunctionDecl>(FDecl)
4575                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4576                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4577                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4578                        : 0;
4579 
4580     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4581       // Args[ArgIdx] can be null in malformed code.
4582       if (const Expr *Arg = Args[ArgIdx]) {
4583         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4584           checkVariadicArgument(Arg, CallType);
4585       }
4586     }
4587   }
4588 
4589   if (FDecl || Proto) {
4590     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4591 
4592     // Type safety checking.
4593     if (FDecl) {
4594       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4595         CheckArgumentWithTypeTag(I, Args, Loc);
4596     }
4597   }
4598 
4599   // Check that passed arguments match the alignment of original arguments.
4600   // Try to get the missing prototype from the declaration.
4601   if (!Proto && FDecl) {
4602     const auto *FT = FDecl->getFunctionType();
4603     if (isa_and_nonnull<FunctionProtoType>(FT))
4604       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4605   }
4606   if (Proto) {
4607     // For variadic functions, we may have more args than parameters.
4608     // For some K&R functions, we may have less args than parameters.
4609     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4610     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4611       // Args[ArgIdx] can be null in malformed code.
4612       if (const Expr *Arg = Args[ArgIdx]) {
4613         QualType ParamTy = Proto->getParamType(ArgIdx);
4614         QualType ArgTy = Arg->getType();
4615         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4616                           ArgTy, ParamTy);
4617       }
4618     }
4619   }
4620 
4621   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4622     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4623     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4624     if (!Arg->isValueDependent()) {
4625       Expr::EvalResult Align;
4626       if (Arg->EvaluateAsInt(Align, Context)) {
4627         const llvm::APSInt &I = Align.Val.getInt();
4628         if (!I.isPowerOf2())
4629           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4630               << Arg->getSourceRange();
4631 
4632         if (I > Sema::MaximumAlignment)
4633           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4634               << Arg->getSourceRange() << Sema::MaximumAlignment;
4635       }
4636     }
4637   }
4638 
4639   if (FD)
4640     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4641 }
4642 
4643 /// CheckConstructorCall - Check a constructor call for correctness and safety
4644 /// properties not enforced by the C type system.
4645 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4646                                 ArrayRef<const Expr *> Args,
4647                                 const FunctionProtoType *Proto,
4648                                 SourceLocation Loc) {
4649   VariadicCallType CallType =
4650       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4651 
4652   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4653   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4654                     Context.getPointerType(Ctor->getThisObjectType()));
4655 
4656   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4657             Loc, SourceRange(), CallType);
4658 }
4659 
4660 /// CheckFunctionCall - Check a direct function call for various correctness
4661 /// and safety properties not strictly enforced by the C type system.
4662 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4663                              const FunctionProtoType *Proto) {
4664   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4665                               isa<CXXMethodDecl>(FDecl);
4666   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4667                           IsMemberOperatorCall;
4668   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4669                                                   TheCall->getCallee());
4670   Expr** Args = TheCall->getArgs();
4671   unsigned NumArgs = TheCall->getNumArgs();
4672 
4673   Expr *ImplicitThis = nullptr;
4674   if (IsMemberOperatorCall) {
4675     // If this is a call to a member operator, hide the first argument
4676     // from checkCall.
4677     // FIXME: Our choice of AST representation here is less than ideal.
4678     ImplicitThis = Args[0];
4679     ++Args;
4680     --NumArgs;
4681   } else if (IsMemberFunction)
4682     ImplicitThis =
4683         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4684 
4685   if (ImplicitThis) {
4686     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4687     // used.
4688     QualType ThisType = ImplicitThis->getType();
4689     if (!ThisType->isPointerType()) {
4690       assert(!ThisType->isReferenceType());
4691       ThisType = Context.getPointerType(ThisType);
4692     }
4693 
4694     QualType ThisTypeFromDecl =
4695         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4696 
4697     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4698                       ThisTypeFromDecl);
4699   }
4700 
4701   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4702             IsMemberFunction, TheCall->getRParenLoc(),
4703             TheCall->getCallee()->getSourceRange(), CallType);
4704 
4705   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4706   // None of the checks below are needed for functions that don't have
4707   // simple names (e.g., C++ conversion functions).
4708   if (!FnInfo)
4709     return false;
4710 
4711   CheckTCBEnforcement(TheCall, FDecl);
4712 
4713   CheckAbsoluteValueFunction(TheCall, FDecl);
4714   CheckMaxUnsignedZero(TheCall, FDecl);
4715 
4716   if (getLangOpts().ObjC)
4717     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4718 
4719   unsigned CMId = FDecl->getMemoryFunctionKind();
4720 
4721   // Handle memory setting and copying functions.
4722   switch (CMId) {
4723   case 0:
4724     return false;
4725   case Builtin::BIstrlcpy: // fallthrough
4726   case Builtin::BIstrlcat:
4727     CheckStrlcpycatArguments(TheCall, FnInfo);
4728     break;
4729   case Builtin::BIstrncat:
4730     CheckStrncatArguments(TheCall, FnInfo);
4731     break;
4732   case Builtin::BIfree:
4733     CheckFreeArguments(TheCall);
4734     break;
4735   default:
4736     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4737   }
4738 
4739   return false;
4740 }
4741 
4742 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4743                                ArrayRef<const Expr *> Args) {
4744   VariadicCallType CallType =
4745       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4746 
4747   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4748             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4749             CallType);
4750 
4751   return false;
4752 }
4753 
4754 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4755                             const FunctionProtoType *Proto) {
4756   QualType Ty;
4757   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4758     Ty = V->getType().getNonReferenceType();
4759   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4760     Ty = F->getType().getNonReferenceType();
4761   else
4762     return false;
4763 
4764   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4765       !Ty->isFunctionProtoType())
4766     return false;
4767 
4768   VariadicCallType CallType;
4769   if (!Proto || !Proto->isVariadic()) {
4770     CallType = VariadicDoesNotApply;
4771   } else if (Ty->isBlockPointerType()) {
4772     CallType = VariadicBlock;
4773   } else { // Ty->isFunctionPointerType()
4774     CallType = VariadicFunction;
4775   }
4776 
4777   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4778             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4779             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4780             TheCall->getCallee()->getSourceRange(), CallType);
4781 
4782   return false;
4783 }
4784 
4785 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4786 /// such as function pointers returned from functions.
4787 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4788   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4789                                                   TheCall->getCallee());
4790   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4791             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4792             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4793             TheCall->getCallee()->getSourceRange(), CallType);
4794 
4795   return false;
4796 }
4797 
4798 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4799   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4800     return false;
4801 
4802   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4803   switch (Op) {
4804   case AtomicExpr::AO__c11_atomic_init:
4805   case AtomicExpr::AO__opencl_atomic_init:
4806     llvm_unreachable("There is no ordering argument for an init");
4807 
4808   case AtomicExpr::AO__c11_atomic_load:
4809   case AtomicExpr::AO__opencl_atomic_load:
4810   case AtomicExpr::AO__atomic_load_n:
4811   case AtomicExpr::AO__atomic_load:
4812     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4813            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4814 
4815   case AtomicExpr::AO__c11_atomic_store:
4816   case AtomicExpr::AO__opencl_atomic_store:
4817   case AtomicExpr::AO__atomic_store:
4818   case AtomicExpr::AO__atomic_store_n:
4819     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4820            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4821            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4822 
4823   default:
4824     return true;
4825   }
4826 }
4827 
4828 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4829                                          AtomicExpr::AtomicOp Op) {
4830   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4831   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4832   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4833   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4834                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4835                          Op);
4836 }
4837 
4838 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4839                                  SourceLocation RParenLoc, MultiExprArg Args,
4840                                  AtomicExpr::AtomicOp Op,
4841                                  AtomicArgumentOrder ArgOrder) {
4842   // All the non-OpenCL operations take one of the following forms.
4843   // The OpenCL operations take the __c11 forms with one extra argument for
4844   // synchronization scope.
4845   enum {
4846     // C    __c11_atomic_init(A *, C)
4847     Init,
4848 
4849     // C    __c11_atomic_load(A *, int)
4850     Load,
4851 
4852     // void __atomic_load(A *, CP, int)
4853     LoadCopy,
4854 
4855     // void __atomic_store(A *, CP, int)
4856     Copy,
4857 
4858     // C    __c11_atomic_add(A *, M, int)
4859     Arithmetic,
4860 
4861     // C    __atomic_exchange_n(A *, CP, int)
4862     Xchg,
4863 
4864     // void __atomic_exchange(A *, C *, CP, int)
4865     GNUXchg,
4866 
4867     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4868     C11CmpXchg,
4869 
4870     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4871     GNUCmpXchg
4872   } Form = Init;
4873 
4874   const unsigned NumForm = GNUCmpXchg + 1;
4875   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4876   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4877   // where:
4878   //   C is an appropriate type,
4879   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4880   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4881   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4882   //   the int parameters are for orderings.
4883 
4884   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4885       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4886       "need to update code for modified forms");
4887   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4888                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4889                         AtomicExpr::AO__atomic_load,
4890                 "need to update code for modified C11 atomics");
4891   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4892                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4893   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4894                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4895                IsOpenCL;
4896   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4897              Op == AtomicExpr::AO__atomic_store_n ||
4898              Op == AtomicExpr::AO__atomic_exchange_n ||
4899              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4900   bool IsAddSub = false;
4901 
4902   switch (Op) {
4903   case AtomicExpr::AO__c11_atomic_init:
4904   case AtomicExpr::AO__opencl_atomic_init:
4905     Form = Init;
4906     break;
4907 
4908   case AtomicExpr::AO__c11_atomic_load:
4909   case AtomicExpr::AO__opencl_atomic_load:
4910   case AtomicExpr::AO__atomic_load_n:
4911     Form = Load;
4912     break;
4913 
4914   case AtomicExpr::AO__atomic_load:
4915     Form = LoadCopy;
4916     break;
4917 
4918   case AtomicExpr::AO__c11_atomic_store:
4919   case AtomicExpr::AO__opencl_atomic_store:
4920   case AtomicExpr::AO__atomic_store:
4921   case AtomicExpr::AO__atomic_store_n:
4922     Form = Copy;
4923     break;
4924 
4925   case AtomicExpr::AO__c11_atomic_fetch_add:
4926   case AtomicExpr::AO__c11_atomic_fetch_sub:
4927   case AtomicExpr::AO__opencl_atomic_fetch_add:
4928   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4929   case AtomicExpr::AO__atomic_fetch_add:
4930   case AtomicExpr::AO__atomic_fetch_sub:
4931   case AtomicExpr::AO__atomic_add_fetch:
4932   case AtomicExpr::AO__atomic_sub_fetch:
4933     IsAddSub = true;
4934     LLVM_FALLTHROUGH;
4935   case AtomicExpr::AO__c11_atomic_fetch_and:
4936   case AtomicExpr::AO__c11_atomic_fetch_or:
4937   case AtomicExpr::AO__c11_atomic_fetch_xor:
4938   case AtomicExpr::AO__opencl_atomic_fetch_and:
4939   case AtomicExpr::AO__opencl_atomic_fetch_or:
4940   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4941   case AtomicExpr::AO__atomic_fetch_and:
4942   case AtomicExpr::AO__atomic_fetch_or:
4943   case AtomicExpr::AO__atomic_fetch_xor:
4944   case AtomicExpr::AO__atomic_fetch_nand:
4945   case AtomicExpr::AO__atomic_and_fetch:
4946   case AtomicExpr::AO__atomic_or_fetch:
4947   case AtomicExpr::AO__atomic_xor_fetch:
4948   case AtomicExpr::AO__atomic_nand_fetch:
4949   case AtomicExpr::AO__c11_atomic_fetch_min:
4950   case AtomicExpr::AO__c11_atomic_fetch_max:
4951   case AtomicExpr::AO__opencl_atomic_fetch_min:
4952   case AtomicExpr::AO__opencl_atomic_fetch_max:
4953   case AtomicExpr::AO__atomic_min_fetch:
4954   case AtomicExpr::AO__atomic_max_fetch:
4955   case AtomicExpr::AO__atomic_fetch_min:
4956   case AtomicExpr::AO__atomic_fetch_max:
4957     Form = Arithmetic;
4958     break;
4959 
4960   case AtomicExpr::AO__c11_atomic_exchange:
4961   case AtomicExpr::AO__opencl_atomic_exchange:
4962   case AtomicExpr::AO__atomic_exchange_n:
4963     Form = Xchg;
4964     break;
4965 
4966   case AtomicExpr::AO__atomic_exchange:
4967     Form = GNUXchg;
4968     break;
4969 
4970   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4971   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4972   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4973   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4974     Form = C11CmpXchg;
4975     break;
4976 
4977   case AtomicExpr::AO__atomic_compare_exchange:
4978   case AtomicExpr::AO__atomic_compare_exchange_n:
4979     Form = GNUCmpXchg;
4980     break;
4981   }
4982 
4983   unsigned AdjustedNumArgs = NumArgs[Form];
4984   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4985     ++AdjustedNumArgs;
4986   // Check we have the right number of arguments.
4987   if (Args.size() < AdjustedNumArgs) {
4988     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4989         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4990         << ExprRange;
4991     return ExprError();
4992   } else if (Args.size() > AdjustedNumArgs) {
4993     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4994          diag::err_typecheck_call_too_many_args)
4995         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4996         << ExprRange;
4997     return ExprError();
4998   }
4999 
5000   // Inspect the first argument of the atomic operation.
5001   Expr *Ptr = Args[0];
5002   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5003   if (ConvertedPtr.isInvalid())
5004     return ExprError();
5005 
5006   Ptr = ConvertedPtr.get();
5007   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5008   if (!pointerType) {
5009     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5010         << Ptr->getType() << Ptr->getSourceRange();
5011     return ExprError();
5012   }
5013 
5014   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5015   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5016   QualType ValType = AtomTy; // 'C'
5017   if (IsC11) {
5018     if (!AtomTy->isAtomicType()) {
5019       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5020           << Ptr->getType() << Ptr->getSourceRange();
5021       return ExprError();
5022     }
5023     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5024         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5025       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5026           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5027           << Ptr->getSourceRange();
5028       return ExprError();
5029     }
5030     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5031   } else if (Form != Load && Form != LoadCopy) {
5032     if (ValType.isConstQualified()) {
5033       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5034           << Ptr->getType() << Ptr->getSourceRange();
5035       return ExprError();
5036     }
5037   }
5038 
5039   // For an arithmetic operation, the implied arithmetic must be well-formed.
5040   if (Form == Arithmetic) {
5041     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
5042     if (IsAddSub && !ValType->isIntegerType()
5043         && !ValType->isPointerType()) {
5044       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5045           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5046       return ExprError();
5047     }
5048     if (!IsAddSub && !ValType->isIntegerType()) {
5049       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5050           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5051       return ExprError();
5052     }
5053     if (IsC11 && ValType->isPointerType() &&
5054         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5055                             diag::err_incomplete_type)) {
5056       return ExprError();
5057     }
5058   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5059     // For __atomic_*_n operations, the value type must be a scalar integral or
5060     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5061     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5062         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5063     return ExprError();
5064   }
5065 
5066   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5067       !AtomTy->isScalarType()) {
5068     // For GNU atomics, require a trivially-copyable type. This is not part of
5069     // the GNU atomics specification, but we enforce it for sanity.
5070     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5071         << Ptr->getType() << Ptr->getSourceRange();
5072     return ExprError();
5073   }
5074 
5075   switch (ValType.getObjCLifetime()) {
5076   case Qualifiers::OCL_None:
5077   case Qualifiers::OCL_ExplicitNone:
5078     // okay
5079     break;
5080 
5081   case Qualifiers::OCL_Weak:
5082   case Qualifiers::OCL_Strong:
5083   case Qualifiers::OCL_Autoreleasing:
5084     // FIXME: Can this happen? By this point, ValType should be known
5085     // to be trivially copyable.
5086     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5087         << ValType << Ptr->getSourceRange();
5088     return ExprError();
5089   }
5090 
5091   // All atomic operations have an overload which takes a pointer to a volatile
5092   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5093   // into the result or the other operands. Similarly atomic_load takes a
5094   // pointer to a const 'A'.
5095   ValType.removeLocalVolatile();
5096   ValType.removeLocalConst();
5097   QualType ResultType = ValType;
5098   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5099       Form == Init)
5100     ResultType = Context.VoidTy;
5101   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5102     ResultType = Context.BoolTy;
5103 
5104   // The type of a parameter passed 'by value'. In the GNU atomics, such
5105   // arguments are actually passed as pointers.
5106   QualType ByValType = ValType; // 'CP'
5107   bool IsPassedByAddress = false;
5108   if (!IsC11 && !IsN) {
5109     ByValType = Ptr->getType();
5110     IsPassedByAddress = true;
5111   }
5112 
5113   SmallVector<Expr *, 5> APIOrderedArgs;
5114   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5115     APIOrderedArgs.push_back(Args[0]);
5116     switch (Form) {
5117     case Init:
5118     case Load:
5119       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5120       break;
5121     case LoadCopy:
5122     case Copy:
5123     case Arithmetic:
5124     case Xchg:
5125       APIOrderedArgs.push_back(Args[2]); // Val1
5126       APIOrderedArgs.push_back(Args[1]); // Order
5127       break;
5128     case GNUXchg:
5129       APIOrderedArgs.push_back(Args[2]); // Val1
5130       APIOrderedArgs.push_back(Args[3]); // Val2
5131       APIOrderedArgs.push_back(Args[1]); // Order
5132       break;
5133     case C11CmpXchg:
5134       APIOrderedArgs.push_back(Args[2]); // Val1
5135       APIOrderedArgs.push_back(Args[4]); // Val2
5136       APIOrderedArgs.push_back(Args[1]); // Order
5137       APIOrderedArgs.push_back(Args[3]); // OrderFail
5138       break;
5139     case GNUCmpXchg:
5140       APIOrderedArgs.push_back(Args[2]); // Val1
5141       APIOrderedArgs.push_back(Args[4]); // Val2
5142       APIOrderedArgs.push_back(Args[5]); // Weak
5143       APIOrderedArgs.push_back(Args[1]); // Order
5144       APIOrderedArgs.push_back(Args[3]); // OrderFail
5145       break;
5146     }
5147   } else
5148     APIOrderedArgs.append(Args.begin(), Args.end());
5149 
5150   // The first argument's non-CV pointer type is used to deduce the type of
5151   // subsequent arguments, except for:
5152   //  - weak flag (always converted to bool)
5153   //  - memory order (always converted to int)
5154   //  - scope  (always converted to int)
5155   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5156     QualType Ty;
5157     if (i < NumVals[Form] + 1) {
5158       switch (i) {
5159       case 0:
5160         // The first argument is always a pointer. It has a fixed type.
5161         // It is always dereferenced, a nullptr is undefined.
5162         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5163         // Nothing else to do: we already know all we want about this pointer.
5164         continue;
5165       case 1:
5166         // The second argument is the non-atomic operand. For arithmetic, this
5167         // is always passed by value, and for a compare_exchange it is always
5168         // passed by address. For the rest, GNU uses by-address and C11 uses
5169         // by-value.
5170         assert(Form != Load);
5171         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5172           Ty = ValType;
5173         else if (Form == Copy || Form == Xchg) {
5174           if (IsPassedByAddress) {
5175             // The value pointer is always dereferenced, a nullptr is undefined.
5176             CheckNonNullArgument(*this, APIOrderedArgs[i],
5177                                  ExprRange.getBegin());
5178           }
5179           Ty = ByValType;
5180         } else if (Form == Arithmetic)
5181           Ty = Context.getPointerDiffType();
5182         else {
5183           Expr *ValArg = APIOrderedArgs[i];
5184           // The value pointer is always dereferenced, a nullptr is undefined.
5185           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5186           LangAS AS = LangAS::Default;
5187           // Keep address space of non-atomic pointer type.
5188           if (const PointerType *PtrTy =
5189                   ValArg->getType()->getAs<PointerType>()) {
5190             AS = PtrTy->getPointeeType().getAddressSpace();
5191           }
5192           Ty = Context.getPointerType(
5193               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5194         }
5195         break;
5196       case 2:
5197         // The third argument to compare_exchange / GNU exchange is the desired
5198         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5199         if (IsPassedByAddress)
5200           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5201         Ty = ByValType;
5202         break;
5203       case 3:
5204         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5205         Ty = Context.BoolTy;
5206         break;
5207       }
5208     } else {
5209       // The order(s) and scope are always converted to int.
5210       Ty = Context.IntTy;
5211     }
5212 
5213     InitializedEntity Entity =
5214         InitializedEntity::InitializeParameter(Context, Ty, false);
5215     ExprResult Arg = APIOrderedArgs[i];
5216     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5217     if (Arg.isInvalid())
5218       return true;
5219     APIOrderedArgs[i] = Arg.get();
5220   }
5221 
5222   // Permute the arguments into a 'consistent' order.
5223   SmallVector<Expr*, 5> SubExprs;
5224   SubExprs.push_back(Ptr);
5225   switch (Form) {
5226   case Init:
5227     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5228     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5229     break;
5230   case Load:
5231     SubExprs.push_back(APIOrderedArgs[1]); // Order
5232     break;
5233   case LoadCopy:
5234   case Copy:
5235   case Arithmetic:
5236   case Xchg:
5237     SubExprs.push_back(APIOrderedArgs[2]); // Order
5238     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5239     break;
5240   case GNUXchg:
5241     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5242     SubExprs.push_back(APIOrderedArgs[3]); // Order
5243     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5244     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5245     break;
5246   case C11CmpXchg:
5247     SubExprs.push_back(APIOrderedArgs[3]); // Order
5248     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5249     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5250     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5251     break;
5252   case GNUCmpXchg:
5253     SubExprs.push_back(APIOrderedArgs[4]); // Order
5254     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5255     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5256     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5257     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5258     break;
5259   }
5260 
5261   if (SubExprs.size() >= 2 && Form != Init) {
5262     if (Optional<llvm::APSInt> Result =
5263             SubExprs[1]->getIntegerConstantExpr(Context))
5264       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5265         Diag(SubExprs[1]->getBeginLoc(),
5266              diag::warn_atomic_op_has_invalid_memory_order)
5267             << SubExprs[1]->getSourceRange();
5268   }
5269 
5270   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5271     auto *Scope = Args[Args.size() - 1];
5272     if (Optional<llvm::APSInt> Result =
5273             Scope->getIntegerConstantExpr(Context)) {
5274       if (!ScopeModel->isValid(Result->getZExtValue()))
5275         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5276             << Scope->getSourceRange();
5277     }
5278     SubExprs.push_back(Scope);
5279   }
5280 
5281   AtomicExpr *AE = new (Context)
5282       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5283 
5284   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5285        Op == AtomicExpr::AO__c11_atomic_store ||
5286        Op == AtomicExpr::AO__opencl_atomic_load ||
5287        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5288       Context.AtomicUsesUnsupportedLibcall(AE))
5289     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5290         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5291              Op == AtomicExpr::AO__opencl_atomic_load)
5292                 ? 0
5293                 : 1);
5294 
5295   if (ValType->isExtIntType()) {
5296     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5297     return ExprError();
5298   }
5299 
5300   return AE;
5301 }
5302 
5303 /// checkBuiltinArgument - Given a call to a builtin function, perform
5304 /// normal type-checking on the given argument, updating the call in
5305 /// place.  This is useful when a builtin function requires custom
5306 /// type-checking for some of its arguments but not necessarily all of
5307 /// them.
5308 ///
5309 /// Returns true on error.
5310 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5311   FunctionDecl *Fn = E->getDirectCallee();
5312   assert(Fn && "builtin call without direct callee!");
5313 
5314   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5315   InitializedEntity Entity =
5316     InitializedEntity::InitializeParameter(S.Context, Param);
5317 
5318   ExprResult Arg = E->getArg(0);
5319   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5320   if (Arg.isInvalid())
5321     return true;
5322 
5323   E->setArg(ArgIndex, Arg.get());
5324   return false;
5325 }
5326 
5327 /// We have a call to a function like __sync_fetch_and_add, which is an
5328 /// overloaded function based on the pointer type of its first argument.
5329 /// The main BuildCallExpr routines have already promoted the types of
5330 /// arguments because all of these calls are prototyped as void(...).
5331 ///
5332 /// This function goes through and does final semantic checking for these
5333 /// builtins, as well as generating any warnings.
5334 ExprResult
5335 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5336   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5337   Expr *Callee = TheCall->getCallee();
5338   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5339   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5340 
5341   // Ensure that we have at least one argument to do type inference from.
5342   if (TheCall->getNumArgs() < 1) {
5343     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5344         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5345     return ExprError();
5346   }
5347 
5348   // Inspect the first argument of the atomic builtin.  This should always be
5349   // a pointer type, whose element is an integral scalar or pointer type.
5350   // Because it is a pointer type, we don't have to worry about any implicit
5351   // casts here.
5352   // FIXME: We don't allow floating point scalars as input.
5353   Expr *FirstArg = TheCall->getArg(0);
5354   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5355   if (FirstArgResult.isInvalid())
5356     return ExprError();
5357   FirstArg = FirstArgResult.get();
5358   TheCall->setArg(0, FirstArg);
5359 
5360   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5361   if (!pointerType) {
5362     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5363         << FirstArg->getType() << FirstArg->getSourceRange();
5364     return ExprError();
5365   }
5366 
5367   QualType ValType = pointerType->getPointeeType();
5368   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5369       !ValType->isBlockPointerType()) {
5370     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5371         << FirstArg->getType() << FirstArg->getSourceRange();
5372     return ExprError();
5373   }
5374 
5375   if (ValType.isConstQualified()) {
5376     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5377         << FirstArg->getType() << FirstArg->getSourceRange();
5378     return ExprError();
5379   }
5380 
5381   switch (ValType.getObjCLifetime()) {
5382   case Qualifiers::OCL_None:
5383   case Qualifiers::OCL_ExplicitNone:
5384     // okay
5385     break;
5386 
5387   case Qualifiers::OCL_Weak:
5388   case Qualifiers::OCL_Strong:
5389   case Qualifiers::OCL_Autoreleasing:
5390     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5391         << ValType << FirstArg->getSourceRange();
5392     return ExprError();
5393   }
5394 
5395   // Strip any qualifiers off ValType.
5396   ValType = ValType.getUnqualifiedType();
5397 
5398   // The majority of builtins return a value, but a few have special return
5399   // types, so allow them to override appropriately below.
5400   QualType ResultType = ValType;
5401 
5402   // We need to figure out which concrete builtin this maps onto.  For example,
5403   // __sync_fetch_and_add with a 2 byte object turns into
5404   // __sync_fetch_and_add_2.
5405 #define BUILTIN_ROW(x) \
5406   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5407     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5408 
5409   static const unsigned BuiltinIndices[][5] = {
5410     BUILTIN_ROW(__sync_fetch_and_add),
5411     BUILTIN_ROW(__sync_fetch_and_sub),
5412     BUILTIN_ROW(__sync_fetch_and_or),
5413     BUILTIN_ROW(__sync_fetch_and_and),
5414     BUILTIN_ROW(__sync_fetch_and_xor),
5415     BUILTIN_ROW(__sync_fetch_and_nand),
5416 
5417     BUILTIN_ROW(__sync_add_and_fetch),
5418     BUILTIN_ROW(__sync_sub_and_fetch),
5419     BUILTIN_ROW(__sync_and_and_fetch),
5420     BUILTIN_ROW(__sync_or_and_fetch),
5421     BUILTIN_ROW(__sync_xor_and_fetch),
5422     BUILTIN_ROW(__sync_nand_and_fetch),
5423 
5424     BUILTIN_ROW(__sync_val_compare_and_swap),
5425     BUILTIN_ROW(__sync_bool_compare_and_swap),
5426     BUILTIN_ROW(__sync_lock_test_and_set),
5427     BUILTIN_ROW(__sync_lock_release),
5428     BUILTIN_ROW(__sync_swap)
5429   };
5430 #undef BUILTIN_ROW
5431 
5432   // Determine the index of the size.
5433   unsigned SizeIndex;
5434   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5435   case 1: SizeIndex = 0; break;
5436   case 2: SizeIndex = 1; break;
5437   case 4: SizeIndex = 2; break;
5438   case 8: SizeIndex = 3; break;
5439   case 16: SizeIndex = 4; break;
5440   default:
5441     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5442         << FirstArg->getType() << FirstArg->getSourceRange();
5443     return ExprError();
5444   }
5445 
5446   // Each of these builtins has one pointer argument, followed by some number of
5447   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5448   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5449   // as the number of fixed args.
5450   unsigned BuiltinID = FDecl->getBuiltinID();
5451   unsigned BuiltinIndex, NumFixed = 1;
5452   bool WarnAboutSemanticsChange = false;
5453   switch (BuiltinID) {
5454   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5455   case Builtin::BI__sync_fetch_and_add:
5456   case Builtin::BI__sync_fetch_and_add_1:
5457   case Builtin::BI__sync_fetch_and_add_2:
5458   case Builtin::BI__sync_fetch_and_add_4:
5459   case Builtin::BI__sync_fetch_and_add_8:
5460   case Builtin::BI__sync_fetch_and_add_16:
5461     BuiltinIndex = 0;
5462     break;
5463 
5464   case Builtin::BI__sync_fetch_and_sub:
5465   case Builtin::BI__sync_fetch_and_sub_1:
5466   case Builtin::BI__sync_fetch_and_sub_2:
5467   case Builtin::BI__sync_fetch_and_sub_4:
5468   case Builtin::BI__sync_fetch_and_sub_8:
5469   case Builtin::BI__sync_fetch_and_sub_16:
5470     BuiltinIndex = 1;
5471     break;
5472 
5473   case Builtin::BI__sync_fetch_and_or:
5474   case Builtin::BI__sync_fetch_and_or_1:
5475   case Builtin::BI__sync_fetch_and_or_2:
5476   case Builtin::BI__sync_fetch_and_or_4:
5477   case Builtin::BI__sync_fetch_and_or_8:
5478   case Builtin::BI__sync_fetch_and_or_16:
5479     BuiltinIndex = 2;
5480     break;
5481 
5482   case Builtin::BI__sync_fetch_and_and:
5483   case Builtin::BI__sync_fetch_and_and_1:
5484   case Builtin::BI__sync_fetch_and_and_2:
5485   case Builtin::BI__sync_fetch_and_and_4:
5486   case Builtin::BI__sync_fetch_and_and_8:
5487   case Builtin::BI__sync_fetch_and_and_16:
5488     BuiltinIndex = 3;
5489     break;
5490 
5491   case Builtin::BI__sync_fetch_and_xor:
5492   case Builtin::BI__sync_fetch_and_xor_1:
5493   case Builtin::BI__sync_fetch_and_xor_2:
5494   case Builtin::BI__sync_fetch_and_xor_4:
5495   case Builtin::BI__sync_fetch_and_xor_8:
5496   case Builtin::BI__sync_fetch_and_xor_16:
5497     BuiltinIndex = 4;
5498     break;
5499 
5500   case Builtin::BI__sync_fetch_and_nand:
5501   case Builtin::BI__sync_fetch_and_nand_1:
5502   case Builtin::BI__sync_fetch_and_nand_2:
5503   case Builtin::BI__sync_fetch_and_nand_4:
5504   case Builtin::BI__sync_fetch_and_nand_8:
5505   case Builtin::BI__sync_fetch_and_nand_16:
5506     BuiltinIndex = 5;
5507     WarnAboutSemanticsChange = true;
5508     break;
5509 
5510   case Builtin::BI__sync_add_and_fetch:
5511   case Builtin::BI__sync_add_and_fetch_1:
5512   case Builtin::BI__sync_add_and_fetch_2:
5513   case Builtin::BI__sync_add_and_fetch_4:
5514   case Builtin::BI__sync_add_and_fetch_8:
5515   case Builtin::BI__sync_add_and_fetch_16:
5516     BuiltinIndex = 6;
5517     break;
5518 
5519   case Builtin::BI__sync_sub_and_fetch:
5520   case Builtin::BI__sync_sub_and_fetch_1:
5521   case Builtin::BI__sync_sub_and_fetch_2:
5522   case Builtin::BI__sync_sub_and_fetch_4:
5523   case Builtin::BI__sync_sub_and_fetch_8:
5524   case Builtin::BI__sync_sub_and_fetch_16:
5525     BuiltinIndex = 7;
5526     break;
5527 
5528   case Builtin::BI__sync_and_and_fetch:
5529   case Builtin::BI__sync_and_and_fetch_1:
5530   case Builtin::BI__sync_and_and_fetch_2:
5531   case Builtin::BI__sync_and_and_fetch_4:
5532   case Builtin::BI__sync_and_and_fetch_8:
5533   case Builtin::BI__sync_and_and_fetch_16:
5534     BuiltinIndex = 8;
5535     break;
5536 
5537   case Builtin::BI__sync_or_and_fetch:
5538   case Builtin::BI__sync_or_and_fetch_1:
5539   case Builtin::BI__sync_or_and_fetch_2:
5540   case Builtin::BI__sync_or_and_fetch_4:
5541   case Builtin::BI__sync_or_and_fetch_8:
5542   case Builtin::BI__sync_or_and_fetch_16:
5543     BuiltinIndex = 9;
5544     break;
5545 
5546   case Builtin::BI__sync_xor_and_fetch:
5547   case Builtin::BI__sync_xor_and_fetch_1:
5548   case Builtin::BI__sync_xor_and_fetch_2:
5549   case Builtin::BI__sync_xor_and_fetch_4:
5550   case Builtin::BI__sync_xor_and_fetch_8:
5551   case Builtin::BI__sync_xor_and_fetch_16:
5552     BuiltinIndex = 10;
5553     break;
5554 
5555   case Builtin::BI__sync_nand_and_fetch:
5556   case Builtin::BI__sync_nand_and_fetch_1:
5557   case Builtin::BI__sync_nand_and_fetch_2:
5558   case Builtin::BI__sync_nand_and_fetch_4:
5559   case Builtin::BI__sync_nand_and_fetch_8:
5560   case Builtin::BI__sync_nand_and_fetch_16:
5561     BuiltinIndex = 11;
5562     WarnAboutSemanticsChange = true;
5563     break;
5564 
5565   case Builtin::BI__sync_val_compare_and_swap:
5566   case Builtin::BI__sync_val_compare_and_swap_1:
5567   case Builtin::BI__sync_val_compare_and_swap_2:
5568   case Builtin::BI__sync_val_compare_and_swap_4:
5569   case Builtin::BI__sync_val_compare_and_swap_8:
5570   case Builtin::BI__sync_val_compare_and_swap_16:
5571     BuiltinIndex = 12;
5572     NumFixed = 2;
5573     break;
5574 
5575   case Builtin::BI__sync_bool_compare_and_swap:
5576   case Builtin::BI__sync_bool_compare_and_swap_1:
5577   case Builtin::BI__sync_bool_compare_and_swap_2:
5578   case Builtin::BI__sync_bool_compare_and_swap_4:
5579   case Builtin::BI__sync_bool_compare_and_swap_8:
5580   case Builtin::BI__sync_bool_compare_and_swap_16:
5581     BuiltinIndex = 13;
5582     NumFixed = 2;
5583     ResultType = Context.BoolTy;
5584     break;
5585 
5586   case Builtin::BI__sync_lock_test_and_set:
5587   case Builtin::BI__sync_lock_test_and_set_1:
5588   case Builtin::BI__sync_lock_test_and_set_2:
5589   case Builtin::BI__sync_lock_test_and_set_4:
5590   case Builtin::BI__sync_lock_test_and_set_8:
5591   case Builtin::BI__sync_lock_test_and_set_16:
5592     BuiltinIndex = 14;
5593     break;
5594 
5595   case Builtin::BI__sync_lock_release:
5596   case Builtin::BI__sync_lock_release_1:
5597   case Builtin::BI__sync_lock_release_2:
5598   case Builtin::BI__sync_lock_release_4:
5599   case Builtin::BI__sync_lock_release_8:
5600   case Builtin::BI__sync_lock_release_16:
5601     BuiltinIndex = 15;
5602     NumFixed = 0;
5603     ResultType = Context.VoidTy;
5604     break;
5605 
5606   case Builtin::BI__sync_swap:
5607   case Builtin::BI__sync_swap_1:
5608   case Builtin::BI__sync_swap_2:
5609   case Builtin::BI__sync_swap_4:
5610   case Builtin::BI__sync_swap_8:
5611   case Builtin::BI__sync_swap_16:
5612     BuiltinIndex = 16;
5613     break;
5614   }
5615 
5616   // Now that we know how many fixed arguments we expect, first check that we
5617   // have at least that many.
5618   if (TheCall->getNumArgs() < 1+NumFixed) {
5619     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5620         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5621         << Callee->getSourceRange();
5622     return ExprError();
5623   }
5624 
5625   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5626       << Callee->getSourceRange();
5627 
5628   if (WarnAboutSemanticsChange) {
5629     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5630         << Callee->getSourceRange();
5631   }
5632 
5633   // Get the decl for the concrete builtin from this, we can tell what the
5634   // concrete integer type we should convert to is.
5635   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5636   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5637   FunctionDecl *NewBuiltinDecl;
5638   if (NewBuiltinID == BuiltinID)
5639     NewBuiltinDecl = FDecl;
5640   else {
5641     // Perform builtin lookup to avoid redeclaring it.
5642     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5643     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5644     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5645     assert(Res.getFoundDecl());
5646     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5647     if (!NewBuiltinDecl)
5648       return ExprError();
5649   }
5650 
5651   // The first argument --- the pointer --- has a fixed type; we
5652   // deduce the types of the rest of the arguments accordingly.  Walk
5653   // the remaining arguments, converting them to the deduced value type.
5654   for (unsigned i = 0; i != NumFixed; ++i) {
5655     ExprResult Arg = TheCall->getArg(i+1);
5656 
5657     // GCC does an implicit conversion to the pointer or integer ValType.  This
5658     // can fail in some cases (1i -> int**), check for this error case now.
5659     // Initialize the argument.
5660     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5661                                                    ValType, /*consume*/ false);
5662     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5663     if (Arg.isInvalid())
5664       return ExprError();
5665 
5666     // Okay, we have something that *can* be converted to the right type.  Check
5667     // to see if there is a potentially weird extension going on here.  This can
5668     // happen when you do an atomic operation on something like an char* and
5669     // pass in 42.  The 42 gets converted to char.  This is even more strange
5670     // for things like 45.123 -> char, etc.
5671     // FIXME: Do this check.
5672     TheCall->setArg(i+1, Arg.get());
5673   }
5674 
5675   // Create a new DeclRefExpr to refer to the new decl.
5676   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5677       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5678       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5679       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5680 
5681   // Set the callee in the CallExpr.
5682   // FIXME: This loses syntactic information.
5683   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5684   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5685                                               CK_BuiltinFnToFnPtr);
5686   TheCall->setCallee(PromotedCall.get());
5687 
5688   // Change the result type of the call to match the original value type. This
5689   // is arbitrary, but the codegen for these builtins ins design to handle it
5690   // gracefully.
5691   TheCall->setType(ResultType);
5692 
5693   // Prohibit use of _ExtInt with atomic builtins.
5694   // The arguments would have already been converted to the first argument's
5695   // type, so only need to check the first argument.
5696   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5697   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5698     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5699     return ExprError();
5700   }
5701 
5702   return TheCallResult;
5703 }
5704 
5705 /// SemaBuiltinNontemporalOverloaded - We have a call to
5706 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5707 /// overloaded function based on the pointer type of its last argument.
5708 ///
5709 /// This function goes through and does final semantic checking for these
5710 /// builtins.
5711 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5712   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5713   DeclRefExpr *DRE =
5714       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5715   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5716   unsigned BuiltinID = FDecl->getBuiltinID();
5717   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5718           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5719          "Unexpected nontemporal load/store builtin!");
5720   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5721   unsigned numArgs = isStore ? 2 : 1;
5722 
5723   // Ensure that we have the proper number of arguments.
5724   if (checkArgCount(*this, TheCall, numArgs))
5725     return ExprError();
5726 
5727   // Inspect the last argument of the nontemporal builtin.  This should always
5728   // be a pointer type, from which we imply the type of the memory access.
5729   // Because it is a pointer type, we don't have to worry about any implicit
5730   // casts here.
5731   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5732   ExprResult PointerArgResult =
5733       DefaultFunctionArrayLvalueConversion(PointerArg);
5734 
5735   if (PointerArgResult.isInvalid())
5736     return ExprError();
5737   PointerArg = PointerArgResult.get();
5738   TheCall->setArg(numArgs - 1, PointerArg);
5739 
5740   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5741   if (!pointerType) {
5742     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5743         << PointerArg->getType() << PointerArg->getSourceRange();
5744     return ExprError();
5745   }
5746 
5747   QualType ValType = pointerType->getPointeeType();
5748 
5749   // Strip any qualifiers off ValType.
5750   ValType = ValType.getUnqualifiedType();
5751   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5752       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5753       !ValType->isVectorType()) {
5754     Diag(DRE->getBeginLoc(),
5755          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5756         << PointerArg->getType() << PointerArg->getSourceRange();
5757     return ExprError();
5758   }
5759 
5760   if (!isStore) {
5761     TheCall->setType(ValType);
5762     return TheCallResult;
5763   }
5764 
5765   ExprResult ValArg = TheCall->getArg(0);
5766   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5767       Context, ValType, /*consume*/ false);
5768   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5769   if (ValArg.isInvalid())
5770     return ExprError();
5771 
5772   TheCall->setArg(0, ValArg.get());
5773   TheCall->setType(Context.VoidTy);
5774   return TheCallResult;
5775 }
5776 
5777 /// CheckObjCString - Checks that the argument to the builtin
5778 /// CFString constructor is correct
5779 /// Note: It might also make sense to do the UTF-16 conversion here (would
5780 /// simplify the backend).
5781 bool Sema::CheckObjCString(Expr *Arg) {
5782   Arg = Arg->IgnoreParenCasts();
5783   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5784 
5785   if (!Literal || !Literal->isAscii()) {
5786     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5787         << Arg->getSourceRange();
5788     return true;
5789   }
5790 
5791   if (Literal->containsNonAsciiOrNull()) {
5792     StringRef String = Literal->getString();
5793     unsigned NumBytes = String.size();
5794     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5795     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5796     llvm::UTF16 *ToPtr = &ToBuf[0];
5797 
5798     llvm::ConversionResult Result =
5799         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5800                                  ToPtr + NumBytes, llvm::strictConversion);
5801     // Check for conversion failure.
5802     if (Result != llvm::conversionOK)
5803       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5804           << Arg->getSourceRange();
5805   }
5806   return false;
5807 }
5808 
5809 /// CheckObjCString - Checks that the format string argument to the os_log()
5810 /// and os_trace() functions is correct, and converts it to const char *.
5811 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5812   Arg = Arg->IgnoreParenCasts();
5813   auto *Literal = dyn_cast<StringLiteral>(Arg);
5814   if (!Literal) {
5815     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5816       Literal = ObjcLiteral->getString();
5817     }
5818   }
5819 
5820   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5821     return ExprError(
5822         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5823         << Arg->getSourceRange());
5824   }
5825 
5826   ExprResult Result(Literal);
5827   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5828   InitializedEntity Entity =
5829       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5830   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5831   return Result;
5832 }
5833 
5834 /// Check that the user is calling the appropriate va_start builtin for the
5835 /// target and calling convention.
5836 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5837   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5838   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5839   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5840                     TT.getArch() == llvm::Triple::aarch64_32);
5841   bool IsWindows = TT.isOSWindows();
5842   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5843   if (IsX64 || IsAArch64) {
5844     CallingConv CC = CC_C;
5845     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5846       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5847     if (IsMSVAStart) {
5848       // Don't allow this in System V ABI functions.
5849       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5850         return S.Diag(Fn->getBeginLoc(),
5851                       diag::err_ms_va_start_used_in_sysv_function);
5852     } else {
5853       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5854       // On x64 Windows, don't allow this in System V ABI functions.
5855       // (Yes, that means there's no corresponding way to support variadic
5856       // System V ABI functions on Windows.)
5857       if ((IsWindows && CC == CC_X86_64SysV) ||
5858           (!IsWindows && CC == CC_Win64))
5859         return S.Diag(Fn->getBeginLoc(),
5860                       diag::err_va_start_used_in_wrong_abi_function)
5861                << !IsWindows;
5862     }
5863     return false;
5864   }
5865 
5866   if (IsMSVAStart)
5867     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5868   return false;
5869 }
5870 
5871 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5872                                              ParmVarDecl **LastParam = nullptr) {
5873   // Determine whether the current function, block, or obj-c method is variadic
5874   // and get its parameter list.
5875   bool IsVariadic = false;
5876   ArrayRef<ParmVarDecl *> Params;
5877   DeclContext *Caller = S.CurContext;
5878   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5879     IsVariadic = Block->isVariadic();
5880     Params = Block->parameters();
5881   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5882     IsVariadic = FD->isVariadic();
5883     Params = FD->parameters();
5884   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5885     IsVariadic = MD->isVariadic();
5886     // FIXME: This isn't correct for methods (results in bogus warning).
5887     Params = MD->parameters();
5888   } else if (isa<CapturedDecl>(Caller)) {
5889     // We don't support va_start in a CapturedDecl.
5890     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5891     return true;
5892   } else {
5893     // This must be some other declcontext that parses exprs.
5894     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5895     return true;
5896   }
5897 
5898   if (!IsVariadic) {
5899     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5900     return true;
5901   }
5902 
5903   if (LastParam)
5904     *LastParam = Params.empty() ? nullptr : Params.back();
5905 
5906   return false;
5907 }
5908 
5909 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5910 /// for validity.  Emit an error and return true on failure; return false
5911 /// on success.
5912 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5913   Expr *Fn = TheCall->getCallee();
5914 
5915   if (checkVAStartABI(*this, BuiltinID, Fn))
5916     return true;
5917 
5918   if (checkArgCount(*this, TheCall, 2))
5919     return true;
5920 
5921   // Type-check the first argument normally.
5922   if (checkBuiltinArgument(*this, TheCall, 0))
5923     return true;
5924 
5925   // Check that the current function is variadic, and get its last parameter.
5926   ParmVarDecl *LastParam;
5927   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5928     return true;
5929 
5930   // Verify that the second argument to the builtin is the last argument of the
5931   // current function or method.
5932   bool SecondArgIsLastNamedArgument = false;
5933   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5934 
5935   // These are valid if SecondArgIsLastNamedArgument is false after the next
5936   // block.
5937   QualType Type;
5938   SourceLocation ParamLoc;
5939   bool IsCRegister = false;
5940 
5941   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5942     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5943       SecondArgIsLastNamedArgument = PV == LastParam;
5944 
5945       Type = PV->getType();
5946       ParamLoc = PV->getLocation();
5947       IsCRegister =
5948           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5949     }
5950   }
5951 
5952   if (!SecondArgIsLastNamedArgument)
5953     Diag(TheCall->getArg(1)->getBeginLoc(),
5954          diag::warn_second_arg_of_va_start_not_last_named_param);
5955   else if (IsCRegister || Type->isReferenceType() ||
5956            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5957              // Promotable integers are UB, but enumerations need a bit of
5958              // extra checking to see what their promotable type actually is.
5959              if (!Type->isPromotableIntegerType())
5960                return false;
5961              if (!Type->isEnumeralType())
5962                return true;
5963              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5964              return !(ED &&
5965                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5966            }()) {
5967     unsigned Reason = 0;
5968     if (Type->isReferenceType())  Reason = 1;
5969     else if (IsCRegister)         Reason = 2;
5970     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5971     Diag(ParamLoc, diag::note_parameter_type) << Type;
5972   }
5973 
5974   TheCall->setType(Context.VoidTy);
5975   return false;
5976 }
5977 
5978 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5979   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5980   //                 const char *named_addr);
5981 
5982   Expr *Func = Call->getCallee();
5983 
5984   if (Call->getNumArgs() < 3)
5985     return Diag(Call->getEndLoc(),
5986                 diag::err_typecheck_call_too_few_args_at_least)
5987            << 0 /*function call*/ << 3 << Call->getNumArgs();
5988 
5989   // Type-check the first argument normally.
5990   if (checkBuiltinArgument(*this, Call, 0))
5991     return true;
5992 
5993   // Check that the current function is variadic.
5994   if (checkVAStartIsInVariadicFunction(*this, Func))
5995     return true;
5996 
5997   // __va_start on Windows does not validate the parameter qualifiers
5998 
5999   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6000   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6001 
6002   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6003   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6004 
6005   const QualType &ConstCharPtrTy =
6006       Context.getPointerType(Context.CharTy.withConst());
6007   if (!Arg1Ty->isPointerType() ||
6008       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6009     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6010         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6011         << 0                                      /* qualifier difference */
6012         << 3                                      /* parameter mismatch */
6013         << 2 << Arg1->getType() << ConstCharPtrTy;
6014 
6015   const QualType SizeTy = Context.getSizeType();
6016   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6017     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6018         << Arg2->getType() << SizeTy << 1 /* different class */
6019         << 0                              /* qualifier difference */
6020         << 3                              /* parameter mismatch */
6021         << 3 << Arg2->getType() << SizeTy;
6022 
6023   return false;
6024 }
6025 
6026 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6027 /// friends.  This is declared to take (...), so we have to check everything.
6028 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6029   if (checkArgCount(*this, TheCall, 2))
6030     return true;
6031 
6032   ExprResult OrigArg0 = TheCall->getArg(0);
6033   ExprResult OrigArg1 = TheCall->getArg(1);
6034 
6035   // Do standard promotions between the two arguments, returning their common
6036   // type.
6037   QualType Res = UsualArithmeticConversions(
6038       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6039   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6040     return true;
6041 
6042   // Make sure any conversions are pushed back into the call; this is
6043   // type safe since unordered compare builtins are declared as "_Bool
6044   // foo(...)".
6045   TheCall->setArg(0, OrigArg0.get());
6046   TheCall->setArg(1, OrigArg1.get());
6047 
6048   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6049     return false;
6050 
6051   // If the common type isn't a real floating type, then the arguments were
6052   // invalid for this operation.
6053   if (Res.isNull() || !Res->isRealFloatingType())
6054     return Diag(OrigArg0.get()->getBeginLoc(),
6055                 diag::err_typecheck_call_invalid_ordered_compare)
6056            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6057            << SourceRange(OrigArg0.get()->getBeginLoc(),
6058                           OrigArg1.get()->getEndLoc());
6059 
6060   return false;
6061 }
6062 
6063 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6064 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6065 /// to check everything. We expect the last argument to be a floating point
6066 /// value.
6067 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6068   if (checkArgCount(*this, TheCall, NumArgs))
6069     return true;
6070 
6071   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6072   // on all preceding parameters just being int.  Try all of those.
6073   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6074     Expr *Arg = TheCall->getArg(i);
6075 
6076     if (Arg->isTypeDependent())
6077       return false;
6078 
6079     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6080 
6081     if (Res.isInvalid())
6082       return true;
6083     TheCall->setArg(i, Res.get());
6084   }
6085 
6086   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6087 
6088   if (OrigArg->isTypeDependent())
6089     return false;
6090 
6091   // Usual Unary Conversions will convert half to float, which we want for
6092   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6093   // type how it is, but do normal L->Rvalue conversions.
6094   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6095     OrigArg = UsualUnaryConversions(OrigArg).get();
6096   else
6097     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6098   TheCall->setArg(NumArgs - 1, OrigArg);
6099 
6100   // This operation requires a non-_Complex floating-point number.
6101   if (!OrigArg->getType()->isRealFloatingType())
6102     return Diag(OrigArg->getBeginLoc(),
6103                 diag::err_typecheck_call_invalid_unary_fp)
6104            << OrigArg->getType() << OrigArg->getSourceRange();
6105 
6106   return false;
6107 }
6108 
6109 /// Perform semantic analysis for a call to __builtin_complex.
6110 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6111   if (checkArgCount(*this, TheCall, 2))
6112     return true;
6113 
6114   bool Dependent = false;
6115   for (unsigned I = 0; I != 2; ++I) {
6116     Expr *Arg = TheCall->getArg(I);
6117     QualType T = Arg->getType();
6118     if (T->isDependentType()) {
6119       Dependent = true;
6120       continue;
6121     }
6122 
6123     // Despite supporting _Complex int, GCC requires a real floating point type
6124     // for the operands of __builtin_complex.
6125     if (!T->isRealFloatingType()) {
6126       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6127              << Arg->getType() << Arg->getSourceRange();
6128     }
6129 
6130     ExprResult Converted = DefaultLvalueConversion(Arg);
6131     if (Converted.isInvalid())
6132       return true;
6133     TheCall->setArg(I, Converted.get());
6134   }
6135 
6136   if (Dependent) {
6137     TheCall->setType(Context.DependentTy);
6138     return false;
6139   }
6140 
6141   Expr *Real = TheCall->getArg(0);
6142   Expr *Imag = TheCall->getArg(1);
6143   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6144     return Diag(Real->getBeginLoc(),
6145                 diag::err_typecheck_call_different_arg_types)
6146            << Real->getType() << Imag->getType()
6147            << Real->getSourceRange() << Imag->getSourceRange();
6148   }
6149 
6150   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6151   // don't allow this builtin to form those types either.
6152   // FIXME: Should we allow these types?
6153   if (Real->getType()->isFloat16Type())
6154     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6155            << "_Float16";
6156   if (Real->getType()->isHalfType())
6157     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6158            << "half";
6159 
6160   TheCall->setType(Context.getComplexType(Real->getType()));
6161   return false;
6162 }
6163 
6164 // Customized Sema Checking for VSX builtins that have the following signature:
6165 // vector [...] builtinName(vector [...], vector [...], const int);
6166 // Which takes the same type of vectors (any legal vector type) for the first
6167 // two arguments and takes compile time constant for the third argument.
6168 // Example builtins are :
6169 // vector double vec_xxpermdi(vector double, vector double, int);
6170 // vector short vec_xxsldwi(vector short, vector short, int);
6171 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6172   unsigned ExpectedNumArgs = 3;
6173   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6174     return true;
6175 
6176   // Check the third argument is a compile time constant
6177   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6178     return Diag(TheCall->getBeginLoc(),
6179                 diag::err_vsx_builtin_nonconstant_argument)
6180            << 3 /* argument index */ << TheCall->getDirectCallee()
6181            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6182                           TheCall->getArg(2)->getEndLoc());
6183 
6184   QualType Arg1Ty = TheCall->getArg(0)->getType();
6185   QualType Arg2Ty = TheCall->getArg(1)->getType();
6186 
6187   // Check the type of argument 1 and argument 2 are vectors.
6188   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6189   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6190       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6191     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6192            << TheCall->getDirectCallee()
6193            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6194                           TheCall->getArg(1)->getEndLoc());
6195   }
6196 
6197   // Check the first two arguments are the same type.
6198   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6199     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6200            << TheCall->getDirectCallee()
6201            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6202                           TheCall->getArg(1)->getEndLoc());
6203   }
6204 
6205   // When default clang type checking is turned off and the customized type
6206   // checking is used, the returning type of the function must be explicitly
6207   // set. Otherwise it is _Bool by default.
6208   TheCall->setType(Arg1Ty);
6209 
6210   return false;
6211 }
6212 
6213 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6214 // This is declared to take (...), so we have to check everything.
6215 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6216   if (TheCall->getNumArgs() < 2)
6217     return ExprError(Diag(TheCall->getEndLoc(),
6218                           diag::err_typecheck_call_too_few_args_at_least)
6219                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6220                      << TheCall->getSourceRange());
6221 
6222   // Determine which of the following types of shufflevector we're checking:
6223   // 1) unary, vector mask: (lhs, mask)
6224   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6225   QualType resType = TheCall->getArg(0)->getType();
6226   unsigned numElements = 0;
6227 
6228   if (!TheCall->getArg(0)->isTypeDependent() &&
6229       !TheCall->getArg(1)->isTypeDependent()) {
6230     QualType LHSType = TheCall->getArg(0)->getType();
6231     QualType RHSType = TheCall->getArg(1)->getType();
6232 
6233     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6234       return ExprError(
6235           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6236           << TheCall->getDirectCallee()
6237           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6238                          TheCall->getArg(1)->getEndLoc()));
6239 
6240     numElements = LHSType->castAs<VectorType>()->getNumElements();
6241     unsigned numResElements = TheCall->getNumArgs() - 2;
6242 
6243     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6244     // with mask.  If so, verify that RHS is an integer vector type with the
6245     // same number of elts as lhs.
6246     if (TheCall->getNumArgs() == 2) {
6247       if (!RHSType->hasIntegerRepresentation() ||
6248           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6249         return ExprError(Diag(TheCall->getBeginLoc(),
6250                               diag::err_vec_builtin_incompatible_vector)
6251                          << TheCall->getDirectCallee()
6252                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6253                                         TheCall->getArg(1)->getEndLoc()));
6254     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6255       return ExprError(Diag(TheCall->getBeginLoc(),
6256                             diag::err_vec_builtin_incompatible_vector)
6257                        << TheCall->getDirectCallee()
6258                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6259                                       TheCall->getArg(1)->getEndLoc()));
6260     } else if (numElements != numResElements) {
6261       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6262       resType = Context.getVectorType(eltType, numResElements,
6263                                       VectorType::GenericVector);
6264     }
6265   }
6266 
6267   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6268     if (TheCall->getArg(i)->isTypeDependent() ||
6269         TheCall->getArg(i)->isValueDependent())
6270       continue;
6271 
6272     Optional<llvm::APSInt> Result;
6273     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6274       return ExprError(Diag(TheCall->getBeginLoc(),
6275                             diag::err_shufflevector_nonconstant_argument)
6276                        << TheCall->getArg(i)->getSourceRange());
6277 
6278     // Allow -1 which will be translated to undef in the IR.
6279     if (Result->isSigned() && Result->isAllOnesValue())
6280       continue;
6281 
6282     if (Result->getActiveBits() > 64 ||
6283         Result->getZExtValue() >= numElements * 2)
6284       return ExprError(Diag(TheCall->getBeginLoc(),
6285                             diag::err_shufflevector_argument_too_large)
6286                        << TheCall->getArg(i)->getSourceRange());
6287   }
6288 
6289   SmallVector<Expr*, 32> exprs;
6290 
6291   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6292     exprs.push_back(TheCall->getArg(i));
6293     TheCall->setArg(i, nullptr);
6294   }
6295 
6296   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6297                                          TheCall->getCallee()->getBeginLoc(),
6298                                          TheCall->getRParenLoc());
6299 }
6300 
6301 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6302 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6303                                        SourceLocation BuiltinLoc,
6304                                        SourceLocation RParenLoc) {
6305   ExprValueKind VK = VK_RValue;
6306   ExprObjectKind OK = OK_Ordinary;
6307   QualType DstTy = TInfo->getType();
6308   QualType SrcTy = E->getType();
6309 
6310   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6311     return ExprError(Diag(BuiltinLoc,
6312                           diag::err_convertvector_non_vector)
6313                      << E->getSourceRange());
6314   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6315     return ExprError(Diag(BuiltinLoc,
6316                           diag::err_convertvector_non_vector_type));
6317 
6318   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6319     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6320     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6321     if (SrcElts != DstElts)
6322       return ExprError(Diag(BuiltinLoc,
6323                             diag::err_convertvector_incompatible_vector)
6324                        << E->getSourceRange());
6325   }
6326 
6327   return new (Context)
6328       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6329 }
6330 
6331 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6332 // This is declared to take (const void*, ...) and can take two
6333 // optional constant int args.
6334 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6335   unsigned NumArgs = TheCall->getNumArgs();
6336 
6337   if (NumArgs > 3)
6338     return Diag(TheCall->getEndLoc(),
6339                 diag::err_typecheck_call_too_many_args_at_most)
6340            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6341 
6342   // Argument 0 is checked for us and the remaining arguments must be
6343   // constant integers.
6344   for (unsigned i = 1; i != NumArgs; ++i)
6345     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6346       return true;
6347 
6348   return false;
6349 }
6350 
6351 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6352 // __assume does not evaluate its arguments, and should warn if its argument
6353 // has side effects.
6354 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6355   Expr *Arg = TheCall->getArg(0);
6356   if (Arg->isInstantiationDependent()) return false;
6357 
6358   if (Arg->HasSideEffects(Context))
6359     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6360         << Arg->getSourceRange()
6361         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6362 
6363   return false;
6364 }
6365 
6366 /// Handle __builtin_alloca_with_align. This is declared
6367 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6368 /// than 8.
6369 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6370   // The alignment must be a constant integer.
6371   Expr *Arg = TheCall->getArg(1);
6372 
6373   // We can't check the value of a dependent argument.
6374   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6375     if (const auto *UE =
6376             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6377       if (UE->getKind() == UETT_AlignOf ||
6378           UE->getKind() == UETT_PreferredAlignOf)
6379         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6380             << Arg->getSourceRange();
6381 
6382     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6383 
6384     if (!Result.isPowerOf2())
6385       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6386              << Arg->getSourceRange();
6387 
6388     if (Result < Context.getCharWidth())
6389       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6390              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6391 
6392     if (Result > std::numeric_limits<int32_t>::max())
6393       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6394              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6395   }
6396 
6397   return false;
6398 }
6399 
6400 /// Handle __builtin_assume_aligned. This is declared
6401 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6402 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6403   unsigned NumArgs = TheCall->getNumArgs();
6404 
6405   if (NumArgs > 3)
6406     return Diag(TheCall->getEndLoc(),
6407                 diag::err_typecheck_call_too_many_args_at_most)
6408            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6409 
6410   // The alignment must be a constant integer.
6411   Expr *Arg = TheCall->getArg(1);
6412 
6413   // We can't check the value of a dependent argument.
6414   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6415     llvm::APSInt Result;
6416     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6417       return true;
6418 
6419     if (!Result.isPowerOf2())
6420       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6421              << Arg->getSourceRange();
6422 
6423     if (Result > Sema::MaximumAlignment)
6424       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6425           << Arg->getSourceRange() << Sema::MaximumAlignment;
6426   }
6427 
6428   if (NumArgs > 2) {
6429     ExprResult Arg(TheCall->getArg(2));
6430     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6431       Context.getSizeType(), false);
6432     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6433     if (Arg.isInvalid()) return true;
6434     TheCall->setArg(2, Arg.get());
6435   }
6436 
6437   return false;
6438 }
6439 
6440 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6441   unsigned BuiltinID =
6442       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6443   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6444 
6445   unsigned NumArgs = TheCall->getNumArgs();
6446   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6447   if (NumArgs < NumRequiredArgs) {
6448     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6449            << 0 /* function call */ << NumRequiredArgs << NumArgs
6450            << TheCall->getSourceRange();
6451   }
6452   if (NumArgs >= NumRequiredArgs + 0x100) {
6453     return Diag(TheCall->getEndLoc(),
6454                 diag::err_typecheck_call_too_many_args_at_most)
6455            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6456            << TheCall->getSourceRange();
6457   }
6458   unsigned i = 0;
6459 
6460   // For formatting call, check buffer arg.
6461   if (!IsSizeCall) {
6462     ExprResult Arg(TheCall->getArg(i));
6463     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6464         Context, Context.VoidPtrTy, false);
6465     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6466     if (Arg.isInvalid())
6467       return true;
6468     TheCall->setArg(i, Arg.get());
6469     i++;
6470   }
6471 
6472   // Check string literal arg.
6473   unsigned FormatIdx = i;
6474   {
6475     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6476     if (Arg.isInvalid())
6477       return true;
6478     TheCall->setArg(i, Arg.get());
6479     i++;
6480   }
6481 
6482   // Make sure variadic args are scalar.
6483   unsigned FirstDataArg = i;
6484   while (i < NumArgs) {
6485     ExprResult Arg = DefaultVariadicArgumentPromotion(
6486         TheCall->getArg(i), VariadicFunction, nullptr);
6487     if (Arg.isInvalid())
6488       return true;
6489     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6490     if (ArgSize.getQuantity() >= 0x100) {
6491       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6492              << i << (int)ArgSize.getQuantity() << 0xff
6493              << TheCall->getSourceRange();
6494     }
6495     TheCall->setArg(i, Arg.get());
6496     i++;
6497   }
6498 
6499   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6500   // call to avoid duplicate diagnostics.
6501   if (!IsSizeCall) {
6502     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6503     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6504     bool Success = CheckFormatArguments(
6505         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6506         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6507         CheckedVarArgs);
6508     if (!Success)
6509       return true;
6510   }
6511 
6512   if (IsSizeCall) {
6513     TheCall->setType(Context.getSizeType());
6514   } else {
6515     TheCall->setType(Context.VoidPtrTy);
6516   }
6517   return false;
6518 }
6519 
6520 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6521 /// TheCall is a constant expression.
6522 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6523                                   llvm::APSInt &Result) {
6524   Expr *Arg = TheCall->getArg(ArgNum);
6525   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6526   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6527 
6528   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6529 
6530   Optional<llvm::APSInt> R;
6531   if (!(R = Arg->getIntegerConstantExpr(Context)))
6532     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6533            << FDecl->getDeclName() << Arg->getSourceRange();
6534   Result = *R;
6535   return false;
6536 }
6537 
6538 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6539 /// TheCall is a constant expression in the range [Low, High].
6540 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6541                                        int Low, int High, bool RangeIsError) {
6542   if (isConstantEvaluated())
6543     return false;
6544   llvm::APSInt Result;
6545 
6546   // We can't check the value of a dependent argument.
6547   Expr *Arg = TheCall->getArg(ArgNum);
6548   if (Arg->isTypeDependent() || Arg->isValueDependent())
6549     return false;
6550 
6551   // Check constant-ness first.
6552   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6553     return true;
6554 
6555   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6556     if (RangeIsError)
6557       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6558              << Result.toString(10) << Low << High << Arg->getSourceRange();
6559     else
6560       // Defer the warning until we know if the code will be emitted so that
6561       // dead code can ignore this.
6562       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6563                           PDiag(diag::warn_argument_invalid_range)
6564                               << Result.toString(10) << Low << High
6565                               << Arg->getSourceRange());
6566   }
6567 
6568   return false;
6569 }
6570 
6571 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6572 /// TheCall is a constant expression is a multiple of Num..
6573 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6574                                           unsigned Num) {
6575   llvm::APSInt Result;
6576 
6577   // We can't check the value of a dependent argument.
6578   Expr *Arg = TheCall->getArg(ArgNum);
6579   if (Arg->isTypeDependent() || Arg->isValueDependent())
6580     return false;
6581 
6582   // Check constant-ness first.
6583   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6584     return true;
6585 
6586   if (Result.getSExtValue() % Num != 0)
6587     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6588            << Num << Arg->getSourceRange();
6589 
6590   return false;
6591 }
6592 
6593 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6594 /// constant expression representing a power of 2.
6595 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6596   llvm::APSInt Result;
6597 
6598   // We can't check the value of a dependent argument.
6599   Expr *Arg = TheCall->getArg(ArgNum);
6600   if (Arg->isTypeDependent() || Arg->isValueDependent())
6601     return false;
6602 
6603   // Check constant-ness first.
6604   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6605     return true;
6606 
6607   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6608   // and only if x is a power of 2.
6609   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6610     return false;
6611 
6612   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6613          << Arg->getSourceRange();
6614 }
6615 
6616 static bool IsShiftedByte(llvm::APSInt Value) {
6617   if (Value.isNegative())
6618     return false;
6619 
6620   // Check if it's a shifted byte, by shifting it down
6621   while (true) {
6622     // If the value fits in the bottom byte, the check passes.
6623     if (Value < 0x100)
6624       return true;
6625 
6626     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6627     // fails.
6628     if ((Value & 0xFF) != 0)
6629       return false;
6630 
6631     // If the bottom 8 bits are all 0, but something above that is nonzero,
6632     // then shifting the value right by 8 bits won't affect whether it's a
6633     // shifted byte or not. So do that, and go round again.
6634     Value >>= 8;
6635   }
6636 }
6637 
6638 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6639 /// a constant expression representing an arbitrary byte value shifted left by
6640 /// a multiple of 8 bits.
6641 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6642                                              unsigned ArgBits) {
6643   llvm::APSInt Result;
6644 
6645   // We can't check the value of a dependent argument.
6646   Expr *Arg = TheCall->getArg(ArgNum);
6647   if (Arg->isTypeDependent() || Arg->isValueDependent())
6648     return false;
6649 
6650   // Check constant-ness first.
6651   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6652     return true;
6653 
6654   // Truncate to the given size.
6655   Result = Result.getLoBits(ArgBits);
6656   Result.setIsUnsigned(true);
6657 
6658   if (IsShiftedByte(Result))
6659     return false;
6660 
6661   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6662          << Arg->getSourceRange();
6663 }
6664 
6665 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6666 /// TheCall is a constant expression representing either a shifted byte value,
6667 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6668 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6669 /// Arm MVE intrinsics.
6670 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6671                                                    int ArgNum,
6672                                                    unsigned ArgBits) {
6673   llvm::APSInt Result;
6674 
6675   // We can't check the value of a dependent argument.
6676   Expr *Arg = TheCall->getArg(ArgNum);
6677   if (Arg->isTypeDependent() || Arg->isValueDependent())
6678     return false;
6679 
6680   // Check constant-ness first.
6681   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6682     return true;
6683 
6684   // Truncate to the given size.
6685   Result = Result.getLoBits(ArgBits);
6686   Result.setIsUnsigned(true);
6687 
6688   // Check to see if it's in either of the required forms.
6689   if (IsShiftedByte(Result) ||
6690       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6691     return false;
6692 
6693   return Diag(TheCall->getBeginLoc(),
6694               diag::err_argument_not_shifted_byte_or_xxff)
6695          << Arg->getSourceRange();
6696 }
6697 
6698 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6699 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6700   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6701     if (checkArgCount(*this, TheCall, 2))
6702       return true;
6703     Expr *Arg0 = TheCall->getArg(0);
6704     Expr *Arg1 = TheCall->getArg(1);
6705 
6706     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6707     if (FirstArg.isInvalid())
6708       return true;
6709     QualType FirstArgType = FirstArg.get()->getType();
6710     if (!FirstArgType->isAnyPointerType())
6711       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6712                << "first" << FirstArgType << Arg0->getSourceRange();
6713     TheCall->setArg(0, FirstArg.get());
6714 
6715     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6716     if (SecArg.isInvalid())
6717       return true;
6718     QualType SecArgType = SecArg.get()->getType();
6719     if (!SecArgType->isIntegerType())
6720       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6721                << "second" << SecArgType << Arg1->getSourceRange();
6722 
6723     // Derive the return type from the pointer argument.
6724     TheCall->setType(FirstArgType);
6725     return false;
6726   }
6727 
6728   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6729     if (checkArgCount(*this, TheCall, 2))
6730       return true;
6731 
6732     Expr *Arg0 = TheCall->getArg(0);
6733     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6734     if (FirstArg.isInvalid())
6735       return true;
6736     QualType FirstArgType = FirstArg.get()->getType();
6737     if (!FirstArgType->isAnyPointerType())
6738       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6739                << "first" << FirstArgType << Arg0->getSourceRange();
6740     TheCall->setArg(0, FirstArg.get());
6741 
6742     // Derive the return type from the pointer argument.
6743     TheCall->setType(FirstArgType);
6744 
6745     // Second arg must be an constant in range [0,15]
6746     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6747   }
6748 
6749   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6750     if (checkArgCount(*this, TheCall, 2))
6751       return true;
6752     Expr *Arg0 = TheCall->getArg(0);
6753     Expr *Arg1 = TheCall->getArg(1);
6754 
6755     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6756     if (FirstArg.isInvalid())
6757       return true;
6758     QualType FirstArgType = FirstArg.get()->getType();
6759     if (!FirstArgType->isAnyPointerType())
6760       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6761                << "first" << FirstArgType << Arg0->getSourceRange();
6762 
6763     QualType SecArgType = Arg1->getType();
6764     if (!SecArgType->isIntegerType())
6765       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6766                << "second" << SecArgType << Arg1->getSourceRange();
6767     TheCall->setType(Context.IntTy);
6768     return false;
6769   }
6770 
6771   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6772       BuiltinID == AArch64::BI__builtin_arm_stg) {
6773     if (checkArgCount(*this, TheCall, 1))
6774       return true;
6775     Expr *Arg0 = TheCall->getArg(0);
6776     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6777     if (FirstArg.isInvalid())
6778       return true;
6779 
6780     QualType FirstArgType = FirstArg.get()->getType();
6781     if (!FirstArgType->isAnyPointerType())
6782       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6783                << "first" << FirstArgType << Arg0->getSourceRange();
6784     TheCall->setArg(0, FirstArg.get());
6785 
6786     // Derive the return type from the pointer argument.
6787     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6788       TheCall->setType(FirstArgType);
6789     return false;
6790   }
6791 
6792   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6793     Expr *ArgA = TheCall->getArg(0);
6794     Expr *ArgB = TheCall->getArg(1);
6795 
6796     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6797     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6798 
6799     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6800       return true;
6801 
6802     QualType ArgTypeA = ArgExprA.get()->getType();
6803     QualType ArgTypeB = ArgExprB.get()->getType();
6804 
6805     auto isNull = [&] (Expr *E) -> bool {
6806       return E->isNullPointerConstant(
6807                         Context, Expr::NPC_ValueDependentIsNotNull); };
6808 
6809     // argument should be either a pointer or null
6810     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6811       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6812         << "first" << ArgTypeA << ArgA->getSourceRange();
6813 
6814     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6815       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6816         << "second" << ArgTypeB << ArgB->getSourceRange();
6817 
6818     // Ensure Pointee types are compatible
6819     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6820         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6821       QualType pointeeA = ArgTypeA->getPointeeType();
6822       QualType pointeeB = ArgTypeB->getPointeeType();
6823       if (!Context.typesAreCompatible(
6824              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6825              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6826         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6827           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6828           << ArgB->getSourceRange();
6829       }
6830     }
6831 
6832     // at least one argument should be pointer type
6833     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6834       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6835         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6836 
6837     if (isNull(ArgA)) // adopt type of the other pointer
6838       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6839 
6840     if (isNull(ArgB))
6841       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6842 
6843     TheCall->setArg(0, ArgExprA.get());
6844     TheCall->setArg(1, ArgExprB.get());
6845     TheCall->setType(Context.LongLongTy);
6846     return false;
6847   }
6848   assert(false && "Unhandled ARM MTE intrinsic");
6849   return true;
6850 }
6851 
6852 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6853 /// TheCall is an ARM/AArch64 special register string literal.
6854 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6855                                     int ArgNum, unsigned ExpectedFieldNum,
6856                                     bool AllowName) {
6857   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6858                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6859                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6860                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6861                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6862                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6863   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6864                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6865                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6866                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6867                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6868                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6869   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6870 
6871   // We can't check the value of a dependent argument.
6872   Expr *Arg = TheCall->getArg(ArgNum);
6873   if (Arg->isTypeDependent() || Arg->isValueDependent())
6874     return false;
6875 
6876   // Check if the argument is a string literal.
6877   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6878     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6879            << Arg->getSourceRange();
6880 
6881   // Check the type of special register given.
6882   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6883   SmallVector<StringRef, 6> Fields;
6884   Reg.split(Fields, ":");
6885 
6886   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6887     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6888            << Arg->getSourceRange();
6889 
6890   // If the string is the name of a register then we cannot check that it is
6891   // valid here but if the string is of one the forms described in ACLE then we
6892   // can check that the supplied fields are integers and within the valid
6893   // ranges.
6894   if (Fields.size() > 1) {
6895     bool FiveFields = Fields.size() == 5;
6896 
6897     bool ValidString = true;
6898     if (IsARMBuiltin) {
6899       ValidString &= Fields[0].startswith_lower("cp") ||
6900                      Fields[0].startswith_lower("p");
6901       if (ValidString)
6902         Fields[0] =
6903           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6904 
6905       ValidString &= Fields[2].startswith_lower("c");
6906       if (ValidString)
6907         Fields[2] = Fields[2].drop_front(1);
6908 
6909       if (FiveFields) {
6910         ValidString &= Fields[3].startswith_lower("c");
6911         if (ValidString)
6912           Fields[3] = Fields[3].drop_front(1);
6913       }
6914     }
6915 
6916     SmallVector<int, 5> Ranges;
6917     if (FiveFields)
6918       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6919     else
6920       Ranges.append({15, 7, 15});
6921 
6922     for (unsigned i=0; i<Fields.size(); ++i) {
6923       int IntField;
6924       ValidString &= !Fields[i].getAsInteger(10, IntField);
6925       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6926     }
6927 
6928     if (!ValidString)
6929       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6930              << Arg->getSourceRange();
6931   } else if (IsAArch64Builtin && Fields.size() == 1) {
6932     // If the register name is one of those that appear in the condition below
6933     // and the special register builtin being used is one of the write builtins,
6934     // then we require that the argument provided for writing to the register
6935     // is an integer constant expression. This is because it will be lowered to
6936     // an MSR (immediate) instruction, so we need to know the immediate at
6937     // compile time.
6938     if (TheCall->getNumArgs() != 2)
6939       return false;
6940 
6941     std::string RegLower = Reg.lower();
6942     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6943         RegLower != "pan" && RegLower != "uao")
6944       return false;
6945 
6946     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6947   }
6948 
6949   return false;
6950 }
6951 
6952 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6953 /// Emit an error and return true on failure; return false on success.
6954 /// TypeStr is a string containing the type descriptor of the value returned by
6955 /// the builtin and the descriptors of the expected type of the arguments.
6956 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6957 
6958   assert((TypeStr[0] != '\0') &&
6959          "Invalid types in PPC MMA builtin declaration");
6960 
6961   unsigned Mask = 0;
6962   unsigned ArgNum = 0;
6963 
6964   // The first type in TypeStr is the type of the value returned by the
6965   // builtin. So we first read that type and change the type of TheCall.
6966   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6967   TheCall->setType(type);
6968 
6969   while (*TypeStr != '\0') {
6970     Mask = 0;
6971     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6972     if (ArgNum >= TheCall->getNumArgs()) {
6973       ArgNum++;
6974       break;
6975     }
6976 
6977     Expr *Arg = TheCall->getArg(ArgNum);
6978     QualType ArgType = Arg->getType();
6979 
6980     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6981         (!ExpectedType->isVoidPointerType() &&
6982            ArgType.getCanonicalType() != ExpectedType))
6983       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6984              << ArgType << ExpectedType << 1 << 0 << 0;
6985 
6986     // If the value of the Mask is not 0, we have a constraint in the size of
6987     // the integer argument so here we ensure the argument is a constant that
6988     // is in the valid range.
6989     if (Mask != 0 &&
6990         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6991       return true;
6992 
6993     ArgNum++;
6994   }
6995 
6996   // In case we exited early from the previous loop, there are other types to
6997   // read from TypeStr. So we need to read them all to ensure we have the right
6998   // number of arguments in TheCall and if it is not the case, to display a
6999   // better error message.
7000   while (*TypeStr != '\0') {
7001     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7002     ArgNum++;
7003   }
7004   if (checkArgCount(*this, TheCall, ArgNum))
7005     return true;
7006 
7007   return false;
7008 }
7009 
7010 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7011 /// This checks that the target supports __builtin_longjmp and
7012 /// that val is a constant 1.
7013 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7014   if (!Context.getTargetInfo().hasSjLjLowering())
7015     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7016            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7017 
7018   Expr *Arg = TheCall->getArg(1);
7019   llvm::APSInt Result;
7020 
7021   // TODO: This is less than ideal. Overload this to take a value.
7022   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7023     return true;
7024 
7025   if (Result != 1)
7026     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7027            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7028 
7029   return false;
7030 }
7031 
7032 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7033 /// This checks that the target supports __builtin_setjmp.
7034 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7035   if (!Context.getTargetInfo().hasSjLjLowering())
7036     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7037            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7038   return false;
7039 }
7040 
7041 namespace {
7042 
7043 class UncoveredArgHandler {
7044   enum { Unknown = -1, AllCovered = -2 };
7045 
7046   signed FirstUncoveredArg = Unknown;
7047   SmallVector<const Expr *, 4> DiagnosticExprs;
7048 
7049 public:
7050   UncoveredArgHandler() = default;
7051 
7052   bool hasUncoveredArg() const {
7053     return (FirstUncoveredArg >= 0);
7054   }
7055 
7056   unsigned getUncoveredArg() const {
7057     assert(hasUncoveredArg() && "no uncovered argument");
7058     return FirstUncoveredArg;
7059   }
7060 
7061   void setAllCovered() {
7062     // A string has been found with all arguments covered, so clear out
7063     // the diagnostics.
7064     DiagnosticExprs.clear();
7065     FirstUncoveredArg = AllCovered;
7066   }
7067 
7068   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7069     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7070 
7071     // Don't update if a previous string covers all arguments.
7072     if (FirstUncoveredArg == AllCovered)
7073       return;
7074 
7075     // UncoveredArgHandler tracks the highest uncovered argument index
7076     // and with it all the strings that match this index.
7077     if (NewFirstUncoveredArg == FirstUncoveredArg)
7078       DiagnosticExprs.push_back(StrExpr);
7079     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7080       DiagnosticExprs.clear();
7081       DiagnosticExprs.push_back(StrExpr);
7082       FirstUncoveredArg = NewFirstUncoveredArg;
7083     }
7084   }
7085 
7086   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7087 };
7088 
7089 enum StringLiteralCheckType {
7090   SLCT_NotALiteral,
7091   SLCT_UncheckedLiteral,
7092   SLCT_CheckedLiteral
7093 };
7094 
7095 } // namespace
7096 
7097 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7098                                      BinaryOperatorKind BinOpKind,
7099                                      bool AddendIsRight) {
7100   unsigned BitWidth = Offset.getBitWidth();
7101   unsigned AddendBitWidth = Addend.getBitWidth();
7102   // There might be negative interim results.
7103   if (Addend.isUnsigned()) {
7104     Addend = Addend.zext(++AddendBitWidth);
7105     Addend.setIsSigned(true);
7106   }
7107   // Adjust the bit width of the APSInts.
7108   if (AddendBitWidth > BitWidth) {
7109     Offset = Offset.sext(AddendBitWidth);
7110     BitWidth = AddendBitWidth;
7111   } else if (BitWidth > AddendBitWidth) {
7112     Addend = Addend.sext(BitWidth);
7113   }
7114 
7115   bool Ov = false;
7116   llvm::APSInt ResOffset = Offset;
7117   if (BinOpKind == BO_Add)
7118     ResOffset = Offset.sadd_ov(Addend, Ov);
7119   else {
7120     assert(AddendIsRight && BinOpKind == BO_Sub &&
7121            "operator must be add or sub with addend on the right");
7122     ResOffset = Offset.ssub_ov(Addend, Ov);
7123   }
7124 
7125   // We add an offset to a pointer here so we should support an offset as big as
7126   // possible.
7127   if (Ov) {
7128     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7129            "index (intermediate) result too big");
7130     Offset = Offset.sext(2 * BitWidth);
7131     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7132     return;
7133   }
7134 
7135   Offset = ResOffset;
7136 }
7137 
7138 namespace {
7139 
7140 // This is a wrapper class around StringLiteral to support offsetted string
7141 // literals as format strings. It takes the offset into account when returning
7142 // the string and its length or the source locations to display notes correctly.
7143 class FormatStringLiteral {
7144   const StringLiteral *FExpr;
7145   int64_t Offset;
7146 
7147  public:
7148   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7149       : FExpr(fexpr), Offset(Offset) {}
7150 
7151   StringRef getString() const {
7152     return FExpr->getString().drop_front(Offset);
7153   }
7154 
7155   unsigned getByteLength() const {
7156     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7157   }
7158 
7159   unsigned getLength() const { return FExpr->getLength() - Offset; }
7160   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7161 
7162   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7163 
7164   QualType getType() const { return FExpr->getType(); }
7165 
7166   bool isAscii() const { return FExpr->isAscii(); }
7167   bool isWide() const { return FExpr->isWide(); }
7168   bool isUTF8() const { return FExpr->isUTF8(); }
7169   bool isUTF16() const { return FExpr->isUTF16(); }
7170   bool isUTF32() const { return FExpr->isUTF32(); }
7171   bool isPascal() const { return FExpr->isPascal(); }
7172 
7173   SourceLocation getLocationOfByte(
7174       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7175       const TargetInfo &Target, unsigned *StartToken = nullptr,
7176       unsigned *StartTokenByteOffset = nullptr) const {
7177     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7178                                     StartToken, StartTokenByteOffset);
7179   }
7180 
7181   SourceLocation getBeginLoc() const LLVM_READONLY {
7182     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7183   }
7184 
7185   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7186 };
7187 
7188 }  // namespace
7189 
7190 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7191                               const Expr *OrigFormatExpr,
7192                               ArrayRef<const Expr *> Args,
7193                               bool HasVAListArg, unsigned format_idx,
7194                               unsigned firstDataArg,
7195                               Sema::FormatStringType Type,
7196                               bool inFunctionCall,
7197                               Sema::VariadicCallType CallType,
7198                               llvm::SmallBitVector &CheckedVarArgs,
7199                               UncoveredArgHandler &UncoveredArg,
7200                               bool IgnoreStringsWithoutSpecifiers);
7201 
7202 // Determine if an expression is a string literal or constant string.
7203 // If this function returns false on the arguments to a function expecting a
7204 // format string, we will usually need to emit a warning.
7205 // True string literals are then checked by CheckFormatString.
7206 static StringLiteralCheckType
7207 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7208                       bool HasVAListArg, unsigned format_idx,
7209                       unsigned firstDataArg, Sema::FormatStringType Type,
7210                       Sema::VariadicCallType CallType, bool InFunctionCall,
7211                       llvm::SmallBitVector &CheckedVarArgs,
7212                       UncoveredArgHandler &UncoveredArg,
7213                       llvm::APSInt Offset,
7214                       bool IgnoreStringsWithoutSpecifiers = false) {
7215   if (S.isConstantEvaluated())
7216     return SLCT_NotALiteral;
7217  tryAgain:
7218   assert(Offset.isSigned() && "invalid offset");
7219 
7220   if (E->isTypeDependent() || E->isValueDependent())
7221     return SLCT_NotALiteral;
7222 
7223   E = E->IgnoreParenCasts();
7224 
7225   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7226     // Technically -Wformat-nonliteral does not warn about this case.
7227     // The behavior of printf and friends in this case is implementation
7228     // dependent.  Ideally if the format string cannot be null then
7229     // it should have a 'nonnull' attribute in the function prototype.
7230     return SLCT_UncheckedLiteral;
7231 
7232   switch (E->getStmtClass()) {
7233   case Stmt::BinaryConditionalOperatorClass:
7234   case Stmt::ConditionalOperatorClass: {
7235     // The expression is a literal if both sub-expressions were, and it was
7236     // completely checked only if both sub-expressions were checked.
7237     const AbstractConditionalOperator *C =
7238         cast<AbstractConditionalOperator>(E);
7239 
7240     // Determine whether it is necessary to check both sub-expressions, for
7241     // example, because the condition expression is a constant that can be
7242     // evaluated at compile time.
7243     bool CheckLeft = true, CheckRight = true;
7244 
7245     bool Cond;
7246     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7247                                                  S.isConstantEvaluated())) {
7248       if (Cond)
7249         CheckRight = false;
7250       else
7251         CheckLeft = false;
7252     }
7253 
7254     // We need to maintain the offsets for the right and the left hand side
7255     // separately to check if every possible indexed expression is a valid
7256     // string literal. They might have different offsets for different string
7257     // literals in the end.
7258     StringLiteralCheckType Left;
7259     if (!CheckLeft)
7260       Left = SLCT_UncheckedLiteral;
7261     else {
7262       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7263                                    HasVAListArg, format_idx, firstDataArg,
7264                                    Type, CallType, InFunctionCall,
7265                                    CheckedVarArgs, UncoveredArg, Offset,
7266                                    IgnoreStringsWithoutSpecifiers);
7267       if (Left == SLCT_NotALiteral || !CheckRight) {
7268         return Left;
7269       }
7270     }
7271 
7272     StringLiteralCheckType Right = checkFormatStringExpr(
7273         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7274         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7275         IgnoreStringsWithoutSpecifiers);
7276 
7277     return (CheckLeft && Left < Right) ? Left : Right;
7278   }
7279 
7280   case Stmt::ImplicitCastExprClass:
7281     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7282     goto tryAgain;
7283 
7284   case Stmt::OpaqueValueExprClass:
7285     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7286       E = src;
7287       goto tryAgain;
7288     }
7289     return SLCT_NotALiteral;
7290 
7291   case Stmt::PredefinedExprClass:
7292     // While __func__, etc., are technically not string literals, they
7293     // cannot contain format specifiers and thus are not a security
7294     // liability.
7295     return SLCT_UncheckedLiteral;
7296 
7297   case Stmt::DeclRefExprClass: {
7298     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7299 
7300     // As an exception, do not flag errors for variables binding to
7301     // const string literals.
7302     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7303       bool isConstant = false;
7304       QualType T = DR->getType();
7305 
7306       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7307         isConstant = AT->getElementType().isConstant(S.Context);
7308       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7309         isConstant = T.isConstant(S.Context) &&
7310                      PT->getPointeeType().isConstant(S.Context);
7311       } else if (T->isObjCObjectPointerType()) {
7312         // In ObjC, there is usually no "const ObjectPointer" type,
7313         // so don't check if the pointee type is constant.
7314         isConstant = T.isConstant(S.Context);
7315       }
7316 
7317       if (isConstant) {
7318         if (const Expr *Init = VD->getAnyInitializer()) {
7319           // Look through initializers like const char c[] = { "foo" }
7320           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7321             if (InitList->isStringLiteralInit())
7322               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7323           }
7324           return checkFormatStringExpr(S, Init, Args,
7325                                        HasVAListArg, format_idx,
7326                                        firstDataArg, Type, CallType,
7327                                        /*InFunctionCall*/ false, CheckedVarArgs,
7328                                        UncoveredArg, Offset);
7329         }
7330       }
7331 
7332       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7333       // special check to see if the format string is a function parameter
7334       // of the function calling the printf function.  If the function
7335       // has an attribute indicating it is a printf-like function, then we
7336       // should suppress warnings concerning non-literals being used in a call
7337       // to a vprintf function.  For example:
7338       //
7339       // void
7340       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7341       //      va_list ap;
7342       //      va_start(ap, fmt);
7343       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7344       //      ...
7345       // }
7346       if (HasVAListArg) {
7347         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7348           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7349             int PVIndex = PV->getFunctionScopeIndex() + 1;
7350             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7351               // adjust for implicit parameter
7352               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7353                 if (MD->isInstance())
7354                   ++PVIndex;
7355               // We also check if the formats are compatible.
7356               // We can't pass a 'scanf' string to a 'printf' function.
7357               if (PVIndex == PVFormat->getFormatIdx() &&
7358                   Type == S.GetFormatStringType(PVFormat))
7359                 return SLCT_UncheckedLiteral;
7360             }
7361           }
7362         }
7363       }
7364     }
7365 
7366     return SLCT_NotALiteral;
7367   }
7368 
7369   case Stmt::CallExprClass:
7370   case Stmt::CXXMemberCallExprClass: {
7371     const CallExpr *CE = cast<CallExpr>(E);
7372     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7373       bool IsFirst = true;
7374       StringLiteralCheckType CommonResult;
7375       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7376         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7377         StringLiteralCheckType Result = checkFormatStringExpr(
7378             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7379             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7380             IgnoreStringsWithoutSpecifiers);
7381         if (IsFirst) {
7382           CommonResult = Result;
7383           IsFirst = false;
7384         }
7385       }
7386       if (!IsFirst)
7387         return CommonResult;
7388 
7389       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7390         unsigned BuiltinID = FD->getBuiltinID();
7391         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7392             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7393           const Expr *Arg = CE->getArg(0);
7394           return checkFormatStringExpr(S, Arg, Args,
7395                                        HasVAListArg, format_idx,
7396                                        firstDataArg, Type, CallType,
7397                                        InFunctionCall, CheckedVarArgs,
7398                                        UncoveredArg, Offset,
7399                                        IgnoreStringsWithoutSpecifiers);
7400         }
7401       }
7402     }
7403 
7404     return SLCT_NotALiteral;
7405   }
7406   case Stmt::ObjCMessageExprClass: {
7407     const auto *ME = cast<ObjCMessageExpr>(E);
7408     if (const auto *MD = ME->getMethodDecl()) {
7409       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7410         // As a special case heuristic, if we're using the method -[NSBundle
7411         // localizedStringForKey:value:table:], ignore any key strings that lack
7412         // format specifiers. The idea is that if the key doesn't have any
7413         // format specifiers then its probably just a key to map to the
7414         // localized strings. If it does have format specifiers though, then its
7415         // likely that the text of the key is the format string in the
7416         // programmer's language, and should be checked.
7417         const ObjCInterfaceDecl *IFace;
7418         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7419             IFace->getIdentifier()->isStr("NSBundle") &&
7420             MD->getSelector().isKeywordSelector(
7421                 {"localizedStringForKey", "value", "table"})) {
7422           IgnoreStringsWithoutSpecifiers = true;
7423         }
7424 
7425         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7426         return checkFormatStringExpr(
7427             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7428             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7429             IgnoreStringsWithoutSpecifiers);
7430       }
7431     }
7432 
7433     return SLCT_NotALiteral;
7434   }
7435   case Stmt::ObjCStringLiteralClass:
7436   case Stmt::StringLiteralClass: {
7437     const StringLiteral *StrE = nullptr;
7438 
7439     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7440       StrE = ObjCFExpr->getString();
7441     else
7442       StrE = cast<StringLiteral>(E);
7443 
7444     if (StrE) {
7445       if (Offset.isNegative() || Offset > StrE->getLength()) {
7446         // TODO: It would be better to have an explicit warning for out of
7447         // bounds literals.
7448         return SLCT_NotALiteral;
7449       }
7450       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7451       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7452                         firstDataArg, Type, InFunctionCall, CallType,
7453                         CheckedVarArgs, UncoveredArg,
7454                         IgnoreStringsWithoutSpecifiers);
7455       return SLCT_CheckedLiteral;
7456     }
7457 
7458     return SLCT_NotALiteral;
7459   }
7460   case Stmt::BinaryOperatorClass: {
7461     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7462 
7463     // A string literal + an int offset is still a string literal.
7464     if (BinOp->isAdditiveOp()) {
7465       Expr::EvalResult LResult, RResult;
7466 
7467       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7468           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7469       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7470           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7471 
7472       if (LIsInt != RIsInt) {
7473         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7474 
7475         if (LIsInt) {
7476           if (BinOpKind == BO_Add) {
7477             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7478             E = BinOp->getRHS();
7479             goto tryAgain;
7480           }
7481         } else {
7482           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7483           E = BinOp->getLHS();
7484           goto tryAgain;
7485         }
7486       }
7487     }
7488 
7489     return SLCT_NotALiteral;
7490   }
7491   case Stmt::UnaryOperatorClass: {
7492     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7493     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7494     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7495       Expr::EvalResult IndexResult;
7496       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7497                                        Expr::SE_NoSideEffects,
7498                                        S.isConstantEvaluated())) {
7499         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7500                    /*RHS is int*/ true);
7501         E = ASE->getBase();
7502         goto tryAgain;
7503       }
7504     }
7505 
7506     return SLCT_NotALiteral;
7507   }
7508 
7509   default:
7510     return SLCT_NotALiteral;
7511   }
7512 }
7513 
7514 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7515   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7516       .Case("scanf", FST_Scanf)
7517       .Cases("printf", "printf0", FST_Printf)
7518       .Cases("NSString", "CFString", FST_NSString)
7519       .Case("strftime", FST_Strftime)
7520       .Case("strfmon", FST_Strfmon)
7521       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7522       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7523       .Case("os_trace", FST_OSLog)
7524       .Case("os_log", FST_OSLog)
7525       .Default(FST_Unknown);
7526 }
7527 
7528 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7529 /// functions) for correct use of format strings.
7530 /// Returns true if a format string has been fully checked.
7531 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7532                                 ArrayRef<const Expr *> Args,
7533                                 bool IsCXXMember,
7534                                 VariadicCallType CallType,
7535                                 SourceLocation Loc, SourceRange Range,
7536                                 llvm::SmallBitVector &CheckedVarArgs) {
7537   FormatStringInfo FSI;
7538   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7539     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7540                                 FSI.FirstDataArg, GetFormatStringType(Format),
7541                                 CallType, Loc, Range, CheckedVarArgs);
7542   return false;
7543 }
7544 
7545 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7546                                 bool HasVAListArg, unsigned format_idx,
7547                                 unsigned firstDataArg, FormatStringType Type,
7548                                 VariadicCallType CallType,
7549                                 SourceLocation Loc, SourceRange Range,
7550                                 llvm::SmallBitVector &CheckedVarArgs) {
7551   // CHECK: printf/scanf-like function is called with no format string.
7552   if (format_idx >= Args.size()) {
7553     Diag(Loc, diag::warn_missing_format_string) << Range;
7554     return false;
7555   }
7556 
7557   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7558 
7559   // CHECK: format string is not a string literal.
7560   //
7561   // Dynamically generated format strings are difficult to
7562   // automatically vet at compile time.  Requiring that format strings
7563   // are string literals: (1) permits the checking of format strings by
7564   // the compiler and thereby (2) can practically remove the source of
7565   // many format string exploits.
7566 
7567   // Format string can be either ObjC string (e.g. @"%d") or
7568   // C string (e.g. "%d")
7569   // ObjC string uses the same format specifiers as C string, so we can use
7570   // the same format string checking logic for both ObjC and C strings.
7571   UncoveredArgHandler UncoveredArg;
7572   StringLiteralCheckType CT =
7573       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7574                             format_idx, firstDataArg, Type, CallType,
7575                             /*IsFunctionCall*/ true, CheckedVarArgs,
7576                             UncoveredArg,
7577                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7578 
7579   // Generate a diagnostic where an uncovered argument is detected.
7580   if (UncoveredArg.hasUncoveredArg()) {
7581     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7582     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7583     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7584   }
7585 
7586   if (CT != SLCT_NotALiteral)
7587     // Literal format string found, check done!
7588     return CT == SLCT_CheckedLiteral;
7589 
7590   // Strftime is particular as it always uses a single 'time' argument,
7591   // so it is safe to pass a non-literal string.
7592   if (Type == FST_Strftime)
7593     return false;
7594 
7595   // Do not emit diag when the string param is a macro expansion and the
7596   // format is either NSString or CFString. This is a hack to prevent
7597   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7598   // which are usually used in place of NS and CF string literals.
7599   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7600   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7601     return false;
7602 
7603   // If there are no arguments specified, warn with -Wformat-security, otherwise
7604   // warn only with -Wformat-nonliteral.
7605   if (Args.size() == firstDataArg) {
7606     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7607       << OrigFormatExpr->getSourceRange();
7608     switch (Type) {
7609     default:
7610       break;
7611     case FST_Kprintf:
7612     case FST_FreeBSDKPrintf:
7613     case FST_Printf:
7614       Diag(FormatLoc, diag::note_format_security_fixit)
7615         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7616       break;
7617     case FST_NSString:
7618       Diag(FormatLoc, diag::note_format_security_fixit)
7619         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7620       break;
7621     }
7622   } else {
7623     Diag(FormatLoc, diag::warn_format_nonliteral)
7624       << OrigFormatExpr->getSourceRange();
7625   }
7626   return false;
7627 }
7628 
7629 namespace {
7630 
7631 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7632 protected:
7633   Sema &S;
7634   const FormatStringLiteral *FExpr;
7635   const Expr *OrigFormatExpr;
7636   const Sema::FormatStringType FSType;
7637   const unsigned FirstDataArg;
7638   const unsigned NumDataArgs;
7639   const char *Beg; // Start of format string.
7640   const bool HasVAListArg;
7641   ArrayRef<const Expr *> Args;
7642   unsigned FormatIdx;
7643   llvm::SmallBitVector CoveredArgs;
7644   bool usesPositionalArgs = false;
7645   bool atFirstArg = true;
7646   bool inFunctionCall;
7647   Sema::VariadicCallType CallType;
7648   llvm::SmallBitVector &CheckedVarArgs;
7649   UncoveredArgHandler &UncoveredArg;
7650 
7651 public:
7652   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7653                      const Expr *origFormatExpr,
7654                      const Sema::FormatStringType type, unsigned firstDataArg,
7655                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7656                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7657                      bool inFunctionCall, Sema::VariadicCallType callType,
7658                      llvm::SmallBitVector &CheckedVarArgs,
7659                      UncoveredArgHandler &UncoveredArg)
7660       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7661         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7662         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7663         inFunctionCall(inFunctionCall), CallType(callType),
7664         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7665     CoveredArgs.resize(numDataArgs);
7666     CoveredArgs.reset();
7667   }
7668 
7669   void DoneProcessing();
7670 
7671   void HandleIncompleteSpecifier(const char *startSpecifier,
7672                                  unsigned specifierLen) override;
7673 
7674   void HandleInvalidLengthModifier(
7675                            const analyze_format_string::FormatSpecifier &FS,
7676                            const analyze_format_string::ConversionSpecifier &CS,
7677                            const char *startSpecifier, unsigned specifierLen,
7678                            unsigned DiagID);
7679 
7680   void HandleNonStandardLengthModifier(
7681                     const analyze_format_string::FormatSpecifier &FS,
7682                     const char *startSpecifier, unsigned specifierLen);
7683 
7684   void HandleNonStandardConversionSpecifier(
7685                     const analyze_format_string::ConversionSpecifier &CS,
7686                     const char *startSpecifier, unsigned specifierLen);
7687 
7688   void HandlePosition(const char *startPos, unsigned posLen) override;
7689 
7690   void HandleInvalidPosition(const char *startSpecifier,
7691                              unsigned specifierLen,
7692                              analyze_format_string::PositionContext p) override;
7693 
7694   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7695 
7696   void HandleNullChar(const char *nullCharacter) override;
7697 
7698   template <typename Range>
7699   static void
7700   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7701                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7702                        bool IsStringLocation, Range StringRange,
7703                        ArrayRef<FixItHint> Fixit = None);
7704 
7705 protected:
7706   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7707                                         const char *startSpec,
7708                                         unsigned specifierLen,
7709                                         const char *csStart, unsigned csLen);
7710 
7711   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7712                                          const char *startSpec,
7713                                          unsigned specifierLen);
7714 
7715   SourceRange getFormatStringRange();
7716   CharSourceRange getSpecifierRange(const char *startSpecifier,
7717                                     unsigned specifierLen);
7718   SourceLocation getLocationOfByte(const char *x);
7719 
7720   const Expr *getDataArg(unsigned i) const;
7721 
7722   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7723                     const analyze_format_string::ConversionSpecifier &CS,
7724                     const char *startSpecifier, unsigned specifierLen,
7725                     unsigned argIndex);
7726 
7727   template <typename Range>
7728   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7729                             bool IsStringLocation, Range StringRange,
7730                             ArrayRef<FixItHint> Fixit = None);
7731 };
7732 
7733 } // namespace
7734 
7735 SourceRange CheckFormatHandler::getFormatStringRange() {
7736   return OrigFormatExpr->getSourceRange();
7737 }
7738 
7739 CharSourceRange CheckFormatHandler::
7740 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7741   SourceLocation Start = getLocationOfByte(startSpecifier);
7742   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7743 
7744   // Advance the end SourceLocation by one due to half-open ranges.
7745   End = End.getLocWithOffset(1);
7746 
7747   return CharSourceRange::getCharRange(Start, End);
7748 }
7749 
7750 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7751   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7752                                   S.getLangOpts(), S.Context.getTargetInfo());
7753 }
7754 
7755 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7756                                                    unsigned specifierLen){
7757   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7758                        getLocationOfByte(startSpecifier),
7759                        /*IsStringLocation*/true,
7760                        getSpecifierRange(startSpecifier, specifierLen));
7761 }
7762 
7763 void CheckFormatHandler::HandleInvalidLengthModifier(
7764     const analyze_format_string::FormatSpecifier &FS,
7765     const analyze_format_string::ConversionSpecifier &CS,
7766     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7767   using namespace analyze_format_string;
7768 
7769   const LengthModifier &LM = FS.getLengthModifier();
7770   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7771 
7772   // See if we know how to fix this length modifier.
7773   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7774   if (FixedLM) {
7775     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7776                          getLocationOfByte(LM.getStart()),
7777                          /*IsStringLocation*/true,
7778                          getSpecifierRange(startSpecifier, specifierLen));
7779 
7780     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7781       << FixedLM->toString()
7782       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7783 
7784   } else {
7785     FixItHint Hint;
7786     if (DiagID == diag::warn_format_nonsensical_length)
7787       Hint = FixItHint::CreateRemoval(LMRange);
7788 
7789     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7790                          getLocationOfByte(LM.getStart()),
7791                          /*IsStringLocation*/true,
7792                          getSpecifierRange(startSpecifier, specifierLen),
7793                          Hint);
7794   }
7795 }
7796 
7797 void CheckFormatHandler::HandleNonStandardLengthModifier(
7798     const analyze_format_string::FormatSpecifier &FS,
7799     const char *startSpecifier, unsigned specifierLen) {
7800   using namespace analyze_format_string;
7801 
7802   const LengthModifier &LM = FS.getLengthModifier();
7803   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7804 
7805   // See if we know how to fix this length modifier.
7806   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7807   if (FixedLM) {
7808     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7809                            << LM.toString() << 0,
7810                          getLocationOfByte(LM.getStart()),
7811                          /*IsStringLocation*/true,
7812                          getSpecifierRange(startSpecifier, specifierLen));
7813 
7814     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7815       << FixedLM->toString()
7816       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7817 
7818   } else {
7819     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7820                            << LM.toString() << 0,
7821                          getLocationOfByte(LM.getStart()),
7822                          /*IsStringLocation*/true,
7823                          getSpecifierRange(startSpecifier, specifierLen));
7824   }
7825 }
7826 
7827 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7828     const analyze_format_string::ConversionSpecifier &CS,
7829     const char *startSpecifier, unsigned specifierLen) {
7830   using namespace analyze_format_string;
7831 
7832   // See if we know how to fix this conversion specifier.
7833   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7834   if (FixedCS) {
7835     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7836                           << CS.toString() << /*conversion specifier*/1,
7837                          getLocationOfByte(CS.getStart()),
7838                          /*IsStringLocation*/true,
7839                          getSpecifierRange(startSpecifier, specifierLen));
7840 
7841     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7842     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7843       << FixedCS->toString()
7844       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7845   } else {
7846     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7847                           << CS.toString() << /*conversion specifier*/1,
7848                          getLocationOfByte(CS.getStart()),
7849                          /*IsStringLocation*/true,
7850                          getSpecifierRange(startSpecifier, specifierLen));
7851   }
7852 }
7853 
7854 void CheckFormatHandler::HandlePosition(const char *startPos,
7855                                         unsigned posLen) {
7856   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7857                                getLocationOfByte(startPos),
7858                                /*IsStringLocation*/true,
7859                                getSpecifierRange(startPos, posLen));
7860 }
7861 
7862 void
7863 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7864                                      analyze_format_string::PositionContext p) {
7865   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7866                          << (unsigned) p,
7867                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7868                        getSpecifierRange(startPos, posLen));
7869 }
7870 
7871 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7872                                             unsigned posLen) {
7873   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7874                                getLocationOfByte(startPos),
7875                                /*IsStringLocation*/true,
7876                                getSpecifierRange(startPos, posLen));
7877 }
7878 
7879 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7880   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7881     // The presence of a null character is likely an error.
7882     EmitFormatDiagnostic(
7883       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7884       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7885       getFormatStringRange());
7886   }
7887 }
7888 
7889 // Note that this may return NULL if there was an error parsing or building
7890 // one of the argument expressions.
7891 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7892   return Args[FirstDataArg + i];
7893 }
7894 
7895 void CheckFormatHandler::DoneProcessing() {
7896   // Does the number of data arguments exceed the number of
7897   // format conversions in the format string?
7898   if (!HasVAListArg) {
7899       // Find any arguments that weren't covered.
7900     CoveredArgs.flip();
7901     signed notCoveredArg = CoveredArgs.find_first();
7902     if (notCoveredArg >= 0) {
7903       assert((unsigned)notCoveredArg < NumDataArgs);
7904       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7905     } else {
7906       UncoveredArg.setAllCovered();
7907     }
7908   }
7909 }
7910 
7911 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7912                                    const Expr *ArgExpr) {
7913   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7914          "Invalid state");
7915 
7916   if (!ArgExpr)
7917     return;
7918 
7919   SourceLocation Loc = ArgExpr->getBeginLoc();
7920 
7921   if (S.getSourceManager().isInSystemMacro(Loc))
7922     return;
7923 
7924   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7925   for (auto E : DiagnosticExprs)
7926     PDiag << E->getSourceRange();
7927 
7928   CheckFormatHandler::EmitFormatDiagnostic(
7929                                   S, IsFunctionCall, DiagnosticExprs[0],
7930                                   PDiag, Loc, /*IsStringLocation*/false,
7931                                   DiagnosticExprs[0]->getSourceRange());
7932 }
7933 
7934 bool
7935 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7936                                                      SourceLocation Loc,
7937                                                      const char *startSpec,
7938                                                      unsigned specifierLen,
7939                                                      const char *csStart,
7940                                                      unsigned csLen) {
7941   bool keepGoing = true;
7942   if (argIndex < NumDataArgs) {
7943     // Consider the argument coverered, even though the specifier doesn't
7944     // make sense.
7945     CoveredArgs.set(argIndex);
7946   }
7947   else {
7948     // If argIndex exceeds the number of data arguments we
7949     // don't issue a warning because that is just a cascade of warnings (and
7950     // they may have intended '%%' anyway). We don't want to continue processing
7951     // the format string after this point, however, as we will like just get
7952     // gibberish when trying to match arguments.
7953     keepGoing = false;
7954   }
7955 
7956   StringRef Specifier(csStart, csLen);
7957 
7958   // If the specifier in non-printable, it could be the first byte of a UTF-8
7959   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7960   // hex value.
7961   std::string CodePointStr;
7962   if (!llvm::sys::locale::isPrint(*csStart)) {
7963     llvm::UTF32 CodePoint;
7964     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7965     const llvm::UTF8 *E =
7966         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7967     llvm::ConversionResult Result =
7968         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7969 
7970     if (Result != llvm::conversionOK) {
7971       unsigned char FirstChar = *csStart;
7972       CodePoint = (llvm::UTF32)FirstChar;
7973     }
7974 
7975     llvm::raw_string_ostream OS(CodePointStr);
7976     if (CodePoint < 256)
7977       OS << "\\x" << llvm::format("%02x", CodePoint);
7978     else if (CodePoint <= 0xFFFF)
7979       OS << "\\u" << llvm::format("%04x", CodePoint);
7980     else
7981       OS << "\\U" << llvm::format("%08x", CodePoint);
7982     OS.flush();
7983     Specifier = CodePointStr;
7984   }
7985 
7986   EmitFormatDiagnostic(
7987       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7988       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7989 
7990   return keepGoing;
7991 }
7992 
7993 void
7994 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7995                                                       const char *startSpec,
7996                                                       unsigned specifierLen) {
7997   EmitFormatDiagnostic(
7998     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7999     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8000 }
8001 
8002 bool
8003 CheckFormatHandler::CheckNumArgs(
8004   const analyze_format_string::FormatSpecifier &FS,
8005   const analyze_format_string::ConversionSpecifier &CS,
8006   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8007 
8008   if (argIndex >= NumDataArgs) {
8009     PartialDiagnostic PDiag = FS.usesPositionalArg()
8010       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8011            << (argIndex+1) << NumDataArgs)
8012       : S.PDiag(diag::warn_printf_insufficient_data_args);
8013     EmitFormatDiagnostic(
8014       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8015       getSpecifierRange(startSpecifier, specifierLen));
8016 
8017     // Since more arguments than conversion tokens are given, by extension
8018     // all arguments are covered, so mark this as so.
8019     UncoveredArg.setAllCovered();
8020     return false;
8021   }
8022   return true;
8023 }
8024 
8025 template<typename Range>
8026 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8027                                               SourceLocation Loc,
8028                                               bool IsStringLocation,
8029                                               Range StringRange,
8030                                               ArrayRef<FixItHint> FixIt) {
8031   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8032                        Loc, IsStringLocation, StringRange, FixIt);
8033 }
8034 
8035 /// If the format string is not within the function call, emit a note
8036 /// so that the function call and string are in diagnostic messages.
8037 ///
8038 /// \param InFunctionCall if true, the format string is within the function
8039 /// call and only one diagnostic message will be produced.  Otherwise, an
8040 /// extra note will be emitted pointing to location of the format string.
8041 ///
8042 /// \param ArgumentExpr the expression that is passed as the format string
8043 /// argument in the function call.  Used for getting locations when two
8044 /// diagnostics are emitted.
8045 ///
8046 /// \param PDiag the callee should already have provided any strings for the
8047 /// diagnostic message.  This function only adds locations and fixits
8048 /// to diagnostics.
8049 ///
8050 /// \param Loc primary location for diagnostic.  If two diagnostics are
8051 /// required, one will be at Loc and a new SourceLocation will be created for
8052 /// the other one.
8053 ///
8054 /// \param IsStringLocation if true, Loc points to the format string should be
8055 /// used for the note.  Otherwise, Loc points to the argument list and will
8056 /// be used with PDiag.
8057 ///
8058 /// \param StringRange some or all of the string to highlight.  This is
8059 /// templated so it can accept either a CharSourceRange or a SourceRange.
8060 ///
8061 /// \param FixIt optional fix it hint for the format string.
8062 template <typename Range>
8063 void CheckFormatHandler::EmitFormatDiagnostic(
8064     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8065     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8066     Range StringRange, ArrayRef<FixItHint> FixIt) {
8067   if (InFunctionCall) {
8068     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8069     D << StringRange;
8070     D << FixIt;
8071   } else {
8072     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8073       << ArgumentExpr->getSourceRange();
8074 
8075     const Sema::SemaDiagnosticBuilder &Note =
8076       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8077              diag::note_format_string_defined);
8078 
8079     Note << StringRange;
8080     Note << FixIt;
8081   }
8082 }
8083 
8084 //===--- CHECK: Printf format string checking ------------------------------===//
8085 
8086 namespace {
8087 
8088 class CheckPrintfHandler : public CheckFormatHandler {
8089 public:
8090   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8091                      const Expr *origFormatExpr,
8092                      const Sema::FormatStringType type, unsigned firstDataArg,
8093                      unsigned numDataArgs, bool isObjC, const char *beg,
8094                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8095                      unsigned formatIdx, bool inFunctionCall,
8096                      Sema::VariadicCallType CallType,
8097                      llvm::SmallBitVector &CheckedVarArgs,
8098                      UncoveredArgHandler &UncoveredArg)
8099       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8100                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8101                            inFunctionCall, CallType, CheckedVarArgs,
8102                            UncoveredArg) {}
8103 
8104   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8105 
8106   /// Returns true if '%@' specifiers are allowed in the format string.
8107   bool allowsObjCArg() const {
8108     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8109            FSType == Sema::FST_OSTrace;
8110   }
8111 
8112   bool HandleInvalidPrintfConversionSpecifier(
8113                                       const analyze_printf::PrintfSpecifier &FS,
8114                                       const char *startSpecifier,
8115                                       unsigned specifierLen) override;
8116 
8117   void handleInvalidMaskType(StringRef MaskType) override;
8118 
8119   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8120                              const char *startSpecifier,
8121                              unsigned specifierLen) override;
8122   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8123                        const char *StartSpecifier,
8124                        unsigned SpecifierLen,
8125                        const Expr *E);
8126 
8127   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8128                     const char *startSpecifier, unsigned specifierLen);
8129   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8130                            const analyze_printf::OptionalAmount &Amt,
8131                            unsigned type,
8132                            const char *startSpecifier, unsigned specifierLen);
8133   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8134                   const analyze_printf::OptionalFlag &flag,
8135                   const char *startSpecifier, unsigned specifierLen);
8136   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8137                          const analyze_printf::OptionalFlag &ignoredFlag,
8138                          const analyze_printf::OptionalFlag &flag,
8139                          const char *startSpecifier, unsigned specifierLen);
8140   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8141                            const Expr *E);
8142 
8143   void HandleEmptyObjCModifierFlag(const char *startFlag,
8144                                    unsigned flagLen) override;
8145 
8146   void HandleInvalidObjCModifierFlag(const char *startFlag,
8147                                             unsigned flagLen) override;
8148 
8149   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8150                                            const char *flagsEnd,
8151                                            const char *conversionPosition)
8152                                              override;
8153 };
8154 
8155 } // namespace
8156 
8157 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8158                                       const analyze_printf::PrintfSpecifier &FS,
8159                                       const char *startSpecifier,
8160                                       unsigned specifierLen) {
8161   const analyze_printf::PrintfConversionSpecifier &CS =
8162     FS.getConversionSpecifier();
8163 
8164   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8165                                           getLocationOfByte(CS.getStart()),
8166                                           startSpecifier, specifierLen,
8167                                           CS.getStart(), CS.getLength());
8168 }
8169 
8170 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8171   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8172 }
8173 
8174 bool CheckPrintfHandler::HandleAmount(
8175                                const analyze_format_string::OptionalAmount &Amt,
8176                                unsigned k, const char *startSpecifier,
8177                                unsigned specifierLen) {
8178   if (Amt.hasDataArgument()) {
8179     if (!HasVAListArg) {
8180       unsigned argIndex = Amt.getArgIndex();
8181       if (argIndex >= NumDataArgs) {
8182         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8183                                << k,
8184                              getLocationOfByte(Amt.getStart()),
8185                              /*IsStringLocation*/true,
8186                              getSpecifierRange(startSpecifier, specifierLen));
8187         // Don't do any more checking.  We will just emit
8188         // spurious errors.
8189         return false;
8190       }
8191 
8192       // Type check the data argument.  It should be an 'int'.
8193       // Although not in conformance with C99, we also allow the argument to be
8194       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8195       // doesn't emit a warning for that case.
8196       CoveredArgs.set(argIndex);
8197       const Expr *Arg = getDataArg(argIndex);
8198       if (!Arg)
8199         return false;
8200 
8201       QualType T = Arg->getType();
8202 
8203       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8204       assert(AT.isValid());
8205 
8206       if (!AT.matchesType(S.Context, T)) {
8207         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8208                                << k << AT.getRepresentativeTypeName(S.Context)
8209                                << T << Arg->getSourceRange(),
8210                              getLocationOfByte(Amt.getStart()),
8211                              /*IsStringLocation*/true,
8212                              getSpecifierRange(startSpecifier, specifierLen));
8213         // Don't do any more checking.  We will just emit
8214         // spurious errors.
8215         return false;
8216       }
8217     }
8218   }
8219   return true;
8220 }
8221 
8222 void CheckPrintfHandler::HandleInvalidAmount(
8223                                       const analyze_printf::PrintfSpecifier &FS,
8224                                       const analyze_printf::OptionalAmount &Amt,
8225                                       unsigned type,
8226                                       const char *startSpecifier,
8227                                       unsigned specifierLen) {
8228   const analyze_printf::PrintfConversionSpecifier &CS =
8229     FS.getConversionSpecifier();
8230 
8231   FixItHint fixit =
8232     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8233       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8234                                  Amt.getConstantLength()))
8235       : FixItHint();
8236 
8237   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8238                          << type << CS.toString(),
8239                        getLocationOfByte(Amt.getStart()),
8240                        /*IsStringLocation*/true,
8241                        getSpecifierRange(startSpecifier, specifierLen),
8242                        fixit);
8243 }
8244 
8245 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8246                                     const analyze_printf::OptionalFlag &flag,
8247                                     const char *startSpecifier,
8248                                     unsigned specifierLen) {
8249   // Warn about pointless flag with a fixit removal.
8250   const analyze_printf::PrintfConversionSpecifier &CS =
8251     FS.getConversionSpecifier();
8252   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8253                          << flag.toString() << CS.toString(),
8254                        getLocationOfByte(flag.getPosition()),
8255                        /*IsStringLocation*/true,
8256                        getSpecifierRange(startSpecifier, specifierLen),
8257                        FixItHint::CreateRemoval(
8258                          getSpecifierRange(flag.getPosition(), 1)));
8259 }
8260 
8261 void CheckPrintfHandler::HandleIgnoredFlag(
8262                                 const analyze_printf::PrintfSpecifier &FS,
8263                                 const analyze_printf::OptionalFlag &ignoredFlag,
8264                                 const analyze_printf::OptionalFlag &flag,
8265                                 const char *startSpecifier,
8266                                 unsigned specifierLen) {
8267   // Warn about ignored flag with a fixit removal.
8268   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8269                          << ignoredFlag.toString() << flag.toString(),
8270                        getLocationOfByte(ignoredFlag.getPosition()),
8271                        /*IsStringLocation*/true,
8272                        getSpecifierRange(startSpecifier, specifierLen),
8273                        FixItHint::CreateRemoval(
8274                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8275 }
8276 
8277 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8278                                                      unsigned flagLen) {
8279   // Warn about an empty flag.
8280   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8281                        getLocationOfByte(startFlag),
8282                        /*IsStringLocation*/true,
8283                        getSpecifierRange(startFlag, flagLen));
8284 }
8285 
8286 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8287                                                        unsigned flagLen) {
8288   // Warn about an invalid flag.
8289   auto Range = getSpecifierRange(startFlag, flagLen);
8290   StringRef flag(startFlag, flagLen);
8291   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8292                       getLocationOfByte(startFlag),
8293                       /*IsStringLocation*/true,
8294                       Range, FixItHint::CreateRemoval(Range));
8295 }
8296 
8297 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8298     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8299     // Warn about using '[...]' without a '@' conversion.
8300     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8301     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8302     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8303                          getLocationOfByte(conversionPosition),
8304                          /*IsStringLocation*/true,
8305                          Range, FixItHint::CreateRemoval(Range));
8306 }
8307 
8308 // Determines if the specified is a C++ class or struct containing
8309 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8310 // "c_str()").
8311 template<typename MemberKind>
8312 static llvm::SmallPtrSet<MemberKind*, 1>
8313 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8314   const RecordType *RT = Ty->getAs<RecordType>();
8315   llvm::SmallPtrSet<MemberKind*, 1> Results;
8316 
8317   if (!RT)
8318     return Results;
8319   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8320   if (!RD || !RD->getDefinition())
8321     return Results;
8322 
8323   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8324                  Sema::LookupMemberName);
8325   R.suppressDiagnostics();
8326 
8327   // We just need to include all members of the right kind turned up by the
8328   // filter, at this point.
8329   if (S.LookupQualifiedName(R, RT->getDecl()))
8330     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8331       NamedDecl *decl = (*I)->getUnderlyingDecl();
8332       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8333         Results.insert(FK);
8334     }
8335   return Results;
8336 }
8337 
8338 /// Check if we could call '.c_str()' on an object.
8339 ///
8340 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8341 /// allow the call, or if it would be ambiguous).
8342 bool Sema::hasCStrMethod(const Expr *E) {
8343   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8344 
8345   MethodSet Results =
8346       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8347   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8348        MI != ME; ++MI)
8349     if ((*MI)->getMinRequiredArguments() == 0)
8350       return true;
8351   return false;
8352 }
8353 
8354 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8355 // better diagnostic if so. AT is assumed to be valid.
8356 // Returns true when a c_str() conversion method is found.
8357 bool CheckPrintfHandler::checkForCStrMembers(
8358     const analyze_printf::ArgType &AT, const Expr *E) {
8359   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8360 
8361   MethodSet Results =
8362       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8363 
8364   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8365        MI != ME; ++MI) {
8366     const CXXMethodDecl *Method = *MI;
8367     if (Method->getMinRequiredArguments() == 0 &&
8368         AT.matchesType(S.Context, Method->getReturnType())) {
8369       // FIXME: Suggest parens if the expression needs them.
8370       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8371       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8372           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8373       return true;
8374     }
8375   }
8376 
8377   return false;
8378 }
8379 
8380 bool
8381 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8382                                             &FS,
8383                                           const char *startSpecifier,
8384                                           unsigned specifierLen) {
8385   using namespace analyze_format_string;
8386   using namespace analyze_printf;
8387 
8388   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8389 
8390   if (FS.consumesDataArgument()) {
8391     if (atFirstArg) {
8392         atFirstArg = false;
8393         usesPositionalArgs = FS.usesPositionalArg();
8394     }
8395     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8396       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8397                                         startSpecifier, specifierLen);
8398       return false;
8399     }
8400   }
8401 
8402   // First check if the field width, precision, and conversion specifier
8403   // have matching data arguments.
8404   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8405                     startSpecifier, specifierLen)) {
8406     return false;
8407   }
8408 
8409   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8410                     startSpecifier, specifierLen)) {
8411     return false;
8412   }
8413 
8414   if (!CS.consumesDataArgument()) {
8415     // FIXME: Technically specifying a precision or field width here
8416     // makes no sense.  Worth issuing a warning at some point.
8417     return true;
8418   }
8419 
8420   // Consume the argument.
8421   unsigned argIndex = FS.getArgIndex();
8422   if (argIndex < NumDataArgs) {
8423     // The check to see if the argIndex is valid will come later.
8424     // We set the bit here because we may exit early from this
8425     // function if we encounter some other error.
8426     CoveredArgs.set(argIndex);
8427   }
8428 
8429   // FreeBSD kernel extensions.
8430   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8431       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8432     // We need at least two arguments.
8433     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8434       return false;
8435 
8436     // Claim the second argument.
8437     CoveredArgs.set(argIndex + 1);
8438 
8439     // Type check the first argument (int for %b, pointer for %D)
8440     const Expr *Ex = getDataArg(argIndex);
8441     const analyze_printf::ArgType &AT =
8442       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8443         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8444     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8445       EmitFormatDiagnostic(
8446           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8447               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8448               << false << Ex->getSourceRange(),
8449           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8450           getSpecifierRange(startSpecifier, specifierLen));
8451 
8452     // Type check the second argument (char * for both %b and %D)
8453     Ex = getDataArg(argIndex + 1);
8454     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8455     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8456       EmitFormatDiagnostic(
8457           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8458               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8459               << false << Ex->getSourceRange(),
8460           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8461           getSpecifierRange(startSpecifier, specifierLen));
8462 
8463      return true;
8464   }
8465 
8466   // Check for using an Objective-C specific conversion specifier
8467   // in a non-ObjC literal.
8468   if (!allowsObjCArg() && CS.isObjCArg()) {
8469     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8470                                                   specifierLen);
8471   }
8472 
8473   // %P can only be used with os_log.
8474   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8475     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8476                                                   specifierLen);
8477   }
8478 
8479   // %n is not allowed with os_log.
8480   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8481     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8482                          getLocationOfByte(CS.getStart()),
8483                          /*IsStringLocation*/ false,
8484                          getSpecifierRange(startSpecifier, specifierLen));
8485 
8486     return true;
8487   }
8488 
8489   // Only scalars are allowed for os_trace.
8490   if (FSType == Sema::FST_OSTrace &&
8491       (CS.getKind() == ConversionSpecifier::PArg ||
8492        CS.getKind() == ConversionSpecifier::sArg ||
8493        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8494     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8495                                                   specifierLen);
8496   }
8497 
8498   // Check for use of public/private annotation outside of os_log().
8499   if (FSType != Sema::FST_OSLog) {
8500     if (FS.isPublic().isSet()) {
8501       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8502                                << "public",
8503                            getLocationOfByte(FS.isPublic().getPosition()),
8504                            /*IsStringLocation*/ false,
8505                            getSpecifierRange(startSpecifier, specifierLen));
8506     }
8507     if (FS.isPrivate().isSet()) {
8508       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8509                                << "private",
8510                            getLocationOfByte(FS.isPrivate().getPosition()),
8511                            /*IsStringLocation*/ false,
8512                            getSpecifierRange(startSpecifier, specifierLen));
8513     }
8514   }
8515 
8516   // Check for invalid use of field width
8517   if (!FS.hasValidFieldWidth()) {
8518     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8519         startSpecifier, specifierLen);
8520   }
8521 
8522   // Check for invalid use of precision
8523   if (!FS.hasValidPrecision()) {
8524     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8525         startSpecifier, specifierLen);
8526   }
8527 
8528   // Precision is mandatory for %P specifier.
8529   if (CS.getKind() == ConversionSpecifier::PArg &&
8530       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8531     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8532                          getLocationOfByte(startSpecifier),
8533                          /*IsStringLocation*/ false,
8534                          getSpecifierRange(startSpecifier, specifierLen));
8535   }
8536 
8537   // Check each flag does not conflict with any other component.
8538   if (!FS.hasValidThousandsGroupingPrefix())
8539     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8540   if (!FS.hasValidLeadingZeros())
8541     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8542   if (!FS.hasValidPlusPrefix())
8543     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8544   if (!FS.hasValidSpacePrefix())
8545     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8546   if (!FS.hasValidAlternativeForm())
8547     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8548   if (!FS.hasValidLeftJustified())
8549     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8550 
8551   // Check that flags are not ignored by another flag
8552   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8553     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8554         startSpecifier, specifierLen);
8555   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8556     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8557             startSpecifier, specifierLen);
8558 
8559   // Check the length modifier is valid with the given conversion specifier.
8560   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8561                                  S.getLangOpts()))
8562     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8563                                 diag::warn_format_nonsensical_length);
8564   else if (!FS.hasStandardLengthModifier())
8565     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8566   else if (!FS.hasStandardLengthConversionCombination())
8567     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8568                                 diag::warn_format_non_standard_conversion_spec);
8569 
8570   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8571     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8572 
8573   // The remaining checks depend on the data arguments.
8574   if (HasVAListArg)
8575     return true;
8576 
8577   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8578     return false;
8579 
8580   const Expr *Arg = getDataArg(argIndex);
8581   if (!Arg)
8582     return true;
8583 
8584   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8585 }
8586 
8587 static bool requiresParensToAddCast(const Expr *E) {
8588   // FIXME: We should have a general way to reason about operator
8589   // precedence and whether parens are actually needed here.
8590   // Take care of a few common cases where they aren't.
8591   const Expr *Inside = E->IgnoreImpCasts();
8592   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8593     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8594 
8595   switch (Inside->getStmtClass()) {
8596   case Stmt::ArraySubscriptExprClass:
8597   case Stmt::CallExprClass:
8598   case Stmt::CharacterLiteralClass:
8599   case Stmt::CXXBoolLiteralExprClass:
8600   case Stmt::DeclRefExprClass:
8601   case Stmt::FloatingLiteralClass:
8602   case Stmt::IntegerLiteralClass:
8603   case Stmt::MemberExprClass:
8604   case Stmt::ObjCArrayLiteralClass:
8605   case Stmt::ObjCBoolLiteralExprClass:
8606   case Stmt::ObjCBoxedExprClass:
8607   case Stmt::ObjCDictionaryLiteralClass:
8608   case Stmt::ObjCEncodeExprClass:
8609   case Stmt::ObjCIvarRefExprClass:
8610   case Stmt::ObjCMessageExprClass:
8611   case Stmt::ObjCPropertyRefExprClass:
8612   case Stmt::ObjCStringLiteralClass:
8613   case Stmt::ObjCSubscriptRefExprClass:
8614   case Stmt::ParenExprClass:
8615   case Stmt::StringLiteralClass:
8616   case Stmt::UnaryOperatorClass:
8617     return false;
8618   default:
8619     return true;
8620   }
8621 }
8622 
8623 static std::pair<QualType, StringRef>
8624 shouldNotPrintDirectly(const ASTContext &Context,
8625                        QualType IntendedTy,
8626                        const Expr *E) {
8627   // Use a 'while' to peel off layers of typedefs.
8628   QualType TyTy = IntendedTy;
8629   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8630     StringRef Name = UserTy->getDecl()->getName();
8631     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8632       .Case("CFIndex", Context.getNSIntegerType())
8633       .Case("NSInteger", Context.getNSIntegerType())
8634       .Case("NSUInteger", Context.getNSUIntegerType())
8635       .Case("SInt32", Context.IntTy)
8636       .Case("UInt32", Context.UnsignedIntTy)
8637       .Default(QualType());
8638 
8639     if (!CastTy.isNull())
8640       return std::make_pair(CastTy, Name);
8641 
8642     TyTy = UserTy->desugar();
8643   }
8644 
8645   // Strip parens if necessary.
8646   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8647     return shouldNotPrintDirectly(Context,
8648                                   PE->getSubExpr()->getType(),
8649                                   PE->getSubExpr());
8650 
8651   // If this is a conditional expression, then its result type is constructed
8652   // via usual arithmetic conversions and thus there might be no necessary
8653   // typedef sugar there.  Recurse to operands to check for NSInteger &
8654   // Co. usage condition.
8655   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8656     QualType TrueTy, FalseTy;
8657     StringRef TrueName, FalseName;
8658 
8659     std::tie(TrueTy, TrueName) =
8660       shouldNotPrintDirectly(Context,
8661                              CO->getTrueExpr()->getType(),
8662                              CO->getTrueExpr());
8663     std::tie(FalseTy, FalseName) =
8664       shouldNotPrintDirectly(Context,
8665                              CO->getFalseExpr()->getType(),
8666                              CO->getFalseExpr());
8667 
8668     if (TrueTy == FalseTy)
8669       return std::make_pair(TrueTy, TrueName);
8670     else if (TrueTy.isNull())
8671       return std::make_pair(FalseTy, FalseName);
8672     else if (FalseTy.isNull())
8673       return std::make_pair(TrueTy, TrueName);
8674   }
8675 
8676   return std::make_pair(QualType(), StringRef());
8677 }
8678 
8679 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8680 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8681 /// type do not count.
8682 static bool
8683 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8684   QualType From = ICE->getSubExpr()->getType();
8685   QualType To = ICE->getType();
8686   // It's an integer promotion if the destination type is the promoted
8687   // source type.
8688   if (ICE->getCastKind() == CK_IntegralCast &&
8689       From->isPromotableIntegerType() &&
8690       S.Context.getPromotedIntegerType(From) == To)
8691     return true;
8692   // Look through vector types, since we do default argument promotion for
8693   // those in OpenCL.
8694   if (const auto *VecTy = From->getAs<ExtVectorType>())
8695     From = VecTy->getElementType();
8696   if (const auto *VecTy = To->getAs<ExtVectorType>())
8697     To = VecTy->getElementType();
8698   // It's a floating promotion if the source type is a lower rank.
8699   return ICE->getCastKind() == CK_FloatingCast &&
8700          S.Context.getFloatingTypeOrder(From, To) < 0;
8701 }
8702 
8703 bool
8704 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8705                                     const char *StartSpecifier,
8706                                     unsigned SpecifierLen,
8707                                     const Expr *E) {
8708   using namespace analyze_format_string;
8709   using namespace analyze_printf;
8710 
8711   // Now type check the data expression that matches the
8712   // format specifier.
8713   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8714   if (!AT.isValid())
8715     return true;
8716 
8717   QualType ExprTy = E->getType();
8718   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8719     ExprTy = TET->getUnderlyingExpr()->getType();
8720   }
8721 
8722   // Diagnose attempts to print a boolean value as a character. Unlike other
8723   // -Wformat diagnostics, this is fine from a type perspective, but it still
8724   // doesn't make sense.
8725   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8726       E->isKnownToHaveBooleanValue()) {
8727     const CharSourceRange &CSR =
8728         getSpecifierRange(StartSpecifier, SpecifierLen);
8729     SmallString<4> FSString;
8730     llvm::raw_svector_ostream os(FSString);
8731     FS.toString(os);
8732     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8733                              << FSString,
8734                          E->getExprLoc(), false, CSR);
8735     return true;
8736   }
8737 
8738   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8739   if (Match == analyze_printf::ArgType::Match)
8740     return true;
8741 
8742   // Look through argument promotions for our error message's reported type.
8743   // This includes the integral and floating promotions, but excludes array
8744   // and function pointer decay (seeing that an argument intended to be a
8745   // string has type 'char [6]' is probably more confusing than 'char *') and
8746   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8747   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8748     if (isArithmeticArgumentPromotion(S, ICE)) {
8749       E = ICE->getSubExpr();
8750       ExprTy = E->getType();
8751 
8752       // Check if we didn't match because of an implicit cast from a 'char'
8753       // or 'short' to an 'int'.  This is done because printf is a varargs
8754       // function.
8755       if (ICE->getType() == S.Context.IntTy ||
8756           ICE->getType() == S.Context.UnsignedIntTy) {
8757         // All further checking is done on the subexpression
8758         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8759             AT.matchesType(S.Context, ExprTy);
8760         if (ImplicitMatch == analyze_printf::ArgType::Match)
8761           return true;
8762         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8763             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8764           Match = ImplicitMatch;
8765       }
8766     }
8767   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8768     // Special case for 'a', which has type 'int' in C.
8769     // Note, however, that we do /not/ want to treat multibyte constants like
8770     // 'MooV' as characters! This form is deprecated but still exists. In
8771     // addition, don't treat expressions as of type 'char' if one byte length
8772     // modifier is provided.
8773     if (ExprTy == S.Context.IntTy &&
8774         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8775       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8776         ExprTy = S.Context.CharTy;
8777   }
8778 
8779   // Look through enums to their underlying type.
8780   bool IsEnum = false;
8781   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8782     ExprTy = EnumTy->getDecl()->getIntegerType();
8783     IsEnum = true;
8784   }
8785 
8786   // %C in an Objective-C context prints a unichar, not a wchar_t.
8787   // If the argument is an integer of some kind, believe the %C and suggest
8788   // a cast instead of changing the conversion specifier.
8789   QualType IntendedTy = ExprTy;
8790   if (isObjCContext() &&
8791       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8792     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8793         !ExprTy->isCharType()) {
8794       // 'unichar' is defined as a typedef of unsigned short, but we should
8795       // prefer using the typedef if it is visible.
8796       IntendedTy = S.Context.UnsignedShortTy;
8797 
8798       // While we are here, check if the value is an IntegerLiteral that happens
8799       // to be within the valid range.
8800       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8801         const llvm::APInt &V = IL->getValue();
8802         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8803           return true;
8804       }
8805 
8806       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8807                           Sema::LookupOrdinaryName);
8808       if (S.LookupName(Result, S.getCurScope())) {
8809         NamedDecl *ND = Result.getFoundDecl();
8810         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8811           if (TD->getUnderlyingType() == IntendedTy)
8812             IntendedTy = S.Context.getTypedefType(TD);
8813       }
8814     }
8815   }
8816 
8817   // Special-case some of Darwin's platform-independence types by suggesting
8818   // casts to primitive types that are known to be large enough.
8819   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8820   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8821     QualType CastTy;
8822     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8823     if (!CastTy.isNull()) {
8824       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8825       // (long in ASTContext). Only complain to pedants.
8826       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8827           (AT.isSizeT() || AT.isPtrdiffT()) &&
8828           AT.matchesType(S.Context, CastTy))
8829         Match = ArgType::NoMatchPedantic;
8830       IntendedTy = CastTy;
8831       ShouldNotPrintDirectly = true;
8832     }
8833   }
8834 
8835   // We may be able to offer a FixItHint if it is a supported type.
8836   PrintfSpecifier fixedFS = FS;
8837   bool Success =
8838       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8839 
8840   if (Success) {
8841     // Get the fix string from the fixed format specifier
8842     SmallString<16> buf;
8843     llvm::raw_svector_ostream os(buf);
8844     fixedFS.toString(os);
8845 
8846     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8847 
8848     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8849       unsigned Diag;
8850       switch (Match) {
8851       case ArgType::Match: llvm_unreachable("expected non-matching");
8852       case ArgType::NoMatchPedantic:
8853         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8854         break;
8855       case ArgType::NoMatchTypeConfusion:
8856         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8857         break;
8858       case ArgType::NoMatch:
8859         Diag = diag::warn_format_conversion_argument_type_mismatch;
8860         break;
8861       }
8862 
8863       // In this case, the specifier is wrong and should be changed to match
8864       // the argument.
8865       EmitFormatDiagnostic(S.PDiag(Diag)
8866                                << AT.getRepresentativeTypeName(S.Context)
8867                                << IntendedTy << IsEnum << E->getSourceRange(),
8868                            E->getBeginLoc(),
8869                            /*IsStringLocation*/ false, SpecRange,
8870                            FixItHint::CreateReplacement(SpecRange, os.str()));
8871     } else {
8872       // The canonical type for formatting this value is different from the
8873       // actual type of the expression. (This occurs, for example, with Darwin's
8874       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8875       // should be printed as 'long' for 64-bit compatibility.)
8876       // Rather than emitting a normal format/argument mismatch, we want to
8877       // add a cast to the recommended type (and correct the format string
8878       // if necessary).
8879       SmallString<16> CastBuf;
8880       llvm::raw_svector_ostream CastFix(CastBuf);
8881       CastFix << "(";
8882       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8883       CastFix << ")";
8884 
8885       SmallVector<FixItHint,4> Hints;
8886       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8887         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8888 
8889       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8890         // If there's already a cast present, just replace it.
8891         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8892         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8893 
8894       } else if (!requiresParensToAddCast(E)) {
8895         // If the expression has high enough precedence,
8896         // just write the C-style cast.
8897         Hints.push_back(
8898             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8899       } else {
8900         // Otherwise, add parens around the expression as well as the cast.
8901         CastFix << "(";
8902         Hints.push_back(
8903             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8904 
8905         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8906         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8907       }
8908 
8909       if (ShouldNotPrintDirectly) {
8910         // The expression has a type that should not be printed directly.
8911         // We extract the name from the typedef because we don't want to show
8912         // the underlying type in the diagnostic.
8913         StringRef Name;
8914         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8915           Name = TypedefTy->getDecl()->getName();
8916         else
8917           Name = CastTyName;
8918         unsigned Diag = Match == ArgType::NoMatchPedantic
8919                             ? diag::warn_format_argument_needs_cast_pedantic
8920                             : diag::warn_format_argument_needs_cast;
8921         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8922                                            << E->getSourceRange(),
8923                              E->getBeginLoc(), /*IsStringLocation=*/false,
8924                              SpecRange, Hints);
8925       } else {
8926         // In this case, the expression could be printed using a different
8927         // specifier, but we've decided that the specifier is probably correct
8928         // and we should cast instead. Just use the normal warning message.
8929         EmitFormatDiagnostic(
8930             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8931                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8932                 << E->getSourceRange(),
8933             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8934       }
8935     }
8936   } else {
8937     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8938                                                    SpecifierLen);
8939     // Since the warning for passing non-POD types to variadic functions
8940     // was deferred until now, we emit a warning for non-POD
8941     // arguments here.
8942     switch (S.isValidVarArgType(ExprTy)) {
8943     case Sema::VAK_Valid:
8944     case Sema::VAK_ValidInCXX11: {
8945       unsigned Diag;
8946       switch (Match) {
8947       case ArgType::Match: llvm_unreachable("expected non-matching");
8948       case ArgType::NoMatchPedantic:
8949         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8950         break;
8951       case ArgType::NoMatchTypeConfusion:
8952         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8953         break;
8954       case ArgType::NoMatch:
8955         Diag = diag::warn_format_conversion_argument_type_mismatch;
8956         break;
8957       }
8958 
8959       EmitFormatDiagnostic(
8960           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8961                         << IsEnum << CSR << E->getSourceRange(),
8962           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8963       break;
8964     }
8965     case Sema::VAK_Undefined:
8966     case Sema::VAK_MSVCUndefined:
8967       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8968                                << S.getLangOpts().CPlusPlus11 << ExprTy
8969                                << CallType
8970                                << AT.getRepresentativeTypeName(S.Context) << CSR
8971                                << E->getSourceRange(),
8972                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8973       checkForCStrMembers(AT, E);
8974       break;
8975 
8976     case Sema::VAK_Invalid:
8977       if (ExprTy->isObjCObjectType())
8978         EmitFormatDiagnostic(
8979             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8980                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8981                 << AT.getRepresentativeTypeName(S.Context) << CSR
8982                 << E->getSourceRange(),
8983             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8984       else
8985         // FIXME: If this is an initializer list, suggest removing the braces
8986         // or inserting a cast to the target type.
8987         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8988             << isa<InitListExpr>(E) << ExprTy << CallType
8989             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8990       break;
8991     }
8992 
8993     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8994            "format string specifier index out of range");
8995     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8996   }
8997 
8998   return true;
8999 }
9000 
9001 //===--- CHECK: Scanf format string checking ------------------------------===//
9002 
9003 namespace {
9004 
9005 class CheckScanfHandler : public CheckFormatHandler {
9006 public:
9007   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9008                     const Expr *origFormatExpr, Sema::FormatStringType type,
9009                     unsigned firstDataArg, unsigned numDataArgs,
9010                     const char *beg, bool hasVAListArg,
9011                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9012                     bool inFunctionCall, Sema::VariadicCallType CallType,
9013                     llvm::SmallBitVector &CheckedVarArgs,
9014                     UncoveredArgHandler &UncoveredArg)
9015       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9016                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9017                            inFunctionCall, CallType, CheckedVarArgs,
9018                            UncoveredArg) {}
9019 
9020   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9021                             const char *startSpecifier,
9022                             unsigned specifierLen) override;
9023 
9024   bool HandleInvalidScanfConversionSpecifier(
9025           const analyze_scanf::ScanfSpecifier &FS,
9026           const char *startSpecifier,
9027           unsigned specifierLen) override;
9028 
9029   void HandleIncompleteScanList(const char *start, const char *end) override;
9030 };
9031 
9032 } // namespace
9033 
9034 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9035                                                  const char *end) {
9036   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9037                        getLocationOfByte(end), /*IsStringLocation*/true,
9038                        getSpecifierRange(start, end - start));
9039 }
9040 
9041 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9042                                         const analyze_scanf::ScanfSpecifier &FS,
9043                                         const char *startSpecifier,
9044                                         unsigned specifierLen) {
9045   const analyze_scanf::ScanfConversionSpecifier &CS =
9046     FS.getConversionSpecifier();
9047 
9048   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9049                                           getLocationOfByte(CS.getStart()),
9050                                           startSpecifier, specifierLen,
9051                                           CS.getStart(), CS.getLength());
9052 }
9053 
9054 bool CheckScanfHandler::HandleScanfSpecifier(
9055                                        const analyze_scanf::ScanfSpecifier &FS,
9056                                        const char *startSpecifier,
9057                                        unsigned specifierLen) {
9058   using namespace analyze_scanf;
9059   using namespace analyze_format_string;
9060 
9061   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9062 
9063   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9064   // be used to decide if we are using positional arguments consistently.
9065   if (FS.consumesDataArgument()) {
9066     if (atFirstArg) {
9067       atFirstArg = false;
9068       usesPositionalArgs = FS.usesPositionalArg();
9069     }
9070     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9071       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9072                                         startSpecifier, specifierLen);
9073       return false;
9074     }
9075   }
9076 
9077   // Check if the field with is non-zero.
9078   const OptionalAmount &Amt = FS.getFieldWidth();
9079   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9080     if (Amt.getConstantAmount() == 0) {
9081       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9082                                                    Amt.getConstantLength());
9083       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9084                            getLocationOfByte(Amt.getStart()),
9085                            /*IsStringLocation*/true, R,
9086                            FixItHint::CreateRemoval(R));
9087     }
9088   }
9089 
9090   if (!FS.consumesDataArgument()) {
9091     // FIXME: Technically specifying a precision or field width here
9092     // makes no sense.  Worth issuing a warning at some point.
9093     return true;
9094   }
9095 
9096   // Consume the argument.
9097   unsigned argIndex = FS.getArgIndex();
9098   if (argIndex < NumDataArgs) {
9099       // The check to see if the argIndex is valid will come later.
9100       // We set the bit here because we may exit early from this
9101       // function if we encounter some other error.
9102     CoveredArgs.set(argIndex);
9103   }
9104 
9105   // Check the length modifier is valid with the given conversion specifier.
9106   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9107                                  S.getLangOpts()))
9108     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9109                                 diag::warn_format_nonsensical_length);
9110   else if (!FS.hasStandardLengthModifier())
9111     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9112   else if (!FS.hasStandardLengthConversionCombination())
9113     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9114                                 diag::warn_format_non_standard_conversion_spec);
9115 
9116   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9117     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9118 
9119   // The remaining checks depend on the data arguments.
9120   if (HasVAListArg)
9121     return true;
9122 
9123   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9124     return false;
9125 
9126   // Check that the argument type matches the format specifier.
9127   const Expr *Ex = getDataArg(argIndex);
9128   if (!Ex)
9129     return true;
9130 
9131   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9132 
9133   if (!AT.isValid()) {
9134     return true;
9135   }
9136 
9137   analyze_format_string::ArgType::MatchKind Match =
9138       AT.matchesType(S.Context, Ex->getType());
9139   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9140   if (Match == analyze_format_string::ArgType::Match)
9141     return true;
9142 
9143   ScanfSpecifier fixedFS = FS;
9144   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9145                                  S.getLangOpts(), S.Context);
9146 
9147   unsigned Diag =
9148       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9149                : diag::warn_format_conversion_argument_type_mismatch;
9150 
9151   if (Success) {
9152     // Get the fix string from the fixed format specifier.
9153     SmallString<128> buf;
9154     llvm::raw_svector_ostream os(buf);
9155     fixedFS.toString(os);
9156 
9157     EmitFormatDiagnostic(
9158         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9159                       << Ex->getType() << false << Ex->getSourceRange(),
9160         Ex->getBeginLoc(),
9161         /*IsStringLocation*/ false,
9162         getSpecifierRange(startSpecifier, specifierLen),
9163         FixItHint::CreateReplacement(
9164             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9165   } else {
9166     EmitFormatDiagnostic(S.PDiag(Diag)
9167                              << AT.getRepresentativeTypeName(S.Context)
9168                              << Ex->getType() << false << Ex->getSourceRange(),
9169                          Ex->getBeginLoc(),
9170                          /*IsStringLocation*/ false,
9171                          getSpecifierRange(startSpecifier, specifierLen));
9172   }
9173 
9174   return true;
9175 }
9176 
9177 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9178                               const Expr *OrigFormatExpr,
9179                               ArrayRef<const Expr *> Args,
9180                               bool HasVAListArg, unsigned format_idx,
9181                               unsigned firstDataArg,
9182                               Sema::FormatStringType Type,
9183                               bool inFunctionCall,
9184                               Sema::VariadicCallType CallType,
9185                               llvm::SmallBitVector &CheckedVarArgs,
9186                               UncoveredArgHandler &UncoveredArg,
9187                               bool IgnoreStringsWithoutSpecifiers) {
9188   // CHECK: is the format string a wide literal?
9189   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9190     CheckFormatHandler::EmitFormatDiagnostic(
9191         S, inFunctionCall, Args[format_idx],
9192         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9193         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9194     return;
9195   }
9196 
9197   // Str - The format string.  NOTE: this is NOT null-terminated!
9198   StringRef StrRef = FExpr->getString();
9199   const char *Str = StrRef.data();
9200   // Account for cases where the string literal is truncated in a declaration.
9201   const ConstantArrayType *T =
9202     S.Context.getAsConstantArrayType(FExpr->getType());
9203   assert(T && "String literal not of constant array type!");
9204   size_t TypeSize = T->getSize().getZExtValue();
9205   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9206   const unsigned numDataArgs = Args.size() - firstDataArg;
9207 
9208   if (IgnoreStringsWithoutSpecifiers &&
9209       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9210           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9211     return;
9212 
9213   // Emit a warning if the string literal is truncated and does not contain an
9214   // embedded null character.
9215   if (TypeSize <= StrRef.size() &&
9216       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9217     CheckFormatHandler::EmitFormatDiagnostic(
9218         S, inFunctionCall, Args[format_idx],
9219         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9220         FExpr->getBeginLoc(),
9221         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9222     return;
9223   }
9224 
9225   // CHECK: empty format string?
9226   if (StrLen == 0 && numDataArgs > 0) {
9227     CheckFormatHandler::EmitFormatDiagnostic(
9228         S, inFunctionCall, Args[format_idx],
9229         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9230         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9231     return;
9232   }
9233 
9234   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9235       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9236       Type == Sema::FST_OSTrace) {
9237     CheckPrintfHandler H(
9238         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9239         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9240         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9241         CheckedVarArgs, UncoveredArg);
9242 
9243     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9244                                                   S.getLangOpts(),
9245                                                   S.Context.getTargetInfo(),
9246                                             Type == Sema::FST_FreeBSDKPrintf))
9247       H.DoneProcessing();
9248   } else if (Type == Sema::FST_Scanf) {
9249     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9250                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9251                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9252 
9253     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9254                                                  S.getLangOpts(),
9255                                                  S.Context.getTargetInfo()))
9256       H.DoneProcessing();
9257   } // TODO: handle other formats
9258 }
9259 
9260 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9261   // Str - The format string.  NOTE: this is NOT null-terminated!
9262   StringRef StrRef = FExpr->getString();
9263   const char *Str = StrRef.data();
9264   // Account for cases where the string literal is truncated in a declaration.
9265   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9266   assert(T && "String literal not of constant array type!");
9267   size_t TypeSize = T->getSize().getZExtValue();
9268   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9269   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9270                                                          getLangOpts(),
9271                                                          Context.getTargetInfo());
9272 }
9273 
9274 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9275 
9276 // Returns the related absolute value function that is larger, of 0 if one
9277 // does not exist.
9278 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9279   switch (AbsFunction) {
9280   default:
9281     return 0;
9282 
9283   case Builtin::BI__builtin_abs:
9284     return Builtin::BI__builtin_labs;
9285   case Builtin::BI__builtin_labs:
9286     return Builtin::BI__builtin_llabs;
9287   case Builtin::BI__builtin_llabs:
9288     return 0;
9289 
9290   case Builtin::BI__builtin_fabsf:
9291     return Builtin::BI__builtin_fabs;
9292   case Builtin::BI__builtin_fabs:
9293     return Builtin::BI__builtin_fabsl;
9294   case Builtin::BI__builtin_fabsl:
9295     return 0;
9296 
9297   case Builtin::BI__builtin_cabsf:
9298     return Builtin::BI__builtin_cabs;
9299   case Builtin::BI__builtin_cabs:
9300     return Builtin::BI__builtin_cabsl;
9301   case Builtin::BI__builtin_cabsl:
9302     return 0;
9303 
9304   case Builtin::BIabs:
9305     return Builtin::BIlabs;
9306   case Builtin::BIlabs:
9307     return Builtin::BIllabs;
9308   case Builtin::BIllabs:
9309     return 0;
9310 
9311   case Builtin::BIfabsf:
9312     return Builtin::BIfabs;
9313   case Builtin::BIfabs:
9314     return Builtin::BIfabsl;
9315   case Builtin::BIfabsl:
9316     return 0;
9317 
9318   case Builtin::BIcabsf:
9319    return Builtin::BIcabs;
9320   case Builtin::BIcabs:
9321     return Builtin::BIcabsl;
9322   case Builtin::BIcabsl:
9323     return 0;
9324   }
9325 }
9326 
9327 // Returns the argument type of the absolute value function.
9328 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9329                                              unsigned AbsType) {
9330   if (AbsType == 0)
9331     return QualType();
9332 
9333   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9334   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9335   if (Error != ASTContext::GE_None)
9336     return QualType();
9337 
9338   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9339   if (!FT)
9340     return QualType();
9341 
9342   if (FT->getNumParams() != 1)
9343     return QualType();
9344 
9345   return FT->getParamType(0);
9346 }
9347 
9348 // Returns the best absolute value function, or zero, based on type and
9349 // current absolute value function.
9350 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9351                                    unsigned AbsFunctionKind) {
9352   unsigned BestKind = 0;
9353   uint64_t ArgSize = Context.getTypeSize(ArgType);
9354   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9355        Kind = getLargerAbsoluteValueFunction(Kind)) {
9356     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9357     if (Context.getTypeSize(ParamType) >= ArgSize) {
9358       if (BestKind == 0)
9359         BestKind = Kind;
9360       else if (Context.hasSameType(ParamType, ArgType)) {
9361         BestKind = Kind;
9362         break;
9363       }
9364     }
9365   }
9366   return BestKind;
9367 }
9368 
9369 enum AbsoluteValueKind {
9370   AVK_Integer,
9371   AVK_Floating,
9372   AVK_Complex
9373 };
9374 
9375 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9376   if (T->isIntegralOrEnumerationType())
9377     return AVK_Integer;
9378   if (T->isRealFloatingType())
9379     return AVK_Floating;
9380   if (T->isAnyComplexType())
9381     return AVK_Complex;
9382 
9383   llvm_unreachable("Type not integer, floating, or complex");
9384 }
9385 
9386 // Changes the absolute value function to a different type.  Preserves whether
9387 // the function is a builtin.
9388 static unsigned changeAbsFunction(unsigned AbsKind,
9389                                   AbsoluteValueKind ValueKind) {
9390   switch (ValueKind) {
9391   case AVK_Integer:
9392     switch (AbsKind) {
9393     default:
9394       return 0;
9395     case Builtin::BI__builtin_fabsf:
9396     case Builtin::BI__builtin_fabs:
9397     case Builtin::BI__builtin_fabsl:
9398     case Builtin::BI__builtin_cabsf:
9399     case Builtin::BI__builtin_cabs:
9400     case Builtin::BI__builtin_cabsl:
9401       return Builtin::BI__builtin_abs;
9402     case Builtin::BIfabsf:
9403     case Builtin::BIfabs:
9404     case Builtin::BIfabsl:
9405     case Builtin::BIcabsf:
9406     case Builtin::BIcabs:
9407     case Builtin::BIcabsl:
9408       return Builtin::BIabs;
9409     }
9410   case AVK_Floating:
9411     switch (AbsKind) {
9412     default:
9413       return 0;
9414     case Builtin::BI__builtin_abs:
9415     case Builtin::BI__builtin_labs:
9416     case Builtin::BI__builtin_llabs:
9417     case Builtin::BI__builtin_cabsf:
9418     case Builtin::BI__builtin_cabs:
9419     case Builtin::BI__builtin_cabsl:
9420       return Builtin::BI__builtin_fabsf;
9421     case Builtin::BIabs:
9422     case Builtin::BIlabs:
9423     case Builtin::BIllabs:
9424     case Builtin::BIcabsf:
9425     case Builtin::BIcabs:
9426     case Builtin::BIcabsl:
9427       return Builtin::BIfabsf;
9428     }
9429   case AVK_Complex:
9430     switch (AbsKind) {
9431     default:
9432       return 0;
9433     case Builtin::BI__builtin_abs:
9434     case Builtin::BI__builtin_labs:
9435     case Builtin::BI__builtin_llabs:
9436     case Builtin::BI__builtin_fabsf:
9437     case Builtin::BI__builtin_fabs:
9438     case Builtin::BI__builtin_fabsl:
9439       return Builtin::BI__builtin_cabsf;
9440     case Builtin::BIabs:
9441     case Builtin::BIlabs:
9442     case Builtin::BIllabs:
9443     case Builtin::BIfabsf:
9444     case Builtin::BIfabs:
9445     case Builtin::BIfabsl:
9446       return Builtin::BIcabsf;
9447     }
9448   }
9449   llvm_unreachable("Unable to convert function");
9450 }
9451 
9452 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9453   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9454   if (!FnInfo)
9455     return 0;
9456 
9457   switch (FDecl->getBuiltinID()) {
9458   default:
9459     return 0;
9460   case Builtin::BI__builtin_abs:
9461   case Builtin::BI__builtin_fabs:
9462   case Builtin::BI__builtin_fabsf:
9463   case Builtin::BI__builtin_fabsl:
9464   case Builtin::BI__builtin_labs:
9465   case Builtin::BI__builtin_llabs:
9466   case Builtin::BI__builtin_cabs:
9467   case Builtin::BI__builtin_cabsf:
9468   case Builtin::BI__builtin_cabsl:
9469   case Builtin::BIabs:
9470   case Builtin::BIlabs:
9471   case Builtin::BIllabs:
9472   case Builtin::BIfabs:
9473   case Builtin::BIfabsf:
9474   case Builtin::BIfabsl:
9475   case Builtin::BIcabs:
9476   case Builtin::BIcabsf:
9477   case Builtin::BIcabsl:
9478     return FDecl->getBuiltinID();
9479   }
9480   llvm_unreachable("Unknown Builtin type");
9481 }
9482 
9483 // If the replacement is valid, emit a note with replacement function.
9484 // Additionally, suggest including the proper header if not already included.
9485 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9486                             unsigned AbsKind, QualType ArgType) {
9487   bool EmitHeaderHint = true;
9488   const char *HeaderName = nullptr;
9489   const char *FunctionName = nullptr;
9490   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9491     FunctionName = "std::abs";
9492     if (ArgType->isIntegralOrEnumerationType()) {
9493       HeaderName = "cstdlib";
9494     } else if (ArgType->isRealFloatingType()) {
9495       HeaderName = "cmath";
9496     } else {
9497       llvm_unreachable("Invalid Type");
9498     }
9499 
9500     // Lookup all std::abs
9501     if (NamespaceDecl *Std = S.getStdNamespace()) {
9502       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9503       R.suppressDiagnostics();
9504       S.LookupQualifiedName(R, Std);
9505 
9506       for (const auto *I : R) {
9507         const FunctionDecl *FDecl = nullptr;
9508         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9509           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9510         } else {
9511           FDecl = dyn_cast<FunctionDecl>(I);
9512         }
9513         if (!FDecl)
9514           continue;
9515 
9516         // Found std::abs(), check that they are the right ones.
9517         if (FDecl->getNumParams() != 1)
9518           continue;
9519 
9520         // Check that the parameter type can handle the argument.
9521         QualType ParamType = FDecl->getParamDecl(0)->getType();
9522         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9523             S.Context.getTypeSize(ArgType) <=
9524                 S.Context.getTypeSize(ParamType)) {
9525           // Found a function, don't need the header hint.
9526           EmitHeaderHint = false;
9527           break;
9528         }
9529       }
9530     }
9531   } else {
9532     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9533     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9534 
9535     if (HeaderName) {
9536       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9537       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9538       R.suppressDiagnostics();
9539       S.LookupName(R, S.getCurScope());
9540 
9541       if (R.isSingleResult()) {
9542         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9543         if (FD && FD->getBuiltinID() == AbsKind) {
9544           EmitHeaderHint = false;
9545         } else {
9546           return;
9547         }
9548       } else if (!R.empty()) {
9549         return;
9550       }
9551     }
9552   }
9553 
9554   S.Diag(Loc, diag::note_replace_abs_function)
9555       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9556 
9557   if (!HeaderName)
9558     return;
9559 
9560   if (!EmitHeaderHint)
9561     return;
9562 
9563   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9564                                                     << FunctionName;
9565 }
9566 
9567 template <std::size_t StrLen>
9568 static bool IsStdFunction(const FunctionDecl *FDecl,
9569                           const char (&Str)[StrLen]) {
9570   if (!FDecl)
9571     return false;
9572   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9573     return false;
9574   if (!FDecl->isInStdNamespace())
9575     return false;
9576 
9577   return true;
9578 }
9579 
9580 // Warn when using the wrong abs() function.
9581 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9582                                       const FunctionDecl *FDecl) {
9583   if (Call->getNumArgs() != 1)
9584     return;
9585 
9586   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9587   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9588   if (AbsKind == 0 && !IsStdAbs)
9589     return;
9590 
9591   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9592   QualType ParamType = Call->getArg(0)->getType();
9593 
9594   // Unsigned types cannot be negative.  Suggest removing the absolute value
9595   // function call.
9596   if (ArgType->isUnsignedIntegerType()) {
9597     const char *FunctionName =
9598         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9599     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9600     Diag(Call->getExprLoc(), diag::note_remove_abs)
9601         << FunctionName
9602         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9603     return;
9604   }
9605 
9606   // Taking the absolute value of a pointer is very suspicious, they probably
9607   // wanted to index into an array, dereference a pointer, call a function, etc.
9608   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9609     unsigned DiagType = 0;
9610     if (ArgType->isFunctionType())
9611       DiagType = 1;
9612     else if (ArgType->isArrayType())
9613       DiagType = 2;
9614 
9615     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9616     return;
9617   }
9618 
9619   // std::abs has overloads which prevent most of the absolute value problems
9620   // from occurring.
9621   if (IsStdAbs)
9622     return;
9623 
9624   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9625   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9626 
9627   // The argument and parameter are the same kind.  Check if they are the right
9628   // size.
9629   if (ArgValueKind == ParamValueKind) {
9630     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9631       return;
9632 
9633     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9634     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9635         << FDecl << ArgType << ParamType;
9636 
9637     if (NewAbsKind == 0)
9638       return;
9639 
9640     emitReplacement(*this, Call->getExprLoc(),
9641                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9642     return;
9643   }
9644 
9645   // ArgValueKind != ParamValueKind
9646   // The wrong type of absolute value function was used.  Attempt to find the
9647   // proper one.
9648   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9649   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9650   if (NewAbsKind == 0)
9651     return;
9652 
9653   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9654       << FDecl << ParamValueKind << ArgValueKind;
9655 
9656   emitReplacement(*this, Call->getExprLoc(),
9657                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9658 }
9659 
9660 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9661 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9662                                 const FunctionDecl *FDecl) {
9663   if (!Call || !FDecl) return;
9664 
9665   // Ignore template specializations and macros.
9666   if (inTemplateInstantiation()) return;
9667   if (Call->getExprLoc().isMacroID()) return;
9668 
9669   // Only care about the one template argument, two function parameter std::max
9670   if (Call->getNumArgs() != 2) return;
9671   if (!IsStdFunction(FDecl, "max")) return;
9672   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9673   if (!ArgList) return;
9674   if (ArgList->size() != 1) return;
9675 
9676   // Check that template type argument is unsigned integer.
9677   const auto& TA = ArgList->get(0);
9678   if (TA.getKind() != TemplateArgument::Type) return;
9679   QualType ArgType = TA.getAsType();
9680   if (!ArgType->isUnsignedIntegerType()) return;
9681 
9682   // See if either argument is a literal zero.
9683   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9684     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9685     if (!MTE) return false;
9686     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9687     if (!Num) return false;
9688     if (Num->getValue() != 0) return false;
9689     return true;
9690   };
9691 
9692   const Expr *FirstArg = Call->getArg(0);
9693   const Expr *SecondArg = Call->getArg(1);
9694   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9695   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9696 
9697   // Only warn when exactly one argument is zero.
9698   if (IsFirstArgZero == IsSecondArgZero) return;
9699 
9700   SourceRange FirstRange = FirstArg->getSourceRange();
9701   SourceRange SecondRange = SecondArg->getSourceRange();
9702 
9703   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9704 
9705   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9706       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9707 
9708   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9709   SourceRange RemovalRange;
9710   if (IsFirstArgZero) {
9711     RemovalRange = SourceRange(FirstRange.getBegin(),
9712                                SecondRange.getBegin().getLocWithOffset(-1));
9713   } else {
9714     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9715                                SecondRange.getEnd());
9716   }
9717 
9718   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9719         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9720         << FixItHint::CreateRemoval(RemovalRange);
9721 }
9722 
9723 //===--- CHECK: Standard memory functions ---------------------------------===//
9724 
9725 /// Takes the expression passed to the size_t parameter of functions
9726 /// such as memcmp, strncat, etc and warns if it's a comparison.
9727 ///
9728 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9729 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9730                                            IdentifierInfo *FnName,
9731                                            SourceLocation FnLoc,
9732                                            SourceLocation RParenLoc) {
9733   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9734   if (!Size)
9735     return false;
9736 
9737   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9738   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9739     return false;
9740 
9741   SourceRange SizeRange = Size->getSourceRange();
9742   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9743       << SizeRange << FnName;
9744   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9745       << FnName
9746       << FixItHint::CreateInsertion(
9747              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9748       << FixItHint::CreateRemoval(RParenLoc);
9749   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9750       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9751       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9752                                     ")");
9753 
9754   return true;
9755 }
9756 
9757 /// Determine whether the given type is or contains a dynamic class type
9758 /// (e.g., whether it has a vtable).
9759 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9760                                                      bool &IsContained) {
9761   // Look through array types while ignoring qualifiers.
9762   const Type *Ty = T->getBaseElementTypeUnsafe();
9763   IsContained = false;
9764 
9765   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9766   RD = RD ? RD->getDefinition() : nullptr;
9767   if (!RD || RD->isInvalidDecl())
9768     return nullptr;
9769 
9770   if (RD->isDynamicClass())
9771     return RD;
9772 
9773   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9774   // It's impossible for a class to transitively contain itself by value, so
9775   // infinite recursion is impossible.
9776   for (auto *FD : RD->fields()) {
9777     bool SubContained;
9778     if (const CXXRecordDecl *ContainedRD =
9779             getContainedDynamicClass(FD->getType(), SubContained)) {
9780       IsContained = true;
9781       return ContainedRD;
9782     }
9783   }
9784 
9785   return nullptr;
9786 }
9787 
9788 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9789   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9790     if (Unary->getKind() == UETT_SizeOf)
9791       return Unary;
9792   return nullptr;
9793 }
9794 
9795 /// If E is a sizeof expression, returns its argument expression,
9796 /// otherwise returns NULL.
9797 static const Expr *getSizeOfExprArg(const Expr *E) {
9798   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9799     if (!SizeOf->isArgumentType())
9800       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9801   return nullptr;
9802 }
9803 
9804 /// If E is a sizeof expression, returns its argument type.
9805 static QualType getSizeOfArgType(const Expr *E) {
9806   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9807     return SizeOf->getTypeOfArgument();
9808   return QualType();
9809 }
9810 
9811 namespace {
9812 
9813 struct SearchNonTrivialToInitializeField
9814     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9815   using Super =
9816       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9817 
9818   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9819 
9820   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9821                      SourceLocation SL) {
9822     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9823       asDerived().visitArray(PDIK, AT, SL);
9824       return;
9825     }
9826 
9827     Super::visitWithKind(PDIK, FT, SL);
9828   }
9829 
9830   void visitARCStrong(QualType FT, SourceLocation SL) {
9831     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9832   }
9833   void visitARCWeak(QualType FT, SourceLocation SL) {
9834     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9835   }
9836   void visitStruct(QualType FT, SourceLocation SL) {
9837     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9838       visit(FD->getType(), FD->getLocation());
9839   }
9840   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9841                   const ArrayType *AT, SourceLocation SL) {
9842     visit(getContext().getBaseElementType(AT), SL);
9843   }
9844   void visitTrivial(QualType FT, SourceLocation SL) {}
9845 
9846   static void diag(QualType RT, const Expr *E, Sema &S) {
9847     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9848   }
9849 
9850   ASTContext &getContext() { return S.getASTContext(); }
9851 
9852   const Expr *E;
9853   Sema &S;
9854 };
9855 
9856 struct SearchNonTrivialToCopyField
9857     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9858   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9859 
9860   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9861 
9862   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9863                      SourceLocation SL) {
9864     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9865       asDerived().visitArray(PCK, AT, SL);
9866       return;
9867     }
9868 
9869     Super::visitWithKind(PCK, FT, SL);
9870   }
9871 
9872   void visitARCStrong(QualType FT, SourceLocation SL) {
9873     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9874   }
9875   void visitARCWeak(QualType FT, SourceLocation SL) {
9876     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9877   }
9878   void visitStruct(QualType FT, SourceLocation SL) {
9879     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9880       visit(FD->getType(), FD->getLocation());
9881   }
9882   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9883                   SourceLocation SL) {
9884     visit(getContext().getBaseElementType(AT), SL);
9885   }
9886   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9887                 SourceLocation SL) {}
9888   void visitTrivial(QualType FT, SourceLocation SL) {}
9889   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9890 
9891   static void diag(QualType RT, const Expr *E, Sema &S) {
9892     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9893   }
9894 
9895   ASTContext &getContext() { return S.getASTContext(); }
9896 
9897   const Expr *E;
9898   Sema &S;
9899 };
9900 
9901 }
9902 
9903 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9904 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9905   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9906 
9907   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9908     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9909       return false;
9910 
9911     return doesExprLikelyComputeSize(BO->getLHS()) ||
9912            doesExprLikelyComputeSize(BO->getRHS());
9913   }
9914 
9915   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9916 }
9917 
9918 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9919 ///
9920 /// \code
9921 ///   #define MACRO 0
9922 ///   foo(MACRO);
9923 ///   foo(0);
9924 /// \endcode
9925 ///
9926 /// This should return true for the first call to foo, but not for the second
9927 /// (regardless of whether foo is a macro or function).
9928 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9929                                         SourceLocation CallLoc,
9930                                         SourceLocation ArgLoc) {
9931   if (!CallLoc.isMacroID())
9932     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9933 
9934   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9935          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9936 }
9937 
9938 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9939 /// last two arguments transposed.
9940 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9941   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9942     return;
9943 
9944   const Expr *SizeArg =
9945     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9946 
9947   auto isLiteralZero = [](const Expr *E) {
9948     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9949   };
9950 
9951   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9952   SourceLocation CallLoc = Call->getRParenLoc();
9953   SourceManager &SM = S.getSourceManager();
9954   if (isLiteralZero(SizeArg) &&
9955       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9956 
9957     SourceLocation DiagLoc = SizeArg->getExprLoc();
9958 
9959     // Some platforms #define bzero to __builtin_memset. See if this is the
9960     // case, and if so, emit a better diagnostic.
9961     if (BId == Builtin::BIbzero ||
9962         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9963                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9964       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9965       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9966     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9967       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9968       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9969     }
9970     return;
9971   }
9972 
9973   // If the second argument to a memset is a sizeof expression and the third
9974   // isn't, this is also likely an error. This should catch
9975   // 'memset(buf, sizeof(buf), 0xff)'.
9976   if (BId == Builtin::BImemset &&
9977       doesExprLikelyComputeSize(Call->getArg(1)) &&
9978       !doesExprLikelyComputeSize(Call->getArg(2))) {
9979     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9980     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9981     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9982     return;
9983   }
9984 }
9985 
9986 /// Check for dangerous or invalid arguments to memset().
9987 ///
9988 /// This issues warnings on known problematic, dangerous or unspecified
9989 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9990 /// function calls.
9991 ///
9992 /// \param Call The call expression to diagnose.
9993 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9994                                    unsigned BId,
9995                                    IdentifierInfo *FnName) {
9996   assert(BId != 0);
9997 
9998   // It is possible to have a non-standard definition of memset.  Validate
9999   // we have enough arguments, and if not, abort further checking.
10000   unsigned ExpectedNumArgs =
10001       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10002   if (Call->getNumArgs() < ExpectedNumArgs)
10003     return;
10004 
10005   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10006                       BId == Builtin::BIstrndup ? 1 : 2);
10007   unsigned LenArg =
10008       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10009   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10010 
10011   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10012                                      Call->getBeginLoc(), Call->getRParenLoc()))
10013     return;
10014 
10015   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10016   CheckMemaccessSize(*this, BId, Call);
10017 
10018   // We have special checking when the length is a sizeof expression.
10019   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10020   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10021   llvm::FoldingSetNodeID SizeOfArgID;
10022 
10023   // Although widely used, 'bzero' is not a standard function. Be more strict
10024   // with the argument types before allowing diagnostics and only allow the
10025   // form bzero(ptr, sizeof(...)).
10026   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10027   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10028     return;
10029 
10030   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10031     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10032     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10033 
10034     QualType DestTy = Dest->getType();
10035     QualType PointeeTy;
10036     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10037       PointeeTy = DestPtrTy->getPointeeType();
10038 
10039       // Never warn about void type pointers. This can be used to suppress
10040       // false positives.
10041       if (PointeeTy->isVoidType())
10042         continue;
10043 
10044       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10045       // actually comparing the expressions for equality. Because computing the
10046       // expression IDs can be expensive, we only do this if the diagnostic is
10047       // enabled.
10048       if (SizeOfArg &&
10049           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10050                            SizeOfArg->getExprLoc())) {
10051         // We only compute IDs for expressions if the warning is enabled, and
10052         // cache the sizeof arg's ID.
10053         if (SizeOfArgID == llvm::FoldingSetNodeID())
10054           SizeOfArg->Profile(SizeOfArgID, Context, true);
10055         llvm::FoldingSetNodeID DestID;
10056         Dest->Profile(DestID, Context, true);
10057         if (DestID == SizeOfArgID) {
10058           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10059           //       over sizeof(src) as well.
10060           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10061           StringRef ReadableName = FnName->getName();
10062 
10063           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10064             if (UnaryOp->getOpcode() == UO_AddrOf)
10065               ActionIdx = 1; // If its an address-of operator, just remove it.
10066           if (!PointeeTy->isIncompleteType() &&
10067               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10068             ActionIdx = 2; // If the pointee's size is sizeof(char),
10069                            // suggest an explicit length.
10070 
10071           // If the function is defined as a builtin macro, do not show macro
10072           // expansion.
10073           SourceLocation SL = SizeOfArg->getExprLoc();
10074           SourceRange DSR = Dest->getSourceRange();
10075           SourceRange SSR = SizeOfArg->getSourceRange();
10076           SourceManager &SM = getSourceManager();
10077 
10078           if (SM.isMacroArgExpansion(SL)) {
10079             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10080             SL = SM.getSpellingLoc(SL);
10081             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10082                              SM.getSpellingLoc(DSR.getEnd()));
10083             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10084                              SM.getSpellingLoc(SSR.getEnd()));
10085           }
10086 
10087           DiagRuntimeBehavior(SL, SizeOfArg,
10088                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10089                                 << ReadableName
10090                                 << PointeeTy
10091                                 << DestTy
10092                                 << DSR
10093                                 << SSR);
10094           DiagRuntimeBehavior(SL, SizeOfArg,
10095                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10096                                 << ActionIdx
10097                                 << SSR);
10098 
10099           break;
10100         }
10101       }
10102 
10103       // Also check for cases where the sizeof argument is the exact same
10104       // type as the memory argument, and where it points to a user-defined
10105       // record type.
10106       if (SizeOfArgTy != QualType()) {
10107         if (PointeeTy->isRecordType() &&
10108             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10109           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10110                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10111                                 << FnName << SizeOfArgTy << ArgIdx
10112                                 << PointeeTy << Dest->getSourceRange()
10113                                 << LenExpr->getSourceRange());
10114           break;
10115         }
10116       }
10117     } else if (DestTy->isArrayType()) {
10118       PointeeTy = DestTy;
10119     }
10120 
10121     if (PointeeTy == QualType())
10122       continue;
10123 
10124     // Always complain about dynamic classes.
10125     bool IsContained;
10126     if (const CXXRecordDecl *ContainedRD =
10127             getContainedDynamicClass(PointeeTy, IsContained)) {
10128 
10129       unsigned OperationType = 0;
10130       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10131       // "overwritten" if we're warning about the destination for any call
10132       // but memcmp; otherwise a verb appropriate to the call.
10133       if (ArgIdx != 0 || IsCmp) {
10134         if (BId == Builtin::BImemcpy)
10135           OperationType = 1;
10136         else if(BId == Builtin::BImemmove)
10137           OperationType = 2;
10138         else if (IsCmp)
10139           OperationType = 3;
10140       }
10141 
10142       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10143                           PDiag(diag::warn_dyn_class_memaccess)
10144                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10145                               << IsContained << ContainedRD << OperationType
10146                               << Call->getCallee()->getSourceRange());
10147     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10148              BId != Builtin::BImemset)
10149       DiagRuntimeBehavior(
10150         Dest->getExprLoc(), Dest,
10151         PDiag(diag::warn_arc_object_memaccess)
10152           << ArgIdx << FnName << PointeeTy
10153           << Call->getCallee()->getSourceRange());
10154     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10155       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10156           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10157         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10158                             PDiag(diag::warn_cstruct_memaccess)
10159                                 << ArgIdx << FnName << PointeeTy << 0);
10160         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10161       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10162                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10163         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10164                             PDiag(diag::warn_cstruct_memaccess)
10165                                 << ArgIdx << FnName << PointeeTy << 1);
10166         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10167       } else {
10168         continue;
10169       }
10170     } else
10171       continue;
10172 
10173     DiagRuntimeBehavior(
10174       Dest->getExprLoc(), Dest,
10175       PDiag(diag::note_bad_memaccess_silence)
10176         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10177     break;
10178   }
10179 }
10180 
10181 // A little helper routine: ignore addition and subtraction of integer literals.
10182 // This intentionally does not ignore all integer constant expressions because
10183 // we don't want to remove sizeof().
10184 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10185   Ex = Ex->IgnoreParenCasts();
10186 
10187   while (true) {
10188     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10189     if (!BO || !BO->isAdditiveOp())
10190       break;
10191 
10192     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10193     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10194 
10195     if (isa<IntegerLiteral>(RHS))
10196       Ex = LHS;
10197     else if (isa<IntegerLiteral>(LHS))
10198       Ex = RHS;
10199     else
10200       break;
10201   }
10202 
10203   return Ex;
10204 }
10205 
10206 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10207                                                       ASTContext &Context) {
10208   // Only handle constant-sized or VLAs, but not flexible members.
10209   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10210     // Only issue the FIXIT for arrays of size > 1.
10211     if (CAT->getSize().getSExtValue() <= 1)
10212       return false;
10213   } else if (!Ty->isVariableArrayType()) {
10214     return false;
10215   }
10216   return true;
10217 }
10218 
10219 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10220 // be the size of the source, instead of the destination.
10221 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10222                                     IdentifierInfo *FnName) {
10223 
10224   // Don't crash if the user has the wrong number of arguments
10225   unsigned NumArgs = Call->getNumArgs();
10226   if ((NumArgs != 3) && (NumArgs != 4))
10227     return;
10228 
10229   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10230   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10231   const Expr *CompareWithSrc = nullptr;
10232 
10233   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10234                                      Call->getBeginLoc(), Call->getRParenLoc()))
10235     return;
10236 
10237   // Look for 'strlcpy(dst, x, sizeof(x))'
10238   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10239     CompareWithSrc = Ex;
10240   else {
10241     // Look for 'strlcpy(dst, x, strlen(x))'
10242     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10243       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10244           SizeCall->getNumArgs() == 1)
10245         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10246     }
10247   }
10248 
10249   if (!CompareWithSrc)
10250     return;
10251 
10252   // Determine if the argument to sizeof/strlen is equal to the source
10253   // argument.  In principle there's all kinds of things you could do
10254   // here, for instance creating an == expression and evaluating it with
10255   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10256   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10257   if (!SrcArgDRE)
10258     return;
10259 
10260   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10261   if (!CompareWithSrcDRE ||
10262       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10263     return;
10264 
10265   const Expr *OriginalSizeArg = Call->getArg(2);
10266   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10267       << OriginalSizeArg->getSourceRange() << FnName;
10268 
10269   // Output a FIXIT hint if the destination is an array (rather than a
10270   // pointer to an array).  This could be enhanced to handle some
10271   // pointers if we know the actual size, like if DstArg is 'array+2'
10272   // we could say 'sizeof(array)-2'.
10273   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10274   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10275     return;
10276 
10277   SmallString<128> sizeString;
10278   llvm::raw_svector_ostream OS(sizeString);
10279   OS << "sizeof(";
10280   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10281   OS << ")";
10282 
10283   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10284       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10285                                       OS.str());
10286 }
10287 
10288 /// Check if two expressions refer to the same declaration.
10289 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10290   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10291     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10292       return D1->getDecl() == D2->getDecl();
10293   return false;
10294 }
10295 
10296 static const Expr *getStrlenExprArg(const Expr *E) {
10297   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10298     const FunctionDecl *FD = CE->getDirectCallee();
10299     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10300       return nullptr;
10301     return CE->getArg(0)->IgnoreParenCasts();
10302   }
10303   return nullptr;
10304 }
10305 
10306 // Warn on anti-patterns as the 'size' argument to strncat.
10307 // The correct size argument should look like following:
10308 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10309 void Sema::CheckStrncatArguments(const CallExpr *CE,
10310                                  IdentifierInfo *FnName) {
10311   // Don't crash if the user has the wrong number of arguments.
10312   if (CE->getNumArgs() < 3)
10313     return;
10314   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10315   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10316   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10317 
10318   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10319                                      CE->getRParenLoc()))
10320     return;
10321 
10322   // Identify common expressions, which are wrongly used as the size argument
10323   // to strncat and may lead to buffer overflows.
10324   unsigned PatternType = 0;
10325   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10326     // - sizeof(dst)
10327     if (referToTheSameDecl(SizeOfArg, DstArg))
10328       PatternType = 1;
10329     // - sizeof(src)
10330     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10331       PatternType = 2;
10332   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10333     if (BE->getOpcode() == BO_Sub) {
10334       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10335       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10336       // - sizeof(dst) - strlen(dst)
10337       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10338           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10339         PatternType = 1;
10340       // - sizeof(src) - (anything)
10341       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10342         PatternType = 2;
10343     }
10344   }
10345 
10346   if (PatternType == 0)
10347     return;
10348 
10349   // Generate the diagnostic.
10350   SourceLocation SL = LenArg->getBeginLoc();
10351   SourceRange SR = LenArg->getSourceRange();
10352   SourceManager &SM = getSourceManager();
10353 
10354   // If the function is defined as a builtin macro, do not show macro expansion.
10355   if (SM.isMacroArgExpansion(SL)) {
10356     SL = SM.getSpellingLoc(SL);
10357     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10358                      SM.getSpellingLoc(SR.getEnd()));
10359   }
10360 
10361   // Check if the destination is an array (rather than a pointer to an array).
10362   QualType DstTy = DstArg->getType();
10363   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10364                                                                     Context);
10365   if (!isKnownSizeArray) {
10366     if (PatternType == 1)
10367       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10368     else
10369       Diag(SL, diag::warn_strncat_src_size) << SR;
10370     return;
10371   }
10372 
10373   if (PatternType == 1)
10374     Diag(SL, diag::warn_strncat_large_size) << SR;
10375   else
10376     Diag(SL, diag::warn_strncat_src_size) << SR;
10377 
10378   SmallString<128> sizeString;
10379   llvm::raw_svector_ostream OS(sizeString);
10380   OS << "sizeof(";
10381   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10382   OS << ") - ";
10383   OS << "strlen(";
10384   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10385   OS << ") - 1";
10386 
10387   Diag(SL, diag::note_strncat_wrong_size)
10388     << FixItHint::CreateReplacement(SR, OS.str());
10389 }
10390 
10391 namespace {
10392 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10393                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10394   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10395     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10396         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10397     return;
10398   }
10399 }
10400 
10401 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10402                                  const UnaryOperator *UnaryExpr) {
10403   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10404     const Decl *D = Lvalue->getDecl();
10405     if (isa<VarDecl, FunctionDecl>(D))
10406       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10407   }
10408 
10409   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10410     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10411                                       Lvalue->getMemberDecl());
10412 }
10413 
10414 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10415                             const UnaryOperator *UnaryExpr) {
10416   const auto *Lambda = dyn_cast<LambdaExpr>(
10417       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10418   if (!Lambda)
10419     return;
10420 
10421   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10422       << CalleeName << 2 /*object: lambda expression*/;
10423 }
10424 
10425 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10426                                   const DeclRefExpr *Lvalue) {
10427   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10428   if (Var == nullptr)
10429     return;
10430 
10431   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10432       << CalleeName << 0 /*object: */ << Var;
10433 }
10434 
10435 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10436                             const CastExpr *Cast) {
10437   SmallString<128> SizeString;
10438   llvm::raw_svector_ostream OS(SizeString);
10439 
10440   clang::CastKind Kind = Cast->getCastKind();
10441   if (Kind == clang::CK_BitCast &&
10442       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10443     return;
10444   if (Kind == clang::CK_IntegralToPointer &&
10445       !isa<IntegerLiteral>(
10446           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10447     return;
10448 
10449   switch (Cast->getCastKind()) {
10450   case clang::CK_BitCast:
10451   case clang::CK_IntegralToPointer:
10452   case clang::CK_FunctionToPointerDecay:
10453     OS << '\'';
10454     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10455     OS << '\'';
10456     break;
10457   default:
10458     return;
10459   }
10460 
10461   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10462       << CalleeName << 0 /*object: */ << OS.str();
10463 }
10464 } // namespace
10465 
10466 /// Alerts the user that they are attempting to free a non-malloc'd object.
10467 void Sema::CheckFreeArguments(const CallExpr *E) {
10468   const std::string CalleeName =
10469       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10470 
10471   { // Prefer something that doesn't involve a cast to make things simpler.
10472     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10473     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10474       switch (UnaryExpr->getOpcode()) {
10475       case UnaryOperator::Opcode::UO_AddrOf:
10476         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10477       case UnaryOperator::Opcode::UO_Plus:
10478         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10479       default:
10480         break;
10481       }
10482 
10483     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10484       if (Lvalue->getType()->isArrayType())
10485         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10486 
10487     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10488       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10489           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10490       return;
10491     }
10492 
10493     if (isa<BlockExpr>(Arg)) {
10494       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10495           << CalleeName << 1 /*object: block*/;
10496       return;
10497     }
10498   }
10499   // Maybe the cast was important, check after the other cases.
10500   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10501     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10502 }
10503 
10504 void
10505 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10506                          SourceLocation ReturnLoc,
10507                          bool isObjCMethod,
10508                          const AttrVec *Attrs,
10509                          const FunctionDecl *FD) {
10510   // Check if the return value is null but should not be.
10511   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10512        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10513       CheckNonNullExpr(*this, RetValExp))
10514     Diag(ReturnLoc, diag::warn_null_ret)
10515       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10516 
10517   // C++11 [basic.stc.dynamic.allocation]p4:
10518   //   If an allocation function declared with a non-throwing
10519   //   exception-specification fails to allocate storage, it shall return
10520   //   a null pointer. Any other allocation function that fails to allocate
10521   //   storage shall indicate failure only by throwing an exception [...]
10522   if (FD) {
10523     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10524     if (Op == OO_New || Op == OO_Array_New) {
10525       const FunctionProtoType *Proto
10526         = FD->getType()->castAs<FunctionProtoType>();
10527       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10528           CheckNonNullExpr(*this, RetValExp))
10529         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10530           << FD << getLangOpts().CPlusPlus11;
10531     }
10532   }
10533 
10534   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10535   // here prevent the user from using a PPC MMA type as trailing return type.
10536   if (Context.getTargetInfo().getTriple().isPPC64())
10537     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10538 }
10539 
10540 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10541 
10542 /// Check for comparisons of floating point operands using != and ==.
10543 /// Issue a warning if these are no self-comparisons, as they are not likely
10544 /// to do what the programmer intended.
10545 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10546   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10547   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10548 
10549   // Special case: check for x == x (which is OK).
10550   // Do not emit warnings for such cases.
10551   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10552     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10553       if (DRL->getDecl() == DRR->getDecl())
10554         return;
10555 
10556   // Special case: check for comparisons against literals that can be exactly
10557   //  represented by APFloat.  In such cases, do not emit a warning.  This
10558   //  is a heuristic: often comparison against such literals are used to
10559   //  detect if a value in a variable has not changed.  This clearly can
10560   //  lead to false negatives.
10561   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10562     if (FLL->isExact())
10563       return;
10564   } else
10565     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10566       if (FLR->isExact())
10567         return;
10568 
10569   // Check for comparisons with builtin types.
10570   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10571     if (CL->getBuiltinCallee())
10572       return;
10573 
10574   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10575     if (CR->getBuiltinCallee())
10576       return;
10577 
10578   // Emit the diagnostic.
10579   Diag(Loc, diag::warn_floatingpoint_eq)
10580     << LHS->getSourceRange() << RHS->getSourceRange();
10581 }
10582 
10583 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10584 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10585 
10586 namespace {
10587 
10588 /// Structure recording the 'active' range of an integer-valued
10589 /// expression.
10590 struct IntRange {
10591   /// The number of bits active in the int. Note that this includes exactly one
10592   /// sign bit if !NonNegative.
10593   unsigned Width;
10594 
10595   /// True if the int is known not to have negative values. If so, all leading
10596   /// bits before Width are known zero, otherwise they are known to be the
10597   /// same as the MSB within Width.
10598   bool NonNegative;
10599 
10600   IntRange(unsigned Width, bool NonNegative)
10601       : Width(Width), NonNegative(NonNegative) {}
10602 
10603   /// Number of bits excluding the sign bit.
10604   unsigned valueBits() const {
10605     return NonNegative ? Width : Width - 1;
10606   }
10607 
10608   /// Returns the range of the bool type.
10609   static IntRange forBoolType() {
10610     return IntRange(1, true);
10611   }
10612 
10613   /// Returns the range of an opaque value of the given integral type.
10614   static IntRange forValueOfType(ASTContext &C, QualType T) {
10615     return forValueOfCanonicalType(C,
10616                           T->getCanonicalTypeInternal().getTypePtr());
10617   }
10618 
10619   /// Returns the range of an opaque value of a canonical integral type.
10620   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10621     assert(T->isCanonicalUnqualified());
10622 
10623     if (const VectorType *VT = dyn_cast<VectorType>(T))
10624       T = VT->getElementType().getTypePtr();
10625     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10626       T = CT->getElementType().getTypePtr();
10627     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10628       T = AT->getValueType().getTypePtr();
10629 
10630     if (!C.getLangOpts().CPlusPlus) {
10631       // For enum types in C code, use the underlying datatype.
10632       if (const EnumType *ET = dyn_cast<EnumType>(T))
10633         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10634     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10635       // For enum types in C++, use the known bit width of the enumerators.
10636       EnumDecl *Enum = ET->getDecl();
10637       // In C++11, enums can have a fixed underlying type. Use this type to
10638       // compute the range.
10639       if (Enum->isFixed()) {
10640         return IntRange(C.getIntWidth(QualType(T, 0)),
10641                         !ET->isSignedIntegerOrEnumerationType());
10642       }
10643 
10644       unsigned NumPositive = Enum->getNumPositiveBits();
10645       unsigned NumNegative = Enum->getNumNegativeBits();
10646 
10647       if (NumNegative == 0)
10648         return IntRange(NumPositive, true/*NonNegative*/);
10649       else
10650         return IntRange(std::max(NumPositive + 1, NumNegative),
10651                         false/*NonNegative*/);
10652     }
10653 
10654     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10655       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10656 
10657     const BuiltinType *BT = cast<BuiltinType>(T);
10658     assert(BT->isInteger());
10659 
10660     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10661   }
10662 
10663   /// Returns the "target" range of a canonical integral type, i.e.
10664   /// the range of values expressible in the type.
10665   ///
10666   /// This matches forValueOfCanonicalType except that enums have the
10667   /// full range of their type, not the range of their enumerators.
10668   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10669     assert(T->isCanonicalUnqualified());
10670 
10671     if (const VectorType *VT = dyn_cast<VectorType>(T))
10672       T = VT->getElementType().getTypePtr();
10673     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10674       T = CT->getElementType().getTypePtr();
10675     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10676       T = AT->getValueType().getTypePtr();
10677     if (const EnumType *ET = dyn_cast<EnumType>(T))
10678       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10679 
10680     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10681       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10682 
10683     const BuiltinType *BT = cast<BuiltinType>(T);
10684     assert(BT->isInteger());
10685 
10686     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10687   }
10688 
10689   /// Returns the supremum of two ranges: i.e. their conservative merge.
10690   static IntRange join(IntRange L, IntRange R) {
10691     bool Unsigned = L.NonNegative && R.NonNegative;
10692     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10693                     L.NonNegative && R.NonNegative);
10694   }
10695 
10696   /// Return the range of a bitwise-AND of the two ranges.
10697   static IntRange bit_and(IntRange L, IntRange R) {
10698     unsigned Bits = std::max(L.Width, R.Width);
10699     bool NonNegative = false;
10700     if (L.NonNegative) {
10701       Bits = std::min(Bits, L.Width);
10702       NonNegative = true;
10703     }
10704     if (R.NonNegative) {
10705       Bits = std::min(Bits, R.Width);
10706       NonNegative = true;
10707     }
10708     return IntRange(Bits, NonNegative);
10709   }
10710 
10711   /// Return the range of a sum of the two ranges.
10712   static IntRange sum(IntRange L, IntRange R) {
10713     bool Unsigned = L.NonNegative && R.NonNegative;
10714     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10715                     Unsigned);
10716   }
10717 
10718   /// Return the range of a difference of the two ranges.
10719   static IntRange difference(IntRange L, IntRange R) {
10720     // We need a 1-bit-wider range if:
10721     //   1) LHS can be negative: least value can be reduced.
10722     //   2) RHS can be negative: greatest value can be increased.
10723     bool CanWiden = !L.NonNegative || !R.NonNegative;
10724     bool Unsigned = L.NonNegative && R.Width == 0;
10725     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10726                         !Unsigned,
10727                     Unsigned);
10728   }
10729 
10730   /// Return the range of a product of the two ranges.
10731   static IntRange product(IntRange L, IntRange R) {
10732     // If both LHS and RHS can be negative, we can form
10733     //   -2^L * -2^R = 2^(L + R)
10734     // which requires L + R + 1 value bits to represent.
10735     bool CanWiden = !L.NonNegative && !R.NonNegative;
10736     bool Unsigned = L.NonNegative && R.NonNegative;
10737     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10738                     Unsigned);
10739   }
10740 
10741   /// Return the range of a remainder operation between the two ranges.
10742   static IntRange rem(IntRange L, IntRange R) {
10743     // The result of a remainder can't be larger than the result of
10744     // either side. The sign of the result is the sign of the LHS.
10745     bool Unsigned = L.NonNegative;
10746     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10747                     Unsigned);
10748   }
10749 };
10750 
10751 } // namespace
10752 
10753 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10754                               unsigned MaxWidth) {
10755   if (value.isSigned() && value.isNegative())
10756     return IntRange(value.getMinSignedBits(), false);
10757 
10758   if (value.getBitWidth() > MaxWidth)
10759     value = value.trunc(MaxWidth);
10760 
10761   // isNonNegative() just checks the sign bit without considering
10762   // signedness.
10763   return IntRange(value.getActiveBits(), true);
10764 }
10765 
10766 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10767                               unsigned MaxWidth) {
10768   if (result.isInt())
10769     return GetValueRange(C, result.getInt(), MaxWidth);
10770 
10771   if (result.isVector()) {
10772     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10773     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10774       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10775       R = IntRange::join(R, El);
10776     }
10777     return R;
10778   }
10779 
10780   if (result.isComplexInt()) {
10781     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10782     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10783     return IntRange::join(R, I);
10784   }
10785 
10786   // This can happen with lossless casts to intptr_t of "based" lvalues.
10787   // Assume it might use arbitrary bits.
10788   // FIXME: The only reason we need to pass the type in here is to get
10789   // the sign right on this one case.  It would be nice if APValue
10790   // preserved this.
10791   assert(result.isLValue() || result.isAddrLabelDiff());
10792   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10793 }
10794 
10795 static QualType GetExprType(const Expr *E) {
10796   QualType Ty = E->getType();
10797   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10798     Ty = AtomicRHS->getValueType();
10799   return Ty;
10800 }
10801 
10802 /// Pseudo-evaluate the given integer expression, estimating the
10803 /// range of values it might take.
10804 ///
10805 /// \param MaxWidth The width to which the value will be truncated.
10806 /// \param Approximate If \c true, return a likely range for the result: in
10807 ///        particular, assume that aritmetic on narrower types doesn't leave
10808 ///        those types. If \c false, return a range including all possible
10809 ///        result values.
10810 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10811                              bool InConstantContext, bool Approximate) {
10812   E = E->IgnoreParens();
10813 
10814   // Try a full evaluation first.
10815   Expr::EvalResult result;
10816   if (E->EvaluateAsRValue(result, C, InConstantContext))
10817     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10818 
10819   // I think we only want to look through implicit casts here; if the
10820   // user has an explicit widening cast, we should treat the value as
10821   // being of the new, wider type.
10822   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10823     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10824       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10825                           Approximate);
10826 
10827     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10828 
10829     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10830                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10831 
10832     // Assume that non-integer casts can span the full range of the type.
10833     if (!isIntegerCast)
10834       return OutputTypeRange;
10835 
10836     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10837                                      std::min(MaxWidth, OutputTypeRange.Width),
10838                                      InConstantContext, Approximate);
10839 
10840     // Bail out if the subexpr's range is as wide as the cast type.
10841     if (SubRange.Width >= OutputTypeRange.Width)
10842       return OutputTypeRange;
10843 
10844     // Otherwise, we take the smaller width, and we're non-negative if
10845     // either the output type or the subexpr is.
10846     return IntRange(SubRange.Width,
10847                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10848   }
10849 
10850   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10851     // If we can fold the condition, just take that operand.
10852     bool CondResult;
10853     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10854       return GetExprRange(C,
10855                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10856                           MaxWidth, InConstantContext, Approximate);
10857 
10858     // Otherwise, conservatively merge.
10859     // GetExprRange requires an integer expression, but a throw expression
10860     // results in a void type.
10861     Expr *E = CO->getTrueExpr();
10862     IntRange L = E->getType()->isVoidType()
10863                      ? IntRange{0, true}
10864                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10865     E = CO->getFalseExpr();
10866     IntRange R = E->getType()->isVoidType()
10867                      ? IntRange{0, true}
10868                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10869     return IntRange::join(L, R);
10870   }
10871 
10872   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10873     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10874 
10875     switch (BO->getOpcode()) {
10876     case BO_Cmp:
10877       llvm_unreachable("builtin <=> should have class type");
10878 
10879     // Boolean-valued operations are single-bit and positive.
10880     case BO_LAnd:
10881     case BO_LOr:
10882     case BO_LT:
10883     case BO_GT:
10884     case BO_LE:
10885     case BO_GE:
10886     case BO_EQ:
10887     case BO_NE:
10888       return IntRange::forBoolType();
10889 
10890     // The type of the assignments is the type of the LHS, so the RHS
10891     // is not necessarily the same type.
10892     case BO_MulAssign:
10893     case BO_DivAssign:
10894     case BO_RemAssign:
10895     case BO_AddAssign:
10896     case BO_SubAssign:
10897     case BO_XorAssign:
10898     case BO_OrAssign:
10899       // TODO: bitfields?
10900       return IntRange::forValueOfType(C, GetExprType(E));
10901 
10902     // Simple assignments just pass through the RHS, which will have
10903     // been coerced to the LHS type.
10904     case BO_Assign:
10905       // TODO: bitfields?
10906       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10907                           Approximate);
10908 
10909     // Operations with opaque sources are black-listed.
10910     case BO_PtrMemD:
10911     case BO_PtrMemI:
10912       return IntRange::forValueOfType(C, GetExprType(E));
10913 
10914     // Bitwise-and uses the *infinum* of the two source ranges.
10915     case BO_And:
10916     case BO_AndAssign:
10917       Combine = IntRange::bit_and;
10918       break;
10919 
10920     // Left shift gets black-listed based on a judgement call.
10921     case BO_Shl:
10922       // ...except that we want to treat '1 << (blah)' as logically
10923       // positive.  It's an important idiom.
10924       if (IntegerLiteral *I
10925             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10926         if (I->getValue() == 1) {
10927           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10928           return IntRange(R.Width, /*NonNegative*/ true);
10929         }
10930       }
10931       LLVM_FALLTHROUGH;
10932 
10933     case BO_ShlAssign:
10934       return IntRange::forValueOfType(C, GetExprType(E));
10935 
10936     // Right shift by a constant can narrow its left argument.
10937     case BO_Shr:
10938     case BO_ShrAssign: {
10939       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10940                                 Approximate);
10941 
10942       // If the shift amount is a positive constant, drop the width by
10943       // that much.
10944       if (Optional<llvm::APSInt> shift =
10945               BO->getRHS()->getIntegerConstantExpr(C)) {
10946         if (shift->isNonNegative()) {
10947           unsigned zext = shift->getZExtValue();
10948           if (zext >= L.Width)
10949             L.Width = (L.NonNegative ? 0 : 1);
10950           else
10951             L.Width -= zext;
10952         }
10953       }
10954 
10955       return L;
10956     }
10957 
10958     // Comma acts as its right operand.
10959     case BO_Comma:
10960       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10961                           Approximate);
10962 
10963     case BO_Add:
10964       if (!Approximate)
10965         Combine = IntRange::sum;
10966       break;
10967 
10968     case BO_Sub:
10969       if (BO->getLHS()->getType()->isPointerType())
10970         return IntRange::forValueOfType(C, GetExprType(E));
10971       if (!Approximate)
10972         Combine = IntRange::difference;
10973       break;
10974 
10975     case BO_Mul:
10976       if (!Approximate)
10977         Combine = IntRange::product;
10978       break;
10979 
10980     // The width of a division result is mostly determined by the size
10981     // of the LHS.
10982     case BO_Div: {
10983       // Don't 'pre-truncate' the operands.
10984       unsigned opWidth = C.getIntWidth(GetExprType(E));
10985       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10986                                 Approximate);
10987 
10988       // If the divisor is constant, use that.
10989       if (Optional<llvm::APSInt> divisor =
10990               BO->getRHS()->getIntegerConstantExpr(C)) {
10991         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10992         if (log2 >= L.Width)
10993           L.Width = (L.NonNegative ? 0 : 1);
10994         else
10995           L.Width = std::min(L.Width - log2, MaxWidth);
10996         return L;
10997       }
10998 
10999       // Otherwise, just use the LHS's width.
11000       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11001       // could be -1.
11002       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11003                                 Approximate);
11004       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11005     }
11006 
11007     case BO_Rem:
11008       Combine = IntRange::rem;
11009       break;
11010 
11011     // The default behavior is okay for these.
11012     case BO_Xor:
11013     case BO_Or:
11014       break;
11015     }
11016 
11017     // Combine the two ranges, but limit the result to the type in which we
11018     // performed the computation.
11019     QualType T = GetExprType(E);
11020     unsigned opWidth = C.getIntWidth(T);
11021     IntRange L =
11022         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11023     IntRange R =
11024         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11025     IntRange C = Combine(L, R);
11026     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11027     C.Width = std::min(C.Width, MaxWidth);
11028     return C;
11029   }
11030 
11031   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11032     switch (UO->getOpcode()) {
11033     // Boolean-valued operations are white-listed.
11034     case UO_LNot:
11035       return IntRange::forBoolType();
11036 
11037     // Operations with opaque sources are black-listed.
11038     case UO_Deref:
11039     case UO_AddrOf: // should be impossible
11040       return IntRange::forValueOfType(C, GetExprType(E));
11041 
11042     default:
11043       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11044                           Approximate);
11045     }
11046   }
11047 
11048   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11049     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11050                         Approximate);
11051 
11052   if (const auto *BitField = E->getSourceBitField())
11053     return IntRange(BitField->getBitWidthValue(C),
11054                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11055 
11056   return IntRange::forValueOfType(C, GetExprType(E));
11057 }
11058 
11059 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11060                              bool InConstantContext, bool Approximate) {
11061   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11062                       Approximate);
11063 }
11064 
11065 /// Checks whether the given value, which currently has the given
11066 /// source semantics, has the same value when coerced through the
11067 /// target semantics.
11068 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11069                                  const llvm::fltSemantics &Src,
11070                                  const llvm::fltSemantics &Tgt) {
11071   llvm::APFloat truncated = value;
11072 
11073   bool ignored;
11074   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11075   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11076 
11077   return truncated.bitwiseIsEqual(value);
11078 }
11079 
11080 /// Checks whether the given value, which currently has the given
11081 /// source semantics, has the same value when coerced through the
11082 /// target semantics.
11083 ///
11084 /// The value might be a vector of floats (or a complex number).
11085 static bool IsSameFloatAfterCast(const APValue &value,
11086                                  const llvm::fltSemantics &Src,
11087                                  const llvm::fltSemantics &Tgt) {
11088   if (value.isFloat())
11089     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11090 
11091   if (value.isVector()) {
11092     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11093       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11094         return false;
11095     return true;
11096   }
11097 
11098   assert(value.isComplexFloat());
11099   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11100           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11101 }
11102 
11103 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11104                                        bool IsListInit = false);
11105 
11106 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11107   // Suppress cases where we are comparing against an enum constant.
11108   if (const DeclRefExpr *DR =
11109       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11110     if (isa<EnumConstantDecl>(DR->getDecl()))
11111       return true;
11112 
11113   // Suppress cases where the value is expanded from a macro, unless that macro
11114   // is how a language represents a boolean literal. This is the case in both C
11115   // and Objective-C.
11116   SourceLocation BeginLoc = E->getBeginLoc();
11117   if (BeginLoc.isMacroID()) {
11118     StringRef MacroName = Lexer::getImmediateMacroName(
11119         BeginLoc, S.getSourceManager(), S.getLangOpts());
11120     return MacroName != "YES" && MacroName != "NO" &&
11121            MacroName != "true" && MacroName != "false";
11122   }
11123 
11124   return false;
11125 }
11126 
11127 static bool isKnownToHaveUnsignedValue(Expr *E) {
11128   return E->getType()->isIntegerType() &&
11129          (!E->getType()->isSignedIntegerType() ||
11130           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11131 }
11132 
11133 namespace {
11134 /// The promoted range of values of a type. In general this has the
11135 /// following structure:
11136 ///
11137 ///     |-----------| . . . |-----------|
11138 ///     ^           ^       ^           ^
11139 ///    Min       HoleMin  HoleMax      Max
11140 ///
11141 /// ... where there is only a hole if a signed type is promoted to unsigned
11142 /// (in which case Min and Max are the smallest and largest representable
11143 /// values).
11144 struct PromotedRange {
11145   // Min, or HoleMax if there is a hole.
11146   llvm::APSInt PromotedMin;
11147   // Max, or HoleMin if there is a hole.
11148   llvm::APSInt PromotedMax;
11149 
11150   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11151     if (R.Width == 0)
11152       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11153     else if (R.Width >= BitWidth && !Unsigned) {
11154       // Promotion made the type *narrower*. This happens when promoting
11155       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11156       // Treat all values of 'signed int' as being in range for now.
11157       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11158       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11159     } else {
11160       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11161                         .extOrTrunc(BitWidth);
11162       PromotedMin.setIsUnsigned(Unsigned);
11163 
11164       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11165                         .extOrTrunc(BitWidth);
11166       PromotedMax.setIsUnsigned(Unsigned);
11167     }
11168   }
11169 
11170   // Determine whether this range is contiguous (has no hole).
11171   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11172 
11173   // Where a constant value is within the range.
11174   enum ComparisonResult {
11175     LT = 0x1,
11176     LE = 0x2,
11177     GT = 0x4,
11178     GE = 0x8,
11179     EQ = 0x10,
11180     NE = 0x20,
11181     InRangeFlag = 0x40,
11182 
11183     Less = LE | LT | NE,
11184     Min = LE | InRangeFlag,
11185     InRange = InRangeFlag,
11186     Max = GE | InRangeFlag,
11187     Greater = GE | GT | NE,
11188 
11189     OnlyValue = LE | GE | EQ | InRangeFlag,
11190     InHole = NE
11191   };
11192 
11193   ComparisonResult compare(const llvm::APSInt &Value) const {
11194     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11195            Value.isUnsigned() == PromotedMin.isUnsigned());
11196     if (!isContiguous()) {
11197       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11198       if (Value.isMinValue()) return Min;
11199       if (Value.isMaxValue()) return Max;
11200       if (Value >= PromotedMin) return InRange;
11201       if (Value <= PromotedMax) return InRange;
11202       return InHole;
11203     }
11204 
11205     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11206     case -1: return Less;
11207     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11208     case 1:
11209       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11210       case -1: return InRange;
11211       case 0: return Max;
11212       case 1: return Greater;
11213       }
11214     }
11215 
11216     llvm_unreachable("impossible compare result");
11217   }
11218 
11219   static llvm::Optional<StringRef>
11220   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11221     if (Op == BO_Cmp) {
11222       ComparisonResult LTFlag = LT, GTFlag = GT;
11223       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11224 
11225       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11226       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11227       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11228       return llvm::None;
11229     }
11230 
11231     ComparisonResult TrueFlag, FalseFlag;
11232     if (Op == BO_EQ) {
11233       TrueFlag = EQ;
11234       FalseFlag = NE;
11235     } else if (Op == BO_NE) {
11236       TrueFlag = NE;
11237       FalseFlag = EQ;
11238     } else {
11239       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11240         TrueFlag = LT;
11241         FalseFlag = GE;
11242       } else {
11243         TrueFlag = GT;
11244         FalseFlag = LE;
11245       }
11246       if (Op == BO_GE || Op == BO_LE)
11247         std::swap(TrueFlag, FalseFlag);
11248     }
11249     if (R & TrueFlag)
11250       return StringRef("true");
11251     if (R & FalseFlag)
11252       return StringRef("false");
11253     return llvm::None;
11254   }
11255 };
11256 }
11257 
11258 static bool HasEnumType(Expr *E) {
11259   // Strip off implicit integral promotions.
11260   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11261     if (ICE->getCastKind() != CK_IntegralCast &&
11262         ICE->getCastKind() != CK_NoOp)
11263       break;
11264     E = ICE->getSubExpr();
11265   }
11266 
11267   return E->getType()->isEnumeralType();
11268 }
11269 
11270 static int classifyConstantValue(Expr *Constant) {
11271   // The values of this enumeration are used in the diagnostics
11272   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11273   enum ConstantValueKind {
11274     Miscellaneous = 0,
11275     LiteralTrue,
11276     LiteralFalse
11277   };
11278   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11279     return BL->getValue() ? ConstantValueKind::LiteralTrue
11280                           : ConstantValueKind::LiteralFalse;
11281   return ConstantValueKind::Miscellaneous;
11282 }
11283 
11284 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11285                                         Expr *Constant, Expr *Other,
11286                                         const llvm::APSInt &Value,
11287                                         bool RhsConstant) {
11288   if (S.inTemplateInstantiation())
11289     return false;
11290 
11291   Expr *OriginalOther = Other;
11292 
11293   Constant = Constant->IgnoreParenImpCasts();
11294   Other = Other->IgnoreParenImpCasts();
11295 
11296   // Suppress warnings on tautological comparisons between values of the same
11297   // enumeration type. There are only two ways we could warn on this:
11298   //  - If the constant is outside the range of representable values of
11299   //    the enumeration. In such a case, we should warn about the cast
11300   //    to enumeration type, not about the comparison.
11301   //  - If the constant is the maximum / minimum in-range value. For an
11302   //    enumeratin type, such comparisons can be meaningful and useful.
11303   if (Constant->getType()->isEnumeralType() &&
11304       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11305     return false;
11306 
11307   IntRange OtherValueRange = GetExprRange(
11308       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11309 
11310   QualType OtherT = Other->getType();
11311   if (const auto *AT = OtherT->getAs<AtomicType>())
11312     OtherT = AT->getValueType();
11313   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11314 
11315   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11316   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11317   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11318                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11319                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11320 
11321   // Whether we're treating Other as being a bool because of the form of
11322   // expression despite it having another type (typically 'int' in C).
11323   bool OtherIsBooleanDespiteType =
11324       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11325   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11326     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11327 
11328   // Check if all values in the range of possible values of this expression
11329   // lead to the same comparison outcome.
11330   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11331                                         Value.isUnsigned());
11332   auto Cmp = OtherPromotedValueRange.compare(Value);
11333   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11334   if (!Result)
11335     return false;
11336 
11337   // Also consider the range determined by the type alone. This allows us to
11338   // classify the warning under the proper diagnostic group.
11339   bool TautologicalTypeCompare = false;
11340   {
11341     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11342                                          Value.isUnsigned());
11343     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11344     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11345                                                        RhsConstant)) {
11346       TautologicalTypeCompare = true;
11347       Cmp = TypeCmp;
11348       Result = TypeResult;
11349     }
11350   }
11351 
11352   // Don't warn if the non-constant operand actually always evaluates to the
11353   // same value.
11354   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11355     return false;
11356 
11357   // Suppress the diagnostic for an in-range comparison if the constant comes
11358   // from a macro or enumerator. We don't want to diagnose
11359   //
11360   //   some_long_value <= INT_MAX
11361   //
11362   // when sizeof(int) == sizeof(long).
11363   bool InRange = Cmp & PromotedRange::InRangeFlag;
11364   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11365     return false;
11366 
11367   // A comparison of an unsigned bit-field against 0 is really a type problem,
11368   // even though at the type level the bit-field might promote to 'signed int'.
11369   if (Other->refersToBitField() && InRange && Value == 0 &&
11370       Other->getType()->isUnsignedIntegerOrEnumerationType())
11371     TautologicalTypeCompare = true;
11372 
11373   // If this is a comparison to an enum constant, include that
11374   // constant in the diagnostic.
11375   const EnumConstantDecl *ED = nullptr;
11376   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11377     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11378 
11379   // Should be enough for uint128 (39 decimal digits)
11380   SmallString<64> PrettySourceValue;
11381   llvm::raw_svector_ostream OS(PrettySourceValue);
11382   if (ED) {
11383     OS << '\'' << *ED << "' (" << Value << ")";
11384   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11385                Constant->IgnoreParenImpCasts())) {
11386     OS << (BL->getValue() ? "YES" : "NO");
11387   } else {
11388     OS << Value;
11389   }
11390 
11391   if (!TautologicalTypeCompare) {
11392     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11393         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11394         << E->getOpcodeStr() << OS.str() << *Result
11395         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11396     return true;
11397   }
11398 
11399   if (IsObjCSignedCharBool) {
11400     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11401                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11402                               << OS.str() << *Result);
11403     return true;
11404   }
11405 
11406   // FIXME: We use a somewhat different formatting for the in-range cases and
11407   // cases involving boolean values for historical reasons. We should pick a
11408   // consistent way of presenting these diagnostics.
11409   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11410 
11411     S.DiagRuntimeBehavior(
11412         E->getOperatorLoc(), E,
11413         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11414                          : diag::warn_tautological_bool_compare)
11415             << OS.str() << classifyConstantValue(Constant) << OtherT
11416             << OtherIsBooleanDespiteType << *Result
11417             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11418   } else {
11419     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11420                         ? (HasEnumType(OriginalOther)
11421                                ? diag::warn_unsigned_enum_always_true_comparison
11422                                : diag::warn_unsigned_always_true_comparison)
11423                         : diag::warn_tautological_constant_compare;
11424 
11425     S.Diag(E->getOperatorLoc(), Diag)
11426         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11427         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11428   }
11429 
11430   return true;
11431 }
11432 
11433 /// Analyze the operands of the given comparison.  Implements the
11434 /// fallback case from AnalyzeComparison.
11435 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11436   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11437   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11438 }
11439 
11440 /// Implements -Wsign-compare.
11441 ///
11442 /// \param E the binary operator to check for warnings
11443 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11444   // The type the comparison is being performed in.
11445   QualType T = E->getLHS()->getType();
11446 
11447   // Only analyze comparison operators where both sides have been converted to
11448   // the same type.
11449   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11450     return AnalyzeImpConvsInComparison(S, E);
11451 
11452   // Don't analyze value-dependent comparisons directly.
11453   if (E->isValueDependent())
11454     return AnalyzeImpConvsInComparison(S, E);
11455 
11456   Expr *LHS = E->getLHS();
11457   Expr *RHS = E->getRHS();
11458 
11459   if (T->isIntegralType(S.Context)) {
11460     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11461     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11462 
11463     // We don't care about expressions whose result is a constant.
11464     if (RHSValue && LHSValue)
11465       return AnalyzeImpConvsInComparison(S, E);
11466 
11467     // We only care about expressions where just one side is literal
11468     if ((bool)RHSValue ^ (bool)LHSValue) {
11469       // Is the constant on the RHS or LHS?
11470       const bool RhsConstant = (bool)RHSValue;
11471       Expr *Const = RhsConstant ? RHS : LHS;
11472       Expr *Other = RhsConstant ? LHS : RHS;
11473       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11474 
11475       // Check whether an integer constant comparison results in a value
11476       // of 'true' or 'false'.
11477       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11478         return AnalyzeImpConvsInComparison(S, E);
11479     }
11480   }
11481 
11482   if (!T->hasUnsignedIntegerRepresentation()) {
11483     // We don't do anything special if this isn't an unsigned integral
11484     // comparison:  we're only interested in integral comparisons, and
11485     // signed comparisons only happen in cases we don't care to warn about.
11486     return AnalyzeImpConvsInComparison(S, E);
11487   }
11488 
11489   LHS = LHS->IgnoreParenImpCasts();
11490   RHS = RHS->IgnoreParenImpCasts();
11491 
11492   if (!S.getLangOpts().CPlusPlus) {
11493     // Avoid warning about comparison of integers with different signs when
11494     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11495     // the type of `E`.
11496     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11497       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11498     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11499       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11500   }
11501 
11502   // Check to see if one of the (unmodified) operands is of different
11503   // signedness.
11504   Expr *signedOperand, *unsignedOperand;
11505   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11506     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11507            "unsigned comparison between two signed integer expressions?");
11508     signedOperand = LHS;
11509     unsignedOperand = RHS;
11510   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11511     signedOperand = RHS;
11512     unsignedOperand = LHS;
11513   } else {
11514     return AnalyzeImpConvsInComparison(S, E);
11515   }
11516 
11517   // Otherwise, calculate the effective range of the signed operand.
11518   IntRange signedRange = GetExprRange(
11519       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11520 
11521   // Go ahead and analyze implicit conversions in the operands.  Note
11522   // that we skip the implicit conversions on both sides.
11523   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11524   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11525 
11526   // If the signed range is non-negative, -Wsign-compare won't fire.
11527   if (signedRange.NonNegative)
11528     return;
11529 
11530   // For (in)equality comparisons, if the unsigned operand is a
11531   // constant which cannot collide with a overflowed signed operand,
11532   // then reinterpreting the signed operand as unsigned will not
11533   // change the result of the comparison.
11534   if (E->isEqualityOp()) {
11535     unsigned comparisonWidth = S.Context.getIntWidth(T);
11536     IntRange unsignedRange =
11537         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11538                      /*Approximate*/ true);
11539 
11540     // We should never be unable to prove that the unsigned operand is
11541     // non-negative.
11542     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11543 
11544     if (unsignedRange.Width < comparisonWidth)
11545       return;
11546   }
11547 
11548   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11549                         S.PDiag(diag::warn_mixed_sign_comparison)
11550                             << LHS->getType() << RHS->getType()
11551                             << LHS->getSourceRange() << RHS->getSourceRange());
11552 }
11553 
11554 /// Analyzes an attempt to assign the given value to a bitfield.
11555 ///
11556 /// Returns true if there was something fishy about the attempt.
11557 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11558                                       SourceLocation InitLoc) {
11559   assert(Bitfield->isBitField());
11560   if (Bitfield->isInvalidDecl())
11561     return false;
11562 
11563   // White-list bool bitfields.
11564   QualType BitfieldType = Bitfield->getType();
11565   if (BitfieldType->isBooleanType())
11566      return false;
11567 
11568   if (BitfieldType->isEnumeralType()) {
11569     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11570     // If the underlying enum type was not explicitly specified as an unsigned
11571     // type and the enum contain only positive values, MSVC++ will cause an
11572     // inconsistency by storing this as a signed type.
11573     if (S.getLangOpts().CPlusPlus11 &&
11574         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11575         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11576         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11577       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11578           << BitfieldEnumDecl;
11579     }
11580   }
11581 
11582   if (Bitfield->getType()->isBooleanType())
11583     return false;
11584 
11585   // Ignore value- or type-dependent expressions.
11586   if (Bitfield->getBitWidth()->isValueDependent() ||
11587       Bitfield->getBitWidth()->isTypeDependent() ||
11588       Init->isValueDependent() ||
11589       Init->isTypeDependent())
11590     return false;
11591 
11592   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11593   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11594 
11595   Expr::EvalResult Result;
11596   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11597                                    Expr::SE_AllowSideEffects)) {
11598     // The RHS is not constant.  If the RHS has an enum type, make sure the
11599     // bitfield is wide enough to hold all the values of the enum without
11600     // truncation.
11601     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11602       EnumDecl *ED = EnumTy->getDecl();
11603       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11604 
11605       // Enum types are implicitly signed on Windows, so check if there are any
11606       // negative enumerators to see if the enum was intended to be signed or
11607       // not.
11608       bool SignedEnum = ED->getNumNegativeBits() > 0;
11609 
11610       // Check for surprising sign changes when assigning enum values to a
11611       // bitfield of different signedness.  If the bitfield is signed and we
11612       // have exactly the right number of bits to store this unsigned enum,
11613       // suggest changing the enum to an unsigned type. This typically happens
11614       // on Windows where unfixed enums always use an underlying type of 'int'.
11615       unsigned DiagID = 0;
11616       if (SignedEnum && !SignedBitfield) {
11617         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11618       } else if (SignedBitfield && !SignedEnum &&
11619                  ED->getNumPositiveBits() == FieldWidth) {
11620         DiagID = diag::warn_signed_bitfield_enum_conversion;
11621       }
11622 
11623       if (DiagID) {
11624         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11625         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11626         SourceRange TypeRange =
11627             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11628         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11629             << SignedEnum << TypeRange;
11630       }
11631 
11632       // Compute the required bitwidth. If the enum has negative values, we need
11633       // one more bit than the normal number of positive bits to represent the
11634       // sign bit.
11635       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11636                                                   ED->getNumNegativeBits())
11637                                        : ED->getNumPositiveBits();
11638 
11639       // Check the bitwidth.
11640       if (BitsNeeded > FieldWidth) {
11641         Expr *WidthExpr = Bitfield->getBitWidth();
11642         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11643             << Bitfield << ED;
11644         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11645             << BitsNeeded << ED << WidthExpr->getSourceRange();
11646       }
11647     }
11648 
11649     return false;
11650   }
11651 
11652   llvm::APSInt Value = Result.Val.getInt();
11653 
11654   unsigned OriginalWidth = Value.getBitWidth();
11655 
11656   if (!Value.isSigned() || Value.isNegative())
11657     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11658       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11659         OriginalWidth = Value.getMinSignedBits();
11660 
11661   if (OriginalWidth <= FieldWidth)
11662     return false;
11663 
11664   // Compute the value which the bitfield will contain.
11665   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11666   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11667 
11668   // Check whether the stored value is equal to the original value.
11669   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11670   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11671     return false;
11672 
11673   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11674   // therefore don't strictly fit into a signed bitfield of width 1.
11675   if (FieldWidth == 1 && Value == 1)
11676     return false;
11677 
11678   std::string PrettyValue = Value.toString(10);
11679   std::string PrettyTrunc = TruncatedValue.toString(10);
11680 
11681   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11682     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11683     << Init->getSourceRange();
11684 
11685   return true;
11686 }
11687 
11688 /// Analyze the given simple or compound assignment for warning-worthy
11689 /// operations.
11690 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11691   // Just recurse on the LHS.
11692   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11693 
11694   // We want to recurse on the RHS as normal unless we're assigning to
11695   // a bitfield.
11696   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11697     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11698                                   E->getOperatorLoc())) {
11699       // Recurse, ignoring any implicit conversions on the RHS.
11700       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11701                                         E->getOperatorLoc());
11702     }
11703   }
11704 
11705   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11706 
11707   // Diagnose implicitly sequentially-consistent atomic assignment.
11708   if (E->getLHS()->getType()->isAtomicType())
11709     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11710 }
11711 
11712 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11713 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11714                             SourceLocation CContext, unsigned diag,
11715                             bool pruneControlFlow = false) {
11716   if (pruneControlFlow) {
11717     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11718                           S.PDiag(diag)
11719                               << SourceType << T << E->getSourceRange()
11720                               << SourceRange(CContext));
11721     return;
11722   }
11723   S.Diag(E->getExprLoc(), diag)
11724     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11725 }
11726 
11727 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11728 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11729                             SourceLocation CContext,
11730                             unsigned diag, bool pruneControlFlow = false) {
11731   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11732 }
11733 
11734 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11735   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11736       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11737 }
11738 
11739 static void adornObjCBoolConversionDiagWithTernaryFixit(
11740     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11741   Expr *Ignored = SourceExpr->IgnoreImplicit();
11742   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11743     Ignored = OVE->getSourceExpr();
11744   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11745                      isa<BinaryOperator>(Ignored) ||
11746                      isa<CXXOperatorCallExpr>(Ignored);
11747   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11748   if (NeedsParens)
11749     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11750             << FixItHint::CreateInsertion(EndLoc, ")");
11751   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11752 }
11753 
11754 /// Diagnose an implicit cast from a floating point value to an integer value.
11755 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11756                                     SourceLocation CContext) {
11757   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11758   const bool PruneWarnings = S.inTemplateInstantiation();
11759 
11760   Expr *InnerE = E->IgnoreParenImpCasts();
11761   // We also want to warn on, e.g., "int i = -1.234"
11762   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11763     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11764       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11765 
11766   const bool IsLiteral =
11767       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11768 
11769   llvm::APFloat Value(0.0);
11770   bool IsConstant =
11771     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11772   if (!IsConstant) {
11773     if (isObjCSignedCharBool(S, T)) {
11774       return adornObjCBoolConversionDiagWithTernaryFixit(
11775           S, E,
11776           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11777               << E->getType());
11778     }
11779 
11780     return DiagnoseImpCast(S, E, T, CContext,
11781                            diag::warn_impcast_float_integer, PruneWarnings);
11782   }
11783 
11784   bool isExact = false;
11785 
11786   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11787                             T->hasUnsignedIntegerRepresentation());
11788   llvm::APFloat::opStatus Result = Value.convertToInteger(
11789       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11790 
11791   // FIXME: Force the precision of the source value down so we don't print
11792   // digits which are usually useless (we don't really care here if we
11793   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11794   // would automatically print the shortest representation, but it's a bit
11795   // tricky to implement.
11796   SmallString<16> PrettySourceValue;
11797   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11798   precision = (precision * 59 + 195) / 196;
11799   Value.toString(PrettySourceValue, precision);
11800 
11801   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11802     return adornObjCBoolConversionDiagWithTernaryFixit(
11803         S, E,
11804         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11805             << PrettySourceValue);
11806   }
11807 
11808   if (Result == llvm::APFloat::opOK && isExact) {
11809     if (IsLiteral) return;
11810     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11811                            PruneWarnings);
11812   }
11813 
11814   // Conversion of a floating-point value to a non-bool integer where the
11815   // integral part cannot be represented by the integer type is undefined.
11816   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11817     return DiagnoseImpCast(
11818         S, E, T, CContext,
11819         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11820                   : diag::warn_impcast_float_to_integer_out_of_range,
11821         PruneWarnings);
11822 
11823   unsigned DiagID = 0;
11824   if (IsLiteral) {
11825     // Warn on floating point literal to integer.
11826     DiagID = diag::warn_impcast_literal_float_to_integer;
11827   } else if (IntegerValue == 0) {
11828     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11829       return DiagnoseImpCast(S, E, T, CContext,
11830                              diag::warn_impcast_float_integer, PruneWarnings);
11831     }
11832     // Warn on non-zero to zero conversion.
11833     DiagID = diag::warn_impcast_float_to_integer_zero;
11834   } else {
11835     if (IntegerValue.isUnsigned()) {
11836       if (!IntegerValue.isMaxValue()) {
11837         return DiagnoseImpCast(S, E, T, CContext,
11838                                diag::warn_impcast_float_integer, PruneWarnings);
11839       }
11840     } else {  // IntegerValue.isSigned()
11841       if (!IntegerValue.isMaxSignedValue() &&
11842           !IntegerValue.isMinSignedValue()) {
11843         return DiagnoseImpCast(S, E, T, CContext,
11844                                diag::warn_impcast_float_integer, PruneWarnings);
11845       }
11846     }
11847     // Warn on evaluatable floating point expression to integer conversion.
11848     DiagID = diag::warn_impcast_float_to_integer;
11849   }
11850 
11851   SmallString<16> PrettyTargetValue;
11852   if (IsBool)
11853     PrettyTargetValue = Value.isZero() ? "false" : "true";
11854   else
11855     IntegerValue.toString(PrettyTargetValue);
11856 
11857   if (PruneWarnings) {
11858     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11859                           S.PDiag(DiagID)
11860                               << E->getType() << T.getUnqualifiedType()
11861                               << PrettySourceValue << PrettyTargetValue
11862                               << E->getSourceRange() << SourceRange(CContext));
11863   } else {
11864     S.Diag(E->getExprLoc(), DiagID)
11865         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11866         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11867   }
11868 }
11869 
11870 /// Analyze the given compound assignment for the possible losing of
11871 /// floating-point precision.
11872 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11873   assert(isa<CompoundAssignOperator>(E) &&
11874          "Must be compound assignment operation");
11875   // Recurse on the LHS and RHS in here
11876   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11877   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11878 
11879   if (E->getLHS()->getType()->isAtomicType())
11880     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11881 
11882   // Now check the outermost expression
11883   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11884   const auto *RBT = cast<CompoundAssignOperator>(E)
11885                         ->getComputationResultType()
11886                         ->getAs<BuiltinType>();
11887 
11888   // The below checks assume source is floating point.
11889   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11890 
11891   // If source is floating point but target is an integer.
11892   if (ResultBT->isInteger())
11893     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11894                            E->getExprLoc(), diag::warn_impcast_float_integer);
11895 
11896   if (!ResultBT->isFloatingPoint())
11897     return;
11898 
11899   // If both source and target are floating points, warn about losing precision.
11900   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11901       QualType(ResultBT, 0), QualType(RBT, 0));
11902   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11903     // warn about dropping FP rank.
11904     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11905                     diag::warn_impcast_float_result_precision);
11906 }
11907 
11908 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11909                                       IntRange Range) {
11910   if (!Range.Width) return "0";
11911 
11912   llvm::APSInt ValueInRange = Value;
11913   ValueInRange.setIsSigned(!Range.NonNegative);
11914   ValueInRange = ValueInRange.trunc(Range.Width);
11915   return ValueInRange.toString(10);
11916 }
11917 
11918 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11919   if (!isa<ImplicitCastExpr>(Ex))
11920     return false;
11921 
11922   Expr *InnerE = Ex->IgnoreParenImpCasts();
11923   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11924   const Type *Source =
11925     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11926   if (Target->isDependentType())
11927     return false;
11928 
11929   const BuiltinType *FloatCandidateBT =
11930     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11931   const Type *BoolCandidateType = ToBool ? Target : Source;
11932 
11933   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11934           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11935 }
11936 
11937 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11938                                              SourceLocation CC) {
11939   unsigned NumArgs = TheCall->getNumArgs();
11940   for (unsigned i = 0; i < NumArgs; ++i) {
11941     Expr *CurrA = TheCall->getArg(i);
11942     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11943       continue;
11944 
11945     bool IsSwapped = ((i > 0) &&
11946         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11947     IsSwapped |= ((i < (NumArgs - 1)) &&
11948         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11949     if (IsSwapped) {
11950       // Warn on this floating-point to bool conversion.
11951       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11952                       CurrA->getType(), CC,
11953                       diag::warn_impcast_floating_point_to_bool);
11954     }
11955   }
11956 }
11957 
11958 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11959                                    SourceLocation CC) {
11960   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11961                         E->getExprLoc()))
11962     return;
11963 
11964   // Don't warn on functions which have return type nullptr_t.
11965   if (isa<CallExpr>(E))
11966     return;
11967 
11968   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11969   const Expr::NullPointerConstantKind NullKind =
11970       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11971   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11972     return;
11973 
11974   // Return if target type is a safe conversion.
11975   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11976       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11977     return;
11978 
11979   SourceLocation Loc = E->getSourceRange().getBegin();
11980 
11981   // Venture through the macro stacks to get to the source of macro arguments.
11982   // The new location is a better location than the complete location that was
11983   // passed in.
11984   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11985   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11986 
11987   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11988   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11989     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11990         Loc, S.SourceMgr, S.getLangOpts());
11991     if (MacroName == "NULL")
11992       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11993   }
11994 
11995   // Only warn if the null and context location are in the same macro expansion.
11996   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11997     return;
11998 
11999   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12000       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12001       << FixItHint::CreateReplacement(Loc,
12002                                       S.getFixItZeroLiteralForType(T, Loc));
12003 }
12004 
12005 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12006                                   ObjCArrayLiteral *ArrayLiteral);
12007 
12008 static void
12009 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12010                            ObjCDictionaryLiteral *DictionaryLiteral);
12011 
12012 /// Check a single element within a collection literal against the
12013 /// target element type.
12014 static void checkObjCCollectionLiteralElement(Sema &S,
12015                                               QualType TargetElementType,
12016                                               Expr *Element,
12017                                               unsigned ElementKind) {
12018   // Skip a bitcast to 'id' or qualified 'id'.
12019   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12020     if (ICE->getCastKind() == CK_BitCast &&
12021         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12022       Element = ICE->getSubExpr();
12023   }
12024 
12025   QualType ElementType = Element->getType();
12026   ExprResult ElementResult(Element);
12027   if (ElementType->getAs<ObjCObjectPointerType>() &&
12028       S.CheckSingleAssignmentConstraints(TargetElementType,
12029                                          ElementResult,
12030                                          false, false)
12031         != Sema::Compatible) {
12032     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12033         << ElementType << ElementKind << TargetElementType
12034         << Element->getSourceRange();
12035   }
12036 
12037   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12038     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12039   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12040     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12041 }
12042 
12043 /// Check an Objective-C array literal being converted to the given
12044 /// target type.
12045 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12046                                   ObjCArrayLiteral *ArrayLiteral) {
12047   if (!S.NSArrayDecl)
12048     return;
12049 
12050   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12051   if (!TargetObjCPtr)
12052     return;
12053 
12054   if (TargetObjCPtr->isUnspecialized() ||
12055       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12056         != S.NSArrayDecl->getCanonicalDecl())
12057     return;
12058 
12059   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12060   if (TypeArgs.size() != 1)
12061     return;
12062 
12063   QualType TargetElementType = TypeArgs[0];
12064   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12065     checkObjCCollectionLiteralElement(S, TargetElementType,
12066                                       ArrayLiteral->getElement(I),
12067                                       0);
12068   }
12069 }
12070 
12071 /// Check an Objective-C dictionary literal being converted to the given
12072 /// target type.
12073 static void
12074 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12075                            ObjCDictionaryLiteral *DictionaryLiteral) {
12076   if (!S.NSDictionaryDecl)
12077     return;
12078 
12079   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12080   if (!TargetObjCPtr)
12081     return;
12082 
12083   if (TargetObjCPtr->isUnspecialized() ||
12084       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12085         != S.NSDictionaryDecl->getCanonicalDecl())
12086     return;
12087 
12088   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12089   if (TypeArgs.size() != 2)
12090     return;
12091 
12092   QualType TargetKeyType = TypeArgs[0];
12093   QualType TargetObjectType = TypeArgs[1];
12094   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12095     auto Element = DictionaryLiteral->getKeyValueElement(I);
12096     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12097     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12098   }
12099 }
12100 
12101 // Helper function to filter out cases for constant width constant conversion.
12102 // Don't warn on char array initialization or for non-decimal values.
12103 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12104                                           SourceLocation CC) {
12105   // If initializing from a constant, and the constant starts with '0',
12106   // then it is a binary, octal, or hexadecimal.  Allow these constants
12107   // to fill all the bits, even if there is a sign change.
12108   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12109     const char FirstLiteralCharacter =
12110         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12111     if (FirstLiteralCharacter == '0')
12112       return false;
12113   }
12114 
12115   // If the CC location points to a '{', and the type is char, then assume
12116   // assume it is an array initialization.
12117   if (CC.isValid() && T->isCharType()) {
12118     const char FirstContextCharacter =
12119         S.getSourceManager().getCharacterData(CC)[0];
12120     if (FirstContextCharacter == '{')
12121       return false;
12122   }
12123 
12124   return true;
12125 }
12126 
12127 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12128   const auto *IL = dyn_cast<IntegerLiteral>(E);
12129   if (!IL) {
12130     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12131       if (UO->getOpcode() == UO_Minus)
12132         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12133     }
12134   }
12135 
12136   return IL;
12137 }
12138 
12139 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12140   E = E->IgnoreParenImpCasts();
12141   SourceLocation ExprLoc = E->getExprLoc();
12142 
12143   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12144     BinaryOperator::Opcode Opc = BO->getOpcode();
12145     Expr::EvalResult Result;
12146     // Do not diagnose unsigned shifts.
12147     if (Opc == BO_Shl) {
12148       const auto *LHS = getIntegerLiteral(BO->getLHS());
12149       const auto *RHS = getIntegerLiteral(BO->getRHS());
12150       if (LHS && LHS->getValue() == 0)
12151         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12152       else if (!E->isValueDependent() && LHS && RHS &&
12153                RHS->getValue().isNonNegative() &&
12154                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12155         S.Diag(ExprLoc, diag::warn_left_shift_always)
12156             << (Result.Val.getInt() != 0);
12157       else if (E->getType()->isSignedIntegerType())
12158         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12159     }
12160   }
12161 
12162   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12163     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12164     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12165     if (!LHS || !RHS)
12166       return;
12167     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12168         (RHS->getValue() == 0 || RHS->getValue() == 1))
12169       // Do not diagnose common idioms.
12170       return;
12171     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12172       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12173   }
12174 }
12175 
12176 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12177                                     SourceLocation CC,
12178                                     bool *ICContext = nullptr,
12179                                     bool IsListInit = false) {
12180   if (E->isTypeDependent() || E->isValueDependent()) return;
12181 
12182   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12183   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12184   if (Source == Target) return;
12185   if (Target->isDependentType()) return;
12186 
12187   // If the conversion context location is invalid don't complain. We also
12188   // don't want to emit a warning if the issue occurs from the expansion of
12189   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12190   // delay this check as long as possible. Once we detect we are in that
12191   // scenario, we just return.
12192   if (CC.isInvalid())
12193     return;
12194 
12195   if (Source->isAtomicType())
12196     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12197 
12198   // Diagnose implicit casts to bool.
12199   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12200     if (isa<StringLiteral>(E))
12201       // Warn on string literal to bool.  Checks for string literals in logical
12202       // and expressions, for instance, assert(0 && "error here"), are
12203       // prevented by a check in AnalyzeImplicitConversions().
12204       return DiagnoseImpCast(S, E, T, CC,
12205                              diag::warn_impcast_string_literal_to_bool);
12206     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12207         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12208       // This covers the literal expressions that evaluate to Objective-C
12209       // objects.
12210       return DiagnoseImpCast(S, E, T, CC,
12211                              diag::warn_impcast_objective_c_literal_to_bool);
12212     }
12213     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12214       // Warn on pointer to bool conversion that is always true.
12215       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12216                                      SourceRange(CC));
12217     }
12218   }
12219 
12220   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12221   // is a typedef for signed char (macOS), then that constant value has to be 1
12222   // or 0.
12223   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12224     Expr::EvalResult Result;
12225     if (E->EvaluateAsInt(Result, S.getASTContext(),
12226                          Expr::SE_AllowSideEffects)) {
12227       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12228         adornObjCBoolConversionDiagWithTernaryFixit(
12229             S, E,
12230             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12231                 << Result.Val.getInt().toString(10));
12232       }
12233       return;
12234     }
12235   }
12236 
12237   // Check implicit casts from Objective-C collection literals to specialized
12238   // collection types, e.g., NSArray<NSString *> *.
12239   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12240     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12241   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12242     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12243 
12244   // Strip vector types.
12245   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12246     if (Target->isVLSTBuiltinType()) {
12247       auto SourceVectorKind = SourceVT->getVectorKind();
12248       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12249           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12250           (SourceVectorKind == VectorType::GenericVector &&
12251            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12252         return;
12253     }
12254 
12255     if (!isa<VectorType>(Target)) {
12256       if (S.SourceMgr.isInSystemMacro(CC))
12257         return;
12258       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12259     }
12260 
12261     // If the vector cast is cast between two vectors of the same size, it is
12262     // a bitcast, not a conversion.
12263     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12264       return;
12265 
12266     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12267     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12268   }
12269   if (auto VecTy = dyn_cast<VectorType>(Target))
12270     Target = VecTy->getElementType().getTypePtr();
12271 
12272   // Strip complex types.
12273   if (isa<ComplexType>(Source)) {
12274     if (!isa<ComplexType>(Target)) {
12275       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12276         return;
12277 
12278       return DiagnoseImpCast(S, E, T, CC,
12279                              S.getLangOpts().CPlusPlus
12280                                  ? diag::err_impcast_complex_scalar
12281                                  : diag::warn_impcast_complex_scalar);
12282     }
12283 
12284     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12285     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12286   }
12287 
12288   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12289   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12290 
12291   // If the source is floating point...
12292   if (SourceBT && SourceBT->isFloatingPoint()) {
12293     // ...and the target is floating point...
12294     if (TargetBT && TargetBT->isFloatingPoint()) {
12295       // ...then warn if we're dropping FP rank.
12296 
12297       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12298           QualType(SourceBT, 0), QualType(TargetBT, 0));
12299       if (Order > 0) {
12300         // Don't warn about float constants that are precisely
12301         // representable in the target type.
12302         Expr::EvalResult result;
12303         if (E->EvaluateAsRValue(result, S.Context)) {
12304           // Value might be a float, a float vector, or a float complex.
12305           if (IsSameFloatAfterCast(result.Val,
12306                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12307                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12308             return;
12309         }
12310 
12311         if (S.SourceMgr.isInSystemMacro(CC))
12312           return;
12313 
12314         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12315       }
12316       // ... or possibly if we're increasing rank, too
12317       else if (Order < 0) {
12318         if (S.SourceMgr.isInSystemMacro(CC))
12319           return;
12320 
12321         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12322       }
12323       return;
12324     }
12325 
12326     // If the target is integral, always warn.
12327     if (TargetBT && TargetBT->isInteger()) {
12328       if (S.SourceMgr.isInSystemMacro(CC))
12329         return;
12330 
12331       DiagnoseFloatingImpCast(S, E, T, CC);
12332     }
12333 
12334     // Detect the case where a call result is converted from floating-point to
12335     // to bool, and the final argument to the call is converted from bool, to
12336     // discover this typo:
12337     //
12338     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12339     //
12340     // FIXME: This is an incredibly special case; is there some more general
12341     // way to detect this class of misplaced-parentheses bug?
12342     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12343       // Check last argument of function call to see if it is an
12344       // implicit cast from a type matching the type the result
12345       // is being cast to.
12346       CallExpr *CEx = cast<CallExpr>(E);
12347       if (unsigned NumArgs = CEx->getNumArgs()) {
12348         Expr *LastA = CEx->getArg(NumArgs - 1);
12349         Expr *InnerE = LastA->IgnoreParenImpCasts();
12350         if (isa<ImplicitCastExpr>(LastA) &&
12351             InnerE->getType()->isBooleanType()) {
12352           // Warn on this floating-point to bool conversion
12353           DiagnoseImpCast(S, E, T, CC,
12354                           diag::warn_impcast_floating_point_to_bool);
12355         }
12356       }
12357     }
12358     return;
12359   }
12360 
12361   // Valid casts involving fixed point types should be accounted for here.
12362   if (Source->isFixedPointType()) {
12363     if (Target->isUnsaturatedFixedPointType()) {
12364       Expr::EvalResult Result;
12365       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12366                                   S.isConstantEvaluated())) {
12367         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12368         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12369         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12370         if (Value > MaxVal || Value < MinVal) {
12371           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12372                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12373                                     << Value.toString() << T
12374                                     << E->getSourceRange()
12375                                     << clang::SourceRange(CC));
12376           return;
12377         }
12378       }
12379     } else if (Target->isIntegerType()) {
12380       Expr::EvalResult Result;
12381       if (!S.isConstantEvaluated() &&
12382           E->EvaluateAsFixedPoint(Result, S.Context,
12383                                   Expr::SE_AllowSideEffects)) {
12384         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12385 
12386         bool Overflowed;
12387         llvm::APSInt IntResult = FXResult.convertToInt(
12388             S.Context.getIntWidth(T),
12389             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12390 
12391         if (Overflowed) {
12392           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12393                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12394                                     << FXResult.toString() << T
12395                                     << E->getSourceRange()
12396                                     << clang::SourceRange(CC));
12397           return;
12398         }
12399       }
12400     }
12401   } else if (Target->isUnsaturatedFixedPointType()) {
12402     if (Source->isIntegerType()) {
12403       Expr::EvalResult Result;
12404       if (!S.isConstantEvaluated() &&
12405           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12406         llvm::APSInt Value = Result.Val.getInt();
12407 
12408         bool Overflowed;
12409         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12410             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12411 
12412         if (Overflowed) {
12413           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12414                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12415                                     << Value.toString(/*Radix=*/10) << T
12416                                     << E->getSourceRange()
12417                                     << clang::SourceRange(CC));
12418           return;
12419         }
12420       }
12421     }
12422   }
12423 
12424   // If we are casting an integer type to a floating point type without
12425   // initialization-list syntax, we might lose accuracy if the floating
12426   // point type has a narrower significand than the integer type.
12427   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12428       TargetBT->isFloatingType() && !IsListInit) {
12429     // Determine the number of precision bits in the source integer type.
12430     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12431                                         /*Approximate*/ true);
12432     unsigned int SourcePrecision = SourceRange.Width;
12433 
12434     // Determine the number of precision bits in the
12435     // target floating point type.
12436     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12437         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12438 
12439     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12440         SourcePrecision > TargetPrecision) {
12441 
12442       if (Optional<llvm::APSInt> SourceInt =
12443               E->getIntegerConstantExpr(S.Context)) {
12444         // If the source integer is a constant, convert it to the target
12445         // floating point type. Issue a warning if the value changes
12446         // during the whole conversion.
12447         llvm::APFloat TargetFloatValue(
12448             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12449         llvm::APFloat::opStatus ConversionStatus =
12450             TargetFloatValue.convertFromAPInt(
12451                 *SourceInt, SourceBT->isSignedInteger(),
12452                 llvm::APFloat::rmNearestTiesToEven);
12453 
12454         if (ConversionStatus != llvm::APFloat::opOK) {
12455           std::string PrettySourceValue = SourceInt->toString(10);
12456           SmallString<32> PrettyTargetValue;
12457           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12458 
12459           S.DiagRuntimeBehavior(
12460               E->getExprLoc(), E,
12461               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12462                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12463                   << E->getSourceRange() << clang::SourceRange(CC));
12464         }
12465       } else {
12466         // Otherwise, the implicit conversion may lose precision.
12467         DiagnoseImpCast(S, E, T, CC,
12468                         diag::warn_impcast_integer_float_precision);
12469       }
12470     }
12471   }
12472 
12473   DiagnoseNullConversion(S, E, T, CC);
12474 
12475   S.DiscardMisalignedMemberAddress(Target, E);
12476 
12477   if (Target->isBooleanType())
12478     DiagnoseIntInBoolContext(S, E);
12479 
12480   if (!Source->isIntegerType() || !Target->isIntegerType())
12481     return;
12482 
12483   // TODO: remove this early return once the false positives for constant->bool
12484   // in templates, macros, etc, are reduced or removed.
12485   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12486     return;
12487 
12488   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12489       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12490     return adornObjCBoolConversionDiagWithTernaryFixit(
12491         S, E,
12492         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12493             << E->getType());
12494   }
12495 
12496   IntRange SourceTypeRange =
12497       IntRange::forTargetOfCanonicalType(S.Context, Source);
12498   IntRange LikelySourceRange =
12499       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12500   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12501 
12502   if (LikelySourceRange.Width > TargetRange.Width) {
12503     // If the source is a constant, use a default-on diagnostic.
12504     // TODO: this should happen for bitfield stores, too.
12505     Expr::EvalResult Result;
12506     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12507                          S.isConstantEvaluated())) {
12508       llvm::APSInt Value(32);
12509       Value = Result.Val.getInt();
12510 
12511       if (S.SourceMgr.isInSystemMacro(CC))
12512         return;
12513 
12514       std::string PrettySourceValue = Value.toString(10);
12515       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12516 
12517       S.DiagRuntimeBehavior(
12518           E->getExprLoc(), E,
12519           S.PDiag(diag::warn_impcast_integer_precision_constant)
12520               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12521               << E->getSourceRange() << SourceRange(CC));
12522       return;
12523     }
12524 
12525     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12526     if (S.SourceMgr.isInSystemMacro(CC))
12527       return;
12528 
12529     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12530       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12531                              /* pruneControlFlow */ true);
12532     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12533   }
12534 
12535   if (TargetRange.Width > SourceTypeRange.Width) {
12536     if (auto *UO = dyn_cast<UnaryOperator>(E))
12537       if (UO->getOpcode() == UO_Minus)
12538         if (Source->isUnsignedIntegerType()) {
12539           if (Target->isUnsignedIntegerType())
12540             return DiagnoseImpCast(S, E, T, CC,
12541                                    diag::warn_impcast_high_order_zero_bits);
12542           if (Target->isSignedIntegerType())
12543             return DiagnoseImpCast(S, E, T, CC,
12544                                    diag::warn_impcast_nonnegative_result);
12545         }
12546   }
12547 
12548   if (TargetRange.Width == LikelySourceRange.Width &&
12549       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12550       Source->isSignedIntegerType()) {
12551     // Warn when doing a signed to signed conversion, warn if the positive
12552     // source value is exactly the width of the target type, which will
12553     // cause a negative value to be stored.
12554 
12555     Expr::EvalResult Result;
12556     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12557         !S.SourceMgr.isInSystemMacro(CC)) {
12558       llvm::APSInt Value = Result.Val.getInt();
12559       if (isSameWidthConstantConversion(S, E, T, CC)) {
12560         std::string PrettySourceValue = Value.toString(10);
12561         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12562 
12563         S.DiagRuntimeBehavior(
12564             E->getExprLoc(), E,
12565             S.PDiag(diag::warn_impcast_integer_precision_constant)
12566                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12567                 << E->getSourceRange() << SourceRange(CC));
12568         return;
12569       }
12570     }
12571 
12572     // Fall through for non-constants to give a sign conversion warning.
12573   }
12574 
12575   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12576       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12577        LikelySourceRange.Width == TargetRange.Width)) {
12578     if (S.SourceMgr.isInSystemMacro(CC))
12579       return;
12580 
12581     unsigned DiagID = diag::warn_impcast_integer_sign;
12582 
12583     // Traditionally, gcc has warned about this under -Wsign-compare.
12584     // We also want to warn about it in -Wconversion.
12585     // So if -Wconversion is off, use a completely identical diagnostic
12586     // in the sign-compare group.
12587     // The conditional-checking code will
12588     if (ICContext) {
12589       DiagID = diag::warn_impcast_integer_sign_conditional;
12590       *ICContext = true;
12591     }
12592 
12593     return DiagnoseImpCast(S, E, T, CC, DiagID);
12594   }
12595 
12596   // Diagnose conversions between different enumeration types.
12597   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12598   // type, to give us better diagnostics.
12599   QualType SourceType = E->getType();
12600   if (!S.getLangOpts().CPlusPlus) {
12601     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12602       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12603         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12604         SourceType = S.Context.getTypeDeclType(Enum);
12605         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12606       }
12607   }
12608 
12609   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12610     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12611       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12612           TargetEnum->getDecl()->hasNameForLinkage() &&
12613           SourceEnum != TargetEnum) {
12614         if (S.SourceMgr.isInSystemMacro(CC))
12615           return;
12616 
12617         return DiagnoseImpCast(S, E, SourceType, T, CC,
12618                                diag::warn_impcast_different_enum_types);
12619       }
12620 }
12621 
12622 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12623                                      SourceLocation CC, QualType T);
12624 
12625 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12626                                     SourceLocation CC, bool &ICContext) {
12627   E = E->IgnoreParenImpCasts();
12628 
12629   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12630     return CheckConditionalOperator(S, CO, CC, T);
12631 
12632   AnalyzeImplicitConversions(S, E, CC);
12633   if (E->getType() != T)
12634     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12635 }
12636 
12637 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12638                                      SourceLocation CC, QualType T) {
12639   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12640 
12641   Expr *TrueExpr = E->getTrueExpr();
12642   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12643     TrueExpr = BCO->getCommon();
12644 
12645   bool Suspicious = false;
12646   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12647   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12648 
12649   if (T->isBooleanType())
12650     DiagnoseIntInBoolContext(S, E);
12651 
12652   // If -Wconversion would have warned about either of the candidates
12653   // for a signedness conversion to the context type...
12654   if (!Suspicious) return;
12655 
12656   // ...but it's currently ignored...
12657   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12658     return;
12659 
12660   // ...then check whether it would have warned about either of the
12661   // candidates for a signedness conversion to the condition type.
12662   if (E->getType() == T) return;
12663 
12664   Suspicious = false;
12665   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12666                           E->getType(), CC, &Suspicious);
12667   if (!Suspicious)
12668     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12669                             E->getType(), CC, &Suspicious);
12670 }
12671 
12672 /// Check conversion of given expression to boolean.
12673 /// Input argument E is a logical expression.
12674 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12675   if (S.getLangOpts().Bool)
12676     return;
12677   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12678     return;
12679   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12680 }
12681 
12682 namespace {
12683 struct AnalyzeImplicitConversionsWorkItem {
12684   Expr *E;
12685   SourceLocation CC;
12686   bool IsListInit;
12687 };
12688 }
12689 
12690 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12691 /// that should be visited are added to WorkList.
12692 static void AnalyzeImplicitConversions(
12693     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12694     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12695   Expr *OrigE = Item.E;
12696   SourceLocation CC = Item.CC;
12697 
12698   QualType T = OrigE->getType();
12699   Expr *E = OrigE->IgnoreParenImpCasts();
12700 
12701   // Propagate whether we are in a C++ list initialization expression.
12702   // If so, we do not issue warnings for implicit int-float conversion
12703   // precision loss, because C++11 narrowing already handles it.
12704   bool IsListInit = Item.IsListInit ||
12705                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12706 
12707   if (E->isTypeDependent() || E->isValueDependent())
12708     return;
12709 
12710   Expr *SourceExpr = E;
12711   // Examine, but don't traverse into the source expression of an
12712   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12713   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12714   // evaluate it in the context of checking the specific conversion to T though.
12715   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12716     if (auto *Src = OVE->getSourceExpr())
12717       SourceExpr = Src;
12718 
12719   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12720     if (UO->getOpcode() == UO_Not &&
12721         UO->getSubExpr()->isKnownToHaveBooleanValue())
12722       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12723           << OrigE->getSourceRange() << T->isBooleanType()
12724           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12725 
12726   // For conditional operators, we analyze the arguments as if they
12727   // were being fed directly into the output.
12728   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12729     CheckConditionalOperator(S, CO, CC, T);
12730     return;
12731   }
12732 
12733   // Check implicit argument conversions for function calls.
12734   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12735     CheckImplicitArgumentConversions(S, Call, CC);
12736 
12737   // Go ahead and check any implicit conversions we might have skipped.
12738   // The non-canonical typecheck is just an optimization;
12739   // CheckImplicitConversion will filter out dead implicit conversions.
12740   if (SourceExpr->getType() != T)
12741     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12742 
12743   // Now continue drilling into this expression.
12744 
12745   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12746     // The bound subexpressions in a PseudoObjectExpr are not reachable
12747     // as transitive children.
12748     // FIXME: Use a more uniform representation for this.
12749     for (auto *SE : POE->semantics())
12750       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12751         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12752   }
12753 
12754   // Skip past explicit casts.
12755   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12756     E = CE->getSubExpr()->IgnoreParenImpCasts();
12757     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12758       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12759     WorkList.push_back({E, CC, IsListInit});
12760     return;
12761   }
12762 
12763   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12764     // Do a somewhat different check with comparison operators.
12765     if (BO->isComparisonOp())
12766       return AnalyzeComparison(S, BO);
12767 
12768     // And with simple assignments.
12769     if (BO->getOpcode() == BO_Assign)
12770       return AnalyzeAssignment(S, BO);
12771     // And with compound assignments.
12772     if (BO->isAssignmentOp())
12773       return AnalyzeCompoundAssignment(S, BO);
12774   }
12775 
12776   // These break the otherwise-useful invariant below.  Fortunately,
12777   // we don't really need to recurse into them, because any internal
12778   // expressions should have been analyzed already when they were
12779   // built into statements.
12780   if (isa<StmtExpr>(E)) return;
12781 
12782   // Don't descend into unevaluated contexts.
12783   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12784 
12785   // Now just recurse over the expression's children.
12786   CC = E->getExprLoc();
12787   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12788   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12789   for (Stmt *SubStmt : E->children()) {
12790     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12791     if (!ChildExpr)
12792       continue;
12793 
12794     if (IsLogicalAndOperator &&
12795         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12796       // Ignore checking string literals that are in logical and operators.
12797       // This is a common pattern for asserts.
12798       continue;
12799     WorkList.push_back({ChildExpr, CC, IsListInit});
12800   }
12801 
12802   if (BO && BO->isLogicalOp()) {
12803     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12804     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12805       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12806 
12807     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12808     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12809       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12810   }
12811 
12812   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12813     if (U->getOpcode() == UO_LNot) {
12814       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12815     } else if (U->getOpcode() != UO_AddrOf) {
12816       if (U->getSubExpr()->getType()->isAtomicType())
12817         S.Diag(U->getSubExpr()->getBeginLoc(),
12818                diag::warn_atomic_implicit_seq_cst);
12819     }
12820   }
12821 }
12822 
12823 /// AnalyzeImplicitConversions - Find and report any interesting
12824 /// implicit conversions in the given expression.  There are a couple
12825 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12826 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12827                                        bool IsListInit/*= false*/) {
12828   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12829   WorkList.push_back({OrigE, CC, IsListInit});
12830   while (!WorkList.empty())
12831     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12832 }
12833 
12834 /// Diagnose integer type and any valid implicit conversion to it.
12835 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12836   // Taking into account implicit conversions,
12837   // allow any integer.
12838   if (!E->getType()->isIntegerType()) {
12839     S.Diag(E->getBeginLoc(),
12840            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12841     return true;
12842   }
12843   // Potentially emit standard warnings for implicit conversions if enabled
12844   // using -Wconversion.
12845   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12846   return false;
12847 }
12848 
12849 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12850 // Returns true when emitting a warning about taking the address of a reference.
12851 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12852                               const PartialDiagnostic &PD) {
12853   E = E->IgnoreParenImpCasts();
12854 
12855   const FunctionDecl *FD = nullptr;
12856 
12857   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12858     if (!DRE->getDecl()->getType()->isReferenceType())
12859       return false;
12860   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12861     if (!M->getMemberDecl()->getType()->isReferenceType())
12862       return false;
12863   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12864     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12865       return false;
12866     FD = Call->getDirectCallee();
12867   } else {
12868     return false;
12869   }
12870 
12871   SemaRef.Diag(E->getExprLoc(), PD);
12872 
12873   // If possible, point to location of function.
12874   if (FD) {
12875     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12876   }
12877 
12878   return true;
12879 }
12880 
12881 // Returns true if the SourceLocation is expanded from any macro body.
12882 // Returns false if the SourceLocation is invalid, is from not in a macro
12883 // expansion, or is from expanded from a top-level macro argument.
12884 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12885   if (Loc.isInvalid())
12886     return false;
12887 
12888   while (Loc.isMacroID()) {
12889     if (SM.isMacroBodyExpansion(Loc))
12890       return true;
12891     Loc = SM.getImmediateMacroCallerLoc(Loc);
12892   }
12893 
12894   return false;
12895 }
12896 
12897 /// Diagnose pointers that are always non-null.
12898 /// \param E the expression containing the pointer
12899 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12900 /// compared to a null pointer
12901 /// \param IsEqual True when the comparison is equal to a null pointer
12902 /// \param Range Extra SourceRange to highlight in the diagnostic
12903 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12904                                         Expr::NullPointerConstantKind NullKind,
12905                                         bool IsEqual, SourceRange Range) {
12906   if (!E)
12907     return;
12908 
12909   // Don't warn inside macros.
12910   if (E->getExprLoc().isMacroID()) {
12911     const SourceManager &SM = getSourceManager();
12912     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12913         IsInAnyMacroBody(SM, Range.getBegin()))
12914       return;
12915   }
12916   E = E->IgnoreImpCasts();
12917 
12918   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12919 
12920   if (isa<CXXThisExpr>(E)) {
12921     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12922                                 : diag::warn_this_bool_conversion;
12923     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12924     return;
12925   }
12926 
12927   bool IsAddressOf = false;
12928 
12929   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12930     if (UO->getOpcode() != UO_AddrOf)
12931       return;
12932     IsAddressOf = true;
12933     E = UO->getSubExpr();
12934   }
12935 
12936   if (IsAddressOf) {
12937     unsigned DiagID = IsCompare
12938                           ? diag::warn_address_of_reference_null_compare
12939                           : diag::warn_address_of_reference_bool_conversion;
12940     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12941                                          << IsEqual;
12942     if (CheckForReference(*this, E, PD)) {
12943       return;
12944     }
12945   }
12946 
12947   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12948     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12949     std::string Str;
12950     llvm::raw_string_ostream S(Str);
12951     E->printPretty(S, nullptr, getPrintingPolicy());
12952     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12953                                 : diag::warn_cast_nonnull_to_bool;
12954     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12955       << E->getSourceRange() << Range << IsEqual;
12956     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12957   };
12958 
12959   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12960   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12961     if (auto *Callee = Call->getDirectCallee()) {
12962       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12963         ComplainAboutNonnullParamOrCall(A);
12964         return;
12965       }
12966     }
12967   }
12968 
12969   // Expect to find a single Decl.  Skip anything more complicated.
12970   ValueDecl *D = nullptr;
12971   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12972     D = R->getDecl();
12973   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12974     D = M->getMemberDecl();
12975   }
12976 
12977   // Weak Decls can be null.
12978   if (!D || D->isWeak())
12979     return;
12980 
12981   // Check for parameter decl with nonnull attribute
12982   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12983     if (getCurFunction() &&
12984         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12985       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12986         ComplainAboutNonnullParamOrCall(A);
12987         return;
12988       }
12989 
12990       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12991         // Skip function template not specialized yet.
12992         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12993           return;
12994         auto ParamIter = llvm::find(FD->parameters(), PV);
12995         assert(ParamIter != FD->param_end());
12996         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12997 
12998         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12999           if (!NonNull->args_size()) {
13000               ComplainAboutNonnullParamOrCall(NonNull);
13001               return;
13002           }
13003 
13004           for (const ParamIdx &ArgNo : NonNull->args()) {
13005             if (ArgNo.getASTIndex() == ParamNo) {
13006               ComplainAboutNonnullParamOrCall(NonNull);
13007               return;
13008             }
13009           }
13010         }
13011       }
13012     }
13013   }
13014 
13015   QualType T = D->getType();
13016   const bool IsArray = T->isArrayType();
13017   const bool IsFunction = T->isFunctionType();
13018 
13019   // Address of function is used to silence the function warning.
13020   if (IsAddressOf && IsFunction) {
13021     return;
13022   }
13023 
13024   // Found nothing.
13025   if (!IsAddressOf && !IsFunction && !IsArray)
13026     return;
13027 
13028   // Pretty print the expression for the diagnostic.
13029   std::string Str;
13030   llvm::raw_string_ostream S(Str);
13031   E->printPretty(S, nullptr, getPrintingPolicy());
13032 
13033   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13034                               : diag::warn_impcast_pointer_to_bool;
13035   enum {
13036     AddressOf,
13037     FunctionPointer,
13038     ArrayPointer
13039   } DiagType;
13040   if (IsAddressOf)
13041     DiagType = AddressOf;
13042   else if (IsFunction)
13043     DiagType = FunctionPointer;
13044   else if (IsArray)
13045     DiagType = ArrayPointer;
13046   else
13047     llvm_unreachable("Could not determine diagnostic.");
13048   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13049                                 << Range << IsEqual;
13050 
13051   if (!IsFunction)
13052     return;
13053 
13054   // Suggest '&' to silence the function warning.
13055   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13056       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13057 
13058   // Check to see if '()' fixit should be emitted.
13059   QualType ReturnType;
13060   UnresolvedSet<4> NonTemplateOverloads;
13061   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13062   if (ReturnType.isNull())
13063     return;
13064 
13065   if (IsCompare) {
13066     // There are two cases here.  If there is null constant, the only suggest
13067     // for a pointer return type.  If the null is 0, then suggest if the return
13068     // type is a pointer or an integer type.
13069     if (!ReturnType->isPointerType()) {
13070       if (NullKind == Expr::NPCK_ZeroExpression ||
13071           NullKind == Expr::NPCK_ZeroLiteral) {
13072         if (!ReturnType->isIntegerType())
13073           return;
13074       } else {
13075         return;
13076       }
13077     }
13078   } else { // !IsCompare
13079     // For function to bool, only suggest if the function pointer has bool
13080     // return type.
13081     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13082       return;
13083   }
13084   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13085       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13086 }
13087 
13088 /// Diagnoses "dangerous" implicit conversions within the given
13089 /// expression (which is a full expression).  Implements -Wconversion
13090 /// and -Wsign-compare.
13091 ///
13092 /// \param CC the "context" location of the implicit conversion, i.e.
13093 ///   the most location of the syntactic entity requiring the implicit
13094 ///   conversion
13095 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13096   // Don't diagnose in unevaluated contexts.
13097   if (isUnevaluatedContext())
13098     return;
13099 
13100   // Don't diagnose for value- or type-dependent expressions.
13101   if (E->isTypeDependent() || E->isValueDependent())
13102     return;
13103 
13104   // Check for array bounds violations in cases where the check isn't triggered
13105   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13106   // ArraySubscriptExpr is on the RHS of a variable initialization.
13107   CheckArrayAccess(E);
13108 
13109   // This is not the right CC for (e.g.) a variable initialization.
13110   AnalyzeImplicitConversions(*this, E, CC);
13111 }
13112 
13113 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13114 /// Input argument E is a logical expression.
13115 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13116   ::CheckBoolLikeConversion(*this, E, CC);
13117 }
13118 
13119 /// Diagnose when expression is an integer constant expression and its evaluation
13120 /// results in integer overflow
13121 void Sema::CheckForIntOverflow (Expr *E) {
13122   // Use a work list to deal with nested struct initializers.
13123   SmallVector<Expr *, 2> Exprs(1, E);
13124 
13125   do {
13126     Expr *OriginalE = Exprs.pop_back_val();
13127     Expr *E = OriginalE->IgnoreParenCasts();
13128 
13129     if (isa<BinaryOperator>(E)) {
13130       E->EvaluateForOverflow(Context);
13131       continue;
13132     }
13133 
13134     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13135       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13136     else if (isa<ObjCBoxedExpr>(OriginalE))
13137       E->EvaluateForOverflow(Context);
13138     else if (auto Call = dyn_cast<CallExpr>(E))
13139       Exprs.append(Call->arg_begin(), Call->arg_end());
13140     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13141       Exprs.append(Message->arg_begin(), Message->arg_end());
13142   } while (!Exprs.empty());
13143 }
13144 
13145 namespace {
13146 
13147 /// Visitor for expressions which looks for unsequenced operations on the
13148 /// same object.
13149 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13150   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13151 
13152   /// A tree of sequenced regions within an expression. Two regions are
13153   /// unsequenced if one is an ancestor or a descendent of the other. When we
13154   /// finish processing an expression with sequencing, such as a comma
13155   /// expression, we fold its tree nodes into its parent, since they are
13156   /// unsequenced with respect to nodes we will visit later.
13157   class SequenceTree {
13158     struct Value {
13159       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13160       unsigned Parent : 31;
13161       unsigned Merged : 1;
13162     };
13163     SmallVector<Value, 8> Values;
13164 
13165   public:
13166     /// A region within an expression which may be sequenced with respect
13167     /// to some other region.
13168     class Seq {
13169       friend class SequenceTree;
13170 
13171       unsigned Index;
13172 
13173       explicit Seq(unsigned N) : Index(N) {}
13174 
13175     public:
13176       Seq() : Index(0) {}
13177     };
13178 
13179     SequenceTree() { Values.push_back(Value(0)); }
13180     Seq root() const { return Seq(0); }
13181 
13182     /// Create a new sequence of operations, which is an unsequenced
13183     /// subset of \p Parent. This sequence of operations is sequenced with
13184     /// respect to other children of \p Parent.
13185     Seq allocate(Seq Parent) {
13186       Values.push_back(Value(Parent.Index));
13187       return Seq(Values.size() - 1);
13188     }
13189 
13190     /// Merge a sequence of operations into its parent.
13191     void merge(Seq S) {
13192       Values[S.Index].Merged = true;
13193     }
13194 
13195     /// Determine whether two operations are unsequenced. This operation
13196     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13197     /// should have been merged into its parent as appropriate.
13198     bool isUnsequenced(Seq Cur, Seq Old) {
13199       unsigned C = representative(Cur.Index);
13200       unsigned Target = representative(Old.Index);
13201       while (C >= Target) {
13202         if (C == Target)
13203           return true;
13204         C = Values[C].Parent;
13205       }
13206       return false;
13207     }
13208 
13209   private:
13210     /// Pick a representative for a sequence.
13211     unsigned representative(unsigned K) {
13212       if (Values[K].Merged)
13213         // Perform path compression as we go.
13214         return Values[K].Parent = representative(Values[K].Parent);
13215       return K;
13216     }
13217   };
13218 
13219   /// An object for which we can track unsequenced uses.
13220   using Object = const NamedDecl *;
13221 
13222   /// Different flavors of object usage which we track. We only track the
13223   /// least-sequenced usage of each kind.
13224   enum UsageKind {
13225     /// A read of an object. Multiple unsequenced reads are OK.
13226     UK_Use,
13227 
13228     /// A modification of an object which is sequenced before the value
13229     /// computation of the expression, such as ++n in C++.
13230     UK_ModAsValue,
13231 
13232     /// A modification of an object which is not sequenced before the value
13233     /// computation of the expression, such as n++.
13234     UK_ModAsSideEffect,
13235 
13236     UK_Count = UK_ModAsSideEffect + 1
13237   };
13238 
13239   /// Bundle together a sequencing region and the expression corresponding
13240   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13241   struct Usage {
13242     const Expr *UsageExpr;
13243     SequenceTree::Seq Seq;
13244 
13245     Usage() : UsageExpr(nullptr), Seq() {}
13246   };
13247 
13248   struct UsageInfo {
13249     Usage Uses[UK_Count];
13250 
13251     /// Have we issued a diagnostic for this object already?
13252     bool Diagnosed;
13253 
13254     UsageInfo() : Uses(), Diagnosed(false) {}
13255   };
13256   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13257 
13258   Sema &SemaRef;
13259 
13260   /// Sequenced regions within the expression.
13261   SequenceTree Tree;
13262 
13263   /// Declaration modifications and references which we have seen.
13264   UsageInfoMap UsageMap;
13265 
13266   /// The region we are currently within.
13267   SequenceTree::Seq Region;
13268 
13269   /// Filled in with declarations which were modified as a side-effect
13270   /// (that is, post-increment operations).
13271   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13272 
13273   /// Expressions to check later. We defer checking these to reduce
13274   /// stack usage.
13275   SmallVectorImpl<const Expr *> &WorkList;
13276 
13277   /// RAII object wrapping the visitation of a sequenced subexpression of an
13278   /// expression. At the end of this process, the side-effects of the evaluation
13279   /// become sequenced with respect to the value computation of the result, so
13280   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13281   /// UK_ModAsValue.
13282   struct SequencedSubexpression {
13283     SequencedSubexpression(SequenceChecker &Self)
13284       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13285       Self.ModAsSideEffect = &ModAsSideEffect;
13286     }
13287 
13288     ~SequencedSubexpression() {
13289       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13290         // Add a new usage with usage kind UK_ModAsValue, and then restore
13291         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13292         // the previous one was empty).
13293         UsageInfo &UI = Self.UsageMap[M.first];
13294         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13295         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13296         SideEffectUsage = M.second;
13297       }
13298       Self.ModAsSideEffect = OldModAsSideEffect;
13299     }
13300 
13301     SequenceChecker &Self;
13302     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13303     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13304   };
13305 
13306   /// RAII object wrapping the visitation of a subexpression which we might
13307   /// choose to evaluate as a constant. If any subexpression is evaluated and
13308   /// found to be non-constant, this allows us to suppress the evaluation of
13309   /// the outer expression.
13310   class EvaluationTracker {
13311   public:
13312     EvaluationTracker(SequenceChecker &Self)
13313         : Self(Self), Prev(Self.EvalTracker) {
13314       Self.EvalTracker = this;
13315     }
13316 
13317     ~EvaluationTracker() {
13318       Self.EvalTracker = Prev;
13319       if (Prev)
13320         Prev->EvalOK &= EvalOK;
13321     }
13322 
13323     bool evaluate(const Expr *E, bool &Result) {
13324       if (!EvalOK || E->isValueDependent())
13325         return false;
13326       EvalOK = E->EvaluateAsBooleanCondition(
13327           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13328       return EvalOK;
13329     }
13330 
13331   private:
13332     SequenceChecker &Self;
13333     EvaluationTracker *Prev;
13334     bool EvalOK = true;
13335   } *EvalTracker = nullptr;
13336 
13337   /// Find the object which is produced by the specified expression,
13338   /// if any.
13339   Object getObject(const Expr *E, bool Mod) const {
13340     E = E->IgnoreParenCasts();
13341     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13342       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13343         return getObject(UO->getSubExpr(), Mod);
13344     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13345       if (BO->getOpcode() == BO_Comma)
13346         return getObject(BO->getRHS(), Mod);
13347       if (Mod && BO->isAssignmentOp())
13348         return getObject(BO->getLHS(), Mod);
13349     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13350       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13351       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13352         return ME->getMemberDecl();
13353     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13354       // FIXME: If this is a reference, map through to its value.
13355       return DRE->getDecl();
13356     return nullptr;
13357   }
13358 
13359   /// Note that an object \p O was modified or used by an expression
13360   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13361   /// the object \p O as obtained via the \p UsageMap.
13362   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13363     // Get the old usage for the given object and usage kind.
13364     Usage &U = UI.Uses[UK];
13365     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13366       // If we have a modification as side effect and are in a sequenced
13367       // subexpression, save the old Usage so that we can restore it later
13368       // in SequencedSubexpression::~SequencedSubexpression.
13369       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13370         ModAsSideEffect->push_back(std::make_pair(O, U));
13371       // Then record the new usage with the current sequencing region.
13372       U.UsageExpr = UsageExpr;
13373       U.Seq = Region;
13374     }
13375   }
13376 
13377   /// Check whether a modification or use of an object \p O in an expression
13378   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13379   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13380   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13381   /// usage and false we are checking for a mod-use unsequenced usage.
13382   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13383                   UsageKind OtherKind, bool IsModMod) {
13384     if (UI.Diagnosed)
13385       return;
13386 
13387     const Usage &U = UI.Uses[OtherKind];
13388     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13389       return;
13390 
13391     const Expr *Mod = U.UsageExpr;
13392     const Expr *ModOrUse = UsageExpr;
13393     if (OtherKind == UK_Use)
13394       std::swap(Mod, ModOrUse);
13395 
13396     SemaRef.DiagRuntimeBehavior(
13397         Mod->getExprLoc(), {Mod, ModOrUse},
13398         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13399                                : diag::warn_unsequenced_mod_use)
13400             << O << SourceRange(ModOrUse->getExprLoc()));
13401     UI.Diagnosed = true;
13402   }
13403 
13404   // A note on note{Pre, Post}{Use, Mod}:
13405   //
13406   // (It helps to follow the algorithm with an expression such as
13407   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13408   //  operations before C++17 and both are well-defined in C++17).
13409   //
13410   // When visiting a node which uses/modify an object we first call notePreUse
13411   // or notePreMod before visiting its sub-expression(s). At this point the
13412   // children of the current node have not yet been visited and so the eventual
13413   // uses/modifications resulting from the children of the current node have not
13414   // been recorded yet.
13415   //
13416   // We then visit the children of the current node. After that notePostUse or
13417   // notePostMod is called. These will 1) detect an unsequenced modification
13418   // as side effect (as in "k++ + k") and 2) add a new usage with the
13419   // appropriate usage kind.
13420   //
13421   // We also have to be careful that some operation sequences modification as
13422   // side effect as well (for example: || or ,). To account for this we wrap
13423   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13424   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13425   // which record usages which are modifications as side effect, and then
13426   // downgrade them (or more accurately restore the previous usage which was a
13427   // modification as side effect) when exiting the scope of the sequenced
13428   // subexpression.
13429 
13430   void notePreUse(Object O, const Expr *UseExpr) {
13431     UsageInfo &UI = UsageMap[O];
13432     // Uses conflict with other modifications.
13433     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13434   }
13435 
13436   void notePostUse(Object O, const Expr *UseExpr) {
13437     UsageInfo &UI = UsageMap[O];
13438     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13439                /*IsModMod=*/false);
13440     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13441   }
13442 
13443   void notePreMod(Object O, const Expr *ModExpr) {
13444     UsageInfo &UI = UsageMap[O];
13445     // Modifications conflict with other modifications and with uses.
13446     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13447     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13448   }
13449 
13450   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13451     UsageInfo &UI = UsageMap[O];
13452     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13453                /*IsModMod=*/true);
13454     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13455   }
13456 
13457 public:
13458   SequenceChecker(Sema &S, const Expr *E,
13459                   SmallVectorImpl<const Expr *> &WorkList)
13460       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13461     Visit(E);
13462     // Silence a -Wunused-private-field since WorkList is now unused.
13463     // TODO: Evaluate if it can be used, and if not remove it.
13464     (void)this->WorkList;
13465   }
13466 
13467   void VisitStmt(const Stmt *S) {
13468     // Skip all statements which aren't expressions for now.
13469   }
13470 
13471   void VisitExpr(const Expr *E) {
13472     // By default, just recurse to evaluated subexpressions.
13473     Base::VisitStmt(E);
13474   }
13475 
13476   void VisitCastExpr(const CastExpr *E) {
13477     Object O = Object();
13478     if (E->getCastKind() == CK_LValueToRValue)
13479       O = getObject(E->getSubExpr(), false);
13480 
13481     if (O)
13482       notePreUse(O, E);
13483     VisitExpr(E);
13484     if (O)
13485       notePostUse(O, E);
13486   }
13487 
13488   void VisitSequencedExpressions(const Expr *SequencedBefore,
13489                                  const Expr *SequencedAfter) {
13490     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13491     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13492     SequenceTree::Seq OldRegion = Region;
13493 
13494     {
13495       SequencedSubexpression SeqBefore(*this);
13496       Region = BeforeRegion;
13497       Visit(SequencedBefore);
13498     }
13499 
13500     Region = AfterRegion;
13501     Visit(SequencedAfter);
13502 
13503     Region = OldRegion;
13504 
13505     Tree.merge(BeforeRegion);
13506     Tree.merge(AfterRegion);
13507   }
13508 
13509   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13510     // C++17 [expr.sub]p1:
13511     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13512     //   expression E1 is sequenced before the expression E2.
13513     if (SemaRef.getLangOpts().CPlusPlus17)
13514       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13515     else {
13516       Visit(ASE->getLHS());
13517       Visit(ASE->getRHS());
13518     }
13519   }
13520 
13521   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13522   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13523   void VisitBinPtrMem(const BinaryOperator *BO) {
13524     // C++17 [expr.mptr.oper]p4:
13525     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13526     //  the expression E1 is sequenced before the expression E2.
13527     if (SemaRef.getLangOpts().CPlusPlus17)
13528       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13529     else {
13530       Visit(BO->getLHS());
13531       Visit(BO->getRHS());
13532     }
13533   }
13534 
13535   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13536   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13537   void VisitBinShlShr(const BinaryOperator *BO) {
13538     // C++17 [expr.shift]p4:
13539     //  The expression E1 is sequenced before the expression E2.
13540     if (SemaRef.getLangOpts().CPlusPlus17)
13541       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13542     else {
13543       Visit(BO->getLHS());
13544       Visit(BO->getRHS());
13545     }
13546   }
13547 
13548   void VisitBinComma(const BinaryOperator *BO) {
13549     // C++11 [expr.comma]p1:
13550     //   Every value computation and side effect associated with the left
13551     //   expression is sequenced before every value computation and side
13552     //   effect associated with the right expression.
13553     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13554   }
13555 
13556   void VisitBinAssign(const BinaryOperator *BO) {
13557     SequenceTree::Seq RHSRegion;
13558     SequenceTree::Seq LHSRegion;
13559     if (SemaRef.getLangOpts().CPlusPlus17) {
13560       RHSRegion = Tree.allocate(Region);
13561       LHSRegion = Tree.allocate(Region);
13562     } else {
13563       RHSRegion = Region;
13564       LHSRegion = Region;
13565     }
13566     SequenceTree::Seq OldRegion = Region;
13567 
13568     // C++11 [expr.ass]p1:
13569     //  [...] the assignment is sequenced after the value computation
13570     //  of the right and left operands, [...]
13571     //
13572     // so check it before inspecting the operands and update the
13573     // map afterwards.
13574     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13575     if (O)
13576       notePreMod(O, BO);
13577 
13578     if (SemaRef.getLangOpts().CPlusPlus17) {
13579       // C++17 [expr.ass]p1:
13580       //  [...] The right operand is sequenced before the left operand. [...]
13581       {
13582         SequencedSubexpression SeqBefore(*this);
13583         Region = RHSRegion;
13584         Visit(BO->getRHS());
13585       }
13586 
13587       Region = LHSRegion;
13588       Visit(BO->getLHS());
13589 
13590       if (O && isa<CompoundAssignOperator>(BO))
13591         notePostUse(O, BO);
13592 
13593     } else {
13594       // C++11 does not specify any sequencing between the LHS and RHS.
13595       Region = LHSRegion;
13596       Visit(BO->getLHS());
13597 
13598       if (O && isa<CompoundAssignOperator>(BO))
13599         notePostUse(O, BO);
13600 
13601       Region = RHSRegion;
13602       Visit(BO->getRHS());
13603     }
13604 
13605     // C++11 [expr.ass]p1:
13606     //  the assignment is sequenced [...] before the value computation of the
13607     //  assignment expression.
13608     // C11 6.5.16/3 has no such rule.
13609     Region = OldRegion;
13610     if (O)
13611       notePostMod(O, BO,
13612                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13613                                                   : UK_ModAsSideEffect);
13614     if (SemaRef.getLangOpts().CPlusPlus17) {
13615       Tree.merge(RHSRegion);
13616       Tree.merge(LHSRegion);
13617     }
13618   }
13619 
13620   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13621     VisitBinAssign(CAO);
13622   }
13623 
13624   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13625   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13626   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13627     Object O = getObject(UO->getSubExpr(), true);
13628     if (!O)
13629       return VisitExpr(UO);
13630 
13631     notePreMod(O, UO);
13632     Visit(UO->getSubExpr());
13633     // C++11 [expr.pre.incr]p1:
13634     //   the expression ++x is equivalent to x+=1
13635     notePostMod(O, UO,
13636                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13637                                                 : UK_ModAsSideEffect);
13638   }
13639 
13640   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13641   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13642   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13643     Object O = getObject(UO->getSubExpr(), true);
13644     if (!O)
13645       return VisitExpr(UO);
13646 
13647     notePreMod(O, UO);
13648     Visit(UO->getSubExpr());
13649     notePostMod(O, UO, UK_ModAsSideEffect);
13650   }
13651 
13652   void VisitBinLOr(const BinaryOperator *BO) {
13653     // C++11 [expr.log.or]p2:
13654     //  If the second expression is evaluated, every value computation and
13655     //  side effect associated with the first expression is sequenced before
13656     //  every value computation and side effect associated with the
13657     //  second expression.
13658     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13659     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13660     SequenceTree::Seq OldRegion = Region;
13661 
13662     EvaluationTracker Eval(*this);
13663     {
13664       SequencedSubexpression Sequenced(*this);
13665       Region = LHSRegion;
13666       Visit(BO->getLHS());
13667     }
13668 
13669     // C++11 [expr.log.or]p1:
13670     //  [...] the second operand is not evaluated if the first operand
13671     //  evaluates to true.
13672     bool EvalResult = false;
13673     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13674     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13675     if (ShouldVisitRHS) {
13676       Region = RHSRegion;
13677       Visit(BO->getRHS());
13678     }
13679 
13680     Region = OldRegion;
13681     Tree.merge(LHSRegion);
13682     Tree.merge(RHSRegion);
13683   }
13684 
13685   void VisitBinLAnd(const BinaryOperator *BO) {
13686     // C++11 [expr.log.and]p2:
13687     //  If the second expression is evaluated, every value computation and
13688     //  side effect associated with the first expression is sequenced before
13689     //  every value computation and side effect associated with the
13690     //  second expression.
13691     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13692     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13693     SequenceTree::Seq OldRegion = Region;
13694 
13695     EvaluationTracker Eval(*this);
13696     {
13697       SequencedSubexpression Sequenced(*this);
13698       Region = LHSRegion;
13699       Visit(BO->getLHS());
13700     }
13701 
13702     // C++11 [expr.log.and]p1:
13703     //  [...] the second operand is not evaluated if the first operand is false.
13704     bool EvalResult = false;
13705     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13706     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13707     if (ShouldVisitRHS) {
13708       Region = RHSRegion;
13709       Visit(BO->getRHS());
13710     }
13711 
13712     Region = OldRegion;
13713     Tree.merge(LHSRegion);
13714     Tree.merge(RHSRegion);
13715   }
13716 
13717   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13718     // C++11 [expr.cond]p1:
13719     //  [...] Every value computation and side effect associated with the first
13720     //  expression is sequenced before every value computation and side effect
13721     //  associated with the second or third expression.
13722     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13723 
13724     // No sequencing is specified between the true and false expression.
13725     // However since exactly one of both is going to be evaluated we can
13726     // consider them to be sequenced. This is needed to avoid warning on
13727     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13728     // both the true and false expressions because we can't evaluate x.
13729     // This will still allow us to detect an expression like (pre C++17)
13730     // "(x ? y += 1 : y += 2) = y".
13731     //
13732     // We don't wrap the visitation of the true and false expression with
13733     // SequencedSubexpression because we don't want to downgrade modifications
13734     // as side effect in the true and false expressions after the visition
13735     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13736     // not warn between the two "y++", but we should warn between the "y++"
13737     // and the "y".
13738     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13739     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13740     SequenceTree::Seq OldRegion = Region;
13741 
13742     EvaluationTracker Eval(*this);
13743     {
13744       SequencedSubexpression Sequenced(*this);
13745       Region = ConditionRegion;
13746       Visit(CO->getCond());
13747     }
13748 
13749     // C++11 [expr.cond]p1:
13750     // [...] The first expression is contextually converted to bool (Clause 4).
13751     // It is evaluated and if it is true, the result of the conditional
13752     // expression is the value of the second expression, otherwise that of the
13753     // third expression. Only one of the second and third expressions is
13754     // evaluated. [...]
13755     bool EvalResult = false;
13756     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13757     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13758     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13759     if (ShouldVisitTrueExpr) {
13760       Region = TrueRegion;
13761       Visit(CO->getTrueExpr());
13762     }
13763     if (ShouldVisitFalseExpr) {
13764       Region = FalseRegion;
13765       Visit(CO->getFalseExpr());
13766     }
13767 
13768     Region = OldRegion;
13769     Tree.merge(ConditionRegion);
13770     Tree.merge(TrueRegion);
13771     Tree.merge(FalseRegion);
13772   }
13773 
13774   void VisitCallExpr(const CallExpr *CE) {
13775     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13776 
13777     if (CE->isUnevaluatedBuiltinCall(Context))
13778       return;
13779 
13780     // C++11 [intro.execution]p15:
13781     //   When calling a function [...], every value computation and side effect
13782     //   associated with any argument expression, or with the postfix expression
13783     //   designating the called function, is sequenced before execution of every
13784     //   expression or statement in the body of the function [and thus before
13785     //   the value computation of its result].
13786     SequencedSubexpression Sequenced(*this);
13787     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13788       // C++17 [expr.call]p5
13789       //   The postfix-expression is sequenced before each expression in the
13790       //   expression-list and any default argument. [...]
13791       SequenceTree::Seq CalleeRegion;
13792       SequenceTree::Seq OtherRegion;
13793       if (SemaRef.getLangOpts().CPlusPlus17) {
13794         CalleeRegion = Tree.allocate(Region);
13795         OtherRegion = Tree.allocate(Region);
13796       } else {
13797         CalleeRegion = Region;
13798         OtherRegion = Region;
13799       }
13800       SequenceTree::Seq OldRegion = Region;
13801 
13802       // Visit the callee expression first.
13803       Region = CalleeRegion;
13804       if (SemaRef.getLangOpts().CPlusPlus17) {
13805         SequencedSubexpression Sequenced(*this);
13806         Visit(CE->getCallee());
13807       } else {
13808         Visit(CE->getCallee());
13809       }
13810 
13811       // Then visit the argument expressions.
13812       Region = OtherRegion;
13813       for (const Expr *Argument : CE->arguments())
13814         Visit(Argument);
13815 
13816       Region = OldRegion;
13817       if (SemaRef.getLangOpts().CPlusPlus17) {
13818         Tree.merge(CalleeRegion);
13819         Tree.merge(OtherRegion);
13820       }
13821     });
13822   }
13823 
13824   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13825     // C++17 [over.match.oper]p2:
13826     //   [...] the operator notation is first transformed to the equivalent
13827     //   function-call notation as summarized in Table 12 (where @ denotes one
13828     //   of the operators covered in the specified subclause). However, the
13829     //   operands are sequenced in the order prescribed for the built-in
13830     //   operator (Clause 8).
13831     //
13832     // From the above only overloaded binary operators and overloaded call
13833     // operators have sequencing rules in C++17 that we need to handle
13834     // separately.
13835     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13836         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13837       return VisitCallExpr(CXXOCE);
13838 
13839     enum {
13840       NoSequencing,
13841       LHSBeforeRHS,
13842       RHSBeforeLHS,
13843       LHSBeforeRest
13844     } SequencingKind;
13845     switch (CXXOCE->getOperator()) {
13846     case OO_Equal:
13847     case OO_PlusEqual:
13848     case OO_MinusEqual:
13849     case OO_StarEqual:
13850     case OO_SlashEqual:
13851     case OO_PercentEqual:
13852     case OO_CaretEqual:
13853     case OO_AmpEqual:
13854     case OO_PipeEqual:
13855     case OO_LessLessEqual:
13856     case OO_GreaterGreaterEqual:
13857       SequencingKind = RHSBeforeLHS;
13858       break;
13859 
13860     case OO_LessLess:
13861     case OO_GreaterGreater:
13862     case OO_AmpAmp:
13863     case OO_PipePipe:
13864     case OO_Comma:
13865     case OO_ArrowStar:
13866     case OO_Subscript:
13867       SequencingKind = LHSBeforeRHS;
13868       break;
13869 
13870     case OO_Call:
13871       SequencingKind = LHSBeforeRest;
13872       break;
13873 
13874     default:
13875       SequencingKind = NoSequencing;
13876       break;
13877     }
13878 
13879     if (SequencingKind == NoSequencing)
13880       return VisitCallExpr(CXXOCE);
13881 
13882     // This is a call, so all subexpressions are sequenced before the result.
13883     SequencedSubexpression Sequenced(*this);
13884 
13885     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13886       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13887              "Should only get there with C++17 and above!");
13888       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13889              "Should only get there with an overloaded binary operator"
13890              " or an overloaded call operator!");
13891 
13892       if (SequencingKind == LHSBeforeRest) {
13893         assert(CXXOCE->getOperator() == OO_Call &&
13894                "We should only have an overloaded call operator here!");
13895 
13896         // This is very similar to VisitCallExpr, except that we only have the
13897         // C++17 case. The postfix-expression is the first argument of the
13898         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13899         // are in the following arguments.
13900         //
13901         // Note that we intentionally do not visit the callee expression since
13902         // it is just a decayed reference to a function.
13903         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13904         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13905         SequenceTree::Seq OldRegion = Region;
13906 
13907         assert(CXXOCE->getNumArgs() >= 1 &&
13908                "An overloaded call operator must have at least one argument"
13909                " for the postfix-expression!");
13910         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13911         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13912                                           CXXOCE->getNumArgs() - 1);
13913 
13914         // Visit the postfix-expression first.
13915         {
13916           Region = PostfixExprRegion;
13917           SequencedSubexpression Sequenced(*this);
13918           Visit(PostfixExpr);
13919         }
13920 
13921         // Then visit the argument expressions.
13922         Region = ArgsRegion;
13923         for (const Expr *Arg : Args)
13924           Visit(Arg);
13925 
13926         Region = OldRegion;
13927         Tree.merge(PostfixExprRegion);
13928         Tree.merge(ArgsRegion);
13929       } else {
13930         assert(CXXOCE->getNumArgs() == 2 &&
13931                "Should only have two arguments here!");
13932         assert((SequencingKind == LHSBeforeRHS ||
13933                 SequencingKind == RHSBeforeLHS) &&
13934                "Unexpected sequencing kind!");
13935 
13936         // We do not visit the callee expression since it is just a decayed
13937         // reference to a function.
13938         const Expr *E1 = CXXOCE->getArg(0);
13939         const Expr *E2 = CXXOCE->getArg(1);
13940         if (SequencingKind == RHSBeforeLHS)
13941           std::swap(E1, E2);
13942 
13943         return VisitSequencedExpressions(E1, E2);
13944       }
13945     });
13946   }
13947 
13948   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13949     // This is a call, so all subexpressions are sequenced before the result.
13950     SequencedSubexpression Sequenced(*this);
13951 
13952     if (!CCE->isListInitialization())
13953       return VisitExpr(CCE);
13954 
13955     // In C++11, list initializations are sequenced.
13956     SmallVector<SequenceTree::Seq, 32> Elts;
13957     SequenceTree::Seq Parent = Region;
13958     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13959                                               E = CCE->arg_end();
13960          I != E; ++I) {
13961       Region = Tree.allocate(Parent);
13962       Elts.push_back(Region);
13963       Visit(*I);
13964     }
13965 
13966     // Forget that the initializers are sequenced.
13967     Region = Parent;
13968     for (unsigned I = 0; I < Elts.size(); ++I)
13969       Tree.merge(Elts[I]);
13970   }
13971 
13972   void VisitInitListExpr(const InitListExpr *ILE) {
13973     if (!SemaRef.getLangOpts().CPlusPlus11)
13974       return VisitExpr(ILE);
13975 
13976     // In C++11, list initializations are sequenced.
13977     SmallVector<SequenceTree::Seq, 32> Elts;
13978     SequenceTree::Seq Parent = Region;
13979     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13980       const Expr *E = ILE->getInit(I);
13981       if (!E)
13982         continue;
13983       Region = Tree.allocate(Parent);
13984       Elts.push_back(Region);
13985       Visit(E);
13986     }
13987 
13988     // Forget that the initializers are sequenced.
13989     Region = Parent;
13990     for (unsigned I = 0; I < Elts.size(); ++I)
13991       Tree.merge(Elts[I]);
13992   }
13993 };
13994 
13995 } // namespace
13996 
13997 void Sema::CheckUnsequencedOperations(const Expr *E) {
13998   SmallVector<const Expr *, 8> WorkList;
13999   WorkList.push_back(E);
14000   while (!WorkList.empty()) {
14001     const Expr *Item = WorkList.pop_back_val();
14002     SequenceChecker(*this, Item, WorkList);
14003   }
14004 }
14005 
14006 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14007                               bool IsConstexpr) {
14008   llvm::SaveAndRestore<bool> ConstantContext(
14009       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14010   CheckImplicitConversions(E, CheckLoc);
14011   if (!E->isInstantiationDependent())
14012     CheckUnsequencedOperations(E);
14013   if (!IsConstexpr && !E->isValueDependent())
14014     CheckForIntOverflow(E);
14015   DiagnoseMisalignedMembers();
14016 }
14017 
14018 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14019                                        FieldDecl *BitField,
14020                                        Expr *Init) {
14021   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14022 }
14023 
14024 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14025                                          SourceLocation Loc) {
14026   if (!PType->isVariablyModifiedType())
14027     return;
14028   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14029     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14030     return;
14031   }
14032   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14033     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14034     return;
14035   }
14036   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14037     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14038     return;
14039   }
14040 
14041   const ArrayType *AT = S.Context.getAsArrayType(PType);
14042   if (!AT)
14043     return;
14044 
14045   if (AT->getSizeModifier() != ArrayType::Star) {
14046     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14047     return;
14048   }
14049 
14050   S.Diag(Loc, diag::err_array_star_in_function_definition);
14051 }
14052 
14053 /// CheckParmsForFunctionDef - Check that the parameters of the given
14054 /// function are appropriate for the definition of a function. This
14055 /// takes care of any checks that cannot be performed on the
14056 /// declaration itself, e.g., that the types of each of the function
14057 /// parameters are complete.
14058 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14059                                     bool CheckParameterNames) {
14060   bool HasInvalidParm = false;
14061   for (ParmVarDecl *Param : Parameters) {
14062     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14063     // function declarator that is part of a function definition of
14064     // that function shall not have incomplete type.
14065     //
14066     // This is also C++ [dcl.fct]p6.
14067     if (!Param->isInvalidDecl() &&
14068         RequireCompleteType(Param->getLocation(), Param->getType(),
14069                             diag::err_typecheck_decl_incomplete_type)) {
14070       Param->setInvalidDecl();
14071       HasInvalidParm = true;
14072     }
14073 
14074     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14075     // declaration of each parameter shall include an identifier.
14076     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14077         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14078       // Diagnose this as an extension in C17 and earlier.
14079       if (!getLangOpts().C2x)
14080         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14081     }
14082 
14083     // C99 6.7.5.3p12:
14084     //   If the function declarator is not part of a definition of that
14085     //   function, parameters may have incomplete type and may use the [*]
14086     //   notation in their sequences of declarator specifiers to specify
14087     //   variable length array types.
14088     QualType PType = Param->getOriginalType();
14089     // FIXME: This diagnostic should point the '[*]' if source-location
14090     // information is added for it.
14091     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14092 
14093     // If the parameter is a c++ class type and it has to be destructed in the
14094     // callee function, declare the destructor so that it can be called by the
14095     // callee function. Do not perform any direct access check on the dtor here.
14096     if (!Param->isInvalidDecl()) {
14097       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14098         if (!ClassDecl->isInvalidDecl() &&
14099             !ClassDecl->hasIrrelevantDestructor() &&
14100             !ClassDecl->isDependentContext() &&
14101             ClassDecl->isParamDestroyedInCallee()) {
14102           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14103           MarkFunctionReferenced(Param->getLocation(), Destructor);
14104           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14105         }
14106       }
14107     }
14108 
14109     // Parameters with the pass_object_size attribute only need to be marked
14110     // constant at function definitions. Because we lack information about
14111     // whether we're on a declaration or definition when we're instantiating the
14112     // attribute, we need to check for constness here.
14113     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14114       if (!Param->getType().isConstQualified())
14115         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14116             << Attr->getSpelling() << 1;
14117 
14118     // Check for parameter names shadowing fields from the class.
14119     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14120       // The owning context for the parameter should be the function, but we
14121       // want to see if this function's declaration context is a record.
14122       DeclContext *DC = Param->getDeclContext();
14123       if (DC && DC->isFunctionOrMethod()) {
14124         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14125           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14126                                      RD, /*DeclIsField*/ false);
14127       }
14128     }
14129   }
14130 
14131   return HasInvalidParm;
14132 }
14133 
14134 Optional<std::pair<CharUnits, CharUnits>>
14135 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14136 
14137 /// Compute the alignment and offset of the base class object given the
14138 /// derived-to-base cast expression and the alignment and offset of the derived
14139 /// class object.
14140 static std::pair<CharUnits, CharUnits>
14141 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14142                                    CharUnits BaseAlignment, CharUnits Offset,
14143                                    ASTContext &Ctx) {
14144   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14145        ++PathI) {
14146     const CXXBaseSpecifier *Base = *PathI;
14147     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14148     if (Base->isVirtual()) {
14149       // The complete object may have a lower alignment than the non-virtual
14150       // alignment of the base, in which case the base may be misaligned. Choose
14151       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14152       // conservative lower bound of the complete object alignment.
14153       CharUnits NonVirtualAlignment =
14154           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14155       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14156       Offset = CharUnits::Zero();
14157     } else {
14158       const ASTRecordLayout &RL =
14159           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14160       Offset += RL.getBaseClassOffset(BaseDecl);
14161     }
14162     DerivedType = Base->getType();
14163   }
14164 
14165   return std::make_pair(BaseAlignment, Offset);
14166 }
14167 
14168 /// Compute the alignment and offset of a binary additive operator.
14169 static Optional<std::pair<CharUnits, CharUnits>>
14170 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14171                                      bool IsSub, ASTContext &Ctx) {
14172   QualType PointeeType = PtrE->getType()->getPointeeType();
14173 
14174   if (!PointeeType->isConstantSizeType())
14175     return llvm::None;
14176 
14177   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14178 
14179   if (!P)
14180     return llvm::None;
14181 
14182   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14183   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14184     CharUnits Offset = EltSize * IdxRes->getExtValue();
14185     if (IsSub)
14186       Offset = -Offset;
14187     return std::make_pair(P->first, P->second + Offset);
14188   }
14189 
14190   // If the integer expression isn't a constant expression, compute the lower
14191   // bound of the alignment using the alignment and offset of the pointer
14192   // expression and the element size.
14193   return std::make_pair(
14194       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14195       CharUnits::Zero());
14196 }
14197 
14198 /// This helper function takes an lvalue expression and returns the alignment of
14199 /// a VarDecl and a constant offset from the VarDecl.
14200 Optional<std::pair<CharUnits, CharUnits>>
14201 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14202   E = E->IgnoreParens();
14203   switch (E->getStmtClass()) {
14204   default:
14205     break;
14206   case Stmt::CStyleCastExprClass:
14207   case Stmt::CXXStaticCastExprClass:
14208   case Stmt::ImplicitCastExprClass: {
14209     auto *CE = cast<CastExpr>(E);
14210     const Expr *From = CE->getSubExpr();
14211     switch (CE->getCastKind()) {
14212     default:
14213       break;
14214     case CK_NoOp:
14215       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14216     case CK_UncheckedDerivedToBase:
14217     case CK_DerivedToBase: {
14218       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14219       if (!P)
14220         break;
14221       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14222                                                 P->second, Ctx);
14223     }
14224     }
14225     break;
14226   }
14227   case Stmt::ArraySubscriptExprClass: {
14228     auto *ASE = cast<ArraySubscriptExpr>(E);
14229     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14230                                                 false, Ctx);
14231   }
14232   case Stmt::DeclRefExprClass: {
14233     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14234       // FIXME: If VD is captured by copy or is an escaping __block variable,
14235       // use the alignment of VD's type.
14236       if (!VD->getType()->isReferenceType())
14237         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14238       if (VD->hasInit())
14239         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14240     }
14241     break;
14242   }
14243   case Stmt::MemberExprClass: {
14244     auto *ME = cast<MemberExpr>(E);
14245     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14246     if (!FD || FD->getType()->isReferenceType())
14247       break;
14248     Optional<std::pair<CharUnits, CharUnits>> P;
14249     if (ME->isArrow())
14250       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14251     else
14252       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14253     if (!P)
14254       break;
14255     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14256     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14257     return std::make_pair(P->first,
14258                           P->second + CharUnits::fromQuantity(Offset));
14259   }
14260   case Stmt::UnaryOperatorClass: {
14261     auto *UO = cast<UnaryOperator>(E);
14262     switch (UO->getOpcode()) {
14263     default:
14264       break;
14265     case UO_Deref:
14266       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14267     }
14268     break;
14269   }
14270   case Stmt::BinaryOperatorClass: {
14271     auto *BO = cast<BinaryOperator>(E);
14272     auto Opcode = BO->getOpcode();
14273     switch (Opcode) {
14274     default:
14275       break;
14276     case BO_Comma:
14277       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14278     }
14279     break;
14280   }
14281   }
14282   return llvm::None;
14283 }
14284 
14285 /// This helper function takes a pointer expression and returns the alignment of
14286 /// a VarDecl and a constant offset from the VarDecl.
14287 Optional<std::pair<CharUnits, CharUnits>>
14288 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14289   E = E->IgnoreParens();
14290   switch (E->getStmtClass()) {
14291   default:
14292     break;
14293   case Stmt::CStyleCastExprClass:
14294   case Stmt::CXXStaticCastExprClass:
14295   case Stmt::ImplicitCastExprClass: {
14296     auto *CE = cast<CastExpr>(E);
14297     const Expr *From = CE->getSubExpr();
14298     switch (CE->getCastKind()) {
14299     default:
14300       break;
14301     case CK_NoOp:
14302       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14303     case CK_ArrayToPointerDecay:
14304       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14305     case CK_UncheckedDerivedToBase:
14306     case CK_DerivedToBase: {
14307       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14308       if (!P)
14309         break;
14310       return getDerivedToBaseAlignmentAndOffset(
14311           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14312     }
14313     }
14314     break;
14315   }
14316   case Stmt::CXXThisExprClass: {
14317     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14318     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14319     return std::make_pair(Alignment, CharUnits::Zero());
14320   }
14321   case Stmt::UnaryOperatorClass: {
14322     auto *UO = cast<UnaryOperator>(E);
14323     if (UO->getOpcode() == UO_AddrOf)
14324       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14325     break;
14326   }
14327   case Stmt::BinaryOperatorClass: {
14328     auto *BO = cast<BinaryOperator>(E);
14329     auto Opcode = BO->getOpcode();
14330     switch (Opcode) {
14331     default:
14332       break;
14333     case BO_Add:
14334     case BO_Sub: {
14335       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14336       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14337         std::swap(LHS, RHS);
14338       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14339                                                   Ctx);
14340     }
14341     case BO_Comma:
14342       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14343     }
14344     break;
14345   }
14346   }
14347   return llvm::None;
14348 }
14349 
14350 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14351   // See if we can compute the alignment of a VarDecl and an offset from it.
14352   Optional<std::pair<CharUnits, CharUnits>> P =
14353       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14354 
14355   if (P)
14356     return P->first.alignmentAtOffset(P->second);
14357 
14358   // If that failed, return the type's alignment.
14359   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14360 }
14361 
14362 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14363 /// pointer cast increases the alignment requirements.
14364 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14365   // This is actually a lot of work to potentially be doing on every
14366   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14367   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14368     return;
14369 
14370   // Ignore dependent types.
14371   if (T->isDependentType() || Op->getType()->isDependentType())
14372     return;
14373 
14374   // Require that the destination be a pointer type.
14375   const PointerType *DestPtr = T->getAs<PointerType>();
14376   if (!DestPtr) return;
14377 
14378   // If the destination has alignment 1, we're done.
14379   QualType DestPointee = DestPtr->getPointeeType();
14380   if (DestPointee->isIncompleteType()) return;
14381   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14382   if (DestAlign.isOne()) return;
14383 
14384   // Require that the source be a pointer type.
14385   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14386   if (!SrcPtr) return;
14387   QualType SrcPointee = SrcPtr->getPointeeType();
14388 
14389   // Explicitly allow casts from cv void*.  We already implicitly
14390   // allowed casts to cv void*, since they have alignment 1.
14391   // Also allow casts involving incomplete types, which implicitly
14392   // includes 'void'.
14393   if (SrcPointee->isIncompleteType()) return;
14394 
14395   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14396 
14397   if (SrcAlign >= DestAlign) return;
14398 
14399   Diag(TRange.getBegin(), diag::warn_cast_align)
14400     << Op->getType() << T
14401     << static_cast<unsigned>(SrcAlign.getQuantity())
14402     << static_cast<unsigned>(DestAlign.getQuantity())
14403     << TRange << Op->getSourceRange();
14404 }
14405 
14406 /// Check whether this array fits the idiom of a size-one tail padded
14407 /// array member of a struct.
14408 ///
14409 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14410 /// commonly used to emulate flexible arrays in C89 code.
14411 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14412                                     const NamedDecl *ND) {
14413   if (Size != 1 || !ND) return false;
14414 
14415   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14416   if (!FD) return false;
14417 
14418   // Don't consider sizes resulting from macro expansions or template argument
14419   // substitution to form C89 tail-padded arrays.
14420 
14421   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14422   while (TInfo) {
14423     TypeLoc TL = TInfo->getTypeLoc();
14424     // Look through typedefs.
14425     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14426       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14427       TInfo = TDL->getTypeSourceInfo();
14428       continue;
14429     }
14430     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14431       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14432       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14433         return false;
14434     }
14435     break;
14436   }
14437 
14438   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14439   if (!RD) return false;
14440   if (RD->isUnion()) return false;
14441   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14442     if (!CRD->isStandardLayout()) return false;
14443   }
14444 
14445   // See if this is the last field decl in the record.
14446   const Decl *D = FD;
14447   while ((D = D->getNextDeclInContext()))
14448     if (isa<FieldDecl>(D))
14449       return false;
14450   return true;
14451 }
14452 
14453 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14454                             const ArraySubscriptExpr *ASE,
14455                             bool AllowOnePastEnd, bool IndexNegated) {
14456   // Already diagnosed by the constant evaluator.
14457   if (isConstantEvaluated())
14458     return;
14459 
14460   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14461   if (IndexExpr->isValueDependent())
14462     return;
14463 
14464   const Type *EffectiveType =
14465       BaseExpr->getType()->getPointeeOrArrayElementType();
14466   BaseExpr = BaseExpr->IgnoreParenCasts();
14467   const ConstantArrayType *ArrayTy =
14468       Context.getAsConstantArrayType(BaseExpr->getType());
14469 
14470   if (!ArrayTy)
14471     return;
14472 
14473   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14474   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14475     return;
14476 
14477   Expr::EvalResult Result;
14478   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14479     return;
14480 
14481   llvm::APSInt index = Result.Val.getInt();
14482   if (IndexNegated)
14483     index = -index;
14484 
14485   const NamedDecl *ND = nullptr;
14486   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14487     ND = DRE->getDecl();
14488   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14489     ND = ME->getMemberDecl();
14490 
14491   if (index.isUnsigned() || !index.isNegative()) {
14492     // It is possible that the type of the base expression after
14493     // IgnoreParenCasts is incomplete, even though the type of the base
14494     // expression before IgnoreParenCasts is complete (see PR39746 for an
14495     // example). In this case we have no information about whether the array
14496     // access exceeds the array bounds. However we can still diagnose an array
14497     // access which precedes the array bounds.
14498     if (BaseType->isIncompleteType())
14499       return;
14500 
14501     llvm::APInt size = ArrayTy->getSize();
14502     if (!size.isStrictlyPositive())
14503       return;
14504 
14505     if (BaseType != EffectiveType) {
14506       // Make sure we're comparing apples to apples when comparing index to size
14507       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14508       uint64_t array_typesize = Context.getTypeSize(BaseType);
14509       // Handle ptrarith_typesize being zero, such as when casting to void*
14510       if (!ptrarith_typesize) ptrarith_typesize = 1;
14511       if (ptrarith_typesize != array_typesize) {
14512         // There's a cast to a different size type involved
14513         uint64_t ratio = array_typesize / ptrarith_typesize;
14514         // TODO: Be smarter about handling cases where array_typesize is not a
14515         // multiple of ptrarith_typesize
14516         if (ptrarith_typesize * ratio == array_typesize)
14517           size *= llvm::APInt(size.getBitWidth(), ratio);
14518       }
14519     }
14520 
14521     if (size.getBitWidth() > index.getBitWidth())
14522       index = index.zext(size.getBitWidth());
14523     else if (size.getBitWidth() < index.getBitWidth())
14524       size = size.zext(index.getBitWidth());
14525 
14526     // For array subscripting the index must be less than size, but for pointer
14527     // arithmetic also allow the index (offset) to be equal to size since
14528     // computing the next address after the end of the array is legal and
14529     // commonly done e.g. in C++ iterators and range-based for loops.
14530     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14531       return;
14532 
14533     // Also don't warn for arrays of size 1 which are members of some
14534     // structure. These are often used to approximate flexible arrays in C89
14535     // code.
14536     if (IsTailPaddedMemberArray(*this, size, ND))
14537       return;
14538 
14539     // Suppress the warning if the subscript expression (as identified by the
14540     // ']' location) and the index expression are both from macro expansions
14541     // within a system header.
14542     if (ASE) {
14543       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14544           ASE->getRBracketLoc());
14545       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14546         SourceLocation IndexLoc =
14547             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14548         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14549           return;
14550       }
14551     }
14552 
14553     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14554     if (ASE)
14555       DiagID = diag::warn_array_index_exceeds_bounds;
14556 
14557     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14558                         PDiag(DiagID) << index.toString(10, true)
14559                                       << size.toString(10, true)
14560                                       << (unsigned)size.getLimitedValue(~0U)
14561                                       << IndexExpr->getSourceRange());
14562   } else {
14563     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14564     if (!ASE) {
14565       DiagID = diag::warn_ptr_arith_precedes_bounds;
14566       if (index.isNegative()) index = -index;
14567     }
14568 
14569     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14570                         PDiag(DiagID) << index.toString(10, true)
14571                                       << IndexExpr->getSourceRange());
14572   }
14573 
14574   if (!ND) {
14575     // Try harder to find a NamedDecl to point at in the note.
14576     while (const ArraySubscriptExpr *ASE =
14577            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14578       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14579     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14580       ND = DRE->getDecl();
14581     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14582       ND = ME->getMemberDecl();
14583   }
14584 
14585   if (ND)
14586     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14587                         PDiag(diag::note_array_declared_here) << ND);
14588 }
14589 
14590 void Sema::CheckArrayAccess(const Expr *expr) {
14591   int AllowOnePastEnd = 0;
14592   while (expr) {
14593     expr = expr->IgnoreParenImpCasts();
14594     switch (expr->getStmtClass()) {
14595       case Stmt::ArraySubscriptExprClass: {
14596         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14597         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14598                          AllowOnePastEnd > 0);
14599         expr = ASE->getBase();
14600         break;
14601       }
14602       case Stmt::MemberExprClass: {
14603         expr = cast<MemberExpr>(expr)->getBase();
14604         break;
14605       }
14606       case Stmt::OMPArraySectionExprClass: {
14607         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14608         if (ASE->getLowerBound())
14609           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14610                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14611         return;
14612       }
14613       case Stmt::UnaryOperatorClass: {
14614         // Only unwrap the * and & unary operators
14615         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14616         expr = UO->getSubExpr();
14617         switch (UO->getOpcode()) {
14618           case UO_AddrOf:
14619             AllowOnePastEnd++;
14620             break;
14621           case UO_Deref:
14622             AllowOnePastEnd--;
14623             break;
14624           default:
14625             return;
14626         }
14627         break;
14628       }
14629       case Stmt::ConditionalOperatorClass: {
14630         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14631         if (const Expr *lhs = cond->getLHS())
14632           CheckArrayAccess(lhs);
14633         if (const Expr *rhs = cond->getRHS())
14634           CheckArrayAccess(rhs);
14635         return;
14636       }
14637       case Stmt::CXXOperatorCallExprClass: {
14638         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14639         for (const auto *Arg : OCE->arguments())
14640           CheckArrayAccess(Arg);
14641         return;
14642       }
14643       default:
14644         return;
14645     }
14646   }
14647 }
14648 
14649 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14650 
14651 namespace {
14652 
14653 struct RetainCycleOwner {
14654   VarDecl *Variable = nullptr;
14655   SourceRange Range;
14656   SourceLocation Loc;
14657   bool Indirect = false;
14658 
14659   RetainCycleOwner() = default;
14660 
14661   void setLocsFrom(Expr *e) {
14662     Loc = e->getExprLoc();
14663     Range = e->getSourceRange();
14664   }
14665 };
14666 
14667 } // namespace
14668 
14669 /// Consider whether capturing the given variable can possibly lead to
14670 /// a retain cycle.
14671 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14672   // In ARC, it's captured strongly iff the variable has __strong
14673   // lifetime.  In MRR, it's captured strongly if the variable is
14674   // __block and has an appropriate type.
14675   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14676     return false;
14677 
14678   owner.Variable = var;
14679   if (ref)
14680     owner.setLocsFrom(ref);
14681   return true;
14682 }
14683 
14684 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14685   while (true) {
14686     e = e->IgnoreParens();
14687     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14688       switch (cast->getCastKind()) {
14689       case CK_BitCast:
14690       case CK_LValueBitCast:
14691       case CK_LValueToRValue:
14692       case CK_ARCReclaimReturnedObject:
14693         e = cast->getSubExpr();
14694         continue;
14695 
14696       default:
14697         return false;
14698       }
14699     }
14700 
14701     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14702       ObjCIvarDecl *ivar = ref->getDecl();
14703       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14704         return false;
14705 
14706       // Try to find a retain cycle in the base.
14707       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14708         return false;
14709 
14710       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14711       owner.Indirect = true;
14712       return true;
14713     }
14714 
14715     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14716       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14717       if (!var) return false;
14718       return considerVariable(var, ref, owner);
14719     }
14720 
14721     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14722       if (member->isArrow()) return false;
14723 
14724       // Don't count this as an indirect ownership.
14725       e = member->getBase();
14726       continue;
14727     }
14728 
14729     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14730       // Only pay attention to pseudo-objects on property references.
14731       ObjCPropertyRefExpr *pre
14732         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14733                                               ->IgnoreParens());
14734       if (!pre) return false;
14735       if (pre->isImplicitProperty()) return false;
14736       ObjCPropertyDecl *property = pre->getExplicitProperty();
14737       if (!property->isRetaining() &&
14738           !(property->getPropertyIvarDecl() &&
14739             property->getPropertyIvarDecl()->getType()
14740               .getObjCLifetime() == Qualifiers::OCL_Strong))
14741           return false;
14742 
14743       owner.Indirect = true;
14744       if (pre->isSuperReceiver()) {
14745         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14746         if (!owner.Variable)
14747           return false;
14748         owner.Loc = pre->getLocation();
14749         owner.Range = pre->getSourceRange();
14750         return true;
14751       }
14752       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14753                               ->getSourceExpr());
14754       continue;
14755     }
14756 
14757     // Array ivars?
14758 
14759     return false;
14760   }
14761 }
14762 
14763 namespace {
14764 
14765   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14766     ASTContext &Context;
14767     VarDecl *Variable;
14768     Expr *Capturer = nullptr;
14769     bool VarWillBeReased = false;
14770 
14771     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14772         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14773           Context(Context), Variable(variable) {}
14774 
14775     void VisitDeclRefExpr(DeclRefExpr *ref) {
14776       if (ref->getDecl() == Variable && !Capturer)
14777         Capturer = ref;
14778     }
14779 
14780     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14781       if (Capturer) return;
14782       Visit(ref->getBase());
14783       if (Capturer && ref->isFreeIvar())
14784         Capturer = ref;
14785     }
14786 
14787     void VisitBlockExpr(BlockExpr *block) {
14788       // Look inside nested blocks
14789       if (block->getBlockDecl()->capturesVariable(Variable))
14790         Visit(block->getBlockDecl()->getBody());
14791     }
14792 
14793     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14794       if (Capturer) return;
14795       if (OVE->getSourceExpr())
14796         Visit(OVE->getSourceExpr());
14797     }
14798 
14799     void VisitBinaryOperator(BinaryOperator *BinOp) {
14800       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14801         return;
14802       Expr *LHS = BinOp->getLHS();
14803       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14804         if (DRE->getDecl() != Variable)
14805           return;
14806         if (Expr *RHS = BinOp->getRHS()) {
14807           RHS = RHS->IgnoreParenCasts();
14808           Optional<llvm::APSInt> Value;
14809           VarWillBeReased =
14810               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14811                *Value == 0);
14812         }
14813       }
14814     }
14815   };
14816 
14817 } // namespace
14818 
14819 /// Check whether the given argument is a block which captures a
14820 /// variable.
14821 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14822   assert(owner.Variable && owner.Loc.isValid());
14823 
14824   e = e->IgnoreParenCasts();
14825 
14826   // Look through [^{...} copy] and Block_copy(^{...}).
14827   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14828     Selector Cmd = ME->getSelector();
14829     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14830       e = ME->getInstanceReceiver();
14831       if (!e)
14832         return nullptr;
14833       e = e->IgnoreParenCasts();
14834     }
14835   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14836     if (CE->getNumArgs() == 1) {
14837       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14838       if (Fn) {
14839         const IdentifierInfo *FnI = Fn->getIdentifier();
14840         if (FnI && FnI->isStr("_Block_copy")) {
14841           e = CE->getArg(0)->IgnoreParenCasts();
14842         }
14843       }
14844     }
14845   }
14846 
14847   BlockExpr *block = dyn_cast<BlockExpr>(e);
14848   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14849     return nullptr;
14850 
14851   FindCaptureVisitor visitor(S.Context, owner.Variable);
14852   visitor.Visit(block->getBlockDecl()->getBody());
14853   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14854 }
14855 
14856 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14857                                 RetainCycleOwner &owner) {
14858   assert(capturer);
14859   assert(owner.Variable && owner.Loc.isValid());
14860 
14861   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14862     << owner.Variable << capturer->getSourceRange();
14863   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14864     << owner.Indirect << owner.Range;
14865 }
14866 
14867 /// Check for a keyword selector that starts with the word 'add' or
14868 /// 'set'.
14869 static bool isSetterLikeSelector(Selector sel) {
14870   if (sel.isUnarySelector()) return false;
14871 
14872   StringRef str = sel.getNameForSlot(0);
14873   while (!str.empty() && str.front() == '_') str = str.substr(1);
14874   if (str.startswith("set"))
14875     str = str.substr(3);
14876   else if (str.startswith("add")) {
14877     // Specially allow 'addOperationWithBlock:'.
14878     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14879       return false;
14880     str = str.substr(3);
14881   }
14882   else
14883     return false;
14884 
14885   if (str.empty()) return true;
14886   return !isLowercase(str.front());
14887 }
14888 
14889 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14890                                                     ObjCMessageExpr *Message) {
14891   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14892                                                 Message->getReceiverInterface(),
14893                                                 NSAPI::ClassId_NSMutableArray);
14894   if (!IsMutableArray) {
14895     return None;
14896   }
14897 
14898   Selector Sel = Message->getSelector();
14899 
14900   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14901     S.NSAPIObj->getNSArrayMethodKind(Sel);
14902   if (!MKOpt) {
14903     return None;
14904   }
14905 
14906   NSAPI::NSArrayMethodKind MK = *MKOpt;
14907 
14908   switch (MK) {
14909     case NSAPI::NSMutableArr_addObject:
14910     case NSAPI::NSMutableArr_insertObjectAtIndex:
14911     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14912       return 0;
14913     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14914       return 1;
14915 
14916     default:
14917       return None;
14918   }
14919 
14920   return None;
14921 }
14922 
14923 static
14924 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14925                                                   ObjCMessageExpr *Message) {
14926   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14927                                             Message->getReceiverInterface(),
14928                                             NSAPI::ClassId_NSMutableDictionary);
14929   if (!IsMutableDictionary) {
14930     return None;
14931   }
14932 
14933   Selector Sel = Message->getSelector();
14934 
14935   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14936     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14937   if (!MKOpt) {
14938     return None;
14939   }
14940 
14941   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14942 
14943   switch (MK) {
14944     case NSAPI::NSMutableDict_setObjectForKey:
14945     case NSAPI::NSMutableDict_setValueForKey:
14946     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14947       return 0;
14948 
14949     default:
14950       return None;
14951   }
14952 
14953   return None;
14954 }
14955 
14956 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14957   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14958                                                 Message->getReceiverInterface(),
14959                                                 NSAPI::ClassId_NSMutableSet);
14960 
14961   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14962                                             Message->getReceiverInterface(),
14963                                             NSAPI::ClassId_NSMutableOrderedSet);
14964   if (!IsMutableSet && !IsMutableOrderedSet) {
14965     return None;
14966   }
14967 
14968   Selector Sel = Message->getSelector();
14969 
14970   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14971   if (!MKOpt) {
14972     return None;
14973   }
14974 
14975   NSAPI::NSSetMethodKind MK = *MKOpt;
14976 
14977   switch (MK) {
14978     case NSAPI::NSMutableSet_addObject:
14979     case NSAPI::NSOrderedSet_setObjectAtIndex:
14980     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14981     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14982       return 0;
14983     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14984       return 1;
14985   }
14986 
14987   return None;
14988 }
14989 
14990 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14991   if (!Message->isInstanceMessage()) {
14992     return;
14993   }
14994 
14995   Optional<int> ArgOpt;
14996 
14997   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14998       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14999       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15000     return;
15001   }
15002 
15003   int ArgIndex = *ArgOpt;
15004 
15005   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15006   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15007     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15008   }
15009 
15010   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15011     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15012       if (ArgRE->isObjCSelfExpr()) {
15013         Diag(Message->getSourceRange().getBegin(),
15014              diag::warn_objc_circular_container)
15015           << ArgRE->getDecl() << StringRef("'super'");
15016       }
15017     }
15018   } else {
15019     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15020 
15021     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15022       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15023     }
15024 
15025     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15026       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15027         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15028           ValueDecl *Decl = ReceiverRE->getDecl();
15029           Diag(Message->getSourceRange().getBegin(),
15030                diag::warn_objc_circular_container)
15031             << Decl << Decl;
15032           if (!ArgRE->isObjCSelfExpr()) {
15033             Diag(Decl->getLocation(),
15034                  diag::note_objc_circular_container_declared_here)
15035               << Decl;
15036           }
15037         }
15038       }
15039     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15040       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15041         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15042           ObjCIvarDecl *Decl = IvarRE->getDecl();
15043           Diag(Message->getSourceRange().getBegin(),
15044                diag::warn_objc_circular_container)
15045             << Decl << Decl;
15046           Diag(Decl->getLocation(),
15047                diag::note_objc_circular_container_declared_here)
15048             << Decl;
15049         }
15050       }
15051     }
15052   }
15053 }
15054 
15055 /// Check a message send to see if it's likely to cause a retain cycle.
15056 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15057   // Only check instance methods whose selector looks like a setter.
15058   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15059     return;
15060 
15061   // Try to find a variable that the receiver is strongly owned by.
15062   RetainCycleOwner owner;
15063   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15064     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15065       return;
15066   } else {
15067     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15068     owner.Variable = getCurMethodDecl()->getSelfDecl();
15069     owner.Loc = msg->getSuperLoc();
15070     owner.Range = msg->getSuperLoc();
15071   }
15072 
15073   // Check whether the receiver is captured by any of the arguments.
15074   const ObjCMethodDecl *MD = msg->getMethodDecl();
15075   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15076     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15077       // noescape blocks should not be retained by the method.
15078       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15079         continue;
15080       return diagnoseRetainCycle(*this, capturer, owner);
15081     }
15082   }
15083 }
15084 
15085 /// Check a property assign to see if it's likely to cause a retain cycle.
15086 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15087   RetainCycleOwner owner;
15088   if (!findRetainCycleOwner(*this, receiver, owner))
15089     return;
15090 
15091   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15092     diagnoseRetainCycle(*this, capturer, owner);
15093 }
15094 
15095 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15096   RetainCycleOwner Owner;
15097   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15098     return;
15099 
15100   // Because we don't have an expression for the variable, we have to set the
15101   // location explicitly here.
15102   Owner.Loc = Var->getLocation();
15103   Owner.Range = Var->getSourceRange();
15104 
15105   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15106     diagnoseRetainCycle(*this, Capturer, Owner);
15107 }
15108 
15109 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15110                                      Expr *RHS, bool isProperty) {
15111   // Check if RHS is an Objective-C object literal, which also can get
15112   // immediately zapped in a weak reference.  Note that we explicitly
15113   // allow ObjCStringLiterals, since those are designed to never really die.
15114   RHS = RHS->IgnoreParenImpCasts();
15115 
15116   // This enum needs to match with the 'select' in
15117   // warn_objc_arc_literal_assign (off-by-1).
15118   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15119   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15120     return false;
15121 
15122   S.Diag(Loc, diag::warn_arc_literal_assign)
15123     << (unsigned) Kind
15124     << (isProperty ? 0 : 1)
15125     << RHS->getSourceRange();
15126 
15127   return true;
15128 }
15129 
15130 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15131                                     Qualifiers::ObjCLifetime LT,
15132                                     Expr *RHS, bool isProperty) {
15133   // Strip off any implicit cast added to get to the one ARC-specific.
15134   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15135     if (cast->getCastKind() == CK_ARCConsumeObject) {
15136       S.Diag(Loc, diag::warn_arc_retained_assign)
15137         << (LT == Qualifiers::OCL_ExplicitNone)
15138         << (isProperty ? 0 : 1)
15139         << RHS->getSourceRange();
15140       return true;
15141     }
15142     RHS = cast->getSubExpr();
15143   }
15144 
15145   if (LT == Qualifiers::OCL_Weak &&
15146       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15147     return true;
15148 
15149   return false;
15150 }
15151 
15152 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15153                               QualType LHS, Expr *RHS) {
15154   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15155 
15156   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15157     return false;
15158 
15159   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15160     return true;
15161 
15162   return false;
15163 }
15164 
15165 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15166                               Expr *LHS, Expr *RHS) {
15167   QualType LHSType;
15168   // PropertyRef on LHS type need be directly obtained from
15169   // its declaration as it has a PseudoType.
15170   ObjCPropertyRefExpr *PRE
15171     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15172   if (PRE && !PRE->isImplicitProperty()) {
15173     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15174     if (PD)
15175       LHSType = PD->getType();
15176   }
15177 
15178   if (LHSType.isNull())
15179     LHSType = LHS->getType();
15180 
15181   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15182 
15183   if (LT == Qualifiers::OCL_Weak) {
15184     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15185       getCurFunction()->markSafeWeakUse(LHS);
15186   }
15187 
15188   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15189     return;
15190 
15191   // FIXME. Check for other life times.
15192   if (LT != Qualifiers::OCL_None)
15193     return;
15194 
15195   if (PRE) {
15196     if (PRE->isImplicitProperty())
15197       return;
15198     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15199     if (!PD)
15200       return;
15201 
15202     unsigned Attributes = PD->getPropertyAttributes();
15203     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15204       // when 'assign' attribute was not explicitly specified
15205       // by user, ignore it and rely on property type itself
15206       // for lifetime info.
15207       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15208       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15209           LHSType->isObjCRetainableType())
15210         return;
15211 
15212       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15213         if (cast->getCastKind() == CK_ARCConsumeObject) {
15214           Diag(Loc, diag::warn_arc_retained_property_assign)
15215           << RHS->getSourceRange();
15216           return;
15217         }
15218         RHS = cast->getSubExpr();
15219       }
15220     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15221       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15222         return;
15223     }
15224   }
15225 }
15226 
15227 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15228 
15229 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15230                                         SourceLocation StmtLoc,
15231                                         const NullStmt *Body) {
15232   // Do not warn if the body is a macro that expands to nothing, e.g:
15233   //
15234   // #define CALL(x)
15235   // if (condition)
15236   //   CALL(0);
15237   if (Body->hasLeadingEmptyMacro())
15238     return false;
15239 
15240   // Get line numbers of statement and body.
15241   bool StmtLineInvalid;
15242   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15243                                                       &StmtLineInvalid);
15244   if (StmtLineInvalid)
15245     return false;
15246 
15247   bool BodyLineInvalid;
15248   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15249                                                       &BodyLineInvalid);
15250   if (BodyLineInvalid)
15251     return false;
15252 
15253   // Warn if null statement and body are on the same line.
15254   if (StmtLine != BodyLine)
15255     return false;
15256 
15257   return true;
15258 }
15259 
15260 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15261                                  const Stmt *Body,
15262                                  unsigned DiagID) {
15263   // Since this is a syntactic check, don't emit diagnostic for template
15264   // instantiations, this just adds noise.
15265   if (CurrentInstantiationScope)
15266     return;
15267 
15268   // The body should be a null statement.
15269   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15270   if (!NBody)
15271     return;
15272 
15273   // Do the usual checks.
15274   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15275     return;
15276 
15277   Diag(NBody->getSemiLoc(), DiagID);
15278   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15279 }
15280 
15281 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15282                                  const Stmt *PossibleBody) {
15283   assert(!CurrentInstantiationScope); // Ensured by caller
15284 
15285   SourceLocation StmtLoc;
15286   const Stmt *Body;
15287   unsigned DiagID;
15288   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15289     StmtLoc = FS->getRParenLoc();
15290     Body = FS->getBody();
15291     DiagID = diag::warn_empty_for_body;
15292   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15293     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15294     Body = WS->getBody();
15295     DiagID = diag::warn_empty_while_body;
15296   } else
15297     return; // Neither `for' nor `while'.
15298 
15299   // The body should be a null statement.
15300   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15301   if (!NBody)
15302     return;
15303 
15304   // Skip expensive checks if diagnostic is disabled.
15305   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15306     return;
15307 
15308   // Do the usual checks.
15309   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15310     return;
15311 
15312   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15313   // noise level low, emit diagnostics only if for/while is followed by a
15314   // CompoundStmt, e.g.:
15315   //    for (int i = 0; i < n; i++);
15316   //    {
15317   //      a(i);
15318   //    }
15319   // or if for/while is followed by a statement with more indentation
15320   // than for/while itself:
15321   //    for (int i = 0; i < n; i++);
15322   //      a(i);
15323   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15324   if (!ProbableTypo) {
15325     bool BodyColInvalid;
15326     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15327         PossibleBody->getBeginLoc(), &BodyColInvalid);
15328     if (BodyColInvalid)
15329       return;
15330 
15331     bool StmtColInvalid;
15332     unsigned StmtCol =
15333         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15334     if (StmtColInvalid)
15335       return;
15336 
15337     if (BodyCol > StmtCol)
15338       ProbableTypo = true;
15339   }
15340 
15341   if (ProbableTypo) {
15342     Diag(NBody->getSemiLoc(), DiagID);
15343     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15344   }
15345 }
15346 
15347 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15348 
15349 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15350 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15351                              SourceLocation OpLoc) {
15352   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15353     return;
15354 
15355   if (inTemplateInstantiation())
15356     return;
15357 
15358   // Strip parens and casts away.
15359   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15360   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15361 
15362   // Check for a call expression
15363   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15364   if (!CE || CE->getNumArgs() != 1)
15365     return;
15366 
15367   // Check for a call to std::move
15368   if (!CE->isCallToStdMove())
15369     return;
15370 
15371   // Get argument from std::move
15372   RHSExpr = CE->getArg(0);
15373 
15374   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15375   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15376 
15377   // Two DeclRefExpr's, check that the decls are the same.
15378   if (LHSDeclRef && RHSDeclRef) {
15379     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15380       return;
15381     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15382         RHSDeclRef->getDecl()->getCanonicalDecl())
15383       return;
15384 
15385     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15386                                         << LHSExpr->getSourceRange()
15387                                         << RHSExpr->getSourceRange();
15388     return;
15389   }
15390 
15391   // Member variables require a different approach to check for self moves.
15392   // MemberExpr's are the same if every nested MemberExpr refers to the same
15393   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15394   // the base Expr's are CXXThisExpr's.
15395   const Expr *LHSBase = LHSExpr;
15396   const Expr *RHSBase = RHSExpr;
15397   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15398   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15399   if (!LHSME || !RHSME)
15400     return;
15401 
15402   while (LHSME && RHSME) {
15403     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15404         RHSME->getMemberDecl()->getCanonicalDecl())
15405       return;
15406 
15407     LHSBase = LHSME->getBase();
15408     RHSBase = RHSME->getBase();
15409     LHSME = dyn_cast<MemberExpr>(LHSBase);
15410     RHSME = dyn_cast<MemberExpr>(RHSBase);
15411   }
15412 
15413   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15414   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15415   if (LHSDeclRef && RHSDeclRef) {
15416     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15417       return;
15418     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15419         RHSDeclRef->getDecl()->getCanonicalDecl())
15420       return;
15421 
15422     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15423                                         << LHSExpr->getSourceRange()
15424                                         << RHSExpr->getSourceRange();
15425     return;
15426   }
15427 
15428   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15429     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15430                                         << LHSExpr->getSourceRange()
15431                                         << RHSExpr->getSourceRange();
15432 }
15433 
15434 //===--- Layout compatibility ----------------------------------------------//
15435 
15436 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15437 
15438 /// Check if two enumeration types are layout-compatible.
15439 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15440   // C++11 [dcl.enum] p8:
15441   // Two enumeration types are layout-compatible if they have the same
15442   // underlying type.
15443   return ED1->isComplete() && ED2->isComplete() &&
15444          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15445 }
15446 
15447 /// Check if two fields are layout-compatible.
15448 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15449                                FieldDecl *Field2) {
15450   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15451     return false;
15452 
15453   if (Field1->isBitField() != Field2->isBitField())
15454     return false;
15455 
15456   if (Field1->isBitField()) {
15457     // Make sure that the bit-fields are the same length.
15458     unsigned Bits1 = Field1->getBitWidthValue(C);
15459     unsigned Bits2 = Field2->getBitWidthValue(C);
15460 
15461     if (Bits1 != Bits2)
15462       return false;
15463   }
15464 
15465   return true;
15466 }
15467 
15468 /// Check if two standard-layout structs are layout-compatible.
15469 /// (C++11 [class.mem] p17)
15470 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15471                                      RecordDecl *RD2) {
15472   // If both records are C++ classes, check that base classes match.
15473   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15474     // If one of records is a CXXRecordDecl we are in C++ mode,
15475     // thus the other one is a CXXRecordDecl, too.
15476     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15477     // Check number of base classes.
15478     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15479       return false;
15480 
15481     // Check the base classes.
15482     for (CXXRecordDecl::base_class_const_iterator
15483                Base1 = D1CXX->bases_begin(),
15484            BaseEnd1 = D1CXX->bases_end(),
15485               Base2 = D2CXX->bases_begin();
15486          Base1 != BaseEnd1;
15487          ++Base1, ++Base2) {
15488       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15489         return false;
15490     }
15491   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15492     // If only RD2 is a C++ class, it should have zero base classes.
15493     if (D2CXX->getNumBases() > 0)
15494       return false;
15495   }
15496 
15497   // Check the fields.
15498   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15499                              Field2End = RD2->field_end(),
15500                              Field1 = RD1->field_begin(),
15501                              Field1End = RD1->field_end();
15502   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15503     if (!isLayoutCompatible(C, *Field1, *Field2))
15504       return false;
15505   }
15506   if (Field1 != Field1End || Field2 != Field2End)
15507     return false;
15508 
15509   return true;
15510 }
15511 
15512 /// Check if two standard-layout unions are layout-compatible.
15513 /// (C++11 [class.mem] p18)
15514 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15515                                     RecordDecl *RD2) {
15516   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15517   for (auto *Field2 : RD2->fields())
15518     UnmatchedFields.insert(Field2);
15519 
15520   for (auto *Field1 : RD1->fields()) {
15521     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15522         I = UnmatchedFields.begin(),
15523         E = UnmatchedFields.end();
15524 
15525     for ( ; I != E; ++I) {
15526       if (isLayoutCompatible(C, Field1, *I)) {
15527         bool Result = UnmatchedFields.erase(*I);
15528         (void) Result;
15529         assert(Result);
15530         break;
15531       }
15532     }
15533     if (I == E)
15534       return false;
15535   }
15536 
15537   return UnmatchedFields.empty();
15538 }
15539 
15540 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15541                                RecordDecl *RD2) {
15542   if (RD1->isUnion() != RD2->isUnion())
15543     return false;
15544 
15545   if (RD1->isUnion())
15546     return isLayoutCompatibleUnion(C, RD1, RD2);
15547   else
15548     return isLayoutCompatibleStruct(C, RD1, RD2);
15549 }
15550 
15551 /// Check if two types are layout-compatible in C++11 sense.
15552 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15553   if (T1.isNull() || T2.isNull())
15554     return false;
15555 
15556   // C++11 [basic.types] p11:
15557   // If two types T1 and T2 are the same type, then T1 and T2 are
15558   // layout-compatible types.
15559   if (C.hasSameType(T1, T2))
15560     return true;
15561 
15562   T1 = T1.getCanonicalType().getUnqualifiedType();
15563   T2 = T2.getCanonicalType().getUnqualifiedType();
15564 
15565   const Type::TypeClass TC1 = T1->getTypeClass();
15566   const Type::TypeClass TC2 = T2->getTypeClass();
15567 
15568   if (TC1 != TC2)
15569     return false;
15570 
15571   if (TC1 == Type::Enum) {
15572     return isLayoutCompatible(C,
15573                               cast<EnumType>(T1)->getDecl(),
15574                               cast<EnumType>(T2)->getDecl());
15575   } else if (TC1 == Type::Record) {
15576     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15577       return false;
15578 
15579     return isLayoutCompatible(C,
15580                               cast<RecordType>(T1)->getDecl(),
15581                               cast<RecordType>(T2)->getDecl());
15582   }
15583 
15584   return false;
15585 }
15586 
15587 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15588 
15589 /// Given a type tag expression find the type tag itself.
15590 ///
15591 /// \param TypeExpr Type tag expression, as it appears in user's code.
15592 ///
15593 /// \param VD Declaration of an identifier that appears in a type tag.
15594 ///
15595 /// \param MagicValue Type tag magic value.
15596 ///
15597 /// \param isConstantEvaluated wether the evalaution should be performed in
15598 
15599 /// constant context.
15600 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15601                             const ValueDecl **VD, uint64_t *MagicValue,
15602                             bool isConstantEvaluated) {
15603   while(true) {
15604     if (!TypeExpr)
15605       return false;
15606 
15607     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15608 
15609     switch (TypeExpr->getStmtClass()) {
15610     case Stmt::UnaryOperatorClass: {
15611       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15612       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15613         TypeExpr = UO->getSubExpr();
15614         continue;
15615       }
15616       return false;
15617     }
15618 
15619     case Stmt::DeclRefExprClass: {
15620       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15621       *VD = DRE->getDecl();
15622       return true;
15623     }
15624 
15625     case Stmt::IntegerLiteralClass: {
15626       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15627       llvm::APInt MagicValueAPInt = IL->getValue();
15628       if (MagicValueAPInt.getActiveBits() <= 64) {
15629         *MagicValue = MagicValueAPInt.getZExtValue();
15630         return true;
15631       } else
15632         return false;
15633     }
15634 
15635     case Stmt::BinaryConditionalOperatorClass:
15636     case Stmt::ConditionalOperatorClass: {
15637       const AbstractConditionalOperator *ACO =
15638           cast<AbstractConditionalOperator>(TypeExpr);
15639       bool Result;
15640       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15641                                                      isConstantEvaluated)) {
15642         if (Result)
15643           TypeExpr = ACO->getTrueExpr();
15644         else
15645           TypeExpr = ACO->getFalseExpr();
15646         continue;
15647       }
15648       return false;
15649     }
15650 
15651     case Stmt::BinaryOperatorClass: {
15652       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15653       if (BO->getOpcode() == BO_Comma) {
15654         TypeExpr = BO->getRHS();
15655         continue;
15656       }
15657       return false;
15658     }
15659 
15660     default:
15661       return false;
15662     }
15663   }
15664 }
15665 
15666 /// Retrieve the C type corresponding to type tag TypeExpr.
15667 ///
15668 /// \param TypeExpr Expression that specifies a type tag.
15669 ///
15670 /// \param MagicValues Registered magic values.
15671 ///
15672 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15673 ///        kind.
15674 ///
15675 /// \param TypeInfo Information about the corresponding C type.
15676 ///
15677 /// \param isConstantEvaluated wether the evalaution should be performed in
15678 /// constant context.
15679 ///
15680 /// \returns true if the corresponding C type was found.
15681 static bool GetMatchingCType(
15682     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15683     const ASTContext &Ctx,
15684     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15685         *MagicValues,
15686     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15687     bool isConstantEvaluated) {
15688   FoundWrongKind = false;
15689 
15690   // Variable declaration that has type_tag_for_datatype attribute.
15691   const ValueDecl *VD = nullptr;
15692 
15693   uint64_t MagicValue;
15694 
15695   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15696     return false;
15697 
15698   if (VD) {
15699     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15700       if (I->getArgumentKind() != ArgumentKind) {
15701         FoundWrongKind = true;
15702         return false;
15703       }
15704       TypeInfo.Type = I->getMatchingCType();
15705       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15706       TypeInfo.MustBeNull = I->getMustBeNull();
15707       return true;
15708     }
15709     return false;
15710   }
15711 
15712   if (!MagicValues)
15713     return false;
15714 
15715   llvm::DenseMap<Sema::TypeTagMagicValue,
15716                  Sema::TypeTagData>::const_iterator I =
15717       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15718   if (I == MagicValues->end())
15719     return false;
15720 
15721   TypeInfo = I->second;
15722   return true;
15723 }
15724 
15725 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15726                                       uint64_t MagicValue, QualType Type,
15727                                       bool LayoutCompatible,
15728                                       bool MustBeNull) {
15729   if (!TypeTagForDatatypeMagicValues)
15730     TypeTagForDatatypeMagicValues.reset(
15731         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15732 
15733   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15734   (*TypeTagForDatatypeMagicValues)[Magic] =
15735       TypeTagData(Type, LayoutCompatible, MustBeNull);
15736 }
15737 
15738 static bool IsSameCharType(QualType T1, QualType T2) {
15739   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15740   if (!BT1)
15741     return false;
15742 
15743   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15744   if (!BT2)
15745     return false;
15746 
15747   BuiltinType::Kind T1Kind = BT1->getKind();
15748   BuiltinType::Kind T2Kind = BT2->getKind();
15749 
15750   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15751          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15752          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15753          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15754 }
15755 
15756 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15757                                     const ArrayRef<const Expr *> ExprArgs,
15758                                     SourceLocation CallSiteLoc) {
15759   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15760   bool IsPointerAttr = Attr->getIsPointer();
15761 
15762   // Retrieve the argument representing the 'type_tag'.
15763   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15764   if (TypeTagIdxAST >= ExprArgs.size()) {
15765     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15766         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15767     return;
15768   }
15769   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15770   bool FoundWrongKind;
15771   TypeTagData TypeInfo;
15772   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15773                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15774                         TypeInfo, isConstantEvaluated())) {
15775     if (FoundWrongKind)
15776       Diag(TypeTagExpr->getExprLoc(),
15777            diag::warn_type_tag_for_datatype_wrong_kind)
15778         << TypeTagExpr->getSourceRange();
15779     return;
15780   }
15781 
15782   // Retrieve the argument representing the 'arg_idx'.
15783   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15784   if (ArgumentIdxAST >= ExprArgs.size()) {
15785     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15786         << 1 << Attr->getArgumentIdx().getSourceIndex();
15787     return;
15788   }
15789   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15790   if (IsPointerAttr) {
15791     // Skip implicit cast of pointer to `void *' (as a function argument).
15792     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15793       if (ICE->getType()->isVoidPointerType() &&
15794           ICE->getCastKind() == CK_BitCast)
15795         ArgumentExpr = ICE->getSubExpr();
15796   }
15797   QualType ArgumentType = ArgumentExpr->getType();
15798 
15799   // Passing a `void*' pointer shouldn't trigger a warning.
15800   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15801     return;
15802 
15803   if (TypeInfo.MustBeNull) {
15804     // Type tag with matching void type requires a null pointer.
15805     if (!ArgumentExpr->isNullPointerConstant(Context,
15806                                              Expr::NPC_ValueDependentIsNotNull)) {
15807       Diag(ArgumentExpr->getExprLoc(),
15808            diag::warn_type_safety_null_pointer_required)
15809           << ArgumentKind->getName()
15810           << ArgumentExpr->getSourceRange()
15811           << TypeTagExpr->getSourceRange();
15812     }
15813     return;
15814   }
15815 
15816   QualType RequiredType = TypeInfo.Type;
15817   if (IsPointerAttr)
15818     RequiredType = Context.getPointerType(RequiredType);
15819 
15820   bool mismatch = false;
15821   if (!TypeInfo.LayoutCompatible) {
15822     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15823 
15824     // C++11 [basic.fundamental] p1:
15825     // Plain char, signed char, and unsigned char are three distinct types.
15826     //
15827     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15828     // char' depending on the current char signedness mode.
15829     if (mismatch)
15830       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15831                                            RequiredType->getPointeeType())) ||
15832           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15833         mismatch = false;
15834   } else
15835     if (IsPointerAttr)
15836       mismatch = !isLayoutCompatible(Context,
15837                                      ArgumentType->getPointeeType(),
15838                                      RequiredType->getPointeeType());
15839     else
15840       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15841 
15842   if (mismatch)
15843     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15844         << ArgumentType << ArgumentKind
15845         << TypeInfo.LayoutCompatible << RequiredType
15846         << ArgumentExpr->getSourceRange()
15847         << TypeTagExpr->getSourceRange();
15848 }
15849 
15850 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15851                                          CharUnits Alignment) {
15852   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15853 }
15854 
15855 void Sema::DiagnoseMisalignedMembers() {
15856   for (MisalignedMember &m : MisalignedMembers) {
15857     const NamedDecl *ND = m.RD;
15858     if (ND->getName().empty()) {
15859       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15860         ND = TD;
15861     }
15862     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15863         << m.MD << ND << m.E->getSourceRange();
15864   }
15865   MisalignedMembers.clear();
15866 }
15867 
15868 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15869   E = E->IgnoreParens();
15870   if (!T->isPointerType() && !T->isIntegerType())
15871     return;
15872   if (isa<UnaryOperator>(E) &&
15873       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15874     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15875     if (isa<MemberExpr>(Op)) {
15876       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15877       if (MA != MisalignedMembers.end() &&
15878           (T->isIntegerType() ||
15879            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15880                                    Context.getTypeAlignInChars(
15881                                        T->getPointeeType()) <= MA->Alignment))))
15882         MisalignedMembers.erase(MA);
15883     }
15884   }
15885 }
15886 
15887 void Sema::RefersToMemberWithReducedAlignment(
15888     Expr *E,
15889     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15890         Action) {
15891   const auto *ME = dyn_cast<MemberExpr>(E);
15892   if (!ME)
15893     return;
15894 
15895   // No need to check expressions with an __unaligned-qualified type.
15896   if (E->getType().getQualifiers().hasUnaligned())
15897     return;
15898 
15899   // For a chain of MemberExpr like "a.b.c.d" this list
15900   // will keep FieldDecl's like [d, c, b].
15901   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15902   const MemberExpr *TopME = nullptr;
15903   bool AnyIsPacked = false;
15904   do {
15905     QualType BaseType = ME->getBase()->getType();
15906     if (BaseType->isDependentType())
15907       return;
15908     if (ME->isArrow())
15909       BaseType = BaseType->getPointeeType();
15910     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15911     if (RD->isInvalidDecl())
15912       return;
15913 
15914     ValueDecl *MD = ME->getMemberDecl();
15915     auto *FD = dyn_cast<FieldDecl>(MD);
15916     // We do not care about non-data members.
15917     if (!FD || FD->isInvalidDecl())
15918       return;
15919 
15920     AnyIsPacked =
15921         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15922     ReverseMemberChain.push_back(FD);
15923 
15924     TopME = ME;
15925     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15926   } while (ME);
15927   assert(TopME && "We did not compute a topmost MemberExpr!");
15928 
15929   // Not the scope of this diagnostic.
15930   if (!AnyIsPacked)
15931     return;
15932 
15933   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15934   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15935   // TODO: The innermost base of the member expression may be too complicated.
15936   // For now, just disregard these cases. This is left for future
15937   // improvement.
15938   if (!DRE && !isa<CXXThisExpr>(TopBase))
15939       return;
15940 
15941   // Alignment expected by the whole expression.
15942   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15943 
15944   // No need to do anything else with this case.
15945   if (ExpectedAlignment.isOne())
15946     return;
15947 
15948   // Synthesize offset of the whole access.
15949   CharUnits Offset;
15950   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15951        I++) {
15952     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15953   }
15954 
15955   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15956   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15957       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15958 
15959   // The base expression of the innermost MemberExpr may give
15960   // stronger guarantees than the class containing the member.
15961   if (DRE && !TopME->isArrow()) {
15962     const ValueDecl *VD = DRE->getDecl();
15963     if (!VD->getType()->isReferenceType())
15964       CompleteObjectAlignment =
15965           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15966   }
15967 
15968   // Check if the synthesized offset fulfills the alignment.
15969   if (Offset % ExpectedAlignment != 0 ||
15970       // It may fulfill the offset it but the effective alignment may still be
15971       // lower than the expected expression alignment.
15972       CompleteObjectAlignment < ExpectedAlignment) {
15973     // If this happens, we want to determine a sensible culprit of this.
15974     // Intuitively, watching the chain of member expressions from right to
15975     // left, we start with the required alignment (as required by the field
15976     // type) but some packed attribute in that chain has reduced the alignment.
15977     // It may happen that another packed structure increases it again. But if
15978     // we are here such increase has not been enough. So pointing the first
15979     // FieldDecl that either is packed or else its RecordDecl is,
15980     // seems reasonable.
15981     FieldDecl *FD = nullptr;
15982     CharUnits Alignment;
15983     for (FieldDecl *FDI : ReverseMemberChain) {
15984       if (FDI->hasAttr<PackedAttr>() ||
15985           FDI->getParent()->hasAttr<PackedAttr>()) {
15986         FD = FDI;
15987         Alignment = std::min(
15988             Context.getTypeAlignInChars(FD->getType()),
15989             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15990         break;
15991       }
15992     }
15993     assert(FD && "We did not find a packed FieldDecl!");
15994     Action(E, FD->getParent(), FD, Alignment);
15995   }
15996 }
15997 
15998 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15999   using namespace std::placeholders;
16000 
16001   RefersToMemberWithReducedAlignment(
16002       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16003                      _2, _3, _4));
16004 }
16005 
16006 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16007                                             ExprResult CallResult) {
16008   if (checkArgCount(*this, TheCall, 1))
16009     return ExprError();
16010 
16011   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16012   if (MatrixArg.isInvalid())
16013     return MatrixArg;
16014   Expr *Matrix = MatrixArg.get();
16015 
16016   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16017   if (!MType) {
16018     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16019     return ExprError();
16020   }
16021 
16022   // Create returned matrix type by swapping rows and columns of the argument
16023   // matrix type.
16024   QualType ResultType = Context.getConstantMatrixType(
16025       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16026 
16027   // Change the return type to the type of the returned matrix.
16028   TheCall->setType(ResultType);
16029 
16030   // Update call argument to use the possibly converted matrix argument.
16031   TheCall->setArg(0, Matrix);
16032   return CallResult;
16033 }
16034 
16035 // Get and verify the matrix dimensions.
16036 static llvm::Optional<unsigned>
16037 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16038   SourceLocation ErrorPos;
16039   Optional<llvm::APSInt> Value =
16040       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16041   if (!Value) {
16042     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16043         << Name;
16044     return {};
16045   }
16046   uint64_t Dim = Value->getZExtValue();
16047   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16048     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16049         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16050     return {};
16051   }
16052   return Dim;
16053 }
16054 
16055 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16056                                                   ExprResult CallResult) {
16057   if (!getLangOpts().MatrixTypes) {
16058     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16059     return ExprError();
16060   }
16061 
16062   if (checkArgCount(*this, TheCall, 4))
16063     return ExprError();
16064 
16065   unsigned PtrArgIdx = 0;
16066   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16067   Expr *RowsExpr = TheCall->getArg(1);
16068   Expr *ColumnsExpr = TheCall->getArg(2);
16069   Expr *StrideExpr = TheCall->getArg(3);
16070 
16071   bool ArgError = false;
16072 
16073   // Check pointer argument.
16074   {
16075     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16076     if (PtrConv.isInvalid())
16077       return PtrConv;
16078     PtrExpr = PtrConv.get();
16079     TheCall->setArg(0, PtrExpr);
16080     if (PtrExpr->isTypeDependent()) {
16081       TheCall->setType(Context.DependentTy);
16082       return TheCall;
16083     }
16084   }
16085 
16086   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16087   QualType ElementTy;
16088   if (!PtrTy) {
16089     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16090         << PtrArgIdx + 1;
16091     ArgError = true;
16092   } else {
16093     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16094 
16095     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16096       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16097           << PtrArgIdx + 1;
16098       ArgError = true;
16099     }
16100   }
16101 
16102   // Apply default Lvalue conversions and convert the expression to size_t.
16103   auto ApplyArgumentConversions = [this](Expr *E) {
16104     ExprResult Conv = DefaultLvalueConversion(E);
16105     if (Conv.isInvalid())
16106       return Conv;
16107 
16108     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16109   };
16110 
16111   // Apply conversion to row and column expressions.
16112   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16113   if (!RowsConv.isInvalid()) {
16114     RowsExpr = RowsConv.get();
16115     TheCall->setArg(1, RowsExpr);
16116   } else
16117     RowsExpr = nullptr;
16118 
16119   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16120   if (!ColumnsConv.isInvalid()) {
16121     ColumnsExpr = ColumnsConv.get();
16122     TheCall->setArg(2, ColumnsExpr);
16123   } else
16124     ColumnsExpr = nullptr;
16125 
16126   // If any any part of the result matrix type is still pending, just use
16127   // Context.DependentTy, until all parts are resolved.
16128   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16129       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16130     TheCall->setType(Context.DependentTy);
16131     return CallResult;
16132   }
16133 
16134   // Check row and column dimenions.
16135   llvm::Optional<unsigned> MaybeRows;
16136   if (RowsExpr)
16137     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16138 
16139   llvm::Optional<unsigned> MaybeColumns;
16140   if (ColumnsExpr)
16141     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16142 
16143   // Check stride argument.
16144   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16145   if (StrideConv.isInvalid())
16146     return ExprError();
16147   StrideExpr = StrideConv.get();
16148   TheCall->setArg(3, StrideExpr);
16149 
16150   if (MaybeRows) {
16151     if (Optional<llvm::APSInt> Value =
16152             StrideExpr->getIntegerConstantExpr(Context)) {
16153       uint64_t Stride = Value->getZExtValue();
16154       if (Stride < *MaybeRows) {
16155         Diag(StrideExpr->getBeginLoc(),
16156              diag::err_builtin_matrix_stride_too_small);
16157         ArgError = true;
16158       }
16159     }
16160   }
16161 
16162   if (ArgError || !MaybeRows || !MaybeColumns)
16163     return ExprError();
16164 
16165   TheCall->setType(
16166       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16167   return CallResult;
16168 }
16169 
16170 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16171                                                    ExprResult CallResult) {
16172   if (checkArgCount(*this, TheCall, 3))
16173     return ExprError();
16174 
16175   unsigned PtrArgIdx = 1;
16176   Expr *MatrixExpr = TheCall->getArg(0);
16177   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16178   Expr *StrideExpr = TheCall->getArg(2);
16179 
16180   bool ArgError = false;
16181 
16182   {
16183     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16184     if (MatrixConv.isInvalid())
16185       return MatrixConv;
16186     MatrixExpr = MatrixConv.get();
16187     TheCall->setArg(0, MatrixExpr);
16188   }
16189   if (MatrixExpr->isTypeDependent()) {
16190     TheCall->setType(Context.DependentTy);
16191     return TheCall;
16192   }
16193 
16194   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16195   if (!MatrixTy) {
16196     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16197     ArgError = true;
16198   }
16199 
16200   {
16201     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16202     if (PtrConv.isInvalid())
16203       return PtrConv;
16204     PtrExpr = PtrConv.get();
16205     TheCall->setArg(1, PtrExpr);
16206     if (PtrExpr->isTypeDependent()) {
16207       TheCall->setType(Context.DependentTy);
16208       return TheCall;
16209     }
16210   }
16211 
16212   // Check pointer argument.
16213   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16214   if (!PtrTy) {
16215     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16216         << PtrArgIdx + 1;
16217     ArgError = true;
16218   } else {
16219     QualType ElementTy = PtrTy->getPointeeType();
16220     if (ElementTy.isConstQualified()) {
16221       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16222       ArgError = true;
16223     }
16224     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16225     if (MatrixTy &&
16226         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16227       Diag(PtrExpr->getBeginLoc(),
16228            diag::err_builtin_matrix_pointer_arg_mismatch)
16229           << ElementTy << MatrixTy->getElementType();
16230       ArgError = true;
16231     }
16232   }
16233 
16234   // Apply default Lvalue conversions and convert the stride expression to
16235   // size_t.
16236   {
16237     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16238     if (StrideConv.isInvalid())
16239       return StrideConv;
16240 
16241     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16242     if (StrideConv.isInvalid())
16243       return StrideConv;
16244     StrideExpr = StrideConv.get();
16245     TheCall->setArg(2, StrideExpr);
16246   }
16247 
16248   // Check stride argument.
16249   if (MatrixTy) {
16250     if (Optional<llvm::APSInt> Value =
16251             StrideExpr->getIntegerConstantExpr(Context)) {
16252       uint64_t Stride = Value->getZExtValue();
16253       if (Stride < MatrixTy->getNumRows()) {
16254         Diag(StrideExpr->getBeginLoc(),
16255              diag::err_builtin_matrix_stride_too_small);
16256         ArgError = true;
16257       }
16258     }
16259   }
16260 
16261   if (ArgError)
16262     return ExprError();
16263 
16264   return CallResult;
16265 }
16266 
16267 /// \brief Enforce the bounds of a TCB
16268 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16269 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16270 /// and enforce_tcb_leaf attributes.
16271 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16272                                const FunctionDecl *Callee) {
16273   const FunctionDecl *Caller = getCurFunctionDecl();
16274 
16275   // Calls to builtins are not enforced.
16276   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16277       Callee->getBuiltinID() != 0)
16278     return;
16279 
16280   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16281   // all TCBs the callee is a part of.
16282   llvm::StringSet<> CalleeTCBs;
16283   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16284            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16285   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16286            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16287 
16288   // Go through the TCBs the caller is a part of and emit warnings if Caller
16289   // is in a TCB that the Callee is not.
16290   for_each(
16291       Caller->specific_attrs<EnforceTCBAttr>(),
16292       [&](const auto *A) {
16293         StringRef CallerTCB = A->getTCBName();
16294         if (CalleeTCBs.count(CallerTCB) == 0) {
16295           this->Diag(TheCall->getExprLoc(),
16296                      diag::warn_tcb_enforcement_violation) << Callee
16297                                                            << CallerTCB;
16298         }
16299       });
16300 }
16301