1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
592                                                CallExpr *TheCall) {
593   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
594       isConstantEvaluated())
595     return;
596 
597   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
598   if (!BuiltinID)
599     return;
600 
601   const TargetInfo &TI = getASTContext().getTargetInfo();
602   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
603 
604   auto ComputeExplicitObjectSizeArgument =
605       [&](unsigned Index) -> Optional<llvm::APSInt> {
606     Expr::EvalResult Result;
607     Expr *SizeArg = TheCall->getArg(Index);
608     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
609       return llvm::None;
610     return Result.Val.getInt();
611   };
612 
613   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
614     // If the parameter has a pass_object_size attribute, then we should use its
615     // (potentially) more strict checking mode. Otherwise, conservatively assume
616     // type 0.
617     int BOSType = 0;
618     if (const auto *POS =
619             FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
620       BOSType = POS->getType();
621 
622     const Expr *ObjArg = TheCall->getArg(Index);
623     uint64_t Result;
624     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
625       return llvm::None;
626 
627     // Get the object size in the target's size_t width.
628     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
629   };
630 
631   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
632     Expr *ObjArg = TheCall->getArg(Index);
633     uint64_t Result;
634     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
635       return llvm::None;
636     // Add 1 for null byte.
637     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
638   };
639 
640   Optional<llvm::APSInt> SourceSize;
641   Optional<llvm::APSInt> DestinationSize;
642   unsigned DiagID = 0;
643   bool IsChkVariant = false;
644 
645   switch (BuiltinID) {
646   default:
647     return;
648   case Builtin::BI__builtin_strcpy:
649   case Builtin::BIstrcpy: {
650     DiagID = diag::warn_fortify_strlen_overflow;
651     SourceSize = ComputeStrLenArgument(1);
652     DestinationSize = ComputeSizeArgument(0);
653     break;
654   }
655 
656   case Builtin::BI__builtin___strcpy_chk: {
657     DiagID = diag::warn_fortify_strlen_overflow;
658     SourceSize = ComputeStrLenArgument(1);
659     DestinationSize = ComputeExplicitObjectSizeArgument(2);
660     IsChkVariant = true;
661     break;
662   }
663 
664   case Builtin::BIsprintf:
665   case Builtin::BI__builtin___sprintf_chk: {
666     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
667     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
668 
669     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
670 
671       if (!Format->isAscii() && !Format->isUTF8())
672         return;
673 
674       StringRef FormatStrRef = Format->getString();
675       EstimateSizeFormatHandler H(FormatStrRef);
676       const char *FormatBytes = FormatStrRef.data();
677       const ConstantArrayType *T =
678           Context.getAsConstantArrayType(Format->getType());
679       assert(T && "String literal not of constant array type!");
680       size_t TypeSize = T->getSize().getZExtValue();
681 
682       // In case there's a null byte somewhere.
683       size_t StrLen =
684           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
685       if (!analyze_format_string::ParsePrintfString(
686               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
687               Context.getTargetInfo(), false)) {
688         DiagID = diag::warn_fortify_source_format_overflow;
689         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
690                          .extOrTrunc(SizeTypeWidth);
691         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
692           DestinationSize = ComputeExplicitObjectSizeArgument(2);
693           IsChkVariant = true;
694         } else {
695           DestinationSize = ComputeSizeArgument(0);
696         }
697         break;
698       }
699     }
700     return;
701   }
702   case Builtin::BI__builtin___memcpy_chk:
703   case Builtin::BI__builtin___memmove_chk:
704   case Builtin::BI__builtin___memset_chk:
705   case Builtin::BI__builtin___strlcat_chk:
706   case Builtin::BI__builtin___strlcpy_chk:
707   case Builtin::BI__builtin___strncat_chk:
708   case Builtin::BI__builtin___strncpy_chk:
709   case Builtin::BI__builtin___stpncpy_chk:
710   case Builtin::BI__builtin___memccpy_chk:
711   case Builtin::BI__builtin___mempcpy_chk: {
712     DiagID = diag::warn_builtin_chk_overflow;
713     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
714     DestinationSize =
715         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
716     IsChkVariant = true;
717     break;
718   }
719 
720   case Builtin::BI__builtin___snprintf_chk:
721   case Builtin::BI__builtin___vsnprintf_chk: {
722     DiagID = diag::warn_builtin_chk_overflow;
723     SourceSize = ComputeExplicitObjectSizeArgument(1);
724     DestinationSize = ComputeExplicitObjectSizeArgument(3);
725     IsChkVariant = true;
726     break;
727   }
728 
729   case Builtin::BIstrncat:
730   case Builtin::BI__builtin_strncat:
731   case Builtin::BIstrncpy:
732   case Builtin::BI__builtin_strncpy:
733   case Builtin::BIstpncpy:
734   case Builtin::BI__builtin_stpncpy: {
735     // Whether these functions overflow depends on the runtime strlen of the
736     // string, not just the buffer size, so emitting the "always overflow"
737     // diagnostic isn't quite right. We should still diagnose passing a buffer
738     // size larger than the destination buffer though; this is a runtime abort
739     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
740     DiagID = diag::warn_fortify_source_size_mismatch;
741     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
742     DestinationSize = ComputeSizeArgument(0);
743     break;
744   }
745 
746   case Builtin::BImemcpy:
747   case Builtin::BI__builtin_memcpy:
748   case Builtin::BImemmove:
749   case Builtin::BI__builtin_memmove:
750   case Builtin::BImemset:
751   case Builtin::BI__builtin_memset:
752   case Builtin::BImempcpy:
753   case Builtin::BI__builtin_mempcpy: {
754     DiagID = diag::warn_fortify_source_overflow;
755     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
756     DestinationSize = ComputeSizeArgument(0);
757     break;
758   }
759   case Builtin::BIsnprintf:
760   case Builtin::BI__builtin_snprintf:
761   case Builtin::BIvsnprintf:
762   case Builtin::BI__builtin_vsnprintf: {
763     DiagID = diag::warn_fortify_source_size_mismatch;
764     SourceSize = ComputeExplicitObjectSizeArgument(1);
765     DestinationSize = ComputeSizeArgument(0);
766     break;
767   }
768   }
769 
770   if (!SourceSize || !DestinationSize ||
771       SourceSize.getValue().ule(DestinationSize.getValue()))
772     return;
773 
774   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775   // Skim off the details of whichever builtin was called to produce a better
776   // diagnostic, as it's unlikely that the user wrote the __builtin explicitly.
777   if (IsChkVariant) {
778     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780   } else if (FunctionName.startswith("__builtin_")) {
781     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782   }
783 
784   SmallString<16> DestinationStr;
785   SmallString<16> SourceStr;
786   DestinationSize->toString(DestinationStr, /*Radix=*/10);
787   SourceSize->toString(SourceStr, /*Radix=*/10);
788   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
789                       PDiag(DiagID)
790                           << FunctionName << DestinationStr << SourceStr);
791 }
792 
793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
794                                      Scope::ScopeFlags NeededScopeFlags,
795                                      unsigned DiagID) {
796   // Scopes aren't available during instantiation. Fortunately, builtin
797   // functions cannot be template args so they cannot be formed through template
798   // instantiation. Therefore checking once during the parse is sufficient.
799   if (SemaRef.inTemplateInstantiation())
800     return false;
801 
802   Scope *S = SemaRef.getCurScope();
803   while (S && !S->isSEHExceptScope())
804     S = S->getParent();
805   if (!S || !(S->getFlags() & NeededScopeFlags)) {
806     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
807     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
808         << DRE->getDecl()->getIdentifier();
809     return true;
810   }
811 
812   return false;
813 }
814 
815 static inline bool isBlockPointer(Expr *Arg) {
816   return Arg->getType()->isBlockPointerType();
817 }
818 
819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
820 /// void*, which is a requirement of device side enqueue.
821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
822   const BlockPointerType *BPT =
823       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
824   ArrayRef<QualType> Params =
825       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
826   unsigned ArgCounter = 0;
827   bool IllegalParams = false;
828   // Iterate through the block parameters until either one is found that is not
829   // a local void*, or the block is valid.
830   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
831        I != E; ++I, ++ArgCounter) {
832     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
833         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
834             LangAS::opencl_local) {
835       // Get the location of the error. If a block literal has been passed
836       // (BlockExpr) then we can point straight to the offending argument,
837       // else we just point to the variable reference.
838       SourceLocation ErrorLoc;
839       if (isa<BlockExpr>(BlockArg)) {
840         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
841         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
842       } else if (isa<DeclRefExpr>(BlockArg)) {
843         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
844       }
845       S.Diag(ErrorLoc,
846              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
847       IllegalParams = true;
848     }
849   }
850 
851   return IllegalParams;
852 }
853 
854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
855   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
856     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
857         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
858     return true;
859   }
860   return false;
861 }
862 
863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
864   if (checkArgCount(S, TheCall, 2))
865     return true;
866 
867   if (checkOpenCLSubgroupExt(S, TheCall))
868     return true;
869 
870   // First argument is an ndrange_t type.
871   Expr *NDRangeArg = TheCall->getArg(0);
872   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
873     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
874         << TheCall->getDirectCallee() << "'ndrange_t'";
875     return true;
876   }
877 
878   Expr *BlockArg = TheCall->getArg(1);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
888 /// get_kernel_work_group_size
889 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
891   if (checkArgCount(S, TheCall, 1))
892     return true;
893 
894   Expr *BlockArg = TheCall->getArg(0);
895   if (!isBlockPointer(BlockArg)) {
896     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
897         << TheCall->getDirectCallee() << "block";
898     return true;
899   }
900   return checkOpenCLBlockArgs(S, BlockArg);
901 }
902 
903 /// Diagnose integer type and any valid implicit conversion to it.
904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
905                                       const QualType &IntType);
906 
907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
908                                             unsigned Start, unsigned End) {
909   bool IllegalParams = false;
910   for (unsigned I = Start; I <= End; ++I)
911     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
912                                               S.Context.getSizeType());
913   return IllegalParams;
914 }
915 
916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
917 /// 'local void*' parameter of passed block.
918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
919                                            Expr *BlockArg,
920                                            unsigned NumNonVarArgs) {
921   const BlockPointerType *BPT =
922       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
923   unsigned NumBlockParams =
924       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
925   unsigned TotalNumArgs = TheCall->getNumArgs();
926 
927   // For each argument passed to the block, a corresponding uint needs to
928   // be passed to describe the size of the local memory.
929   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
930     S.Diag(TheCall->getBeginLoc(),
931            diag::err_opencl_enqueue_kernel_local_size_args);
932     return true;
933   }
934 
935   // Check that the sizes of the local memory are specified by integers.
936   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
937                                          TotalNumArgs - 1);
938 }
939 
940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
941 /// overload formats specified in Table 6.13.17.1.
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    void (^block)(void))
946 /// int enqueue_kernel(queue_t queue,
947 ///                    kernel_enqueue_flags_t flags,
948 ///                    const ndrange_t ndrange,
949 ///                    uint num_events_in_wait_list,
950 ///                    clk_event_t *event_wait_list,
951 ///                    clk_event_t *event_ret,
952 ///                    void (^block)(void))
953 /// int enqueue_kernel(queue_t queue,
954 ///                    kernel_enqueue_flags_t flags,
955 ///                    const ndrange_t ndrange,
956 ///                    void (^block)(local void*, ...),
957 ///                    uint size0, ...)
958 /// int enqueue_kernel(queue_t queue,
959 ///                    kernel_enqueue_flags_t flags,
960 ///                    const ndrange_t ndrange,
961 ///                    uint num_events_in_wait_list,
962 ///                    clk_event_t *event_wait_list,
963 ///                    clk_event_t *event_ret,
964 ///                    void (^block)(local void*, ...),
965 ///                    uint size0, ...)
966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
967   unsigned NumArgs = TheCall->getNumArgs();
968 
969   if (NumArgs < 4) {
970     S.Diag(TheCall->getBeginLoc(),
971            diag::err_typecheck_call_too_few_args_at_least)
972         << 0 << 4 << NumArgs;
973     return true;
974   }
975 
976   Expr *Arg0 = TheCall->getArg(0);
977   Expr *Arg1 = TheCall->getArg(1);
978   Expr *Arg2 = TheCall->getArg(2);
979   Expr *Arg3 = TheCall->getArg(3);
980 
981   // First argument always needs to be a queue_t type.
982   if (!Arg0->getType()->isQueueT()) {
983     S.Diag(TheCall->getArg(0)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
986     return true;
987   }
988 
989   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
990   if (!Arg1->getType()->isIntegerType()) {
991     S.Diag(TheCall->getArg(1)->getBeginLoc(),
992            diag::err_opencl_builtin_expected_type)
993         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
994     return true;
995   }
996 
997   // Third argument is always an ndrange_t type.
998   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
999     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1000            diag::err_opencl_builtin_expected_type)
1001         << TheCall->getDirectCallee() << "'ndrange_t'";
1002     return true;
1003   }
1004 
1005   // With four arguments, there is only one form that the function could be
1006   // called in: no events and no variable arguments.
1007   if (NumArgs == 4) {
1008     // check that the last argument is the right block type.
1009     if (!isBlockPointer(Arg3)) {
1010       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1011           << TheCall->getDirectCallee() << "block";
1012       return true;
1013     }
1014     // we have a block type, check the prototype
1015     const BlockPointerType *BPT =
1016         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1017     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1018       S.Diag(Arg3->getBeginLoc(),
1019              diag::err_opencl_enqueue_kernel_blocks_no_args);
1020       return true;
1021     }
1022     return false;
1023   }
1024   // we can have block + varargs.
1025   if (isBlockPointer(Arg3))
1026     return (checkOpenCLBlockArgs(S, Arg3) ||
1027             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1028   // last two cases with either exactly 7 args or 7 args and varargs.
1029   if (NumArgs >= 7) {
1030     // check common block argument.
1031     Expr *Arg6 = TheCall->getArg(6);
1032     if (!isBlockPointer(Arg6)) {
1033       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1034           << TheCall->getDirectCallee() << "block";
1035       return true;
1036     }
1037     if (checkOpenCLBlockArgs(S, Arg6))
1038       return true;
1039 
1040     // Forth argument has to be any integer type.
1041     if (!Arg3->getType()->isIntegerType()) {
1042       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee() << "integer";
1045       return true;
1046     }
1047     // check remaining common arguments.
1048     Expr *Arg4 = TheCall->getArg(4);
1049     Expr *Arg5 = TheCall->getArg(5);
1050 
1051     // Fifth argument is always passed as a pointer to clk_event_t.
1052     if (!Arg4->isNullPointerConstant(S.Context,
1053                                      Expr::NPC_ValueDependentIsNotNull) &&
1054         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1055       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1056              diag::err_opencl_builtin_expected_type)
1057           << TheCall->getDirectCallee()
1058           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1059       return true;
1060     }
1061 
1062     // Sixth argument is always passed as a pointer to clk_event_t.
1063     if (!Arg5->isNullPointerConstant(S.Context,
1064                                      Expr::NPC_ValueDependentIsNotNull) &&
1065         !(Arg5->getType()->isPointerType() &&
1066           Arg5->getType()->getPointeeType()->isClkEventT())) {
1067       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1068              diag::err_opencl_builtin_expected_type)
1069           << TheCall->getDirectCallee()
1070           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1071       return true;
1072     }
1073 
1074     if (NumArgs == 7)
1075       return false;
1076 
1077     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1078   }
1079 
1080   // None of the specific case has been detected, give generic error
1081   S.Diag(TheCall->getBeginLoc(),
1082          diag::err_opencl_enqueue_kernel_incorrect_args);
1083   return true;
1084 }
1085 
1086 /// Returns OpenCL access qual.
1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1088     return D->getAttr<OpenCLAccessAttr>();
1089 }
1090 
1091 /// Returns true if pipe element type is different from the pointer.
1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1093   const Expr *Arg0 = Call->getArg(0);
1094   // First argument type should always be pipe.
1095   if (!Arg0->getType()->isPipeType()) {
1096     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1097         << Call->getDirectCallee() << Arg0->getSourceRange();
1098     return true;
1099   }
1100   OpenCLAccessAttr *AccessQual =
1101       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1102   // Validates the access qualifier is compatible with the call.
1103   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1104   // read_only and write_only, and assumed to be read_only if no qualifier is
1105   // specified.
1106   switch (Call->getDirectCallee()->getBuiltinID()) {
1107   case Builtin::BIread_pipe:
1108   case Builtin::BIreserve_read_pipe:
1109   case Builtin::BIcommit_read_pipe:
1110   case Builtin::BIwork_group_reserve_read_pipe:
1111   case Builtin::BIsub_group_reserve_read_pipe:
1112   case Builtin::BIwork_group_commit_read_pipe:
1113   case Builtin::BIsub_group_commit_read_pipe:
1114     if (!(!AccessQual || AccessQual->isReadOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "read_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   case Builtin::BIwrite_pipe:
1122   case Builtin::BIreserve_write_pipe:
1123   case Builtin::BIcommit_write_pipe:
1124   case Builtin::BIwork_group_reserve_write_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126   case Builtin::BIwork_group_commit_write_pipe:
1127   case Builtin::BIsub_group_commit_write_pipe:
1128     if (!(AccessQual && AccessQual->isWriteOnly())) {
1129       S.Diag(Arg0->getBeginLoc(),
1130              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1131           << "write_only" << Arg0->getSourceRange();
1132       return true;
1133     }
1134     break;
1135   default:
1136     break;
1137   }
1138   return false;
1139 }
1140 
1141 /// Returns true if pipe element type is different from the pointer.
1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1143   const Expr *Arg0 = Call->getArg(0);
1144   const Expr *ArgIdx = Call->getArg(Idx);
1145   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1146   const QualType EltTy = PipeTy->getElementType();
1147   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1148   // The Idx argument should be a pointer and the type of the pointer and
1149   // the type of pipe element should also be the same.
1150   if (!ArgTy ||
1151       !S.Context.hasSameType(
1152           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1153     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1154         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1155         << ArgIdx->getType() << ArgIdx->getSourceRange();
1156     return true;
1157   }
1158   return false;
1159 }
1160 
1161 // Performs semantic analysis for the read/write_pipe call.
1162 // \param S Reference to the semantic analyzer.
1163 // \param Call A pointer to the builtin call.
1164 // \return True if a semantic error has been found, false otherwise.
1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1166   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1167   // functions have two forms.
1168   switch (Call->getNumArgs()) {
1169   case 2:
1170     if (checkOpenCLPipeArg(S, Call))
1171       return true;
1172     // The call with 2 arguments should be
1173     // read/write_pipe(pipe T, T*).
1174     // Check packet type T.
1175     if (checkOpenCLPipePacketType(S, Call, 1))
1176       return true;
1177     break;
1178 
1179   case 4: {
1180     if (checkOpenCLPipeArg(S, Call))
1181       return true;
1182     // The call with 4 arguments should be
1183     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1184     // Check reserve_id_t.
1185     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1186       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1187           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1188           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1189       return true;
1190     }
1191 
1192     // Check the index.
1193     const Expr *Arg2 = Call->getArg(2);
1194     if (!Arg2->getType()->isIntegerType() &&
1195         !Arg2->getType()->isUnsignedIntegerType()) {
1196       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1197           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1198           << Arg2->getType() << Arg2->getSourceRange();
1199       return true;
1200     }
1201 
1202     // Check packet type T.
1203     if (checkOpenCLPipePacketType(S, Call, 3))
1204       return true;
1205   } break;
1206   default:
1207     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1208         << Call->getDirectCallee() << Call->getSourceRange();
1209     return true;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on the {work_group_/sub_group_
1216 //        /_}reserve_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check the reserve size.
1228   if (!Call->getArg(1)->getType()->isIntegerType() &&
1229       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1230     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1231         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1232         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1233     return true;
1234   }
1235 
1236   // Since return type of reserve_read/write_pipe built-in function is
1237   // reserve_id_t, which is not defined in the builtin def file , we used int
1238   // as return type and need to override the return type of these functions.
1239   Call->setType(S.Context.OCLReserveIDTy);
1240 
1241   return false;
1242 }
1243 
1244 // Performs a semantic analysis on {work_group_/sub_group_
1245 //        /_}commit_{read/write}_pipe
1246 // \param S Reference to the semantic analyzer.
1247 // \param Call The call to the builtin function to be analyzed.
1248 // \return True if a semantic error was found, false otherwise.
1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1250   if (checkArgCount(S, Call, 2))
1251     return true;
1252 
1253   if (checkOpenCLPipeArg(S, Call))
1254     return true;
1255 
1256   // Check reserve_id_t.
1257   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1258     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1259         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1260         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 // Performs a semantic analysis on the call to built-in Pipe
1268 //        Query Functions.
1269 // \param S Reference to the semantic analyzer.
1270 // \param Call The call to the builtin function to be analyzed.
1271 // \return True if a semantic error was found, false otherwise.
1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1273   if (checkArgCount(S, Call, 1))
1274     return true;
1275 
1276   if (!Call->getArg(0)->getType()->isPipeType()) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1278         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1279     return true;
1280   }
1281 
1282   return false;
1283 }
1284 
1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1286 // Performs semantic analysis for the to_global/local/private call.
1287 // \param S Reference to the semantic analyzer.
1288 // \param BuiltinID ID of the builtin function.
1289 // \param Call A pointer to the builtin call.
1290 // \return True if a semantic error has been found, false otherwise.
1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1292                                     CallExpr *Call) {
1293   if (checkArgCount(S, Call, 1))
1294     return true;
1295 
1296   auto RT = Call->getArg(0)->getType();
1297   if (!RT->isPointerType() || RT->getPointeeType()
1298       .getAddressSpace() == LangAS::opencl_constant) {
1299     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1300         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1301     return true;
1302   }
1303 
1304   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1305     S.Diag(Call->getArg(0)->getBeginLoc(),
1306            diag::warn_opencl_generic_address_space_arg)
1307         << Call->getDirectCallee()->getNameInfo().getAsString()
1308         << Call->getArg(0)->getSourceRange();
1309   }
1310 
1311   RT = RT->getPointeeType();
1312   auto Qual = RT.getQualifiers();
1313   switch (BuiltinID) {
1314   case Builtin::BIto_global:
1315     Qual.setAddressSpace(LangAS::opencl_global);
1316     break;
1317   case Builtin::BIto_local:
1318     Qual.setAddressSpace(LangAS::opencl_local);
1319     break;
1320   case Builtin::BIto_private:
1321     Qual.setAddressSpace(LangAS::opencl_private);
1322     break;
1323   default:
1324     llvm_unreachable("Invalid builtin function");
1325   }
1326   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1327       RT.getUnqualifiedType(), Qual)));
1328 
1329   return false;
1330 }
1331 
1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1333   if (checkArgCount(S, TheCall, 1))
1334     return ExprError();
1335 
1336   // Compute __builtin_launder's parameter type from the argument.
1337   // The parameter type is:
1338   //  * The type of the argument if it's not an array or function type,
1339   //  Otherwise,
1340   //  * The decayed argument type.
1341   QualType ParamTy = [&]() {
1342     QualType ArgTy = TheCall->getArg(0)->getType();
1343     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1344       return S.Context.getPointerType(Ty->getElementType());
1345     if (ArgTy->isFunctionType()) {
1346       return S.Context.getPointerType(ArgTy);
1347     }
1348     return ArgTy;
1349   }();
1350 
1351   TheCall->setType(ParamTy);
1352 
1353   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1354     if (!ParamTy->isPointerType())
1355       return 0;
1356     if (ParamTy->isFunctionPointerType())
1357       return 1;
1358     if (ParamTy->isVoidPointerType())
1359       return 2;
1360     return llvm::Optional<unsigned>{};
1361   }();
1362   if (DiagSelect.hasValue()) {
1363     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1364         << DiagSelect.getValue() << TheCall->getSourceRange();
1365     return ExprError();
1366   }
1367 
1368   // We either have an incomplete class type, or we have a class template
1369   // whose instantiation has not been forced. Example:
1370   //
1371   //   template <class T> struct Foo { T value; };
1372   //   Foo<int> *p = nullptr;
1373   //   auto *d = __builtin_launder(p);
1374   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1375                             diag::err_incomplete_type))
1376     return ExprError();
1377 
1378   assert(ParamTy->getPointeeType()->isObjectType() &&
1379          "Unhandled non-object pointer case");
1380 
1381   InitializedEntity Entity =
1382       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1383   ExprResult Arg =
1384       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1385   if (Arg.isInvalid())
1386     return ExprError();
1387   TheCall->setArg(0, Arg.get());
1388 
1389   return TheCall;
1390 }
1391 
1392 // Emit an error and return true if the current architecture is not in the list
1393 // of supported architectures.
1394 static bool
1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1396                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1397   llvm::Triple::ArchType CurArch =
1398       S.getASTContext().getTargetInfo().getTriple().getArch();
1399   if (llvm::is_contained(SupportedArchs, CurArch))
1400     return false;
1401   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1402       << TheCall->getSourceRange();
1403   return true;
1404 }
1405 
1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1407                                  SourceLocation CallSiteLoc);
1408 
1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1410                                       CallExpr *TheCall) {
1411   switch (TI.getTriple().getArch()) {
1412   default:
1413     // Some builtins don't require additional checking, so just consider these
1414     // acceptable.
1415     return false;
1416   case llvm::Triple::arm:
1417   case llvm::Triple::armeb:
1418   case llvm::Triple::thumb:
1419   case llvm::Triple::thumbeb:
1420     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::aarch64:
1422   case llvm::Triple::aarch64_32:
1423   case llvm::Triple::aarch64_be:
1424     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::bpfeb:
1426   case llvm::Triple::bpfel:
1427     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1428   case llvm::Triple::hexagon:
1429     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1430   case llvm::Triple::mips:
1431   case llvm::Triple::mipsel:
1432   case llvm::Triple::mips64:
1433   case llvm::Triple::mips64el:
1434     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   case llvm::Triple::systemz:
1436     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1437   case llvm::Triple::x86:
1438   case llvm::Triple::x86_64:
1439     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1440   case llvm::Triple::ppc:
1441   case llvm::Triple::ppcle:
1442   case llvm::Triple::ppc64:
1443   case llvm::Triple::ppc64le:
1444     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1445   case llvm::Triple::amdgcn:
1446     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1447   case llvm::Triple::riscv32:
1448   case llvm::Triple::riscv64:
1449     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1450   }
1451 }
1452 
1453 ExprResult
1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1455                                CallExpr *TheCall) {
1456   ExprResult TheCallResult(TheCall);
1457 
1458   // Find out if any arguments are required to be integer constant expressions.
1459   unsigned ICEArguments = 0;
1460   ASTContext::GetBuiltinTypeError Error;
1461   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1462   if (Error != ASTContext::GE_None)
1463     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1464 
1465   // If any arguments are required to be ICE's, check and diagnose.
1466   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1467     // Skip arguments not required to be ICE's.
1468     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1469 
1470     llvm::APSInt Result;
1471     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1472       return true;
1473     ICEArguments &= ~(1 << ArgNo);
1474   }
1475 
1476   switch (BuiltinID) {
1477   case Builtin::BI__builtin___CFStringMakeConstantString:
1478     assert(TheCall->getNumArgs() == 1 &&
1479            "Wrong # arguments to builtin CFStringMakeConstantString");
1480     if (CheckObjCString(TheCall->getArg(0)))
1481       return ExprError();
1482     break;
1483   case Builtin::BI__builtin_ms_va_start:
1484   case Builtin::BI__builtin_stdarg_start:
1485   case Builtin::BI__builtin_va_start:
1486     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BI__va_start: {
1490     switch (Context.getTargetInfo().getTriple().getArch()) {
1491     case llvm::Triple::aarch64:
1492     case llvm::Triple::arm:
1493     case llvm::Triple::thumb:
1494       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1495         return ExprError();
1496       break;
1497     default:
1498       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1499         return ExprError();
1500       break;
1501     }
1502     break;
1503   }
1504 
1505   // The acquire, release, and no fence variants are ARM and AArch64 only.
1506   case Builtin::BI_interlockedbittestandset_acq:
1507   case Builtin::BI_interlockedbittestandset_rel:
1508   case Builtin::BI_interlockedbittestandset_nf:
1509   case Builtin::BI_interlockedbittestandreset_acq:
1510   case Builtin::BI_interlockedbittestandreset_rel:
1511   case Builtin::BI_interlockedbittestandreset_nf:
1512     if (CheckBuiltinTargetSupport(
1513             *this, BuiltinID, TheCall,
1514             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1519   case Builtin::BI_bittest64:
1520   case Builtin::BI_bittestandcomplement64:
1521   case Builtin::BI_bittestandreset64:
1522   case Builtin::BI_bittestandset64:
1523   case Builtin::BI_interlockedbittestandreset64:
1524   case Builtin::BI_interlockedbittestandset64:
1525     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1526                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1527                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1528       return ExprError();
1529     break;
1530 
1531   case Builtin::BI__builtin_isgreater:
1532   case Builtin::BI__builtin_isgreaterequal:
1533   case Builtin::BI__builtin_isless:
1534   case Builtin::BI__builtin_islessequal:
1535   case Builtin::BI__builtin_islessgreater:
1536   case Builtin::BI__builtin_isunordered:
1537     if (SemaBuiltinUnorderedCompare(TheCall))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_fpclassify:
1541     if (SemaBuiltinFPClassification(TheCall, 6))
1542       return ExprError();
1543     break;
1544   case Builtin::BI__builtin_isfinite:
1545   case Builtin::BI__builtin_isinf:
1546   case Builtin::BI__builtin_isinf_sign:
1547   case Builtin::BI__builtin_isnan:
1548   case Builtin::BI__builtin_isnormal:
1549   case Builtin::BI__builtin_signbit:
1550   case Builtin::BI__builtin_signbitf:
1551   case Builtin::BI__builtin_signbitl:
1552     if (SemaBuiltinFPClassification(TheCall, 1))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_shufflevector:
1556     return SemaBuiltinShuffleVector(TheCall);
1557     // TheCall will be freed by the smart pointer here, but that's fine, since
1558     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1559   case Builtin::BI__builtin_prefetch:
1560     if (SemaBuiltinPrefetch(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_alloca_with_align:
1564     if (SemaBuiltinAllocaWithAlign(TheCall))
1565       return ExprError();
1566     LLVM_FALLTHROUGH;
1567   case Builtin::BI__builtin_alloca:
1568     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1569         << TheCall->getDirectCallee();
1570     break;
1571   case Builtin::BI__arithmetic_fence:
1572     if (SemaBuiltinArithmeticFence(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__assume:
1576   case Builtin::BI__builtin_assume:
1577     if (SemaBuiltinAssume(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_assume_aligned:
1581     if (SemaBuiltinAssumeAligned(TheCall))
1582       return ExprError();
1583     break;
1584   case Builtin::BI__builtin_dynamic_object_size:
1585   case Builtin::BI__builtin_object_size:
1586     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1587       return ExprError();
1588     break;
1589   case Builtin::BI__builtin_longjmp:
1590     if (SemaBuiltinLongjmp(TheCall))
1591       return ExprError();
1592     break;
1593   case Builtin::BI__builtin_setjmp:
1594     if (SemaBuiltinSetjmp(TheCall))
1595       return ExprError();
1596     break;
1597   case Builtin::BI__builtin_classify_type:
1598     if (checkArgCount(*this, TheCall, 1)) return true;
1599     TheCall->setType(Context.IntTy);
1600     break;
1601   case Builtin::BI__builtin_complex:
1602     if (SemaBuiltinComplex(TheCall))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_constant_p: {
1606     if (checkArgCount(*this, TheCall, 1)) return true;
1607     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1608     if (Arg.isInvalid()) return true;
1609     TheCall->setArg(0, Arg.get());
1610     TheCall->setType(Context.IntTy);
1611     break;
1612   }
1613   case Builtin::BI__builtin_launder:
1614     return SemaBuiltinLaunder(*this, TheCall);
1615   case Builtin::BI__sync_fetch_and_add:
1616   case Builtin::BI__sync_fetch_and_add_1:
1617   case Builtin::BI__sync_fetch_and_add_2:
1618   case Builtin::BI__sync_fetch_and_add_4:
1619   case Builtin::BI__sync_fetch_and_add_8:
1620   case Builtin::BI__sync_fetch_and_add_16:
1621   case Builtin::BI__sync_fetch_and_sub:
1622   case Builtin::BI__sync_fetch_and_sub_1:
1623   case Builtin::BI__sync_fetch_and_sub_2:
1624   case Builtin::BI__sync_fetch_and_sub_4:
1625   case Builtin::BI__sync_fetch_and_sub_8:
1626   case Builtin::BI__sync_fetch_and_sub_16:
1627   case Builtin::BI__sync_fetch_and_or:
1628   case Builtin::BI__sync_fetch_and_or_1:
1629   case Builtin::BI__sync_fetch_and_or_2:
1630   case Builtin::BI__sync_fetch_and_or_4:
1631   case Builtin::BI__sync_fetch_and_or_8:
1632   case Builtin::BI__sync_fetch_and_or_16:
1633   case Builtin::BI__sync_fetch_and_and:
1634   case Builtin::BI__sync_fetch_and_and_1:
1635   case Builtin::BI__sync_fetch_and_and_2:
1636   case Builtin::BI__sync_fetch_and_and_4:
1637   case Builtin::BI__sync_fetch_and_and_8:
1638   case Builtin::BI__sync_fetch_and_and_16:
1639   case Builtin::BI__sync_fetch_and_xor:
1640   case Builtin::BI__sync_fetch_and_xor_1:
1641   case Builtin::BI__sync_fetch_and_xor_2:
1642   case Builtin::BI__sync_fetch_and_xor_4:
1643   case Builtin::BI__sync_fetch_and_xor_8:
1644   case Builtin::BI__sync_fetch_and_xor_16:
1645   case Builtin::BI__sync_fetch_and_nand:
1646   case Builtin::BI__sync_fetch_and_nand_1:
1647   case Builtin::BI__sync_fetch_and_nand_2:
1648   case Builtin::BI__sync_fetch_and_nand_4:
1649   case Builtin::BI__sync_fetch_and_nand_8:
1650   case Builtin::BI__sync_fetch_and_nand_16:
1651   case Builtin::BI__sync_add_and_fetch:
1652   case Builtin::BI__sync_add_and_fetch_1:
1653   case Builtin::BI__sync_add_and_fetch_2:
1654   case Builtin::BI__sync_add_and_fetch_4:
1655   case Builtin::BI__sync_add_and_fetch_8:
1656   case Builtin::BI__sync_add_and_fetch_16:
1657   case Builtin::BI__sync_sub_and_fetch:
1658   case Builtin::BI__sync_sub_and_fetch_1:
1659   case Builtin::BI__sync_sub_and_fetch_2:
1660   case Builtin::BI__sync_sub_and_fetch_4:
1661   case Builtin::BI__sync_sub_and_fetch_8:
1662   case Builtin::BI__sync_sub_and_fetch_16:
1663   case Builtin::BI__sync_and_and_fetch:
1664   case Builtin::BI__sync_and_and_fetch_1:
1665   case Builtin::BI__sync_and_and_fetch_2:
1666   case Builtin::BI__sync_and_and_fetch_4:
1667   case Builtin::BI__sync_and_and_fetch_8:
1668   case Builtin::BI__sync_and_and_fetch_16:
1669   case Builtin::BI__sync_or_and_fetch:
1670   case Builtin::BI__sync_or_and_fetch_1:
1671   case Builtin::BI__sync_or_and_fetch_2:
1672   case Builtin::BI__sync_or_and_fetch_4:
1673   case Builtin::BI__sync_or_and_fetch_8:
1674   case Builtin::BI__sync_or_and_fetch_16:
1675   case Builtin::BI__sync_xor_and_fetch:
1676   case Builtin::BI__sync_xor_and_fetch_1:
1677   case Builtin::BI__sync_xor_and_fetch_2:
1678   case Builtin::BI__sync_xor_and_fetch_4:
1679   case Builtin::BI__sync_xor_and_fetch_8:
1680   case Builtin::BI__sync_xor_and_fetch_16:
1681   case Builtin::BI__sync_nand_and_fetch:
1682   case Builtin::BI__sync_nand_and_fetch_1:
1683   case Builtin::BI__sync_nand_and_fetch_2:
1684   case Builtin::BI__sync_nand_and_fetch_4:
1685   case Builtin::BI__sync_nand_and_fetch_8:
1686   case Builtin::BI__sync_nand_and_fetch_16:
1687   case Builtin::BI__sync_val_compare_and_swap:
1688   case Builtin::BI__sync_val_compare_and_swap_1:
1689   case Builtin::BI__sync_val_compare_and_swap_2:
1690   case Builtin::BI__sync_val_compare_and_swap_4:
1691   case Builtin::BI__sync_val_compare_and_swap_8:
1692   case Builtin::BI__sync_val_compare_and_swap_16:
1693   case Builtin::BI__sync_bool_compare_and_swap:
1694   case Builtin::BI__sync_bool_compare_and_swap_1:
1695   case Builtin::BI__sync_bool_compare_and_swap_2:
1696   case Builtin::BI__sync_bool_compare_and_swap_4:
1697   case Builtin::BI__sync_bool_compare_and_swap_8:
1698   case Builtin::BI__sync_bool_compare_and_swap_16:
1699   case Builtin::BI__sync_lock_test_and_set:
1700   case Builtin::BI__sync_lock_test_and_set_1:
1701   case Builtin::BI__sync_lock_test_and_set_2:
1702   case Builtin::BI__sync_lock_test_and_set_4:
1703   case Builtin::BI__sync_lock_test_and_set_8:
1704   case Builtin::BI__sync_lock_test_and_set_16:
1705   case Builtin::BI__sync_lock_release:
1706   case Builtin::BI__sync_lock_release_1:
1707   case Builtin::BI__sync_lock_release_2:
1708   case Builtin::BI__sync_lock_release_4:
1709   case Builtin::BI__sync_lock_release_8:
1710   case Builtin::BI__sync_lock_release_16:
1711   case Builtin::BI__sync_swap:
1712   case Builtin::BI__sync_swap_1:
1713   case Builtin::BI__sync_swap_2:
1714   case Builtin::BI__sync_swap_4:
1715   case Builtin::BI__sync_swap_8:
1716   case Builtin::BI__sync_swap_16:
1717     return SemaBuiltinAtomicOverloaded(TheCallResult);
1718   case Builtin::BI__sync_synchronize:
1719     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1720         << TheCall->getCallee()->getSourceRange();
1721     break;
1722   case Builtin::BI__builtin_nontemporal_load:
1723   case Builtin::BI__builtin_nontemporal_store:
1724     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1725   case Builtin::BI__builtin_memcpy_inline: {
1726     clang::Expr *SizeOp = TheCall->getArg(2);
1727     // We warn about copying to or from `nullptr` pointers when `size` is
1728     // greater than 0. When `size` is value dependent we cannot evaluate its
1729     // value so we bail out.
1730     if (SizeOp->isValueDependent())
1731       break;
1732     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1733       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1734       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1735     }
1736     break;
1737   }
1738 #define BUILTIN(ID, TYPE, ATTRS)
1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1740   case Builtin::BI##ID: \
1741     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1742 #include "clang/Basic/Builtins.def"
1743   case Builtin::BI__annotation:
1744     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_annotation:
1748     if (SemaBuiltinAnnotation(*this, TheCall))
1749       return ExprError();
1750     break;
1751   case Builtin::BI__builtin_addressof:
1752     if (SemaBuiltinAddressof(*this, TheCall))
1753       return ExprError();
1754     break;
1755   case Builtin::BI__builtin_is_aligned:
1756   case Builtin::BI__builtin_align_up:
1757   case Builtin::BI__builtin_align_down:
1758     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__builtin_add_overflow:
1762   case Builtin::BI__builtin_sub_overflow:
1763   case Builtin::BI__builtin_mul_overflow:
1764     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1765       return ExprError();
1766     break;
1767   case Builtin::BI__builtin_operator_new:
1768   case Builtin::BI__builtin_operator_delete: {
1769     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1770     ExprResult Res =
1771         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1772     if (Res.isInvalid())
1773       CorrectDelayedTyposInExpr(TheCallResult.get());
1774     return Res;
1775   }
1776   case Builtin::BI__builtin_dump_struct: {
1777     // We first want to ensure we are called with 2 arguments
1778     if (checkArgCount(*this, TheCall, 2))
1779       return ExprError();
1780     // Ensure that the first argument is of type 'struct XX *'
1781     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1782     const QualType PtrArgType = PtrArg->getType();
1783     if (!PtrArgType->isPointerType() ||
1784         !PtrArgType->getPointeeType()->isRecordType()) {
1785       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1787           << "structure pointer";
1788       return ExprError();
1789     }
1790 
1791     // Ensure that the second argument is of type 'FunctionType'
1792     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1793     const QualType FnPtrArgType = FnPtrArg->getType();
1794     if (!FnPtrArgType->isPointerType()) {
1795       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1797           << FnPtrArgType << "'int (*)(const char *, ...)'";
1798       return ExprError();
1799     }
1800 
1801     const auto *FuncType =
1802         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1803 
1804     if (!FuncType) {
1805       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1806           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1807           << FnPtrArgType << "'int (*)(const char *, ...)'";
1808       return ExprError();
1809     }
1810 
1811     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1812       if (!FT->getNumParams()) {
1813         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1814             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1815             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1816         return ExprError();
1817       }
1818       QualType PT = FT->getParamType(0);
1819       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1820           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1821           !PT->getPointeeType().isConstQualified()) {
1822         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1823             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1824             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1825         return ExprError();
1826       }
1827     }
1828 
1829     TheCall->setType(Context.IntTy);
1830     break;
1831   }
1832   case Builtin::BI__builtin_expect_with_probability: {
1833     // We first want to ensure we are called with 3 arguments
1834     if (checkArgCount(*this, TheCall, 3))
1835       return ExprError();
1836     // then check probability is constant float in range [0.0, 1.0]
1837     const Expr *ProbArg = TheCall->getArg(2);
1838     SmallVector<PartialDiagnosticAt, 8> Notes;
1839     Expr::EvalResult Eval;
1840     Eval.Diag = &Notes;
1841     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1842         !Eval.Val.isFloat()) {
1843       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1844           << ProbArg->getSourceRange();
1845       for (const PartialDiagnosticAt &PDiag : Notes)
1846         Diag(PDiag.first, PDiag.second);
1847       return ExprError();
1848     }
1849     llvm::APFloat Probability = Eval.Val.getFloat();
1850     bool LoseInfo = false;
1851     Probability.convert(llvm::APFloat::IEEEdouble(),
1852                         llvm::RoundingMode::Dynamic, &LoseInfo);
1853     if (!(Probability >= llvm::APFloat(0.0) &&
1854           Probability <= llvm::APFloat(1.0))) {
1855       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1856           << ProbArg->getSourceRange();
1857       return ExprError();
1858     }
1859     break;
1860   }
1861   case Builtin::BI__builtin_preserve_access_index:
1862     if (SemaBuiltinPreserveAI(*this, TheCall))
1863       return ExprError();
1864     break;
1865   case Builtin::BI__builtin_call_with_static_chain:
1866     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__exception_code:
1870   case Builtin::BI_exception_code:
1871     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1872                                  diag::err_seh___except_block))
1873       return ExprError();
1874     break;
1875   case Builtin::BI__exception_info:
1876   case Builtin::BI_exception_info:
1877     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1878                                  diag::err_seh___except_filter))
1879       return ExprError();
1880     break;
1881   case Builtin::BI__GetExceptionInfo:
1882     if (checkArgCount(*this, TheCall, 1))
1883       return ExprError();
1884 
1885     if (CheckCXXThrowOperand(
1886             TheCall->getBeginLoc(),
1887             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1888             TheCall))
1889       return ExprError();
1890 
1891     TheCall->setType(Context.VoidPtrTy);
1892     break;
1893   // OpenCL v2.0, s6.13.16 - Pipe functions
1894   case Builtin::BIread_pipe:
1895   case Builtin::BIwrite_pipe:
1896     // Since those two functions are declared with var args, we need a semantic
1897     // check for the argument.
1898     if (SemaBuiltinRWPipe(*this, TheCall))
1899       return ExprError();
1900     break;
1901   case Builtin::BIreserve_read_pipe:
1902   case Builtin::BIreserve_write_pipe:
1903   case Builtin::BIwork_group_reserve_read_pipe:
1904   case Builtin::BIwork_group_reserve_write_pipe:
1905     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIsub_group_reserve_read_pipe:
1909   case Builtin::BIsub_group_reserve_write_pipe:
1910     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1911         SemaBuiltinReserveRWPipe(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIcommit_read_pipe:
1915   case Builtin::BIcommit_write_pipe:
1916   case Builtin::BIwork_group_commit_read_pipe:
1917   case Builtin::BIwork_group_commit_write_pipe:
1918     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1919       return ExprError();
1920     break;
1921   case Builtin::BIsub_group_commit_read_pipe:
1922   case Builtin::BIsub_group_commit_write_pipe:
1923     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1924         SemaBuiltinCommitRWPipe(*this, TheCall))
1925       return ExprError();
1926     break;
1927   case Builtin::BIget_pipe_num_packets:
1928   case Builtin::BIget_pipe_max_packets:
1929     if (SemaBuiltinPipePackets(*this, TheCall))
1930       return ExprError();
1931     break;
1932   case Builtin::BIto_global:
1933   case Builtin::BIto_local:
1934   case Builtin::BIto_private:
1935     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1936       return ExprError();
1937     break;
1938   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1939   case Builtin::BIenqueue_kernel:
1940     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1941       return ExprError();
1942     break;
1943   case Builtin::BIget_kernel_work_group_size:
1944   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1945     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1946       return ExprError();
1947     break;
1948   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1949   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1950     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1951       return ExprError();
1952     break;
1953   case Builtin::BI__builtin_os_log_format:
1954     Cleanup.setExprNeedsCleanups(true);
1955     LLVM_FALLTHROUGH;
1956   case Builtin::BI__builtin_os_log_format_buffer_size:
1957     if (SemaBuiltinOSLogFormat(TheCall))
1958       return ExprError();
1959     break;
1960   case Builtin::BI__builtin_frame_address:
1961   case Builtin::BI__builtin_return_address: {
1962     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1963       return ExprError();
1964 
1965     // -Wframe-address warning if non-zero passed to builtin
1966     // return/frame address.
1967     Expr::EvalResult Result;
1968     if (!TheCall->getArg(0)->isValueDependent() &&
1969         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1970         Result.Val.getInt() != 0)
1971       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1972           << ((BuiltinID == Builtin::BI__builtin_return_address)
1973                   ? "__builtin_return_address"
1974                   : "__builtin_frame_address")
1975           << TheCall->getSourceRange();
1976     break;
1977   }
1978 
1979   case Builtin::BI__builtin_elementwise_min:
1980   case Builtin::BI__builtin_elementwise_max:
1981     if (SemaBuiltinElementwiseMath(TheCall))
1982       return ExprError();
1983     break;
1984   case Builtin::BI__builtin_matrix_transpose:
1985     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1986 
1987   case Builtin::BI__builtin_matrix_column_major_load:
1988     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1989 
1990   case Builtin::BI__builtin_matrix_column_major_store:
1991     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1992 
1993   case Builtin::BI__builtin_get_device_side_mangled_name: {
1994     auto Check = [](CallExpr *TheCall) {
1995       if (TheCall->getNumArgs() != 1)
1996         return false;
1997       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1998       if (!DRE)
1999         return false;
2000       auto *D = DRE->getDecl();
2001       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2002         return false;
2003       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2004              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2005     };
2006     if (!Check(TheCall)) {
2007       Diag(TheCall->getBeginLoc(),
2008            diag::err_hip_invalid_args_builtin_mangled_name);
2009       return ExprError();
2010     }
2011   }
2012   }
2013 
2014   // Since the target specific builtins for each arch overlap, only check those
2015   // of the arch we are compiling for.
2016   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2017     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2018       assert(Context.getAuxTargetInfo() &&
2019              "Aux Target Builtin, but not an aux target?");
2020 
2021       if (CheckTSBuiltinFunctionCall(
2022               *Context.getAuxTargetInfo(),
2023               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2024         return ExprError();
2025     } else {
2026       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2027                                      TheCall))
2028         return ExprError();
2029     }
2030   }
2031 
2032   return TheCallResult;
2033 }
2034 
2035 // Get the valid immediate range for the specified NEON type code.
2036 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2037   NeonTypeFlags Type(t);
2038   int IsQuad = ForceQuad ? true : Type.isQuad();
2039   switch (Type.getEltType()) {
2040   case NeonTypeFlags::Int8:
2041   case NeonTypeFlags::Poly8:
2042     return shift ? 7 : (8 << IsQuad) - 1;
2043   case NeonTypeFlags::Int16:
2044   case NeonTypeFlags::Poly16:
2045     return shift ? 15 : (4 << IsQuad) - 1;
2046   case NeonTypeFlags::Int32:
2047     return shift ? 31 : (2 << IsQuad) - 1;
2048   case NeonTypeFlags::Int64:
2049   case NeonTypeFlags::Poly64:
2050     return shift ? 63 : (1 << IsQuad) - 1;
2051   case NeonTypeFlags::Poly128:
2052     return shift ? 127 : (1 << IsQuad) - 1;
2053   case NeonTypeFlags::Float16:
2054     assert(!shift && "cannot shift float types!");
2055     return (4 << IsQuad) - 1;
2056   case NeonTypeFlags::Float32:
2057     assert(!shift && "cannot shift float types!");
2058     return (2 << IsQuad) - 1;
2059   case NeonTypeFlags::Float64:
2060     assert(!shift && "cannot shift float types!");
2061     return (1 << IsQuad) - 1;
2062   case NeonTypeFlags::BFloat16:
2063     assert(!shift && "cannot shift float types!");
2064     return (4 << IsQuad) - 1;
2065   }
2066   llvm_unreachable("Invalid NeonTypeFlag!");
2067 }
2068 
2069 /// getNeonEltType - Return the QualType corresponding to the elements of
2070 /// the vector type specified by the NeonTypeFlags.  This is used to check
2071 /// the pointer arguments for Neon load/store intrinsics.
2072 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2073                                bool IsPolyUnsigned, bool IsInt64Long) {
2074   switch (Flags.getEltType()) {
2075   case NeonTypeFlags::Int8:
2076     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2077   case NeonTypeFlags::Int16:
2078     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2079   case NeonTypeFlags::Int32:
2080     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2081   case NeonTypeFlags::Int64:
2082     if (IsInt64Long)
2083       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2084     else
2085       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2086                                 : Context.LongLongTy;
2087   case NeonTypeFlags::Poly8:
2088     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2089   case NeonTypeFlags::Poly16:
2090     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2091   case NeonTypeFlags::Poly64:
2092     if (IsInt64Long)
2093       return Context.UnsignedLongTy;
2094     else
2095       return Context.UnsignedLongLongTy;
2096   case NeonTypeFlags::Poly128:
2097     break;
2098   case NeonTypeFlags::Float16:
2099     return Context.HalfTy;
2100   case NeonTypeFlags::Float32:
2101     return Context.FloatTy;
2102   case NeonTypeFlags::Float64:
2103     return Context.DoubleTy;
2104   case NeonTypeFlags::BFloat16:
2105     return Context.BFloat16Ty;
2106   }
2107   llvm_unreachable("Invalid NeonTypeFlag!");
2108 }
2109 
2110 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2111   // Range check SVE intrinsics that take immediate values.
2112   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2113 
2114   switch (BuiltinID) {
2115   default:
2116     return false;
2117 #define GET_SVE_IMMEDIATE_CHECK
2118 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2119 #undef GET_SVE_IMMEDIATE_CHECK
2120   }
2121 
2122   // Perform all the immediate checks for this builtin call.
2123   bool HasError = false;
2124   for (auto &I : ImmChecks) {
2125     int ArgNum, CheckTy, ElementSizeInBits;
2126     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2127 
2128     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2129 
2130     // Function that checks whether the operand (ArgNum) is an immediate
2131     // that is one of the predefined values.
2132     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2133                                    int ErrDiag) -> bool {
2134       // We can't check the value of a dependent argument.
2135       Expr *Arg = TheCall->getArg(ArgNum);
2136       if (Arg->isTypeDependent() || Arg->isValueDependent())
2137         return false;
2138 
2139       // Check constant-ness first.
2140       llvm::APSInt Imm;
2141       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2142         return true;
2143 
2144       if (!CheckImm(Imm.getSExtValue()))
2145         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2146       return false;
2147     };
2148 
2149     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2150     case SVETypeFlags::ImmCheck0_31:
2151       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2152         HasError = true;
2153       break;
2154     case SVETypeFlags::ImmCheck0_13:
2155       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2156         HasError = true;
2157       break;
2158     case SVETypeFlags::ImmCheck1_16:
2159       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2160         HasError = true;
2161       break;
2162     case SVETypeFlags::ImmCheck0_7:
2163       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckExtract:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2168                                       (2048 / ElementSizeInBits) - 1))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheckShiftRight:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheckShiftRightNarrow:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2177                                       ElementSizeInBits / 2))
2178         HasError = true;
2179       break;
2180     case SVETypeFlags::ImmCheckShiftLeft:
2181       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2182                                       ElementSizeInBits - 1))
2183         HasError = true;
2184       break;
2185     case SVETypeFlags::ImmCheckLaneIndex:
2186       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2187                                       (128 / (1 * ElementSizeInBits)) - 1))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2192                                       (128 / (2 * ElementSizeInBits)) - 1))
2193         HasError = true;
2194       break;
2195     case SVETypeFlags::ImmCheckLaneIndexDot:
2196       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2197                                       (128 / (4 * ElementSizeInBits)) - 1))
2198         HasError = true;
2199       break;
2200     case SVETypeFlags::ImmCheckComplexRot90_270:
2201       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2202                               diag::err_rotation_argument_to_cadd))
2203         HasError = true;
2204       break;
2205     case SVETypeFlags::ImmCheckComplexRotAll90:
2206       if (CheckImmediateInSet(
2207               [](int64_t V) {
2208                 return V == 0 || V == 90 || V == 180 || V == 270;
2209               },
2210               diag::err_rotation_argument_to_cmla))
2211         HasError = true;
2212       break;
2213     case SVETypeFlags::ImmCheck0_1:
2214       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2215         HasError = true;
2216       break;
2217     case SVETypeFlags::ImmCheck0_2:
2218       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2219         HasError = true;
2220       break;
2221     case SVETypeFlags::ImmCheck0_3:
2222       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2223         HasError = true;
2224       break;
2225     }
2226   }
2227 
2228   return HasError;
2229 }
2230 
2231 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2232                                         unsigned BuiltinID, CallExpr *TheCall) {
2233   llvm::APSInt Result;
2234   uint64_t mask = 0;
2235   unsigned TV = 0;
2236   int PtrArgNum = -1;
2237   bool HasConstPtr = false;
2238   switch (BuiltinID) {
2239 #define GET_NEON_OVERLOAD_CHECK
2240 #include "clang/Basic/arm_neon.inc"
2241 #include "clang/Basic/arm_fp16.inc"
2242 #undef GET_NEON_OVERLOAD_CHECK
2243   }
2244 
2245   // For NEON intrinsics which are overloaded on vector element type, validate
2246   // the immediate which specifies which variant to emit.
2247   unsigned ImmArg = TheCall->getNumArgs()-1;
2248   if (mask) {
2249     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2250       return true;
2251 
2252     TV = Result.getLimitedValue(64);
2253     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2254       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2255              << TheCall->getArg(ImmArg)->getSourceRange();
2256   }
2257 
2258   if (PtrArgNum >= 0) {
2259     // Check that pointer arguments have the specified type.
2260     Expr *Arg = TheCall->getArg(PtrArgNum);
2261     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2262       Arg = ICE->getSubExpr();
2263     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2264     QualType RHSTy = RHS.get()->getType();
2265 
2266     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2267     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2268                           Arch == llvm::Triple::aarch64_32 ||
2269                           Arch == llvm::Triple::aarch64_be;
2270     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2271     QualType EltTy =
2272         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2273     if (HasConstPtr)
2274       EltTy = EltTy.withConst();
2275     QualType LHSTy = Context.getPointerType(EltTy);
2276     AssignConvertType ConvTy;
2277     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2278     if (RHS.isInvalid())
2279       return true;
2280     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2281                                  RHS.get(), AA_Assigning))
2282       return true;
2283   }
2284 
2285   // For NEON intrinsics which take an immediate value as part of the
2286   // instruction, range check them here.
2287   unsigned i = 0, l = 0, u = 0;
2288   switch (BuiltinID) {
2289   default:
2290     return false;
2291   #define GET_NEON_IMMEDIATE_CHECK
2292   #include "clang/Basic/arm_neon.inc"
2293   #include "clang/Basic/arm_fp16.inc"
2294   #undef GET_NEON_IMMEDIATE_CHECK
2295   }
2296 
2297   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2298 }
2299 
2300 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2301   switch (BuiltinID) {
2302   default:
2303     return false;
2304   #include "clang/Basic/arm_mve_builtin_sema.inc"
2305   }
2306 }
2307 
2308 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2309                                        CallExpr *TheCall) {
2310   bool Err = false;
2311   switch (BuiltinID) {
2312   default:
2313     return false;
2314 #include "clang/Basic/arm_cde_builtin_sema.inc"
2315   }
2316 
2317   if (Err)
2318     return true;
2319 
2320   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2321 }
2322 
2323 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2324                                         const Expr *CoprocArg, bool WantCDE) {
2325   if (isConstantEvaluated())
2326     return false;
2327 
2328   // We can't check the value of a dependent argument.
2329   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2330     return false;
2331 
2332   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2333   int64_t CoprocNo = CoprocNoAP.getExtValue();
2334   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2335 
2336   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2337   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2338 
2339   if (IsCDECoproc != WantCDE)
2340     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2341            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2342 
2343   return false;
2344 }
2345 
2346 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2347                                         unsigned MaxWidth) {
2348   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2349           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2350           BuiltinID == ARM::BI__builtin_arm_strex ||
2351           BuiltinID == ARM::BI__builtin_arm_stlex ||
2352           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2353           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2354           BuiltinID == AArch64::BI__builtin_arm_strex ||
2355           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2356          "unexpected ARM builtin");
2357   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2358                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2359                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2360                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2361 
2362   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2363 
2364   // Ensure that we have the proper number of arguments.
2365   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2366     return true;
2367 
2368   // Inspect the pointer argument of the atomic builtin.  This should always be
2369   // a pointer type, whose element is an integral scalar or pointer type.
2370   // Because it is a pointer type, we don't have to worry about any implicit
2371   // casts here.
2372   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2373   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2374   if (PointerArgRes.isInvalid())
2375     return true;
2376   PointerArg = PointerArgRes.get();
2377 
2378   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2379   if (!pointerType) {
2380     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2381         << PointerArg->getType() << PointerArg->getSourceRange();
2382     return true;
2383   }
2384 
2385   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2386   // task is to insert the appropriate casts into the AST. First work out just
2387   // what the appropriate type is.
2388   QualType ValType = pointerType->getPointeeType();
2389   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2390   if (IsLdrex)
2391     AddrType.addConst();
2392 
2393   // Issue a warning if the cast is dodgy.
2394   CastKind CastNeeded = CK_NoOp;
2395   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2396     CastNeeded = CK_BitCast;
2397     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2398         << PointerArg->getType() << Context.getPointerType(AddrType)
2399         << AA_Passing << PointerArg->getSourceRange();
2400   }
2401 
2402   // Finally, do the cast and replace the argument with the corrected version.
2403   AddrType = Context.getPointerType(AddrType);
2404   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2405   if (PointerArgRes.isInvalid())
2406     return true;
2407   PointerArg = PointerArgRes.get();
2408 
2409   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2410 
2411   // In general, we allow ints, floats and pointers to be loaded and stored.
2412   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2413       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2414     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2415         << PointerArg->getType() << PointerArg->getSourceRange();
2416     return true;
2417   }
2418 
2419   // But ARM doesn't have instructions to deal with 128-bit versions.
2420   if (Context.getTypeSize(ValType) > MaxWidth) {
2421     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2422     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2423         << PointerArg->getType() << PointerArg->getSourceRange();
2424     return true;
2425   }
2426 
2427   switch (ValType.getObjCLifetime()) {
2428   case Qualifiers::OCL_None:
2429   case Qualifiers::OCL_ExplicitNone:
2430     // okay
2431     break;
2432 
2433   case Qualifiers::OCL_Weak:
2434   case Qualifiers::OCL_Strong:
2435   case Qualifiers::OCL_Autoreleasing:
2436     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2437         << ValType << PointerArg->getSourceRange();
2438     return true;
2439   }
2440 
2441   if (IsLdrex) {
2442     TheCall->setType(ValType);
2443     return false;
2444   }
2445 
2446   // Initialize the argument to be stored.
2447   ExprResult ValArg = TheCall->getArg(0);
2448   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2449       Context, ValType, /*consume*/ false);
2450   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2451   if (ValArg.isInvalid())
2452     return true;
2453   TheCall->setArg(0, ValArg.get());
2454 
2455   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2456   // but the custom checker bypasses all default analysis.
2457   TheCall->setType(Context.IntTy);
2458   return false;
2459 }
2460 
2461 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2462                                        CallExpr *TheCall) {
2463   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2464       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2465       BuiltinID == ARM::BI__builtin_arm_strex ||
2466       BuiltinID == ARM::BI__builtin_arm_stlex) {
2467     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2468   }
2469 
2470   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2471     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2472       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2473   }
2474 
2475   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2476       BuiltinID == ARM::BI__builtin_arm_wsr64)
2477     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2478 
2479   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2480       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2481       BuiltinID == ARM::BI__builtin_arm_wsr ||
2482       BuiltinID == ARM::BI__builtin_arm_wsrp)
2483     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2484 
2485   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2486     return true;
2487   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2488     return true;
2489   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2490     return true;
2491 
2492   // For intrinsics which take an immediate value as part of the instruction,
2493   // range check them here.
2494   // FIXME: VFP Intrinsics should error if VFP not present.
2495   switch (BuiltinID) {
2496   default: return false;
2497   case ARM::BI__builtin_arm_ssat:
2498     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2499   case ARM::BI__builtin_arm_usat:
2500     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2501   case ARM::BI__builtin_arm_ssat16:
2502     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2503   case ARM::BI__builtin_arm_usat16:
2504     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2505   case ARM::BI__builtin_arm_vcvtr_f:
2506   case ARM::BI__builtin_arm_vcvtr_d:
2507     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2508   case ARM::BI__builtin_arm_dmb:
2509   case ARM::BI__builtin_arm_dsb:
2510   case ARM::BI__builtin_arm_isb:
2511   case ARM::BI__builtin_arm_dbg:
2512     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2513   case ARM::BI__builtin_arm_cdp:
2514   case ARM::BI__builtin_arm_cdp2:
2515   case ARM::BI__builtin_arm_mcr:
2516   case ARM::BI__builtin_arm_mcr2:
2517   case ARM::BI__builtin_arm_mrc:
2518   case ARM::BI__builtin_arm_mrc2:
2519   case ARM::BI__builtin_arm_mcrr:
2520   case ARM::BI__builtin_arm_mcrr2:
2521   case ARM::BI__builtin_arm_mrrc:
2522   case ARM::BI__builtin_arm_mrrc2:
2523   case ARM::BI__builtin_arm_ldc:
2524   case ARM::BI__builtin_arm_ldcl:
2525   case ARM::BI__builtin_arm_ldc2:
2526   case ARM::BI__builtin_arm_ldc2l:
2527   case ARM::BI__builtin_arm_stc:
2528   case ARM::BI__builtin_arm_stcl:
2529   case ARM::BI__builtin_arm_stc2:
2530   case ARM::BI__builtin_arm_stc2l:
2531     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2532            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2533                                         /*WantCDE*/ false);
2534   }
2535 }
2536 
2537 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2538                                            unsigned BuiltinID,
2539                                            CallExpr *TheCall) {
2540   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2541       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2542       BuiltinID == AArch64::BI__builtin_arm_strex ||
2543       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2544     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2545   }
2546 
2547   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2548     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2549       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2550       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2551       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2552   }
2553 
2554   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2555       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2556     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2557 
2558   // Memory Tagging Extensions (MTE) Intrinsics
2559   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2560       BuiltinID == AArch64::BI__builtin_arm_addg ||
2561       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2562       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2563       BuiltinID == AArch64::BI__builtin_arm_stg ||
2564       BuiltinID == AArch64::BI__builtin_arm_subp) {
2565     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2566   }
2567 
2568   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2569       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2570       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2571       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2572     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2573 
2574   // Only check the valid encoding range. Any constant in this range would be
2575   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2576   // an exception for incorrect registers. This matches MSVC behavior.
2577   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2578       BuiltinID == AArch64::BI_WriteStatusReg)
2579     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2580 
2581   if (BuiltinID == AArch64::BI__getReg)
2582     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2583 
2584   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2585     return true;
2586 
2587   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2588     return true;
2589 
2590   // For intrinsics which take an immediate value as part of the instruction,
2591   // range check them here.
2592   unsigned i = 0, l = 0, u = 0;
2593   switch (BuiltinID) {
2594   default: return false;
2595   case AArch64::BI__builtin_arm_dmb:
2596   case AArch64::BI__builtin_arm_dsb:
2597   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2598   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2599   }
2600 
2601   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2602 }
2603 
2604 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2605   if (Arg->getType()->getAsPlaceholderType())
2606     return false;
2607 
2608   // The first argument needs to be a record field access.
2609   // If it is an array element access, we delay decision
2610   // to BPF backend to check whether the access is a
2611   // field access or not.
2612   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2613           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2614           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2615 }
2616 
2617 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2618                             QualType VectorTy, QualType EltTy) {
2619   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2620   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2621     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2622         << Call->getSourceRange() << VectorEltTy << EltTy;
2623     return false;
2624   }
2625   return true;
2626 }
2627 
2628 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2629   QualType ArgType = Arg->getType();
2630   if (ArgType->getAsPlaceholderType())
2631     return false;
2632 
2633   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2634   // format:
2635   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2636   //   2. <type> var;
2637   //      __builtin_preserve_type_info(var, flag);
2638   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2639       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2640     return false;
2641 
2642   // Typedef type.
2643   if (ArgType->getAs<TypedefType>())
2644     return true;
2645 
2646   // Record type or Enum type.
2647   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2648   if (const auto *RT = Ty->getAs<RecordType>()) {
2649     if (!RT->getDecl()->getDeclName().isEmpty())
2650       return true;
2651   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2652     if (!ET->getDecl()->getDeclName().isEmpty())
2653       return true;
2654   }
2655 
2656   return false;
2657 }
2658 
2659 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2660   QualType ArgType = Arg->getType();
2661   if (ArgType->getAsPlaceholderType())
2662     return false;
2663 
2664   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2665   // format:
2666   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2667   //                                 flag);
2668   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2669   if (!UO)
2670     return false;
2671 
2672   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2673   if (!CE)
2674     return false;
2675   if (CE->getCastKind() != CK_IntegralToPointer &&
2676       CE->getCastKind() != CK_NullToPointer)
2677     return false;
2678 
2679   // The integer must be from an EnumConstantDecl.
2680   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2681   if (!DR)
2682     return false;
2683 
2684   const EnumConstantDecl *Enumerator =
2685       dyn_cast<EnumConstantDecl>(DR->getDecl());
2686   if (!Enumerator)
2687     return false;
2688 
2689   // The type must be EnumType.
2690   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2691   const auto *ET = Ty->getAs<EnumType>();
2692   if (!ET)
2693     return false;
2694 
2695   // The enum value must be supported.
2696   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2697 }
2698 
2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2700                                        CallExpr *TheCall) {
2701   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2702           BuiltinID == BPF::BI__builtin_btf_type_id ||
2703           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2704           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2705          "unexpected BPF builtin");
2706 
2707   if (checkArgCount(*this, TheCall, 2))
2708     return true;
2709 
2710   // The second argument needs to be a constant int
2711   Expr *Arg = TheCall->getArg(1);
2712   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2713   diag::kind kind;
2714   if (!Value) {
2715     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2716       kind = diag::err_preserve_field_info_not_const;
2717     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2718       kind = diag::err_btf_type_id_not_const;
2719     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2720       kind = diag::err_preserve_type_info_not_const;
2721     else
2722       kind = diag::err_preserve_enum_value_not_const;
2723     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2724     return true;
2725   }
2726 
2727   // The first argument
2728   Arg = TheCall->getArg(0);
2729   bool InvalidArg = false;
2730   bool ReturnUnsignedInt = true;
2731   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2732     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2733       InvalidArg = true;
2734       kind = diag::err_preserve_field_info_not_field;
2735     }
2736   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2737     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2738       InvalidArg = true;
2739       kind = diag::err_preserve_type_info_invalid;
2740     }
2741   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2742     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2743       InvalidArg = true;
2744       kind = diag::err_preserve_enum_value_invalid;
2745     }
2746     ReturnUnsignedInt = false;
2747   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2748     ReturnUnsignedInt = false;
2749   }
2750 
2751   if (InvalidArg) {
2752     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2753     return true;
2754   }
2755 
2756   if (ReturnUnsignedInt)
2757     TheCall->setType(Context.UnsignedIntTy);
2758   else
2759     TheCall->setType(Context.UnsignedLongTy);
2760   return false;
2761 }
2762 
2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2764   struct ArgInfo {
2765     uint8_t OpNum;
2766     bool IsSigned;
2767     uint8_t BitWidth;
2768     uint8_t Align;
2769   };
2770   struct BuiltinInfo {
2771     unsigned BuiltinID;
2772     ArgInfo Infos[2];
2773   };
2774 
2775   static BuiltinInfo Infos[] = {
2776     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2777     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2778     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2780     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2782     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2783     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2785     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2786     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2787 
2788     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2791     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2792     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2793     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2799 
2800     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2852                                                       {{ 1, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2860                                                       {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2867                                                        { 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2869                                                        { 2, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2871                                                        { 3, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2873                                                        { 3, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2890                                                       {{ 2, false, 4,  0 },
2891                                                        { 3, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2893                                                       {{ 2, false, 4,  0 },
2894                                                        { 3, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2896                                                       {{ 2, false, 4,  0 },
2897                                                        { 3, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2899                                                       {{ 2, false, 4,  0 },
2900                                                        { 3, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2912                                                        { 2, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2914                                                        { 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2924                                                       {{ 1, false, 4,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2927                                                       {{ 1, false, 4,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2948                                                       {{ 3, false, 1,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2953                                                       {{ 3, false, 1,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2958                                                       {{ 3, false, 1,  0 }} },
2959   };
2960 
2961   // Use a dynamically initialized static to sort the table exactly once on
2962   // first run.
2963   static const bool SortOnce =
2964       (llvm::sort(Infos,
2965                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2966                    return LHS.BuiltinID < RHS.BuiltinID;
2967                  }),
2968        true);
2969   (void)SortOnce;
2970 
2971   const BuiltinInfo *F = llvm::partition_point(
2972       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2973   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2974     return false;
2975 
2976   bool Error = false;
2977 
2978   for (const ArgInfo &A : F->Infos) {
2979     // Ignore empty ArgInfo elements.
2980     if (A.BitWidth == 0)
2981       continue;
2982 
2983     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2984     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2985     if (!A.Align) {
2986       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2987     } else {
2988       unsigned M = 1 << A.Align;
2989       Min *= M;
2990       Max *= M;
2991       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2992       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2993     }
2994   }
2995   return Error;
2996 }
2997 
2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2999                                            CallExpr *TheCall) {
3000   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3001 }
3002 
3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3004                                         unsigned BuiltinID, CallExpr *TheCall) {
3005   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3006          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3007 }
3008 
3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3010                                CallExpr *TheCall) {
3011 
3012   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3013       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3014     if (!TI.hasFeature("dsp"))
3015       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3016   }
3017 
3018   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3019       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3020     if (!TI.hasFeature("dspr2"))
3021       return Diag(TheCall->getBeginLoc(),
3022                   diag::err_mips_builtin_requires_dspr2);
3023   }
3024 
3025   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3026       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3027     if (!TI.hasFeature("msa"))
3028       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3029   }
3030 
3031   return false;
3032 }
3033 
3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3036 // ordering for DSP is unspecified. MSA is ordered by the data format used
3037 // by the underlying instruction i.e., df/m, df/n and then by size.
3038 //
3039 // FIXME: The size tests here should instead be tablegen'd along with the
3040 //        definitions from include/clang/Basic/BuiltinsMips.def.
3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3042 //        be too.
3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3044   unsigned i = 0, l = 0, u = 0, m = 0;
3045   switch (BuiltinID) {
3046   default: return false;
3047   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3048   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3049   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3050   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3051   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3052   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3053   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3054   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3055   // df/m field.
3056   // These intrinsics take an unsigned 3 bit immediate.
3057   case Mips::BI__builtin_msa_bclri_b:
3058   case Mips::BI__builtin_msa_bnegi_b:
3059   case Mips::BI__builtin_msa_bseti_b:
3060   case Mips::BI__builtin_msa_sat_s_b:
3061   case Mips::BI__builtin_msa_sat_u_b:
3062   case Mips::BI__builtin_msa_slli_b:
3063   case Mips::BI__builtin_msa_srai_b:
3064   case Mips::BI__builtin_msa_srari_b:
3065   case Mips::BI__builtin_msa_srli_b:
3066   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3067   case Mips::BI__builtin_msa_binsli_b:
3068   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3069   // These intrinsics take an unsigned 4 bit immediate.
3070   case Mips::BI__builtin_msa_bclri_h:
3071   case Mips::BI__builtin_msa_bnegi_h:
3072   case Mips::BI__builtin_msa_bseti_h:
3073   case Mips::BI__builtin_msa_sat_s_h:
3074   case Mips::BI__builtin_msa_sat_u_h:
3075   case Mips::BI__builtin_msa_slli_h:
3076   case Mips::BI__builtin_msa_srai_h:
3077   case Mips::BI__builtin_msa_srari_h:
3078   case Mips::BI__builtin_msa_srli_h:
3079   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3080   case Mips::BI__builtin_msa_binsli_h:
3081   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3082   // These intrinsics take an unsigned 5 bit immediate.
3083   // The first block of intrinsics actually have an unsigned 5 bit field,
3084   // not a df/n field.
3085   case Mips::BI__builtin_msa_cfcmsa:
3086   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3087   case Mips::BI__builtin_msa_clei_u_b:
3088   case Mips::BI__builtin_msa_clei_u_h:
3089   case Mips::BI__builtin_msa_clei_u_w:
3090   case Mips::BI__builtin_msa_clei_u_d:
3091   case Mips::BI__builtin_msa_clti_u_b:
3092   case Mips::BI__builtin_msa_clti_u_h:
3093   case Mips::BI__builtin_msa_clti_u_w:
3094   case Mips::BI__builtin_msa_clti_u_d:
3095   case Mips::BI__builtin_msa_maxi_u_b:
3096   case Mips::BI__builtin_msa_maxi_u_h:
3097   case Mips::BI__builtin_msa_maxi_u_w:
3098   case Mips::BI__builtin_msa_maxi_u_d:
3099   case Mips::BI__builtin_msa_mini_u_b:
3100   case Mips::BI__builtin_msa_mini_u_h:
3101   case Mips::BI__builtin_msa_mini_u_w:
3102   case Mips::BI__builtin_msa_mini_u_d:
3103   case Mips::BI__builtin_msa_addvi_b:
3104   case Mips::BI__builtin_msa_addvi_h:
3105   case Mips::BI__builtin_msa_addvi_w:
3106   case Mips::BI__builtin_msa_addvi_d:
3107   case Mips::BI__builtin_msa_bclri_w:
3108   case Mips::BI__builtin_msa_bnegi_w:
3109   case Mips::BI__builtin_msa_bseti_w:
3110   case Mips::BI__builtin_msa_sat_s_w:
3111   case Mips::BI__builtin_msa_sat_u_w:
3112   case Mips::BI__builtin_msa_slli_w:
3113   case Mips::BI__builtin_msa_srai_w:
3114   case Mips::BI__builtin_msa_srari_w:
3115   case Mips::BI__builtin_msa_srli_w:
3116   case Mips::BI__builtin_msa_srlri_w:
3117   case Mips::BI__builtin_msa_subvi_b:
3118   case Mips::BI__builtin_msa_subvi_h:
3119   case Mips::BI__builtin_msa_subvi_w:
3120   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3121   case Mips::BI__builtin_msa_binsli_w:
3122   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3123   // These intrinsics take an unsigned 6 bit immediate.
3124   case Mips::BI__builtin_msa_bclri_d:
3125   case Mips::BI__builtin_msa_bnegi_d:
3126   case Mips::BI__builtin_msa_bseti_d:
3127   case Mips::BI__builtin_msa_sat_s_d:
3128   case Mips::BI__builtin_msa_sat_u_d:
3129   case Mips::BI__builtin_msa_slli_d:
3130   case Mips::BI__builtin_msa_srai_d:
3131   case Mips::BI__builtin_msa_srari_d:
3132   case Mips::BI__builtin_msa_srli_d:
3133   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3134   case Mips::BI__builtin_msa_binsli_d:
3135   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3136   // These intrinsics take a signed 5 bit immediate.
3137   case Mips::BI__builtin_msa_ceqi_b:
3138   case Mips::BI__builtin_msa_ceqi_h:
3139   case Mips::BI__builtin_msa_ceqi_w:
3140   case Mips::BI__builtin_msa_ceqi_d:
3141   case Mips::BI__builtin_msa_clti_s_b:
3142   case Mips::BI__builtin_msa_clti_s_h:
3143   case Mips::BI__builtin_msa_clti_s_w:
3144   case Mips::BI__builtin_msa_clti_s_d:
3145   case Mips::BI__builtin_msa_clei_s_b:
3146   case Mips::BI__builtin_msa_clei_s_h:
3147   case Mips::BI__builtin_msa_clei_s_w:
3148   case Mips::BI__builtin_msa_clei_s_d:
3149   case Mips::BI__builtin_msa_maxi_s_b:
3150   case Mips::BI__builtin_msa_maxi_s_h:
3151   case Mips::BI__builtin_msa_maxi_s_w:
3152   case Mips::BI__builtin_msa_maxi_s_d:
3153   case Mips::BI__builtin_msa_mini_s_b:
3154   case Mips::BI__builtin_msa_mini_s_h:
3155   case Mips::BI__builtin_msa_mini_s_w:
3156   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3157   // These intrinsics take an unsigned 8 bit immediate.
3158   case Mips::BI__builtin_msa_andi_b:
3159   case Mips::BI__builtin_msa_nori_b:
3160   case Mips::BI__builtin_msa_ori_b:
3161   case Mips::BI__builtin_msa_shf_b:
3162   case Mips::BI__builtin_msa_shf_h:
3163   case Mips::BI__builtin_msa_shf_w:
3164   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3165   case Mips::BI__builtin_msa_bseli_b:
3166   case Mips::BI__builtin_msa_bmnzi_b:
3167   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3168   // df/n format
3169   // These intrinsics take an unsigned 4 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_b:
3171   case Mips::BI__builtin_msa_copy_u_b:
3172   case Mips::BI__builtin_msa_insve_b:
3173   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3174   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3175   // These intrinsics take an unsigned 3 bit immediate.
3176   case Mips::BI__builtin_msa_copy_s_h:
3177   case Mips::BI__builtin_msa_copy_u_h:
3178   case Mips::BI__builtin_msa_insve_h:
3179   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3180   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3181   // These intrinsics take an unsigned 2 bit immediate.
3182   case Mips::BI__builtin_msa_copy_s_w:
3183   case Mips::BI__builtin_msa_copy_u_w:
3184   case Mips::BI__builtin_msa_insve_w:
3185   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3186   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3187   // These intrinsics take an unsigned 1 bit immediate.
3188   case Mips::BI__builtin_msa_copy_s_d:
3189   case Mips::BI__builtin_msa_copy_u_d:
3190   case Mips::BI__builtin_msa_insve_d:
3191   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3192   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3193   // Memory offsets and immediate loads.
3194   // These intrinsics take a signed 10 bit immediate.
3195   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3196   case Mips::BI__builtin_msa_ldi_h:
3197   case Mips::BI__builtin_msa_ldi_w:
3198   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3199   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3200   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3201   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3202   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3203   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3204   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3205   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3206   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3207   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3208   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3209   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3210   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3211   }
3212 
3213   if (!m)
3214     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3215 
3216   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3217          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3218 }
3219 
3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3221 /// advancing the pointer over the consumed characters. The decoded type is
3222 /// returned. If the decoded type represents a constant integer with a
3223 /// constraint on its value then Mask is set to that value. The type descriptors
3224 /// used in Str are specific to PPC MMA builtins and are documented in the file
3225 /// defining the PPC builtins.
3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3227                                         unsigned &Mask) {
3228   bool RequireICE = false;
3229   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3230   switch (*Str++) {
3231   case 'V':
3232     return Context.getVectorType(Context.UnsignedCharTy, 16,
3233                                  VectorType::VectorKind::AltiVecVector);
3234   case 'i': {
3235     char *End;
3236     unsigned size = strtoul(Str, &End, 10);
3237     assert(End != Str && "Missing constant parameter constraint");
3238     Str = End;
3239     Mask = size;
3240     return Context.IntTy;
3241   }
3242   case 'W': {
3243     char *End;
3244     unsigned size = strtoul(Str, &End, 10);
3245     assert(End != Str && "Missing PowerPC MMA type size");
3246     Str = End;
3247     QualType Type;
3248     switch (size) {
3249   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3250     case size: Type = Context.Id##Ty; break;
3251   #include "clang/Basic/PPCTypes.def"
3252     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3253     }
3254     bool CheckVectorArgs = false;
3255     while (!CheckVectorArgs) {
3256       switch (*Str++) {
3257       case '*':
3258         Type = Context.getPointerType(Type);
3259         break;
3260       case 'C':
3261         Type = Type.withConst();
3262         break;
3263       default:
3264         CheckVectorArgs = true;
3265         --Str;
3266         break;
3267       }
3268     }
3269     return Type;
3270   }
3271   default:
3272     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3273   }
3274 }
3275 
3276 static bool isPPC_64Builtin(unsigned BuiltinID) {
3277   // These builtins only work on PPC 64bit targets.
3278   switch (BuiltinID) {
3279   case PPC::BI__builtin_divde:
3280   case PPC::BI__builtin_divdeu:
3281   case PPC::BI__builtin_bpermd:
3282   case PPC::BI__builtin_ppc_ldarx:
3283   case PPC::BI__builtin_ppc_stdcx:
3284   case PPC::BI__builtin_ppc_tdw:
3285   case PPC::BI__builtin_ppc_trapd:
3286   case PPC::BI__builtin_ppc_cmpeqb:
3287   case PPC::BI__builtin_ppc_setb:
3288   case PPC::BI__builtin_ppc_mulhd:
3289   case PPC::BI__builtin_ppc_mulhdu:
3290   case PPC::BI__builtin_ppc_maddhd:
3291   case PPC::BI__builtin_ppc_maddhdu:
3292   case PPC::BI__builtin_ppc_maddld:
3293   case PPC::BI__builtin_ppc_load8r:
3294   case PPC::BI__builtin_ppc_store8r:
3295   case PPC::BI__builtin_ppc_insert_exp:
3296   case PPC::BI__builtin_ppc_extract_sig:
3297   case PPC::BI__builtin_ppc_addex:
3298   case PPC::BI__builtin_darn:
3299   case PPC::BI__builtin_darn_raw:
3300   case PPC::BI__builtin_ppc_compare_and_swaplp:
3301   case PPC::BI__builtin_ppc_fetch_and_addlp:
3302   case PPC::BI__builtin_ppc_fetch_and_andlp:
3303   case PPC::BI__builtin_ppc_fetch_and_orlp:
3304   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3305     return true;
3306   }
3307   return false;
3308 }
3309 
3310 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3311                              StringRef FeatureToCheck, unsigned DiagID,
3312                              StringRef DiagArg = "") {
3313   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3314     return false;
3315 
3316   if (DiagArg.empty())
3317     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3318   else
3319     S.Diag(TheCall->getBeginLoc(), DiagID)
3320         << DiagArg << TheCall->getSourceRange();
3321 
3322   return true;
3323 }
3324 
3325 /// Returns true if the argument consists of one contiguous run of 1s with any
3326 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3327 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3328 /// since all 1s are not contiguous.
3329 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3330   llvm::APSInt Result;
3331   // We can't check the value of a dependent argument.
3332   Expr *Arg = TheCall->getArg(ArgNum);
3333   if (Arg->isTypeDependent() || Arg->isValueDependent())
3334     return false;
3335 
3336   // Check constant-ness first.
3337   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3338     return true;
3339 
3340   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3341   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3342     return false;
3343 
3344   return Diag(TheCall->getBeginLoc(),
3345               diag::err_argument_not_contiguous_bit_field)
3346          << ArgNum << Arg->getSourceRange();
3347 }
3348 
3349 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3350                                        CallExpr *TheCall) {
3351   unsigned i = 0, l = 0, u = 0;
3352   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3353   llvm::APSInt Result;
3354 
3355   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3356     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3357            << TheCall->getSourceRange();
3358 
3359   switch (BuiltinID) {
3360   default: return false;
3361   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3362   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3363     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3364            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3365   case PPC::BI__builtin_altivec_dss:
3366     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3367   case PPC::BI__builtin_tbegin:
3368   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3369   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3370   case PPC::BI__builtin_tabortwc:
3371   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3372   case PPC::BI__builtin_tabortwci:
3373   case PPC::BI__builtin_tabortdci:
3374     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3375            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3376   case PPC::BI__builtin_altivec_dst:
3377   case PPC::BI__builtin_altivec_dstt:
3378   case PPC::BI__builtin_altivec_dstst:
3379   case PPC::BI__builtin_altivec_dststt:
3380     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3381   case PPC::BI__builtin_vsx_xxpermdi:
3382   case PPC::BI__builtin_vsx_xxsldwi:
3383     return SemaBuiltinVSX(TheCall);
3384   case PPC::BI__builtin_divwe:
3385   case PPC::BI__builtin_divweu:
3386   case PPC::BI__builtin_divde:
3387   case PPC::BI__builtin_divdeu:
3388     return SemaFeatureCheck(*this, TheCall, "extdiv",
3389                             diag::err_ppc_builtin_only_on_arch, "7");
3390   case PPC::BI__builtin_bpermd:
3391     return SemaFeatureCheck(*this, TheCall, "bpermd",
3392                             diag::err_ppc_builtin_only_on_arch, "7");
3393   case PPC::BI__builtin_unpack_vector_int128:
3394     return SemaFeatureCheck(*this, TheCall, "vsx",
3395                             diag::err_ppc_builtin_only_on_arch, "7") ||
3396            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3397   case PPC::BI__builtin_pack_vector_int128:
3398     return SemaFeatureCheck(*this, TheCall, "vsx",
3399                             diag::err_ppc_builtin_only_on_arch, "7");
3400   case PPC::BI__builtin_altivec_vgnb:
3401      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3402   case PPC::BI__builtin_altivec_vec_replace_elt:
3403   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3404     QualType VecTy = TheCall->getArg(0)->getType();
3405     QualType EltTy = TheCall->getArg(1)->getType();
3406     unsigned Width = Context.getIntWidth(EltTy);
3407     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3408            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3409   }
3410   case PPC::BI__builtin_vsx_xxeval:
3411      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3412   case PPC::BI__builtin_altivec_vsldbi:
3413      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3414   case PPC::BI__builtin_altivec_vsrdbi:
3415      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3416   case PPC::BI__builtin_vsx_xxpermx:
3417      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3418   case PPC::BI__builtin_ppc_tw:
3419   case PPC::BI__builtin_ppc_tdw:
3420     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3421   case PPC::BI__builtin_ppc_cmpeqb:
3422   case PPC::BI__builtin_ppc_setb:
3423   case PPC::BI__builtin_ppc_maddhd:
3424   case PPC::BI__builtin_ppc_maddhdu:
3425   case PPC::BI__builtin_ppc_maddld:
3426     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3427                             diag::err_ppc_builtin_only_on_arch, "9");
3428   case PPC::BI__builtin_ppc_cmprb:
3429     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3430                             diag::err_ppc_builtin_only_on_arch, "9") ||
3431            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3432   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3433   // be a constant that represents a contiguous bit field.
3434   case PPC::BI__builtin_ppc_rlwnm:
3435     return SemaValueIsRunOfOnes(TheCall, 2);
3436   case PPC::BI__builtin_ppc_rlwimi:
3437   case PPC::BI__builtin_ppc_rldimi:
3438     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3439            SemaValueIsRunOfOnes(TheCall, 3);
3440   case PPC::BI__builtin_ppc_extract_exp:
3441   case PPC::BI__builtin_ppc_extract_sig:
3442   case PPC::BI__builtin_ppc_insert_exp:
3443     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3444                             diag::err_ppc_builtin_only_on_arch, "9");
3445   case PPC::BI__builtin_ppc_addex: {
3446     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3447                          diag::err_ppc_builtin_only_on_arch, "9") ||
3448         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3449       return true;
3450     // Output warning for reserved values 1 to 3.
3451     int ArgValue =
3452         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3453     if (ArgValue != 0)
3454       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3455           << ArgValue;
3456     return false;
3457   }
3458   case PPC::BI__builtin_ppc_mtfsb0:
3459   case PPC::BI__builtin_ppc_mtfsb1:
3460     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3461   case PPC::BI__builtin_ppc_mtfsf:
3462     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3463   case PPC::BI__builtin_ppc_mtfsfi:
3464     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3465            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3466   case PPC::BI__builtin_ppc_alignx:
3467     return SemaBuiltinConstantArgPower2(TheCall, 0);
3468   case PPC::BI__builtin_ppc_rdlam:
3469     return SemaValueIsRunOfOnes(TheCall, 2);
3470   case PPC::BI__builtin_ppc_icbt:
3471   case PPC::BI__builtin_ppc_sthcx:
3472   case PPC::BI__builtin_ppc_stbcx:
3473   case PPC::BI__builtin_ppc_lharx:
3474   case PPC::BI__builtin_ppc_lbarx:
3475     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3476                             diag::err_ppc_builtin_only_on_arch, "8");
3477   case PPC::BI__builtin_vsx_ldrmb:
3478   case PPC::BI__builtin_vsx_strmb:
3479     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3480                             diag::err_ppc_builtin_only_on_arch, "8") ||
3481            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3482   case PPC::BI__builtin_altivec_vcntmbb:
3483   case PPC::BI__builtin_altivec_vcntmbh:
3484   case PPC::BI__builtin_altivec_vcntmbw:
3485   case PPC::BI__builtin_altivec_vcntmbd:
3486     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3487   case PPC::BI__builtin_darn:
3488   case PPC::BI__builtin_darn_raw:
3489   case PPC::BI__builtin_darn_32:
3490     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3491                             diag::err_ppc_builtin_only_on_arch, "9");
3492   case PPC::BI__builtin_vsx_xxgenpcvbm:
3493   case PPC::BI__builtin_vsx_xxgenpcvhm:
3494   case PPC::BI__builtin_vsx_xxgenpcvwm:
3495   case PPC::BI__builtin_vsx_xxgenpcvdm:
3496     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3497   case PPC::BI__builtin_ppc_compare_exp_uo:
3498   case PPC::BI__builtin_ppc_compare_exp_lt:
3499   case PPC::BI__builtin_ppc_compare_exp_gt:
3500   case PPC::BI__builtin_ppc_compare_exp_eq:
3501     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3502                             diag::err_ppc_builtin_only_on_arch, "9") ||
3503            SemaFeatureCheck(*this, TheCall, "vsx",
3504                             diag::err_ppc_builtin_requires_vsx);
3505   case PPC::BI__builtin_ppc_test_data_class: {
3506     // Check if the first argument of the __builtin_ppc_test_data_class call is
3507     // valid. The argument must be either a 'float' or a 'double'.
3508     QualType ArgType = TheCall->getArg(0)->getType();
3509     if (ArgType != QualType(Context.FloatTy) &&
3510         ArgType != QualType(Context.DoubleTy))
3511       return Diag(TheCall->getBeginLoc(),
3512                   diag::err_ppc_invalid_test_data_class_type);
3513     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3514                             diag::err_ppc_builtin_only_on_arch, "9") ||
3515            SemaFeatureCheck(*this, TheCall, "vsx",
3516                             diag::err_ppc_builtin_requires_vsx) ||
3517            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3518   }
3519   case PPC::BI__builtin_ppc_load8r:
3520   case PPC::BI__builtin_ppc_store8r:
3521     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3522                             diag::err_ppc_builtin_only_on_arch, "7");
3523 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3524   case PPC::BI__builtin_##Name:                                                \
3525     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3526 #include "clang/Basic/BuiltinsPPC.def"
3527   }
3528   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3529 }
3530 
3531 // Check if the given type is a non-pointer PPC MMA type. This function is used
3532 // in Sema to prevent invalid uses of restricted PPC MMA types.
3533 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3534   if (Type->isPointerType() || Type->isArrayType())
3535     return false;
3536 
3537   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3538 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3539   if (false
3540 #include "clang/Basic/PPCTypes.def"
3541      ) {
3542     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3543     return true;
3544   }
3545   return false;
3546 }
3547 
3548 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3549                                           CallExpr *TheCall) {
3550   // position of memory order and scope arguments in the builtin
3551   unsigned OrderIndex, ScopeIndex;
3552   switch (BuiltinID) {
3553   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3554   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3555   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3556   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3557     OrderIndex = 2;
3558     ScopeIndex = 3;
3559     break;
3560   case AMDGPU::BI__builtin_amdgcn_fence:
3561     OrderIndex = 0;
3562     ScopeIndex = 1;
3563     break;
3564   default:
3565     return false;
3566   }
3567 
3568   ExprResult Arg = TheCall->getArg(OrderIndex);
3569   auto ArgExpr = Arg.get();
3570   Expr::EvalResult ArgResult;
3571 
3572   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3573     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3574            << ArgExpr->getType();
3575   auto Ord = ArgResult.Val.getInt().getZExtValue();
3576 
3577   // Check validity of memory ordering as per C11 / C++11's memody model.
3578   // Only fence needs check. Atomic dec/inc allow all memory orders.
3579   if (!llvm::isValidAtomicOrderingCABI(Ord))
3580     return Diag(ArgExpr->getBeginLoc(),
3581                 diag::warn_atomic_op_has_invalid_memory_order)
3582            << ArgExpr->getSourceRange();
3583   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3584   case llvm::AtomicOrderingCABI::relaxed:
3585   case llvm::AtomicOrderingCABI::consume:
3586     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3587       return Diag(ArgExpr->getBeginLoc(),
3588                   diag::warn_atomic_op_has_invalid_memory_order)
3589              << ArgExpr->getSourceRange();
3590     break;
3591   case llvm::AtomicOrderingCABI::acquire:
3592   case llvm::AtomicOrderingCABI::release:
3593   case llvm::AtomicOrderingCABI::acq_rel:
3594   case llvm::AtomicOrderingCABI::seq_cst:
3595     break;
3596   }
3597 
3598   Arg = TheCall->getArg(ScopeIndex);
3599   ArgExpr = Arg.get();
3600   Expr::EvalResult ArgResult1;
3601   // Check that sync scope is a constant literal
3602   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3603     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3604            << ArgExpr->getType();
3605 
3606   return false;
3607 }
3608 
3609 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3610   llvm::APSInt Result;
3611 
3612   // We can't check the value of a dependent argument.
3613   Expr *Arg = TheCall->getArg(ArgNum);
3614   if (Arg->isTypeDependent() || Arg->isValueDependent())
3615     return false;
3616 
3617   // Check constant-ness first.
3618   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3619     return true;
3620 
3621   int64_t Val = Result.getSExtValue();
3622   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3623     return false;
3624 
3625   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3626          << Arg->getSourceRange();
3627 }
3628 
3629 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3630                                          unsigned BuiltinID,
3631                                          CallExpr *TheCall) {
3632   // CodeGenFunction can also detect this, but this gives a better error
3633   // message.
3634   bool FeatureMissing = false;
3635   SmallVector<StringRef> ReqFeatures;
3636   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3637   Features.split(ReqFeatures, ',');
3638 
3639   // Check if each required feature is included
3640   for (StringRef F : ReqFeatures) {
3641     if (TI.hasFeature(F))
3642       continue;
3643 
3644     // If the feature is 64bit, alter the string so it will print better in
3645     // the diagnostic.
3646     if (F == "64bit")
3647       F = "RV64";
3648 
3649     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3650     F.consume_front("experimental-");
3651     std::string FeatureStr = F.str();
3652     FeatureStr[0] = std::toupper(FeatureStr[0]);
3653 
3654     // Error message
3655     FeatureMissing = true;
3656     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3657         << TheCall->getSourceRange() << StringRef(FeatureStr);
3658   }
3659 
3660   if (FeatureMissing)
3661     return true;
3662 
3663   switch (BuiltinID) {
3664   case RISCVVector::BI__builtin_rvv_vsetvli:
3665     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3666            CheckRISCVLMUL(TheCall, 2);
3667   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3668     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3669            CheckRISCVLMUL(TheCall, 1);
3670   }
3671 
3672   return false;
3673 }
3674 
3675 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3676                                            CallExpr *TheCall) {
3677   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3678     Expr *Arg = TheCall->getArg(0);
3679     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3680       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3681         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3682                << Arg->getSourceRange();
3683   }
3684 
3685   // For intrinsics which take an immediate value as part of the instruction,
3686   // range check them here.
3687   unsigned i = 0, l = 0, u = 0;
3688   switch (BuiltinID) {
3689   default: return false;
3690   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3691   case SystemZ::BI__builtin_s390_verimb:
3692   case SystemZ::BI__builtin_s390_verimh:
3693   case SystemZ::BI__builtin_s390_verimf:
3694   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3695   case SystemZ::BI__builtin_s390_vfaeb:
3696   case SystemZ::BI__builtin_s390_vfaeh:
3697   case SystemZ::BI__builtin_s390_vfaef:
3698   case SystemZ::BI__builtin_s390_vfaebs:
3699   case SystemZ::BI__builtin_s390_vfaehs:
3700   case SystemZ::BI__builtin_s390_vfaefs:
3701   case SystemZ::BI__builtin_s390_vfaezb:
3702   case SystemZ::BI__builtin_s390_vfaezh:
3703   case SystemZ::BI__builtin_s390_vfaezf:
3704   case SystemZ::BI__builtin_s390_vfaezbs:
3705   case SystemZ::BI__builtin_s390_vfaezhs:
3706   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3707   case SystemZ::BI__builtin_s390_vfisb:
3708   case SystemZ::BI__builtin_s390_vfidb:
3709     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3710            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3711   case SystemZ::BI__builtin_s390_vftcisb:
3712   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3713   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3714   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3715   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3716   case SystemZ::BI__builtin_s390_vstrcb:
3717   case SystemZ::BI__builtin_s390_vstrch:
3718   case SystemZ::BI__builtin_s390_vstrcf:
3719   case SystemZ::BI__builtin_s390_vstrczb:
3720   case SystemZ::BI__builtin_s390_vstrczh:
3721   case SystemZ::BI__builtin_s390_vstrczf:
3722   case SystemZ::BI__builtin_s390_vstrcbs:
3723   case SystemZ::BI__builtin_s390_vstrchs:
3724   case SystemZ::BI__builtin_s390_vstrcfs:
3725   case SystemZ::BI__builtin_s390_vstrczbs:
3726   case SystemZ::BI__builtin_s390_vstrczhs:
3727   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3728   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3729   case SystemZ::BI__builtin_s390_vfminsb:
3730   case SystemZ::BI__builtin_s390_vfmaxsb:
3731   case SystemZ::BI__builtin_s390_vfmindb:
3732   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3733   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3734   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3735   case SystemZ::BI__builtin_s390_vclfnhs:
3736   case SystemZ::BI__builtin_s390_vclfnls:
3737   case SystemZ::BI__builtin_s390_vcfn:
3738   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3739   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3740   }
3741   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3742 }
3743 
3744 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3745 /// This checks that the target supports __builtin_cpu_supports and
3746 /// that the string argument is constant and valid.
3747 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3748                                    CallExpr *TheCall) {
3749   Expr *Arg = TheCall->getArg(0);
3750 
3751   // Check if the argument is a string literal.
3752   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3753     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3754            << Arg->getSourceRange();
3755 
3756   // Check the contents of the string.
3757   StringRef Feature =
3758       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3759   if (!TI.validateCpuSupports(Feature))
3760     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3761            << Arg->getSourceRange();
3762   return false;
3763 }
3764 
3765 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3766 /// This checks that the target supports __builtin_cpu_is and
3767 /// that the string argument is constant and valid.
3768 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3769   Expr *Arg = TheCall->getArg(0);
3770 
3771   // Check if the argument is a string literal.
3772   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3773     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3774            << Arg->getSourceRange();
3775 
3776   // Check the contents of the string.
3777   StringRef Feature =
3778       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3779   if (!TI.validateCpuIs(Feature))
3780     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3781            << Arg->getSourceRange();
3782   return false;
3783 }
3784 
3785 // Check if the rounding mode is legal.
3786 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3787   // Indicates if this instruction has rounding control or just SAE.
3788   bool HasRC = false;
3789 
3790   unsigned ArgNum = 0;
3791   switch (BuiltinID) {
3792   default:
3793     return false;
3794   case X86::BI__builtin_ia32_vcvttsd2si32:
3795   case X86::BI__builtin_ia32_vcvttsd2si64:
3796   case X86::BI__builtin_ia32_vcvttsd2usi32:
3797   case X86::BI__builtin_ia32_vcvttsd2usi64:
3798   case X86::BI__builtin_ia32_vcvttss2si32:
3799   case X86::BI__builtin_ia32_vcvttss2si64:
3800   case X86::BI__builtin_ia32_vcvttss2usi32:
3801   case X86::BI__builtin_ia32_vcvttss2usi64:
3802   case X86::BI__builtin_ia32_vcvttsh2si32:
3803   case X86::BI__builtin_ia32_vcvttsh2si64:
3804   case X86::BI__builtin_ia32_vcvttsh2usi32:
3805   case X86::BI__builtin_ia32_vcvttsh2usi64:
3806     ArgNum = 1;
3807     break;
3808   case X86::BI__builtin_ia32_maxpd512:
3809   case X86::BI__builtin_ia32_maxps512:
3810   case X86::BI__builtin_ia32_minpd512:
3811   case X86::BI__builtin_ia32_minps512:
3812   case X86::BI__builtin_ia32_maxph512:
3813   case X86::BI__builtin_ia32_minph512:
3814     ArgNum = 2;
3815     break;
3816   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3817   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3818   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3819   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3820   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3821   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3822   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3823   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3824   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3825   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3826   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3827   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3828   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3829   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3830   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3831   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3832   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3833   case X86::BI__builtin_ia32_exp2pd_mask:
3834   case X86::BI__builtin_ia32_exp2ps_mask:
3835   case X86::BI__builtin_ia32_getexppd512_mask:
3836   case X86::BI__builtin_ia32_getexpps512_mask:
3837   case X86::BI__builtin_ia32_getexpph512_mask:
3838   case X86::BI__builtin_ia32_rcp28pd_mask:
3839   case X86::BI__builtin_ia32_rcp28ps_mask:
3840   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3841   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3842   case X86::BI__builtin_ia32_vcomisd:
3843   case X86::BI__builtin_ia32_vcomiss:
3844   case X86::BI__builtin_ia32_vcomish:
3845   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3846     ArgNum = 3;
3847     break;
3848   case X86::BI__builtin_ia32_cmppd512_mask:
3849   case X86::BI__builtin_ia32_cmpps512_mask:
3850   case X86::BI__builtin_ia32_cmpsd_mask:
3851   case X86::BI__builtin_ia32_cmpss_mask:
3852   case X86::BI__builtin_ia32_cmpsh_mask:
3853   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3854   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3855   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3856   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3857   case X86::BI__builtin_ia32_getexpss128_round_mask:
3858   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3859   case X86::BI__builtin_ia32_getmantpd512_mask:
3860   case X86::BI__builtin_ia32_getmantps512_mask:
3861   case X86::BI__builtin_ia32_getmantph512_mask:
3862   case X86::BI__builtin_ia32_maxsd_round_mask:
3863   case X86::BI__builtin_ia32_maxss_round_mask:
3864   case X86::BI__builtin_ia32_maxsh_round_mask:
3865   case X86::BI__builtin_ia32_minsd_round_mask:
3866   case X86::BI__builtin_ia32_minss_round_mask:
3867   case X86::BI__builtin_ia32_minsh_round_mask:
3868   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3869   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3870   case X86::BI__builtin_ia32_reducepd512_mask:
3871   case X86::BI__builtin_ia32_reduceps512_mask:
3872   case X86::BI__builtin_ia32_reduceph512_mask:
3873   case X86::BI__builtin_ia32_rndscalepd_mask:
3874   case X86::BI__builtin_ia32_rndscaleps_mask:
3875   case X86::BI__builtin_ia32_rndscaleph_mask:
3876   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3877   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3878     ArgNum = 4;
3879     break;
3880   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3881   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3882   case X86::BI__builtin_ia32_fixupimmps512_mask:
3883   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3884   case X86::BI__builtin_ia32_fixupimmsd_mask:
3885   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3886   case X86::BI__builtin_ia32_fixupimmss_mask:
3887   case X86::BI__builtin_ia32_fixupimmss_maskz:
3888   case X86::BI__builtin_ia32_getmantsd_round_mask:
3889   case X86::BI__builtin_ia32_getmantss_round_mask:
3890   case X86::BI__builtin_ia32_getmantsh_round_mask:
3891   case X86::BI__builtin_ia32_rangepd512_mask:
3892   case X86::BI__builtin_ia32_rangeps512_mask:
3893   case X86::BI__builtin_ia32_rangesd128_round_mask:
3894   case X86::BI__builtin_ia32_rangess128_round_mask:
3895   case X86::BI__builtin_ia32_reducesd_mask:
3896   case X86::BI__builtin_ia32_reducess_mask:
3897   case X86::BI__builtin_ia32_reducesh_mask:
3898   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3899   case X86::BI__builtin_ia32_rndscaless_round_mask:
3900   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3901     ArgNum = 5;
3902     break;
3903   case X86::BI__builtin_ia32_vcvtsd2si64:
3904   case X86::BI__builtin_ia32_vcvtsd2si32:
3905   case X86::BI__builtin_ia32_vcvtsd2usi32:
3906   case X86::BI__builtin_ia32_vcvtsd2usi64:
3907   case X86::BI__builtin_ia32_vcvtss2si32:
3908   case X86::BI__builtin_ia32_vcvtss2si64:
3909   case X86::BI__builtin_ia32_vcvtss2usi32:
3910   case X86::BI__builtin_ia32_vcvtss2usi64:
3911   case X86::BI__builtin_ia32_vcvtsh2si32:
3912   case X86::BI__builtin_ia32_vcvtsh2si64:
3913   case X86::BI__builtin_ia32_vcvtsh2usi32:
3914   case X86::BI__builtin_ia32_vcvtsh2usi64:
3915   case X86::BI__builtin_ia32_sqrtpd512:
3916   case X86::BI__builtin_ia32_sqrtps512:
3917   case X86::BI__builtin_ia32_sqrtph512:
3918     ArgNum = 1;
3919     HasRC = true;
3920     break;
3921   case X86::BI__builtin_ia32_addph512:
3922   case X86::BI__builtin_ia32_divph512:
3923   case X86::BI__builtin_ia32_mulph512:
3924   case X86::BI__builtin_ia32_subph512:
3925   case X86::BI__builtin_ia32_addpd512:
3926   case X86::BI__builtin_ia32_addps512:
3927   case X86::BI__builtin_ia32_divpd512:
3928   case X86::BI__builtin_ia32_divps512:
3929   case X86::BI__builtin_ia32_mulpd512:
3930   case X86::BI__builtin_ia32_mulps512:
3931   case X86::BI__builtin_ia32_subpd512:
3932   case X86::BI__builtin_ia32_subps512:
3933   case X86::BI__builtin_ia32_cvtsi2sd64:
3934   case X86::BI__builtin_ia32_cvtsi2ss32:
3935   case X86::BI__builtin_ia32_cvtsi2ss64:
3936   case X86::BI__builtin_ia32_cvtusi2sd64:
3937   case X86::BI__builtin_ia32_cvtusi2ss32:
3938   case X86::BI__builtin_ia32_cvtusi2ss64:
3939   case X86::BI__builtin_ia32_vcvtusi2sh:
3940   case X86::BI__builtin_ia32_vcvtusi642sh:
3941   case X86::BI__builtin_ia32_vcvtsi2sh:
3942   case X86::BI__builtin_ia32_vcvtsi642sh:
3943     ArgNum = 2;
3944     HasRC = true;
3945     break;
3946   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3947   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3948   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
3949   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
3950   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3951   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3952   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3953   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3954   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3955   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3956   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3957   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3958   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3959   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3960   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3961   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3962   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3963   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
3964   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
3965   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
3966   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
3967   case X86::BI__builtin_ia32_vcvtph2w512_mask:
3968   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
3969   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
3970   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
3971   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
3972   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
3973   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
3974   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
3975     ArgNum = 3;
3976     HasRC = true;
3977     break;
3978   case X86::BI__builtin_ia32_addsh_round_mask:
3979   case X86::BI__builtin_ia32_addss_round_mask:
3980   case X86::BI__builtin_ia32_addsd_round_mask:
3981   case X86::BI__builtin_ia32_divsh_round_mask:
3982   case X86::BI__builtin_ia32_divss_round_mask:
3983   case X86::BI__builtin_ia32_divsd_round_mask:
3984   case X86::BI__builtin_ia32_mulsh_round_mask:
3985   case X86::BI__builtin_ia32_mulss_round_mask:
3986   case X86::BI__builtin_ia32_mulsd_round_mask:
3987   case X86::BI__builtin_ia32_subsh_round_mask:
3988   case X86::BI__builtin_ia32_subss_round_mask:
3989   case X86::BI__builtin_ia32_subsd_round_mask:
3990   case X86::BI__builtin_ia32_scalefph512_mask:
3991   case X86::BI__builtin_ia32_scalefpd512_mask:
3992   case X86::BI__builtin_ia32_scalefps512_mask:
3993   case X86::BI__builtin_ia32_scalefsd_round_mask:
3994   case X86::BI__builtin_ia32_scalefss_round_mask:
3995   case X86::BI__builtin_ia32_scalefsh_round_mask:
3996   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3997   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
3998   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
3999   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4000   case X86::BI__builtin_ia32_sqrtss_round_mask:
4001   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4002   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4003   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4004   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4005   case X86::BI__builtin_ia32_vfmaddss3_mask:
4006   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4007   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4008   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4009   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4010   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4011   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4012   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4013   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4014   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4015   case X86::BI__builtin_ia32_vfmaddps512_mask:
4016   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4017   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4018   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4019   case X86::BI__builtin_ia32_vfmaddph512_mask:
4020   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4021   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4022   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4023   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4024   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4025   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4026   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4027   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4028   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4029   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4030   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4031   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4032   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4033   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4034   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4035   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4036   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4037   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4038   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4039   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4040   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4041   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4042   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4043   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4044   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4045   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4046   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4047   case X86::BI__builtin_ia32_vfmulcsh_mask:
4048   case X86::BI__builtin_ia32_vfmulcph512_mask:
4049   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4050   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4051     ArgNum = 4;
4052     HasRC = true;
4053     break;
4054   }
4055 
4056   llvm::APSInt Result;
4057 
4058   // We can't check the value of a dependent argument.
4059   Expr *Arg = TheCall->getArg(ArgNum);
4060   if (Arg->isTypeDependent() || Arg->isValueDependent())
4061     return false;
4062 
4063   // Check constant-ness first.
4064   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4065     return true;
4066 
4067   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4068   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4069   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4070   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4071   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4072       Result == 8/*ROUND_NO_EXC*/ ||
4073       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4074       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4075     return false;
4076 
4077   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4078          << Arg->getSourceRange();
4079 }
4080 
4081 // Check if the gather/scatter scale is legal.
4082 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4083                                              CallExpr *TheCall) {
4084   unsigned ArgNum = 0;
4085   switch (BuiltinID) {
4086   default:
4087     return false;
4088   case X86::BI__builtin_ia32_gatherpfdpd:
4089   case X86::BI__builtin_ia32_gatherpfdps:
4090   case X86::BI__builtin_ia32_gatherpfqpd:
4091   case X86::BI__builtin_ia32_gatherpfqps:
4092   case X86::BI__builtin_ia32_scatterpfdpd:
4093   case X86::BI__builtin_ia32_scatterpfdps:
4094   case X86::BI__builtin_ia32_scatterpfqpd:
4095   case X86::BI__builtin_ia32_scatterpfqps:
4096     ArgNum = 3;
4097     break;
4098   case X86::BI__builtin_ia32_gatherd_pd:
4099   case X86::BI__builtin_ia32_gatherd_pd256:
4100   case X86::BI__builtin_ia32_gatherq_pd:
4101   case X86::BI__builtin_ia32_gatherq_pd256:
4102   case X86::BI__builtin_ia32_gatherd_ps:
4103   case X86::BI__builtin_ia32_gatherd_ps256:
4104   case X86::BI__builtin_ia32_gatherq_ps:
4105   case X86::BI__builtin_ia32_gatherq_ps256:
4106   case X86::BI__builtin_ia32_gatherd_q:
4107   case X86::BI__builtin_ia32_gatherd_q256:
4108   case X86::BI__builtin_ia32_gatherq_q:
4109   case X86::BI__builtin_ia32_gatherq_q256:
4110   case X86::BI__builtin_ia32_gatherd_d:
4111   case X86::BI__builtin_ia32_gatherd_d256:
4112   case X86::BI__builtin_ia32_gatherq_d:
4113   case X86::BI__builtin_ia32_gatherq_d256:
4114   case X86::BI__builtin_ia32_gather3div2df:
4115   case X86::BI__builtin_ia32_gather3div2di:
4116   case X86::BI__builtin_ia32_gather3div4df:
4117   case X86::BI__builtin_ia32_gather3div4di:
4118   case X86::BI__builtin_ia32_gather3div4sf:
4119   case X86::BI__builtin_ia32_gather3div4si:
4120   case X86::BI__builtin_ia32_gather3div8sf:
4121   case X86::BI__builtin_ia32_gather3div8si:
4122   case X86::BI__builtin_ia32_gather3siv2df:
4123   case X86::BI__builtin_ia32_gather3siv2di:
4124   case X86::BI__builtin_ia32_gather3siv4df:
4125   case X86::BI__builtin_ia32_gather3siv4di:
4126   case X86::BI__builtin_ia32_gather3siv4sf:
4127   case X86::BI__builtin_ia32_gather3siv4si:
4128   case X86::BI__builtin_ia32_gather3siv8sf:
4129   case X86::BI__builtin_ia32_gather3siv8si:
4130   case X86::BI__builtin_ia32_gathersiv8df:
4131   case X86::BI__builtin_ia32_gathersiv16sf:
4132   case X86::BI__builtin_ia32_gatherdiv8df:
4133   case X86::BI__builtin_ia32_gatherdiv16sf:
4134   case X86::BI__builtin_ia32_gathersiv8di:
4135   case X86::BI__builtin_ia32_gathersiv16si:
4136   case X86::BI__builtin_ia32_gatherdiv8di:
4137   case X86::BI__builtin_ia32_gatherdiv16si:
4138   case X86::BI__builtin_ia32_scatterdiv2df:
4139   case X86::BI__builtin_ia32_scatterdiv2di:
4140   case X86::BI__builtin_ia32_scatterdiv4df:
4141   case X86::BI__builtin_ia32_scatterdiv4di:
4142   case X86::BI__builtin_ia32_scatterdiv4sf:
4143   case X86::BI__builtin_ia32_scatterdiv4si:
4144   case X86::BI__builtin_ia32_scatterdiv8sf:
4145   case X86::BI__builtin_ia32_scatterdiv8si:
4146   case X86::BI__builtin_ia32_scattersiv2df:
4147   case X86::BI__builtin_ia32_scattersiv2di:
4148   case X86::BI__builtin_ia32_scattersiv4df:
4149   case X86::BI__builtin_ia32_scattersiv4di:
4150   case X86::BI__builtin_ia32_scattersiv4sf:
4151   case X86::BI__builtin_ia32_scattersiv4si:
4152   case X86::BI__builtin_ia32_scattersiv8sf:
4153   case X86::BI__builtin_ia32_scattersiv8si:
4154   case X86::BI__builtin_ia32_scattersiv8df:
4155   case X86::BI__builtin_ia32_scattersiv16sf:
4156   case X86::BI__builtin_ia32_scatterdiv8df:
4157   case X86::BI__builtin_ia32_scatterdiv16sf:
4158   case X86::BI__builtin_ia32_scattersiv8di:
4159   case X86::BI__builtin_ia32_scattersiv16si:
4160   case X86::BI__builtin_ia32_scatterdiv8di:
4161   case X86::BI__builtin_ia32_scatterdiv16si:
4162     ArgNum = 4;
4163     break;
4164   }
4165 
4166   llvm::APSInt Result;
4167 
4168   // We can't check the value of a dependent argument.
4169   Expr *Arg = TheCall->getArg(ArgNum);
4170   if (Arg->isTypeDependent() || Arg->isValueDependent())
4171     return false;
4172 
4173   // Check constant-ness first.
4174   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4175     return true;
4176 
4177   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4178     return false;
4179 
4180   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4181          << Arg->getSourceRange();
4182 }
4183 
4184 enum { TileRegLow = 0, TileRegHigh = 7 };
4185 
4186 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4187                                              ArrayRef<int> ArgNums) {
4188   for (int ArgNum : ArgNums) {
4189     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4190       return true;
4191   }
4192   return false;
4193 }
4194 
4195 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4196                                         ArrayRef<int> ArgNums) {
4197   // Because the max number of tile register is TileRegHigh + 1, so here we use
4198   // each bit to represent the usage of them in bitset.
4199   std::bitset<TileRegHigh + 1> ArgValues;
4200   for (int ArgNum : ArgNums) {
4201     Expr *Arg = TheCall->getArg(ArgNum);
4202     if (Arg->isTypeDependent() || Arg->isValueDependent())
4203       continue;
4204 
4205     llvm::APSInt Result;
4206     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4207       return true;
4208     int ArgExtValue = Result.getExtValue();
4209     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4210            "Incorrect tile register num.");
4211     if (ArgValues.test(ArgExtValue))
4212       return Diag(TheCall->getBeginLoc(),
4213                   diag::err_x86_builtin_tile_arg_duplicate)
4214              << TheCall->getArg(ArgNum)->getSourceRange();
4215     ArgValues.set(ArgExtValue);
4216   }
4217   return false;
4218 }
4219 
4220 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4221                                                 ArrayRef<int> ArgNums) {
4222   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4223          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4224 }
4225 
4226 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4227   switch (BuiltinID) {
4228   default:
4229     return false;
4230   case X86::BI__builtin_ia32_tileloadd64:
4231   case X86::BI__builtin_ia32_tileloaddt164:
4232   case X86::BI__builtin_ia32_tilestored64:
4233   case X86::BI__builtin_ia32_tilezero:
4234     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4235   case X86::BI__builtin_ia32_tdpbssd:
4236   case X86::BI__builtin_ia32_tdpbsud:
4237   case X86::BI__builtin_ia32_tdpbusd:
4238   case X86::BI__builtin_ia32_tdpbuud:
4239   case X86::BI__builtin_ia32_tdpbf16ps:
4240     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4241   }
4242 }
4243 static bool isX86_32Builtin(unsigned BuiltinID) {
4244   // These builtins only work on x86-32 targets.
4245   switch (BuiltinID) {
4246   case X86::BI__builtin_ia32_readeflags_u32:
4247   case X86::BI__builtin_ia32_writeeflags_u32:
4248     return true;
4249   }
4250 
4251   return false;
4252 }
4253 
4254 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4255                                        CallExpr *TheCall) {
4256   if (BuiltinID == X86::BI__builtin_cpu_supports)
4257     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4258 
4259   if (BuiltinID == X86::BI__builtin_cpu_is)
4260     return SemaBuiltinCpuIs(*this, TI, TheCall);
4261 
4262   // Check for 32-bit only builtins on a 64-bit target.
4263   const llvm::Triple &TT = TI.getTriple();
4264   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4265     return Diag(TheCall->getCallee()->getBeginLoc(),
4266                 diag::err_32_bit_builtin_64_bit_tgt);
4267 
4268   // If the intrinsic has rounding or SAE make sure its valid.
4269   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4270     return true;
4271 
4272   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4273   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4274     return true;
4275 
4276   // If the intrinsic has a tile arguments, make sure they are valid.
4277   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4278     return true;
4279 
4280   // For intrinsics which take an immediate value as part of the instruction,
4281   // range check them here.
4282   int i = 0, l = 0, u = 0;
4283   switch (BuiltinID) {
4284   default:
4285     return false;
4286   case X86::BI__builtin_ia32_vec_ext_v2si:
4287   case X86::BI__builtin_ia32_vec_ext_v2di:
4288   case X86::BI__builtin_ia32_vextractf128_pd256:
4289   case X86::BI__builtin_ia32_vextractf128_ps256:
4290   case X86::BI__builtin_ia32_vextractf128_si256:
4291   case X86::BI__builtin_ia32_extract128i256:
4292   case X86::BI__builtin_ia32_extractf64x4_mask:
4293   case X86::BI__builtin_ia32_extracti64x4_mask:
4294   case X86::BI__builtin_ia32_extractf32x8_mask:
4295   case X86::BI__builtin_ia32_extracti32x8_mask:
4296   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4297   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4298   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4299   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4300     i = 1; l = 0; u = 1;
4301     break;
4302   case X86::BI__builtin_ia32_vec_set_v2di:
4303   case X86::BI__builtin_ia32_vinsertf128_pd256:
4304   case X86::BI__builtin_ia32_vinsertf128_ps256:
4305   case X86::BI__builtin_ia32_vinsertf128_si256:
4306   case X86::BI__builtin_ia32_insert128i256:
4307   case X86::BI__builtin_ia32_insertf32x8:
4308   case X86::BI__builtin_ia32_inserti32x8:
4309   case X86::BI__builtin_ia32_insertf64x4:
4310   case X86::BI__builtin_ia32_inserti64x4:
4311   case X86::BI__builtin_ia32_insertf64x2_256:
4312   case X86::BI__builtin_ia32_inserti64x2_256:
4313   case X86::BI__builtin_ia32_insertf32x4_256:
4314   case X86::BI__builtin_ia32_inserti32x4_256:
4315     i = 2; l = 0; u = 1;
4316     break;
4317   case X86::BI__builtin_ia32_vpermilpd:
4318   case X86::BI__builtin_ia32_vec_ext_v4hi:
4319   case X86::BI__builtin_ia32_vec_ext_v4si:
4320   case X86::BI__builtin_ia32_vec_ext_v4sf:
4321   case X86::BI__builtin_ia32_vec_ext_v4di:
4322   case X86::BI__builtin_ia32_extractf32x4_mask:
4323   case X86::BI__builtin_ia32_extracti32x4_mask:
4324   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4325   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4326     i = 1; l = 0; u = 3;
4327     break;
4328   case X86::BI_mm_prefetch:
4329   case X86::BI__builtin_ia32_vec_ext_v8hi:
4330   case X86::BI__builtin_ia32_vec_ext_v8si:
4331     i = 1; l = 0; u = 7;
4332     break;
4333   case X86::BI__builtin_ia32_sha1rnds4:
4334   case X86::BI__builtin_ia32_blendpd:
4335   case X86::BI__builtin_ia32_shufpd:
4336   case X86::BI__builtin_ia32_vec_set_v4hi:
4337   case X86::BI__builtin_ia32_vec_set_v4si:
4338   case X86::BI__builtin_ia32_vec_set_v4di:
4339   case X86::BI__builtin_ia32_shuf_f32x4_256:
4340   case X86::BI__builtin_ia32_shuf_f64x2_256:
4341   case X86::BI__builtin_ia32_shuf_i32x4_256:
4342   case X86::BI__builtin_ia32_shuf_i64x2_256:
4343   case X86::BI__builtin_ia32_insertf64x2_512:
4344   case X86::BI__builtin_ia32_inserti64x2_512:
4345   case X86::BI__builtin_ia32_insertf32x4:
4346   case X86::BI__builtin_ia32_inserti32x4:
4347     i = 2; l = 0; u = 3;
4348     break;
4349   case X86::BI__builtin_ia32_vpermil2pd:
4350   case X86::BI__builtin_ia32_vpermil2pd256:
4351   case X86::BI__builtin_ia32_vpermil2ps:
4352   case X86::BI__builtin_ia32_vpermil2ps256:
4353     i = 3; l = 0; u = 3;
4354     break;
4355   case X86::BI__builtin_ia32_cmpb128_mask:
4356   case X86::BI__builtin_ia32_cmpw128_mask:
4357   case X86::BI__builtin_ia32_cmpd128_mask:
4358   case X86::BI__builtin_ia32_cmpq128_mask:
4359   case X86::BI__builtin_ia32_cmpb256_mask:
4360   case X86::BI__builtin_ia32_cmpw256_mask:
4361   case X86::BI__builtin_ia32_cmpd256_mask:
4362   case X86::BI__builtin_ia32_cmpq256_mask:
4363   case X86::BI__builtin_ia32_cmpb512_mask:
4364   case X86::BI__builtin_ia32_cmpw512_mask:
4365   case X86::BI__builtin_ia32_cmpd512_mask:
4366   case X86::BI__builtin_ia32_cmpq512_mask:
4367   case X86::BI__builtin_ia32_ucmpb128_mask:
4368   case X86::BI__builtin_ia32_ucmpw128_mask:
4369   case X86::BI__builtin_ia32_ucmpd128_mask:
4370   case X86::BI__builtin_ia32_ucmpq128_mask:
4371   case X86::BI__builtin_ia32_ucmpb256_mask:
4372   case X86::BI__builtin_ia32_ucmpw256_mask:
4373   case X86::BI__builtin_ia32_ucmpd256_mask:
4374   case X86::BI__builtin_ia32_ucmpq256_mask:
4375   case X86::BI__builtin_ia32_ucmpb512_mask:
4376   case X86::BI__builtin_ia32_ucmpw512_mask:
4377   case X86::BI__builtin_ia32_ucmpd512_mask:
4378   case X86::BI__builtin_ia32_ucmpq512_mask:
4379   case X86::BI__builtin_ia32_vpcomub:
4380   case X86::BI__builtin_ia32_vpcomuw:
4381   case X86::BI__builtin_ia32_vpcomud:
4382   case X86::BI__builtin_ia32_vpcomuq:
4383   case X86::BI__builtin_ia32_vpcomb:
4384   case X86::BI__builtin_ia32_vpcomw:
4385   case X86::BI__builtin_ia32_vpcomd:
4386   case X86::BI__builtin_ia32_vpcomq:
4387   case X86::BI__builtin_ia32_vec_set_v8hi:
4388   case X86::BI__builtin_ia32_vec_set_v8si:
4389     i = 2; l = 0; u = 7;
4390     break;
4391   case X86::BI__builtin_ia32_vpermilpd256:
4392   case X86::BI__builtin_ia32_roundps:
4393   case X86::BI__builtin_ia32_roundpd:
4394   case X86::BI__builtin_ia32_roundps256:
4395   case X86::BI__builtin_ia32_roundpd256:
4396   case X86::BI__builtin_ia32_getmantpd128_mask:
4397   case X86::BI__builtin_ia32_getmantpd256_mask:
4398   case X86::BI__builtin_ia32_getmantps128_mask:
4399   case X86::BI__builtin_ia32_getmantps256_mask:
4400   case X86::BI__builtin_ia32_getmantpd512_mask:
4401   case X86::BI__builtin_ia32_getmantps512_mask:
4402   case X86::BI__builtin_ia32_getmantph128_mask:
4403   case X86::BI__builtin_ia32_getmantph256_mask:
4404   case X86::BI__builtin_ia32_getmantph512_mask:
4405   case X86::BI__builtin_ia32_vec_ext_v16qi:
4406   case X86::BI__builtin_ia32_vec_ext_v16hi:
4407     i = 1; l = 0; u = 15;
4408     break;
4409   case X86::BI__builtin_ia32_pblendd128:
4410   case X86::BI__builtin_ia32_blendps:
4411   case X86::BI__builtin_ia32_blendpd256:
4412   case X86::BI__builtin_ia32_shufpd256:
4413   case X86::BI__builtin_ia32_roundss:
4414   case X86::BI__builtin_ia32_roundsd:
4415   case X86::BI__builtin_ia32_rangepd128_mask:
4416   case X86::BI__builtin_ia32_rangepd256_mask:
4417   case X86::BI__builtin_ia32_rangepd512_mask:
4418   case X86::BI__builtin_ia32_rangeps128_mask:
4419   case X86::BI__builtin_ia32_rangeps256_mask:
4420   case X86::BI__builtin_ia32_rangeps512_mask:
4421   case X86::BI__builtin_ia32_getmantsd_round_mask:
4422   case X86::BI__builtin_ia32_getmantss_round_mask:
4423   case X86::BI__builtin_ia32_getmantsh_round_mask:
4424   case X86::BI__builtin_ia32_vec_set_v16qi:
4425   case X86::BI__builtin_ia32_vec_set_v16hi:
4426     i = 2; l = 0; u = 15;
4427     break;
4428   case X86::BI__builtin_ia32_vec_ext_v32qi:
4429     i = 1; l = 0; u = 31;
4430     break;
4431   case X86::BI__builtin_ia32_cmpps:
4432   case X86::BI__builtin_ia32_cmpss:
4433   case X86::BI__builtin_ia32_cmppd:
4434   case X86::BI__builtin_ia32_cmpsd:
4435   case X86::BI__builtin_ia32_cmpps256:
4436   case X86::BI__builtin_ia32_cmppd256:
4437   case X86::BI__builtin_ia32_cmpps128_mask:
4438   case X86::BI__builtin_ia32_cmppd128_mask:
4439   case X86::BI__builtin_ia32_cmpps256_mask:
4440   case X86::BI__builtin_ia32_cmppd256_mask:
4441   case X86::BI__builtin_ia32_cmpps512_mask:
4442   case X86::BI__builtin_ia32_cmppd512_mask:
4443   case X86::BI__builtin_ia32_cmpsd_mask:
4444   case X86::BI__builtin_ia32_cmpss_mask:
4445   case X86::BI__builtin_ia32_vec_set_v32qi:
4446     i = 2; l = 0; u = 31;
4447     break;
4448   case X86::BI__builtin_ia32_permdf256:
4449   case X86::BI__builtin_ia32_permdi256:
4450   case X86::BI__builtin_ia32_permdf512:
4451   case X86::BI__builtin_ia32_permdi512:
4452   case X86::BI__builtin_ia32_vpermilps:
4453   case X86::BI__builtin_ia32_vpermilps256:
4454   case X86::BI__builtin_ia32_vpermilpd512:
4455   case X86::BI__builtin_ia32_vpermilps512:
4456   case X86::BI__builtin_ia32_pshufd:
4457   case X86::BI__builtin_ia32_pshufd256:
4458   case X86::BI__builtin_ia32_pshufd512:
4459   case X86::BI__builtin_ia32_pshufhw:
4460   case X86::BI__builtin_ia32_pshufhw256:
4461   case X86::BI__builtin_ia32_pshufhw512:
4462   case X86::BI__builtin_ia32_pshuflw:
4463   case X86::BI__builtin_ia32_pshuflw256:
4464   case X86::BI__builtin_ia32_pshuflw512:
4465   case X86::BI__builtin_ia32_vcvtps2ph:
4466   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4467   case X86::BI__builtin_ia32_vcvtps2ph256:
4468   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4469   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4470   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4471   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4472   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4473   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4474   case X86::BI__builtin_ia32_rndscaleps_mask:
4475   case X86::BI__builtin_ia32_rndscalepd_mask:
4476   case X86::BI__builtin_ia32_rndscaleph_mask:
4477   case X86::BI__builtin_ia32_reducepd128_mask:
4478   case X86::BI__builtin_ia32_reducepd256_mask:
4479   case X86::BI__builtin_ia32_reducepd512_mask:
4480   case X86::BI__builtin_ia32_reduceps128_mask:
4481   case X86::BI__builtin_ia32_reduceps256_mask:
4482   case X86::BI__builtin_ia32_reduceps512_mask:
4483   case X86::BI__builtin_ia32_reduceph128_mask:
4484   case X86::BI__builtin_ia32_reduceph256_mask:
4485   case X86::BI__builtin_ia32_reduceph512_mask:
4486   case X86::BI__builtin_ia32_prold512:
4487   case X86::BI__builtin_ia32_prolq512:
4488   case X86::BI__builtin_ia32_prold128:
4489   case X86::BI__builtin_ia32_prold256:
4490   case X86::BI__builtin_ia32_prolq128:
4491   case X86::BI__builtin_ia32_prolq256:
4492   case X86::BI__builtin_ia32_prord512:
4493   case X86::BI__builtin_ia32_prorq512:
4494   case X86::BI__builtin_ia32_prord128:
4495   case X86::BI__builtin_ia32_prord256:
4496   case X86::BI__builtin_ia32_prorq128:
4497   case X86::BI__builtin_ia32_prorq256:
4498   case X86::BI__builtin_ia32_fpclasspd128_mask:
4499   case X86::BI__builtin_ia32_fpclasspd256_mask:
4500   case X86::BI__builtin_ia32_fpclassps128_mask:
4501   case X86::BI__builtin_ia32_fpclassps256_mask:
4502   case X86::BI__builtin_ia32_fpclassps512_mask:
4503   case X86::BI__builtin_ia32_fpclasspd512_mask:
4504   case X86::BI__builtin_ia32_fpclassph128_mask:
4505   case X86::BI__builtin_ia32_fpclassph256_mask:
4506   case X86::BI__builtin_ia32_fpclassph512_mask:
4507   case X86::BI__builtin_ia32_fpclasssd_mask:
4508   case X86::BI__builtin_ia32_fpclassss_mask:
4509   case X86::BI__builtin_ia32_fpclasssh_mask:
4510   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4511   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4512   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4513   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4514   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4515   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4516   case X86::BI__builtin_ia32_kshiftliqi:
4517   case X86::BI__builtin_ia32_kshiftlihi:
4518   case X86::BI__builtin_ia32_kshiftlisi:
4519   case X86::BI__builtin_ia32_kshiftlidi:
4520   case X86::BI__builtin_ia32_kshiftriqi:
4521   case X86::BI__builtin_ia32_kshiftrihi:
4522   case X86::BI__builtin_ia32_kshiftrisi:
4523   case X86::BI__builtin_ia32_kshiftridi:
4524     i = 1; l = 0; u = 255;
4525     break;
4526   case X86::BI__builtin_ia32_vperm2f128_pd256:
4527   case X86::BI__builtin_ia32_vperm2f128_ps256:
4528   case X86::BI__builtin_ia32_vperm2f128_si256:
4529   case X86::BI__builtin_ia32_permti256:
4530   case X86::BI__builtin_ia32_pblendw128:
4531   case X86::BI__builtin_ia32_pblendw256:
4532   case X86::BI__builtin_ia32_blendps256:
4533   case X86::BI__builtin_ia32_pblendd256:
4534   case X86::BI__builtin_ia32_palignr128:
4535   case X86::BI__builtin_ia32_palignr256:
4536   case X86::BI__builtin_ia32_palignr512:
4537   case X86::BI__builtin_ia32_alignq512:
4538   case X86::BI__builtin_ia32_alignd512:
4539   case X86::BI__builtin_ia32_alignd128:
4540   case X86::BI__builtin_ia32_alignd256:
4541   case X86::BI__builtin_ia32_alignq128:
4542   case X86::BI__builtin_ia32_alignq256:
4543   case X86::BI__builtin_ia32_vcomisd:
4544   case X86::BI__builtin_ia32_vcomiss:
4545   case X86::BI__builtin_ia32_shuf_f32x4:
4546   case X86::BI__builtin_ia32_shuf_f64x2:
4547   case X86::BI__builtin_ia32_shuf_i32x4:
4548   case X86::BI__builtin_ia32_shuf_i64x2:
4549   case X86::BI__builtin_ia32_shufpd512:
4550   case X86::BI__builtin_ia32_shufps:
4551   case X86::BI__builtin_ia32_shufps256:
4552   case X86::BI__builtin_ia32_shufps512:
4553   case X86::BI__builtin_ia32_dbpsadbw128:
4554   case X86::BI__builtin_ia32_dbpsadbw256:
4555   case X86::BI__builtin_ia32_dbpsadbw512:
4556   case X86::BI__builtin_ia32_vpshldd128:
4557   case X86::BI__builtin_ia32_vpshldd256:
4558   case X86::BI__builtin_ia32_vpshldd512:
4559   case X86::BI__builtin_ia32_vpshldq128:
4560   case X86::BI__builtin_ia32_vpshldq256:
4561   case X86::BI__builtin_ia32_vpshldq512:
4562   case X86::BI__builtin_ia32_vpshldw128:
4563   case X86::BI__builtin_ia32_vpshldw256:
4564   case X86::BI__builtin_ia32_vpshldw512:
4565   case X86::BI__builtin_ia32_vpshrdd128:
4566   case X86::BI__builtin_ia32_vpshrdd256:
4567   case X86::BI__builtin_ia32_vpshrdd512:
4568   case X86::BI__builtin_ia32_vpshrdq128:
4569   case X86::BI__builtin_ia32_vpshrdq256:
4570   case X86::BI__builtin_ia32_vpshrdq512:
4571   case X86::BI__builtin_ia32_vpshrdw128:
4572   case X86::BI__builtin_ia32_vpshrdw256:
4573   case X86::BI__builtin_ia32_vpshrdw512:
4574     i = 2; l = 0; u = 255;
4575     break;
4576   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4577   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4578   case X86::BI__builtin_ia32_fixupimmps512_mask:
4579   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4580   case X86::BI__builtin_ia32_fixupimmsd_mask:
4581   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4582   case X86::BI__builtin_ia32_fixupimmss_mask:
4583   case X86::BI__builtin_ia32_fixupimmss_maskz:
4584   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4585   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4586   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4587   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4588   case X86::BI__builtin_ia32_fixupimmps128_mask:
4589   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4590   case X86::BI__builtin_ia32_fixupimmps256_mask:
4591   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4592   case X86::BI__builtin_ia32_pternlogd512_mask:
4593   case X86::BI__builtin_ia32_pternlogd512_maskz:
4594   case X86::BI__builtin_ia32_pternlogq512_mask:
4595   case X86::BI__builtin_ia32_pternlogq512_maskz:
4596   case X86::BI__builtin_ia32_pternlogd128_mask:
4597   case X86::BI__builtin_ia32_pternlogd128_maskz:
4598   case X86::BI__builtin_ia32_pternlogd256_mask:
4599   case X86::BI__builtin_ia32_pternlogd256_maskz:
4600   case X86::BI__builtin_ia32_pternlogq128_mask:
4601   case X86::BI__builtin_ia32_pternlogq128_maskz:
4602   case X86::BI__builtin_ia32_pternlogq256_mask:
4603   case X86::BI__builtin_ia32_pternlogq256_maskz:
4604     i = 3; l = 0; u = 255;
4605     break;
4606   case X86::BI__builtin_ia32_gatherpfdpd:
4607   case X86::BI__builtin_ia32_gatherpfdps:
4608   case X86::BI__builtin_ia32_gatherpfqpd:
4609   case X86::BI__builtin_ia32_gatherpfqps:
4610   case X86::BI__builtin_ia32_scatterpfdpd:
4611   case X86::BI__builtin_ia32_scatterpfdps:
4612   case X86::BI__builtin_ia32_scatterpfqpd:
4613   case X86::BI__builtin_ia32_scatterpfqps:
4614     i = 4; l = 2; u = 3;
4615     break;
4616   case X86::BI__builtin_ia32_reducesd_mask:
4617   case X86::BI__builtin_ia32_reducess_mask:
4618   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4619   case X86::BI__builtin_ia32_rndscaless_round_mask:
4620   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4621   case X86::BI__builtin_ia32_reducesh_mask:
4622     i = 4; l = 0; u = 255;
4623     break;
4624   }
4625 
4626   // Note that we don't force a hard error on the range check here, allowing
4627   // template-generated or macro-generated dead code to potentially have out-of-
4628   // range values. These need to code generate, but don't need to necessarily
4629   // make any sense. We use a warning that defaults to an error.
4630   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4631 }
4632 
4633 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4634 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4635 /// Returns true when the format fits the function and the FormatStringInfo has
4636 /// been populated.
4637 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4638                                FormatStringInfo *FSI) {
4639   FSI->HasVAListArg = Format->getFirstArg() == 0;
4640   FSI->FormatIdx = Format->getFormatIdx() - 1;
4641   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4642 
4643   // The way the format attribute works in GCC, the implicit this argument
4644   // of member functions is counted. However, it doesn't appear in our own
4645   // lists, so decrement format_idx in that case.
4646   if (IsCXXMember) {
4647     if(FSI->FormatIdx == 0)
4648       return false;
4649     --FSI->FormatIdx;
4650     if (FSI->FirstDataArg != 0)
4651       --FSI->FirstDataArg;
4652   }
4653   return true;
4654 }
4655 
4656 /// Checks if a the given expression evaluates to null.
4657 ///
4658 /// Returns true if the value evaluates to null.
4659 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4660   // If the expression has non-null type, it doesn't evaluate to null.
4661   if (auto nullability
4662         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4663     if (*nullability == NullabilityKind::NonNull)
4664       return false;
4665   }
4666 
4667   // As a special case, transparent unions initialized with zero are
4668   // considered null for the purposes of the nonnull attribute.
4669   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4670     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4671       if (const CompoundLiteralExpr *CLE =
4672           dyn_cast<CompoundLiteralExpr>(Expr))
4673         if (const InitListExpr *ILE =
4674             dyn_cast<InitListExpr>(CLE->getInitializer()))
4675           Expr = ILE->getInit(0);
4676   }
4677 
4678   bool Result;
4679   return (!Expr->isValueDependent() &&
4680           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4681           !Result);
4682 }
4683 
4684 static void CheckNonNullArgument(Sema &S,
4685                                  const Expr *ArgExpr,
4686                                  SourceLocation CallSiteLoc) {
4687   if (CheckNonNullExpr(S, ArgExpr))
4688     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4689                           S.PDiag(diag::warn_null_arg)
4690                               << ArgExpr->getSourceRange());
4691 }
4692 
4693 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4694   FormatStringInfo FSI;
4695   if ((GetFormatStringType(Format) == FST_NSString) &&
4696       getFormatStringInfo(Format, false, &FSI)) {
4697     Idx = FSI.FormatIdx;
4698     return true;
4699   }
4700   return false;
4701 }
4702 
4703 /// Diagnose use of %s directive in an NSString which is being passed
4704 /// as formatting string to formatting method.
4705 static void
4706 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4707                                         const NamedDecl *FDecl,
4708                                         Expr **Args,
4709                                         unsigned NumArgs) {
4710   unsigned Idx = 0;
4711   bool Format = false;
4712   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4713   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4714     Idx = 2;
4715     Format = true;
4716   }
4717   else
4718     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4719       if (S.GetFormatNSStringIdx(I, Idx)) {
4720         Format = true;
4721         break;
4722       }
4723     }
4724   if (!Format || NumArgs <= Idx)
4725     return;
4726   const Expr *FormatExpr = Args[Idx];
4727   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4728     FormatExpr = CSCE->getSubExpr();
4729   const StringLiteral *FormatString;
4730   if (const ObjCStringLiteral *OSL =
4731       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4732     FormatString = OSL->getString();
4733   else
4734     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4735   if (!FormatString)
4736     return;
4737   if (S.FormatStringHasSArg(FormatString)) {
4738     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4739       << "%s" << 1 << 1;
4740     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4741       << FDecl->getDeclName();
4742   }
4743 }
4744 
4745 /// Determine whether the given type has a non-null nullability annotation.
4746 static bool isNonNullType(ASTContext &ctx, QualType type) {
4747   if (auto nullability = type->getNullability(ctx))
4748     return *nullability == NullabilityKind::NonNull;
4749 
4750   return false;
4751 }
4752 
4753 static void CheckNonNullArguments(Sema &S,
4754                                   const NamedDecl *FDecl,
4755                                   const FunctionProtoType *Proto,
4756                                   ArrayRef<const Expr *> Args,
4757                                   SourceLocation CallSiteLoc) {
4758   assert((FDecl || Proto) && "Need a function declaration or prototype");
4759 
4760   // Already checked by by constant evaluator.
4761   if (S.isConstantEvaluated())
4762     return;
4763   // Check the attributes attached to the method/function itself.
4764   llvm::SmallBitVector NonNullArgs;
4765   if (FDecl) {
4766     // Handle the nonnull attribute on the function/method declaration itself.
4767     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4768       if (!NonNull->args_size()) {
4769         // Easy case: all pointer arguments are nonnull.
4770         for (const auto *Arg : Args)
4771           if (S.isValidPointerAttrType(Arg->getType()))
4772             CheckNonNullArgument(S, Arg, CallSiteLoc);
4773         return;
4774       }
4775 
4776       for (const ParamIdx &Idx : NonNull->args()) {
4777         unsigned IdxAST = Idx.getASTIndex();
4778         if (IdxAST >= Args.size())
4779           continue;
4780         if (NonNullArgs.empty())
4781           NonNullArgs.resize(Args.size());
4782         NonNullArgs.set(IdxAST);
4783       }
4784     }
4785   }
4786 
4787   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4788     // Handle the nonnull attribute on the parameters of the
4789     // function/method.
4790     ArrayRef<ParmVarDecl*> parms;
4791     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4792       parms = FD->parameters();
4793     else
4794       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4795 
4796     unsigned ParamIndex = 0;
4797     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4798          I != E; ++I, ++ParamIndex) {
4799       const ParmVarDecl *PVD = *I;
4800       if (PVD->hasAttr<NonNullAttr>() ||
4801           isNonNullType(S.Context, PVD->getType())) {
4802         if (NonNullArgs.empty())
4803           NonNullArgs.resize(Args.size());
4804 
4805         NonNullArgs.set(ParamIndex);
4806       }
4807     }
4808   } else {
4809     // If we have a non-function, non-method declaration but no
4810     // function prototype, try to dig out the function prototype.
4811     if (!Proto) {
4812       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4813         QualType type = VD->getType().getNonReferenceType();
4814         if (auto pointerType = type->getAs<PointerType>())
4815           type = pointerType->getPointeeType();
4816         else if (auto blockType = type->getAs<BlockPointerType>())
4817           type = blockType->getPointeeType();
4818         // FIXME: data member pointers?
4819 
4820         // Dig out the function prototype, if there is one.
4821         Proto = type->getAs<FunctionProtoType>();
4822       }
4823     }
4824 
4825     // Fill in non-null argument information from the nullability
4826     // information on the parameter types (if we have them).
4827     if (Proto) {
4828       unsigned Index = 0;
4829       for (auto paramType : Proto->getParamTypes()) {
4830         if (isNonNullType(S.Context, paramType)) {
4831           if (NonNullArgs.empty())
4832             NonNullArgs.resize(Args.size());
4833 
4834           NonNullArgs.set(Index);
4835         }
4836 
4837         ++Index;
4838       }
4839     }
4840   }
4841 
4842   // Check for non-null arguments.
4843   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4844        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4845     if (NonNullArgs[ArgIndex])
4846       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4847   }
4848 }
4849 
4850 /// Warn if a pointer or reference argument passed to a function points to an
4851 /// object that is less aligned than the parameter. This can happen when
4852 /// creating a typedef with a lower alignment than the original type and then
4853 /// calling functions defined in terms of the original type.
4854 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4855                              StringRef ParamName, QualType ArgTy,
4856                              QualType ParamTy) {
4857 
4858   // If a function accepts a pointer or reference type
4859   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4860     return;
4861 
4862   // If the parameter is a pointer type, get the pointee type for the
4863   // argument too. If the parameter is a reference type, don't try to get
4864   // the pointee type for the argument.
4865   if (ParamTy->isPointerType())
4866     ArgTy = ArgTy->getPointeeType();
4867 
4868   // Remove reference or pointer
4869   ParamTy = ParamTy->getPointeeType();
4870 
4871   // Find expected alignment, and the actual alignment of the passed object.
4872   // getTypeAlignInChars requires complete types
4873   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4874       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4875       ArgTy->isUndeducedType())
4876     return;
4877 
4878   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4879   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4880 
4881   // If the argument is less aligned than the parameter, there is a
4882   // potential alignment issue.
4883   if (ArgAlign < ParamAlign)
4884     Diag(Loc, diag::warn_param_mismatched_alignment)
4885         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4886         << ParamName << FDecl;
4887 }
4888 
4889 /// Handles the checks for format strings, non-POD arguments to vararg
4890 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4891 /// attributes.
4892 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4893                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4894                      bool IsMemberFunction, SourceLocation Loc,
4895                      SourceRange Range, VariadicCallType CallType) {
4896   // FIXME: We should check as much as we can in the template definition.
4897   if (CurContext->isDependentContext())
4898     return;
4899 
4900   // Printf and scanf checking.
4901   llvm::SmallBitVector CheckedVarArgs;
4902   if (FDecl) {
4903     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4904       // Only create vector if there are format attributes.
4905       CheckedVarArgs.resize(Args.size());
4906 
4907       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4908                            CheckedVarArgs);
4909     }
4910   }
4911 
4912   // Refuse POD arguments that weren't caught by the format string
4913   // checks above.
4914   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4915   if (CallType != VariadicDoesNotApply &&
4916       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4917     unsigned NumParams = Proto ? Proto->getNumParams()
4918                        : FDecl && isa<FunctionDecl>(FDecl)
4919                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4920                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4921                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4922                        : 0;
4923 
4924     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4925       // Args[ArgIdx] can be null in malformed code.
4926       if (const Expr *Arg = Args[ArgIdx]) {
4927         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4928           checkVariadicArgument(Arg, CallType);
4929       }
4930     }
4931   }
4932 
4933   if (FDecl || Proto) {
4934     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4935 
4936     // Type safety checking.
4937     if (FDecl) {
4938       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4939         CheckArgumentWithTypeTag(I, Args, Loc);
4940     }
4941   }
4942 
4943   // Check that passed arguments match the alignment of original arguments.
4944   // Try to get the missing prototype from the declaration.
4945   if (!Proto && FDecl) {
4946     const auto *FT = FDecl->getFunctionType();
4947     if (isa_and_nonnull<FunctionProtoType>(FT))
4948       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4949   }
4950   if (Proto) {
4951     // For variadic functions, we may have more args than parameters.
4952     // For some K&R functions, we may have less args than parameters.
4953     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4954     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4955       // Args[ArgIdx] can be null in malformed code.
4956       if (const Expr *Arg = Args[ArgIdx]) {
4957         if (Arg->containsErrors())
4958           continue;
4959 
4960         QualType ParamTy = Proto->getParamType(ArgIdx);
4961         QualType ArgTy = Arg->getType();
4962         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4963                           ArgTy, ParamTy);
4964       }
4965     }
4966   }
4967 
4968   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4969     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4970     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4971     if (!Arg->isValueDependent()) {
4972       Expr::EvalResult Align;
4973       if (Arg->EvaluateAsInt(Align, Context)) {
4974         const llvm::APSInt &I = Align.Val.getInt();
4975         if (!I.isPowerOf2())
4976           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4977               << Arg->getSourceRange();
4978 
4979         if (I > Sema::MaximumAlignment)
4980           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4981               << Arg->getSourceRange() << Sema::MaximumAlignment;
4982       }
4983     }
4984   }
4985 
4986   if (FD)
4987     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4988 }
4989 
4990 /// CheckConstructorCall - Check a constructor call for correctness and safety
4991 /// properties not enforced by the C type system.
4992 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4993                                 ArrayRef<const Expr *> Args,
4994                                 const FunctionProtoType *Proto,
4995                                 SourceLocation Loc) {
4996   VariadicCallType CallType =
4997       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4998 
4999   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5000   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5001                     Context.getPointerType(Ctor->getThisObjectType()));
5002 
5003   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5004             Loc, SourceRange(), CallType);
5005 }
5006 
5007 /// CheckFunctionCall - Check a direct function call for various correctness
5008 /// and safety properties not strictly enforced by the C type system.
5009 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5010                              const FunctionProtoType *Proto) {
5011   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5012                               isa<CXXMethodDecl>(FDecl);
5013   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5014                           IsMemberOperatorCall;
5015   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5016                                                   TheCall->getCallee());
5017   Expr** Args = TheCall->getArgs();
5018   unsigned NumArgs = TheCall->getNumArgs();
5019 
5020   Expr *ImplicitThis = nullptr;
5021   if (IsMemberOperatorCall) {
5022     // If this is a call to a member operator, hide the first argument
5023     // from checkCall.
5024     // FIXME: Our choice of AST representation here is less than ideal.
5025     ImplicitThis = Args[0];
5026     ++Args;
5027     --NumArgs;
5028   } else if (IsMemberFunction)
5029     ImplicitThis =
5030         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5031 
5032   if (ImplicitThis) {
5033     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5034     // used.
5035     QualType ThisType = ImplicitThis->getType();
5036     if (!ThisType->isPointerType()) {
5037       assert(!ThisType->isReferenceType());
5038       ThisType = Context.getPointerType(ThisType);
5039     }
5040 
5041     QualType ThisTypeFromDecl =
5042         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5043 
5044     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5045                       ThisTypeFromDecl);
5046   }
5047 
5048   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5049             IsMemberFunction, TheCall->getRParenLoc(),
5050             TheCall->getCallee()->getSourceRange(), CallType);
5051 
5052   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5053   // None of the checks below are needed for functions that don't have
5054   // simple names (e.g., C++ conversion functions).
5055   if (!FnInfo)
5056     return false;
5057 
5058   CheckTCBEnforcement(TheCall, FDecl);
5059 
5060   CheckAbsoluteValueFunction(TheCall, FDecl);
5061   CheckMaxUnsignedZero(TheCall, FDecl);
5062 
5063   if (getLangOpts().ObjC)
5064     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5065 
5066   unsigned CMId = FDecl->getMemoryFunctionKind();
5067 
5068   // Handle memory setting and copying functions.
5069   switch (CMId) {
5070   case 0:
5071     return false;
5072   case Builtin::BIstrlcpy: // fallthrough
5073   case Builtin::BIstrlcat:
5074     CheckStrlcpycatArguments(TheCall, FnInfo);
5075     break;
5076   case Builtin::BIstrncat:
5077     CheckStrncatArguments(TheCall, FnInfo);
5078     break;
5079   case Builtin::BIfree:
5080     CheckFreeArguments(TheCall);
5081     break;
5082   default:
5083     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5084   }
5085 
5086   return false;
5087 }
5088 
5089 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5090                                ArrayRef<const Expr *> Args) {
5091   VariadicCallType CallType =
5092       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5093 
5094   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5095             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5096             CallType);
5097 
5098   return false;
5099 }
5100 
5101 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5102                             const FunctionProtoType *Proto) {
5103   QualType Ty;
5104   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5105     Ty = V->getType().getNonReferenceType();
5106   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5107     Ty = F->getType().getNonReferenceType();
5108   else
5109     return false;
5110 
5111   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5112       !Ty->isFunctionProtoType())
5113     return false;
5114 
5115   VariadicCallType CallType;
5116   if (!Proto || !Proto->isVariadic()) {
5117     CallType = VariadicDoesNotApply;
5118   } else if (Ty->isBlockPointerType()) {
5119     CallType = VariadicBlock;
5120   } else { // Ty->isFunctionPointerType()
5121     CallType = VariadicFunction;
5122   }
5123 
5124   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5125             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5126             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5127             TheCall->getCallee()->getSourceRange(), CallType);
5128 
5129   return false;
5130 }
5131 
5132 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5133 /// such as function pointers returned from functions.
5134 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5135   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5136                                                   TheCall->getCallee());
5137   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5138             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5139             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5140             TheCall->getCallee()->getSourceRange(), CallType);
5141 
5142   return false;
5143 }
5144 
5145 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5146   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5147     return false;
5148 
5149   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5150   switch (Op) {
5151   case AtomicExpr::AO__c11_atomic_init:
5152   case AtomicExpr::AO__opencl_atomic_init:
5153     llvm_unreachable("There is no ordering argument for an init");
5154 
5155   case AtomicExpr::AO__c11_atomic_load:
5156   case AtomicExpr::AO__opencl_atomic_load:
5157   case AtomicExpr::AO__atomic_load_n:
5158   case AtomicExpr::AO__atomic_load:
5159     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5160            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5161 
5162   case AtomicExpr::AO__c11_atomic_store:
5163   case AtomicExpr::AO__opencl_atomic_store:
5164   case AtomicExpr::AO__atomic_store:
5165   case AtomicExpr::AO__atomic_store_n:
5166     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5167            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5168            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5169 
5170   default:
5171     return true;
5172   }
5173 }
5174 
5175 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5176                                          AtomicExpr::AtomicOp Op) {
5177   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5178   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5179   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5180   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5181                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5182                          Op);
5183 }
5184 
5185 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5186                                  SourceLocation RParenLoc, MultiExprArg Args,
5187                                  AtomicExpr::AtomicOp Op,
5188                                  AtomicArgumentOrder ArgOrder) {
5189   // All the non-OpenCL operations take one of the following forms.
5190   // The OpenCL operations take the __c11 forms with one extra argument for
5191   // synchronization scope.
5192   enum {
5193     // C    __c11_atomic_init(A *, C)
5194     Init,
5195 
5196     // C    __c11_atomic_load(A *, int)
5197     Load,
5198 
5199     // void __atomic_load(A *, CP, int)
5200     LoadCopy,
5201 
5202     // void __atomic_store(A *, CP, int)
5203     Copy,
5204 
5205     // C    __c11_atomic_add(A *, M, int)
5206     Arithmetic,
5207 
5208     // C    __atomic_exchange_n(A *, CP, int)
5209     Xchg,
5210 
5211     // void __atomic_exchange(A *, C *, CP, int)
5212     GNUXchg,
5213 
5214     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5215     C11CmpXchg,
5216 
5217     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5218     GNUCmpXchg
5219   } Form = Init;
5220 
5221   const unsigned NumForm = GNUCmpXchg + 1;
5222   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5223   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5224   // where:
5225   //   C is an appropriate type,
5226   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5227   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5228   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5229   //   the int parameters are for orderings.
5230 
5231   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5232       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5233       "need to update code for modified forms");
5234   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5235                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5236                         AtomicExpr::AO__atomic_load,
5237                 "need to update code for modified C11 atomics");
5238   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5239                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5240   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5241                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5242                IsOpenCL;
5243   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5244              Op == AtomicExpr::AO__atomic_store_n ||
5245              Op == AtomicExpr::AO__atomic_exchange_n ||
5246              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5247   bool IsAddSub = false;
5248 
5249   switch (Op) {
5250   case AtomicExpr::AO__c11_atomic_init:
5251   case AtomicExpr::AO__opencl_atomic_init:
5252     Form = Init;
5253     break;
5254 
5255   case AtomicExpr::AO__c11_atomic_load:
5256   case AtomicExpr::AO__opencl_atomic_load:
5257   case AtomicExpr::AO__atomic_load_n:
5258     Form = Load;
5259     break;
5260 
5261   case AtomicExpr::AO__atomic_load:
5262     Form = LoadCopy;
5263     break;
5264 
5265   case AtomicExpr::AO__c11_atomic_store:
5266   case AtomicExpr::AO__opencl_atomic_store:
5267   case AtomicExpr::AO__atomic_store:
5268   case AtomicExpr::AO__atomic_store_n:
5269     Form = Copy;
5270     break;
5271 
5272   case AtomicExpr::AO__c11_atomic_fetch_add:
5273   case AtomicExpr::AO__c11_atomic_fetch_sub:
5274   case AtomicExpr::AO__opencl_atomic_fetch_add:
5275   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5276   case AtomicExpr::AO__atomic_fetch_add:
5277   case AtomicExpr::AO__atomic_fetch_sub:
5278   case AtomicExpr::AO__atomic_add_fetch:
5279   case AtomicExpr::AO__atomic_sub_fetch:
5280     IsAddSub = true;
5281     Form = Arithmetic;
5282     break;
5283   case AtomicExpr::AO__c11_atomic_fetch_and:
5284   case AtomicExpr::AO__c11_atomic_fetch_or:
5285   case AtomicExpr::AO__c11_atomic_fetch_xor:
5286   case AtomicExpr::AO__opencl_atomic_fetch_and:
5287   case AtomicExpr::AO__opencl_atomic_fetch_or:
5288   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5289   case AtomicExpr::AO__atomic_fetch_and:
5290   case AtomicExpr::AO__atomic_fetch_or:
5291   case AtomicExpr::AO__atomic_fetch_xor:
5292   case AtomicExpr::AO__atomic_fetch_nand:
5293   case AtomicExpr::AO__atomic_and_fetch:
5294   case AtomicExpr::AO__atomic_or_fetch:
5295   case AtomicExpr::AO__atomic_xor_fetch:
5296   case AtomicExpr::AO__atomic_nand_fetch:
5297     Form = Arithmetic;
5298     break;
5299   case AtomicExpr::AO__c11_atomic_fetch_min:
5300   case AtomicExpr::AO__c11_atomic_fetch_max:
5301   case AtomicExpr::AO__opencl_atomic_fetch_min:
5302   case AtomicExpr::AO__opencl_atomic_fetch_max:
5303   case AtomicExpr::AO__atomic_min_fetch:
5304   case AtomicExpr::AO__atomic_max_fetch:
5305   case AtomicExpr::AO__atomic_fetch_min:
5306   case AtomicExpr::AO__atomic_fetch_max:
5307     Form = Arithmetic;
5308     break;
5309 
5310   case AtomicExpr::AO__c11_atomic_exchange:
5311   case AtomicExpr::AO__opencl_atomic_exchange:
5312   case AtomicExpr::AO__atomic_exchange_n:
5313     Form = Xchg;
5314     break;
5315 
5316   case AtomicExpr::AO__atomic_exchange:
5317     Form = GNUXchg;
5318     break;
5319 
5320   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5321   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5322   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5323   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5324     Form = C11CmpXchg;
5325     break;
5326 
5327   case AtomicExpr::AO__atomic_compare_exchange:
5328   case AtomicExpr::AO__atomic_compare_exchange_n:
5329     Form = GNUCmpXchg;
5330     break;
5331   }
5332 
5333   unsigned AdjustedNumArgs = NumArgs[Form];
5334   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5335     ++AdjustedNumArgs;
5336   // Check we have the right number of arguments.
5337   if (Args.size() < AdjustedNumArgs) {
5338     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5339         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5340         << ExprRange;
5341     return ExprError();
5342   } else if (Args.size() > AdjustedNumArgs) {
5343     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5344          diag::err_typecheck_call_too_many_args)
5345         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5346         << ExprRange;
5347     return ExprError();
5348   }
5349 
5350   // Inspect the first argument of the atomic operation.
5351   Expr *Ptr = Args[0];
5352   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5353   if (ConvertedPtr.isInvalid())
5354     return ExprError();
5355 
5356   Ptr = ConvertedPtr.get();
5357   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5358   if (!pointerType) {
5359     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5360         << Ptr->getType() << Ptr->getSourceRange();
5361     return ExprError();
5362   }
5363 
5364   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5365   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5366   QualType ValType = AtomTy; // 'C'
5367   if (IsC11) {
5368     if (!AtomTy->isAtomicType()) {
5369       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5370           << Ptr->getType() << Ptr->getSourceRange();
5371       return ExprError();
5372     }
5373     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5374         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5375       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5376           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5377           << Ptr->getSourceRange();
5378       return ExprError();
5379     }
5380     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5381   } else if (Form != Load && Form != LoadCopy) {
5382     if (ValType.isConstQualified()) {
5383       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5384           << Ptr->getType() << Ptr->getSourceRange();
5385       return ExprError();
5386     }
5387   }
5388 
5389   // For an arithmetic operation, the implied arithmetic must be well-formed.
5390   if (Form == Arithmetic) {
5391     // gcc does not enforce these rules for GNU atomics, but we do so for
5392     // sanity.
5393     auto IsAllowedValueType = [&](QualType ValType) {
5394       if (ValType->isIntegerType())
5395         return true;
5396       if (ValType->isPointerType())
5397         return true;
5398       if (!ValType->isFloatingType())
5399         return false;
5400       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5401       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5402           &Context.getTargetInfo().getLongDoubleFormat() ==
5403               &llvm::APFloat::x87DoubleExtended())
5404         return false;
5405       return true;
5406     };
5407     if (IsAddSub && !IsAllowedValueType(ValType)) {
5408       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5409           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5410       return ExprError();
5411     }
5412     if (!IsAddSub && !ValType->isIntegerType()) {
5413       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5414           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5415       return ExprError();
5416     }
5417     if (IsC11 && ValType->isPointerType() &&
5418         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5419                             diag::err_incomplete_type)) {
5420       return ExprError();
5421     }
5422   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5423     // For __atomic_*_n operations, the value type must be a scalar integral or
5424     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5425     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5426         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5427     return ExprError();
5428   }
5429 
5430   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5431       !AtomTy->isScalarType()) {
5432     // For GNU atomics, require a trivially-copyable type. This is not part of
5433     // the GNU atomics specification, but we enforce it for sanity.
5434     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5435         << Ptr->getType() << Ptr->getSourceRange();
5436     return ExprError();
5437   }
5438 
5439   switch (ValType.getObjCLifetime()) {
5440   case Qualifiers::OCL_None:
5441   case Qualifiers::OCL_ExplicitNone:
5442     // okay
5443     break;
5444 
5445   case Qualifiers::OCL_Weak:
5446   case Qualifiers::OCL_Strong:
5447   case Qualifiers::OCL_Autoreleasing:
5448     // FIXME: Can this happen? By this point, ValType should be known
5449     // to be trivially copyable.
5450     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5451         << ValType << Ptr->getSourceRange();
5452     return ExprError();
5453   }
5454 
5455   // All atomic operations have an overload which takes a pointer to a volatile
5456   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5457   // into the result or the other operands. Similarly atomic_load takes a
5458   // pointer to a const 'A'.
5459   ValType.removeLocalVolatile();
5460   ValType.removeLocalConst();
5461   QualType ResultType = ValType;
5462   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5463       Form == Init)
5464     ResultType = Context.VoidTy;
5465   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5466     ResultType = Context.BoolTy;
5467 
5468   // The type of a parameter passed 'by value'. In the GNU atomics, such
5469   // arguments are actually passed as pointers.
5470   QualType ByValType = ValType; // 'CP'
5471   bool IsPassedByAddress = false;
5472   if (!IsC11 && !IsN) {
5473     ByValType = Ptr->getType();
5474     IsPassedByAddress = true;
5475   }
5476 
5477   SmallVector<Expr *, 5> APIOrderedArgs;
5478   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5479     APIOrderedArgs.push_back(Args[0]);
5480     switch (Form) {
5481     case Init:
5482     case Load:
5483       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5484       break;
5485     case LoadCopy:
5486     case Copy:
5487     case Arithmetic:
5488     case Xchg:
5489       APIOrderedArgs.push_back(Args[2]); // Val1
5490       APIOrderedArgs.push_back(Args[1]); // Order
5491       break;
5492     case GNUXchg:
5493       APIOrderedArgs.push_back(Args[2]); // Val1
5494       APIOrderedArgs.push_back(Args[3]); // Val2
5495       APIOrderedArgs.push_back(Args[1]); // Order
5496       break;
5497     case C11CmpXchg:
5498       APIOrderedArgs.push_back(Args[2]); // Val1
5499       APIOrderedArgs.push_back(Args[4]); // Val2
5500       APIOrderedArgs.push_back(Args[1]); // Order
5501       APIOrderedArgs.push_back(Args[3]); // OrderFail
5502       break;
5503     case GNUCmpXchg:
5504       APIOrderedArgs.push_back(Args[2]); // Val1
5505       APIOrderedArgs.push_back(Args[4]); // Val2
5506       APIOrderedArgs.push_back(Args[5]); // Weak
5507       APIOrderedArgs.push_back(Args[1]); // Order
5508       APIOrderedArgs.push_back(Args[3]); // OrderFail
5509       break;
5510     }
5511   } else
5512     APIOrderedArgs.append(Args.begin(), Args.end());
5513 
5514   // The first argument's non-CV pointer type is used to deduce the type of
5515   // subsequent arguments, except for:
5516   //  - weak flag (always converted to bool)
5517   //  - memory order (always converted to int)
5518   //  - scope  (always converted to int)
5519   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5520     QualType Ty;
5521     if (i < NumVals[Form] + 1) {
5522       switch (i) {
5523       case 0:
5524         // The first argument is always a pointer. It has a fixed type.
5525         // It is always dereferenced, a nullptr is undefined.
5526         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5527         // Nothing else to do: we already know all we want about this pointer.
5528         continue;
5529       case 1:
5530         // The second argument is the non-atomic operand. For arithmetic, this
5531         // is always passed by value, and for a compare_exchange it is always
5532         // passed by address. For the rest, GNU uses by-address and C11 uses
5533         // by-value.
5534         assert(Form != Load);
5535         if (Form == Arithmetic && ValType->isPointerType())
5536           Ty = Context.getPointerDiffType();
5537         else if (Form == Init || Form == Arithmetic)
5538           Ty = ValType;
5539         else if (Form == Copy || Form == Xchg) {
5540           if (IsPassedByAddress) {
5541             // The value pointer is always dereferenced, a nullptr is undefined.
5542             CheckNonNullArgument(*this, APIOrderedArgs[i],
5543                                  ExprRange.getBegin());
5544           }
5545           Ty = ByValType;
5546         } else {
5547           Expr *ValArg = APIOrderedArgs[i];
5548           // The value pointer is always dereferenced, a nullptr is undefined.
5549           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5550           LangAS AS = LangAS::Default;
5551           // Keep address space of non-atomic pointer type.
5552           if (const PointerType *PtrTy =
5553                   ValArg->getType()->getAs<PointerType>()) {
5554             AS = PtrTy->getPointeeType().getAddressSpace();
5555           }
5556           Ty = Context.getPointerType(
5557               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5558         }
5559         break;
5560       case 2:
5561         // The third argument to compare_exchange / GNU exchange is the desired
5562         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5563         if (IsPassedByAddress)
5564           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5565         Ty = ByValType;
5566         break;
5567       case 3:
5568         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5569         Ty = Context.BoolTy;
5570         break;
5571       }
5572     } else {
5573       // The order(s) and scope are always converted to int.
5574       Ty = Context.IntTy;
5575     }
5576 
5577     InitializedEntity Entity =
5578         InitializedEntity::InitializeParameter(Context, Ty, false);
5579     ExprResult Arg = APIOrderedArgs[i];
5580     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5581     if (Arg.isInvalid())
5582       return true;
5583     APIOrderedArgs[i] = Arg.get();
5584   }
5585 
5586   // Permute the arguments into a 'consistent' order.
5587   SmallVector<Expr*, 5> SubExprs;
5588   SubExprs.push_back(Ptr);
5589   switch (Form) {
5590   case Init:
5591     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5592     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5593     break;
5594   case Load:
5595     SubExprs.push_back(APIOrderedArgs[1]); // Order
5596     break;
5597   case LoadCopy:
5598   case Copy:
5599   case Arithmetic:
5600   case Xchg:
5601     SubExprs.push_back(APIOrderedArgs[2]); // Order
5602     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5603     break;
5604   case GNUXchg:
5605     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5606     SubExprs.push_back(APIOrderedArgs[3]); // Order
5607     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5608     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5609     break;
5610   case C11CmpXchg:
5611     SubExprs.push_back(APIOrderedArgs[3]); // Order
5612     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5613     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5614     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5615     break;
5616   case GNUCmpXchg:
5617     SubExprs.push_back(APIOrderedArgs[4]); // Order
5618     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5619     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5620     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5621     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5622     break;
5623   }
5624 
5625   if (SubExprs.size() >= 2 && Form != Init) {
5626     if (Optional<llvm::APSInt> Result =
5627             SubExprs[1]->getIntegerConstantExpr(Context))
5628       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5629         Diag(SubExprs[1]->getBeginLoc(),
5630              diag::warn_atomic_op_has_invalid_memory_order)
5631             << SubExprs[1]->getSourceRange();
5632   }
5633 
5634   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5635     auto *Scope = Args[Args.size() - 1];
5636     if (Optional<llvm::APSInt> Result =
5637             Scope->getIntegerConstantExpr(Context)) {
5638       if (!ScopeModel->isValid(Result->getZExtValue()))
5639         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5640             << Scope->getSourceRange();
5641     }
5642     SubExprs.push_back(Scope);
5643   }
5644 
5645   AtomicExpr *AE = new (Context)
5646       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5647 
5648   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5649        Op == AtomicExpr::AO__c11_atomic_store ||
5650        Op == AtomicExpr::AO__opencl_atomic_load ||
5651        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5652       Context.AtomicUsesUnsupportedLibcall(AE))
5653     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5654         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5655              Op == AtomicExpr::AO__opencl_atomic_load)
5656                 ? 0
5657                 : 1);
5658 
5659   if (ValType->isExtIntType()) {
5660     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5661     return ExprError();
5662   }
5663 
5664   return AE;
5665 }
5666 
5667 /// checkBuiltinArgument - Given a call to a builtin function, perform
5668 /// normal type-checking on the given argument, updating the call in
5669 /// place.  This is useful when a builtin function requires custom
5670 /// type-checking for some of its arguments but not necessarily all of
5671 /// them.
5672 ///
5673 /// Returns true on error.
5674 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5675   FunctionDecl *Fn = E->getDirectCallee();
5676   assert(Fn && "builtin call without direct callee!");
5677 
5678   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5679   InitializedEntity Entity =
5680     InitializedEntity::InitializeParameter(S.Context, Param);
5681 
5682   ExprResult Arg = E->getArg(0);
5683   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5684   if (Arg.isInvalid())
5685     return true;
5686 
5687   E->setArg(ArgIndex, Arg.get());
5688   return false;
5689 }
5690 
5691 /// We have a call to a function like __sync_fetch_and_add, which is an
5692 /// overloaded function based on the pointer type of its first argument.
5693 /// The main BuildCallExpr routines have already promoted the types of
5694 /// arguments because all of these calls are prototyped as void(...).
5695 ///
5696 /// This function goes through and does final semantic checking for these
5697 /// builtins, as well as generating any warnings.
5698 ExprResult
5699 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5700   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5701   Expr *Callee = TheCall->getCallee();
5702   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5703   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5704 
5705   // Ensure that we have at least one argument to do type inference from.
5706   if (TheCall->getNumArgs() < 1) {
5707     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5708         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5709     return ExprError();
5710   }
5711 
5712   // Inspect the first argument of the atomic builtin.  This should always be
5713   // a pointer type, whose element is an integral scalar or pointer type.
5714   // Because it is a pointer type, we don't have to worry about any implicit
5715   // casts here.
5716   // FIXME: We don't allow floating point scalars as input.
5717   Expr *FirstArg = TheCall->getArg(0);
5718   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5719   if (FirstArgResult.isInvalid())
5720     return ExprError();
5721   FirstArg = FirstArgResult.get();
5722   TheCall->setArg(0, FirstArg);
5723 
5724   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5725   if (!pointerType) {
5726     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5727         << FirstArg->getType() << FirstArg->getSourceRange();
5728     return ExprError();
5729   }
5730 
5731   QualType ValType = pointerType->getPointeeType();
5732   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5733       !ValType->isBlockPointerType()) {
5734     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5735         << FirstArg->getType() << FirstArg->getSourceRange();
5736     return ExprError();
5737   }
5738 
5739   if (ValType.isConstQualified()) {
5740     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5741         << FirstArg->getType() << FirstArg->getSourceRange();
5742     return ExprError();
5743   }
5744 
5745   switch (ValType.getObjCLifetime()) {
5746   case Qualifiers::OCL_None:
5747   case Qualifiers::OCL_ExplicitNone:
5748     // okay
5749     break;
5750 
5751   case Qualifiers::OCL_Weak:
5752   case Qualifiers::OCL_Strong:
5753   case Qualifiers::OCL_Autoreleasing:
5754     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5755         << ValType << FirstArg->getSourceRange();
5756     return ExprError();
5757   }
5758 
5759   // Strip any qualifiers off ValType.
5760   ValType = ValType.getUnqualifiedType();
5761 
5762   // The majority of builtins return a value, but a few have special return
5763   // types, so allow them to override appropriately below.
5764   QualType ResultType = ValType;
5765 
5766   // We need to figure out which concrete builtin this maps onto.  For example,
5767   // __sync_fetch_and_add with a 2 byte object turns into
5768   // __sync_fetch_and_add_2.
5769 #define BUILTIN_ROW(x) \
5770   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5771     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5772 
5773   static const unsigned BuiltinIndices[][5] = {
5774     BUILTIN_ROW(__sync_fetch_and_add),
5775     BUILTIN_ROW(__sync_fetch_and_sub),
5776     BUILTIN_ROW(__sync_fetch_and_or),
5777     BUILTIN_ROW(__sync_fetch_and_and),
5778     BUILTIN_ROW(__sync_fetch_and_xor),
5779     BUILTIN_ROW(__sync_fetch_and_nand),
5780 
5781     BUILTIN_ROW(__sync_add_and_fetch),
5782     BUILTIN_ROW(__sync_sub_and_fetch),
5783     BUILTIN_ROW(__sync_and_and_fetch),
5784     BUILTIN_ROW(__sync_or_and_fetch),
5785     BUILTIN_ROW(__sync_xor_and_fetch),
5786     BUILTIN_ROW(__sync_nand_and_fetch),
5787 
5788     BUILTIN_ROW(__sync_val_compare_and_swap),
5789     BUILTIN_ROW(__sync_bool_compare_and_swap),
5790     BUILTIN_ROW(__sync_lock_test_and_set),
5791     BUILTIN_ROW(__sync_lock_release),
5792     BUILTIN_ROW(__sync_swap)
5793   };
5794 #undef BUILTIN_ROW
5795 
5796   // Determine the index of the size.
5797   unsigned SizeIndex;
5798   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5799   case 1: SizeIndex = 0; break;
5800   case 2: SizeIndex = 1; break;
5801   case 4: SizeIndex = 2; break;
5802   case 8: SizeIndex = 3; break;
5803   case 16: SizeIndex = 4; break;
5804   default:
5805     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5806         << FirstArg->getType() << FirstArg->getSourceRange();
5807     return ExprError();
5808   }
5809 
5810   // Each of these builtins has one pointer argument, followed by some number of
5811   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5812   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5813   // as the number of fixed args.
5814   unsigned BuiltinID = FDecl->getBuiltinID();
5815   unsigned BuiltinIndex, NumFixed = 1;
5816   bool WarnAboutSemanticsChange = false;
5817   switch (BuiltinID) {
5818   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5819   case Builtin::BI__sync_fetch_and_add:
5820   case Builtin::BI__sync_fetch_and_add_1:
5821   case Builtin::BI__sync_fetch_and_add_2:
5822   case Builtin::BI__sync_fetch_and_add_4:
5823   case Builtin::BI__sync_fetch_and_add_8:
5824   case Builtin::BI__sync_fetch_and_add_16:
5825     BuiltinIndex = 0;
5826     break;
5827 
5828   case Builtin::BI__sync_fetch_and_sub:
5829   case Builtin::BI__sync_fetch_and_sub_1:
5830   case Builtin::BI__sync_fetch_and_sub_2:
5831   case Builtin::BI__sync_fetch_and_sub_4:
5832   case Builtin::BI__sync_fetch_and_sub_8:
5833   case Builtin::BI__sync_fetch_and_sub_16:
5834     BuiltinIndex = 1;
5835     break;
5836 
5837   case Builtin::BI__sync_fetch_and_or:
5838   case Builtin::BI__sync_fetch_and_or_1:
5839   case Builtin::BI__sync_fetch_and_or_2:
5840   case Builtin::BI__sync_fetch_and_or_4:
5841   case Builtin::BI__sync_fetch_and_or_8:
5842   case Builtin::BI__sync_fetch_and_or_16:
5843     BuiltinIndex = 2;
5844     break;
5845 
5846   case Builtin::BI__sync_fetch_and_and:
5847   case Builtin::BI__sync_fetch_and_and_1:
5848   case Builtin::BI__sync_fetch_and_and_2:
5849   case Builtin::BI__sync_fetch_and_and_4:
5850   case Builtin::BI__sync_fetch_and_and_8:
5851   case Builtin::BI__sync_fetch_and_and_16:
5852     BuiltinIndex = 3;
5853     break;
5854 
5855   case Builtin::BI__sync_fetch_and_xor:
5856   case Builtin::BI__sync_fetch_and_xor_1:
5857   case Builtin::BI__sync_fetch_and_xor_2:
5858   case Builtin::BI__sync_fetch_and_xor_4:
5859   case Builtin::BI__sync_fetch_and_xor_8:
5860   case Builtin::BI__sync_fetch_and_xor_16:
5861     BuiltinIndex = 4;
5862     break;
5863 
5864   case Builtin::BI__sync_fetch_and_nand:
5865   case Builtin::BI__sync_fetch_and_nand_1:
5866   case Builtin::BI__sync_fetch_and_nand_2:
5867   case Builtin::BI__sync_fetch_and_nand_4:
5868   case Builtin::BI__sync_fetch_and_nand_8:
5869   case Builtin::BI__sync_fetch_and_nand_16:
5870     BuiltinIndex = 5;
5871     WarnAboutSemanticsChange = true;
5872     break;
5873 
5874   case Builtin::BI__sync_add_and_fetch:
5875   case Builtin::BI__sync_add_and_fetch_1:
5876   case Builtin::BI__sync_add_and_fetch_2:
5877   case Builtin::BI__sync_add_and_fetch_4:
5878   case Builtin::BI__sync_add_and_fetch_8:
5879   case Builtin::BI__sync_add_and_fetch_16:
5880     BuiltinIndex = 6;
5881     break;
5882 
5883   case Builtin::BI__sync_sub_and_fetch:
5884   case Builtin::BI__sync_sub_and_fetch_1:
5885   case Builtin::BI__sync_sub_and_fetch_2:
5886   case Builtin::BI__sync_sub_and_fetch_4:
5887   case Builtin::BI__sync_sub_and_fetch_8:
5888   case Builtin::BI__sync_sub_and_fetch_16:
5889     BuiltinIndex = 7;
5890     break;
5891 
5892   case Builtin::BI__sync_and_and_fetch:
5893   case Builtin::BI__sync_and_and_fetch_1:
5894   case Builtin::BI__sync_and_and_fetch_2:
5895   case Builtin::BI__sync_and_and_fetch_4:
5896   case Builtin::BI__sync_and_and_fetch_8:
5897   case Builtin::BI__sync_and_and_fetch_16:
5898     BuiltinIndex = 8;
5899     break;
5900 
5901   case Builtin::BI__sync_or_and_fetch:
5902   case Builtin::BI__sync_or_and_fetch_1:
5903   case Builtin::BI__sync_or_and_fetch_2:
5904   case Builtin::BI__sync_or_and_fetch_4:
5905   case Builtin::BI__sync_or_and_fetch_8:
5906   case Builtin::BI__sync_or_and_fetch_16:
5907     BuiltinIndex = 9;
5908     break;
5909 
5910   case Builtin::BI__sync_xor_and_fetch:
5911   case Builtin::BI__sync_xor_and_fetch_1:
5912   case Builtin::BI__sync_xor_and_fetch_2:
5913   case Builtin::BI__sync_xor_and_fetch_4:
5914   case Builtin::BI__sync_xor_and_fetch_8:
5915   case Builtin::BI__sync_xor_and_fetch_16:
5916     BuiltinIndex = 10;
5917     break;
5918 
5919   case Builtin::BI__sync_nand_and_fetch:
5920   case Builtin::BI__sync_nand_and_fetch_1:
5921   case Builtin::BI__sync_nand_and_fetch_2:
5922   case Builtin::BI__sync_nand_and_fetch_4:
5923   case Builtin::BI__sync_nand_and_fetch_8:
5924   case Builtin::BI__sync_nand_and_fetch_16:
5925     BuiltinIndex = 11;
5926     WarnAboutSemanticsChange = true;
5927     break;
5928 
5929   case Builtin::BI__sync_val_compare_and_swap:
5930   case Builtin::BI__sync_val_compare_and_swap_1:
5931   case Builtin::BI__sync_val_compare_and_swap_2:
5932   case Builtin::BI__sync_val_compare_and_swap_4:
5933   case Builtin::BI__sync_val_compare_and_swap_8:
5934   case Builtin::BI__sync_val_compare_and_swap_16:
5935     BuiltinIndex = 12;
5936     NumFixed = 2;
5937     break;
5938 
5939   case Builtin::BI__sync_bool_compare_and_swap:
5940   case Builtin::BI__sync_bool_compare_and_swap_1:
5941   case Builtin::BI__sync_bool_compare_and_swap_2:
5942   case Builtin::BI__sync_bool_compare_and_swap_4:
5943   case Builtin::BI__sync_bool_compare_and_swap_8:
5944   case Builtin::BI__sync_bool_compare_and_swap_16:
5945     BuiltinIndex = 13;
5946     NumFixed = 2;
5947     ResultType = Context.BoolTy;
5948     break;
5949 
5950   case Builtin::BI__sync_lock_test_and_set:
5951   case Builtin::BI__sync_lock_test_and_set_1:
5952   case Builtin::BI__sync_lock_test_and_set_2:
5953   case Builtin::BI__sync_lock_test_and_set_4:
5954   case Builtin::BI__sync_lock_test_and_set_8:
5955   case Builtin::BI__sync_lock_test_and_set_16:
5956     BuiltinIndex = 14;
5957     break;
5958 
5959   case Builtin::BI__sync_lock_release:
5960   case Builtin::BI__sync_lock_release_1:
5961   case Builtin::BI__sync_lock_release_2:
5962   case Builtin::BI__sync_lock_release_4:
5963   case Builtin::BI__sync_lock_release_8:
5964   case Builtin::BI__sync_lock_release_16:
5965     BuiltinIndex = 15;
5966     NumFixed = 0;
5967     ResultType = Context.VoidTy;
5968     break;
5969 
5970   case Builtin::BI__sync_swap:
5971   case Builtin::BI__sync_swap_1:
5972   case Builtin::BI__sync_swap_2:
5973   case Builtin::BI__sync_swap_4:
5974   case Builtin::BI__sync_swap_8:
5975   case Builtin::BI__sync_swap_16:
5976     BuiltinIndex = 16;
5977     break;
5978   }
5979 
5980   // Now that we know how many fixed arguments we expect, first check that we
5981   // have at least that many.
5982   if (TheCall->getNumArgs() < 1+NumFixed) {
5983     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5984         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5985         << Callee->getSourceRange();
5986     return ExprError();
5987   }
5988 
5989   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5990       << Callee->getSourceRange();
5991 
5992   if (WarnAboutSemanticsChange) {
5993     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5994         << Callee->getSourceRange();
5995   }
5996 
5997   // Get the decl for the concrete builtin from this, we can tell what the
5998   // concrete integer type we should convert to is.
5999   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6000   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6001   FunctionDecl *NewBuiltinDecl;
6002   if (NewBuiltinID == BuiltinID)
6003     NewBuiltinDecl = FDecl;
6004   else {
6005     // Perform builtin lookup to avoid redeclaring it.
6006     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6007     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6008     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6009     assert(Res.getFoundDecl());
6010     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6011     if (!NewBuiltinDecl)
6012       return ExprError();
6013   }
6014 
6015   // The first argument --- the pointer --- has a fixed type; we
6016   // deduce the types of the rest of the arguments accordingly.  Walk
6017   // the remaining arguments, converting them to the deduced value type.
6018   for (unsigned i = 0; i != NumFixed; ++i) {
6019     ExprResult Arg = TheCall->getArg(i+1);
6020 
6021     // GCC does an implicit conversion to the pointer or integer ValType.  This
6022     // can fail in some cases (1i -> int**), check for this error case now.
6023     // Initialize the argument.
6024     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6025                                                    ValType, /*consume*/ false);
6026     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6027     if (Arg.isInvalid())
6028       return ExprError();
6029 
6030     // Okay, we have something that *can* be converted to the right type.  Check
6031     // to see if there is a potentially weird extension going on here.  This can
6032     // happen when you do an atomic operation on something like an char* and
6033     // pass in 42.  The 42 gets converted to char.  This is even more strange
6034     // for things like 45.123 -> char, etc.
6035     // FIXME: Do this check.
6036     TheCall->setArg(i+1, Arg.get());
6037   }
6038 
6039   // Create a new DeclRefExpr to refer to the new decl.
6040   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6041       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6042       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6043       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6044 
6045   // Set the callee in the CallExpr.
6046   // FIXME: This loses syntactic information.
6047   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6048   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6049                                               CK_BuiltinFnToFnPtr);
6050   TheCall->setCallee(PromotedCall.get());
6051 
6052   // Change the result type of the call to match the original value type. This
6053   // is arbitrary, but the codegen for these builtins ins design to handle it
6054   // gracefully.
6055   TheCall->setType(ResultType);
6056 
6057   // Prohibit use of _ExtInt with atomic builtins.
6058   // The arguments would have already been converted to the first argument's
6059   // type, so only need to check the first argument.
6060   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6061   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6062     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6063     return ExprError();
6064   }
6065 
6066   return TheCallResult;
6067 }
6068 
6069 /// SemaBuiltinNontemporalOverloaded - We have a call to
6070 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6071 /// overloaded function based on the pointer type of its last argument.
6072 ///
6073 /// This function goes through and does final semantic checking for these
6074 /// builtins.
6075 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6076   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6077   DeclRefExpr *DRE =
6078       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6079   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6080   unsigned BuiltinID = FDecl->getBuiltinID();
6081   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6082           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6083          "Unexpected nontemporal load/store builtin!");
6084   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6085   unsigned numArgs = isStore ? 2 : 1;
6086 
6087   // Ensure that we have the proper number of arguments.
6088   if (checkArgCount(*this, TheCall, numArgs))
6089     return ExprError();
6090 
6091   // Inspect the last argument of the nontemporal builtin.  This should always
6092   // be a pointer type, from which we imply the type of the memory access.
6093   // Because it is a pointer type, we don't have to worry about any implicit
6094   // casts here.
6095   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6096   ExprResult PointerArgResult =
6097       DefaultFunctionArrayLvalueConversion(PointerArg);
6098 
6099   if (PointerArgResult.isInvalid())
6100     return ExprError();
6101   PointerArg = PointerArgResult.get();
6102   TheCall->setArg(numArgs - 1, PointerArg);
6103 
6104   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6105   if (!pointerType) {
6106     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6107         << PointerArg->getType() << PointerArg->getSourceRange();
6108     return ExprError();
6109   }
6110 
6111   QualType ValType = pointerType->getPointeeType();
6112 
6113   // Strip any qualifiers off ValType.
6114   ValType = ValType.getUnqualifiedType();
6115   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6116       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6117       !ValType->isVectorType()) {
6118     Diag(DRE->getBeginLoc(),
6119          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6120         << PointerArg->getType() << PointerArg->getSourceRange();
6121     return ExprError();
6122   }
6123 
6124   if (!isStore) {
6125     TheCall->setType(ValType);
6126     return TheCallResult;
6127   }
6128 
6129   ExprResult ValArg = TheCall->getArg(0);
6130   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6131       Context, ValType, /*consume*/ false);
6132   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6133   if (ValArg.isInvalid())
6134     return ExprError();
6135 
6136   TheCall->setArg(0, ValArg.get());
6137   TheCall->setType(Context.VoidTy);
6138   return TheCallResult;
6139 }
6140 
6141 /// CheckObjCString - Checks that the argument to the builtin
6142 /// CFString constructor is correct
6143 /// Note: It might also make sense to do the UTF-16 conversion here (would
6144 /// simplify the backend).
6145 bool Sema::CheckObjCString(Expr *Arg) {
6146   Arg = Arg->IgnoreParenCasts();
6147   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6148 
6149   if (!Literal || !Literal->isAscii()) {
6150     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6151         << Arg->getSourceRange();
6152     return true;
6153   }
6154 
6155   if (Literal->containsNonAsciiOrNull()) {
6156     StringRef String = Literal->getString();
6157     unsigned NumBytes = String.size();
6158     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6159     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6160     llvm::UTF16 *ToPtr = &ToBuf[0];
6161 
6162     llvm::ConversionResult Result =
6163         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6164                                  ToPtr + NumBytes, llvm::strictConversion);
6165     // Check for conversion failure.
6166     if (Result != llvm::conversionOK)
6167       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6168           << Arg->getSourceRange();
6169   }
6170   return false;
6171 }
6172 
6173 /// CheckObjCString - Checks that the format string argument to the os_log()
6174 /// and os_trace() functions is correct, and converts it to const char *.
6175 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6176   Arg = Arg->IgnoreParenCasts();
6177   auto *Literal = dyn_cast<StringLiteral>(Arg);
6178   if (!Literal) {
6179     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6180       Literal = ObjcLiteral->getString();
6181     }
6182   }
6183 
6184   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6185     return ExprError(
6186         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6187         << Arg->getSourceRange());
6188   }
6189 
6190   ExprResult Result(Literal);
6191   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6192   InitializedEntity Entity =
6193       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6194   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6195   return Result;
6196 }
6197 
6198 /// Check that the user is calling the appropriate va_start builtin for the
6199 /// target and calling convention.
6200 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6201   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6202   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6203   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6204                     TT.getArch() == llvm::Triple::aarch64_32);
6205   bool IsWindows = TT.isOSWindows();
6206   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6207   if (IsX64 || IsAArch64) {
6208     CallingConv CC = CC_C;
6209     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6210       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6211     if (IsMSVAStart) {
6212       // Don't allow this in System V ABI functions.
6213       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6214         return S.Diag(Fn->getBeginLoc(),
6215                       diag::err_ms_va_start_used_in_sysv_function);
6216     } else {
6217       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6218       // On x64 Windows, don't allow this in System V ABI functions.
6219       // (Yes, that means there's no corresponding way to support variadic
6220       // System V ABI functions on Windows.)
6221       if ((IsWindows && CC == CC_X86_64SysV) ||
6222           (!IsWindows && CC == CC_Win64))
6223         return S.Diag(Fn->getBeginLoc(),
6224                       diag::err_va_start_used_in_wrong_abi_function)
6225                << !IsWindows;
6226     }
6227     return false;
6228   }
6229 
6230   if (IsMSVAStart)
6231     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6232   return false;
6233 }
6234 
6235 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6236                                              ParmVarDecl **LastParam = nullptr) {
6237   // Determine whether the current function, block, or obj-c method is variadic
6238   // and get its parameter list.
6239   bool IsVariadic = false;
6240   ArrayRef<ParmVarDecl *> Params;
6241   DeclContext *Caller = S.CurContext;
6242   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6243     IsVariadic = Block->isVariadic();
6244     Params = Block->parameters();
6245   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6246     IsVariadic = FD->isVariadic();
6247     Params = FD->parameters();
6248   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6249     IsVariadic = MD->isVariadic();
6250     // FIXME: This isn't correct for methods (results in bogus warning).
6251     Params = MD->parameters();
6252   } else if (isa<CapturedDecl>(Caller)) {
6253     // We don't support va_start in a CapturedDecl.
6254     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6255     return true;
6256   } else {
6257     // This must be some other declcontext that parses exprs.
6258     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6259     return true;
6260   }
6261 
6262   if (!IsVariadic) {
6263     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6264     return true;
6265   }
6266 
6267   if (LastParam)
6268     *LastParam = Params.empty() ? nullptr : Params.back();
6269 
6270   return false;
6271 }
6272 
6273 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6274 /// for validity.  Emit an error and return true on failure; return false
6275 /// on success.
6276 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6277   Expr *Fn = TheCall->getCallee();
6278 
6279   if (checkVAStartABI(*this, BuiltinID, Fn))
6280     return true;
6281 
6282   if (checkArgCount(*this, TheCall, 2))
6283     return true;
6284 
6285   // Type-check the first argument normally.
6286   if (checkBuiltinArgument(*this, TheCall, 0))
6287     return true;
6288 
6289   // Check that the current function is variadic, and get its last parameter.
6290   ParmVarDecl *LastParam;
6291   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6292     return true;
6293 
6294   // Verify that the second argument to the builtin is the last argument of the
6295   // current function or method.
6296   bool SecondArgIsLastNamedArgument = false;
6297   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6298 
6299   // These are valid if SecondArgIsLastNamedArgument is false after the next
6300   // block.
6301   QualType Type;
6302   SourceLocation ParamLoc;
6303   bool IsCRegister = false;
6304 
6305   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6306     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6307       SecondArgIsLastNamedArgument = PV == LastParam;
6308 
6309       Type = PV->getType();
6310       ParamLoc = PV->getLocation();
6311       IsCRegister =
6312           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6313     }
6314   }
6315 
6316   if (!SecondArgIsLastNamedArgument)
6317     Diag(TheCall->getArg(1)->getBeginLoc(),
6318          diag::warn_second_arg_of_va_start_not_last_named_param);
6319   else if (IsCRegister || Type->isReferenceType() ||
6320            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6321              // Promotable integers are UB, but enumerations need a bit of
6322              // extra checking to see what their promotable type actually is.
6323              if (!Type->isPromotableIntegerType())
6324                return false;
6325              if (!Type->isEnumeralType())
6326                return true;
6327              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6328              return !(ED &&
6329                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6330            }()) {
6331     unsigned Reason = 0;
6332     if (Type->isReferenceType())  Reason = 1;
6333     else if (IsCRegister)         Reason = 2;
6334     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6335     Diag(ParamLoc, diag::note_parameter_type) << Type;
6336   }
6337 
6338   TheCall->setType(Context.VoidTy);
6339   return false;
6340 }
6341 
6342 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6343   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6344     const LangOptions &LO = getLangOpts();
6345 
6346     if (LO.CPlusPlus)
6347       return Arg->getType()
6348                  .getCanonicalType()
6349                  .getTypePtr()
6350                  ->getPointeeType()
6351                  .withoutLocalFastQualifiers() == Context.CharTy;
6352 
6353     // In C, allow aliasing through `char *`, this is required for AArch64 at
6354     // least.
6355     return true;
6356   };
6357 
6358   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6359   //                 const char *named_addr);
6360 
6361   Expr *Func = Call->getCallee();
6362 
6363   if (Call->getNumArgs() < 3)
6364     return Diag(Call->getEndLoc(),
6365                 diag::err_typecheck_call_too_few_args_at_least)
6366            << 0 /*function call*/ << 3 << Call->getNumArgs();
6367 
6368   // Type-check the first argument normally.
6369   if (checkBuiltinArgument(*this, Call, 0))
6370     return true;
6371 
6372   // Check that the current function is variadic.
6373   if (checkVAStartIsInVariadicFunction(*this, Func))
6374     return true;
6375 
6376   // __va_start on Windows does not validate the parameter qualifiers
6377 
6378   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6379   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6380 
6381   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6382   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6383 
6384   const QualType &ConstCharPtrTy =
6385       Context.getPointerType(Context.CharTy.withConst());
6386   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6387     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6388         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6389         << 0                                      /* qualifier difference */
6390         << 3                                      /* parameter mismatch */
6391         << 2 << Arg1->getType() << ConstCharPtrTy;
6392 
6393   const QualType SizeTy = Context.getSizeType();
6394   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6395     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6396         << Arg2->getType() << SizeTy << 1 /* different class */
6397         << 0                              /* qualifier difference */
6398         << 3                              /* parameter mismatch */
6399         << 3 << Arg2->getType() << SizeTy;
6400 
6401   return false;
6402 }
6403 
6404 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6405 /// friends.  This is declared to take (...), so we have to check everything.
6406 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6407   if (checkArgCount(*this, TheCall, 2))
6408     return true;
6409 
6410   ExprResult OrigArg0 = TheCall->getArg(0);
6411   ExprResult OrigArg1 = TheCall->getArg(1);
6412 
6413   // Do standard promotions between the two arguments, returning their common
6414   // type.
6415   QualType Res = UsualArithmeticConversions(
6416       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6417   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6418     return true;
6419 
6420   // Make sure any conversions are pushed back into the call; this is
6421   // type safe since unordered compare builtins are declared as "_Bool
6422   // foo(...)".
6423   TheCall->setArg(0, OrigArg0.get());
6424   TheCall->setArg(1, OrigArg1.get());
6425 
6426   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6427     return false;
6428 
6429   // If the common type isn't a real floating type, then the arguments were
6430   // invalid for this operation.
6431   if (Res.isNull() || !Res->isRealFloatingType())
6432     return Diag(OrigArg0.get()->getBeginLoc(),
6433                 diag::err_typecheck_call_invalid_ordered_compare)
6434            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6435            << SourceRange(OrigArg0.get()->getBeginLoc(),
6436                           OrigArg1.get()->getEndLoc());
6437 
6438   return false;
6439 }
6440 
6441 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6442 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6443 /// to check everything. We expect the last argument to be a floating point
6444 /// value.
6445 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6446   if (checkArgCount(*this, TheCall, NumArgs))
6447     return true;
6448 
6449   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6450   // on all preceding parameters just being int.  Try all of those.
6451   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6452     Expr *Arg = TheCall->getArg(i);
6453 
6454     if (Arg->isTypeDependent())
6455       return false;
6456 
6457     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6458 
6459     if (Res.isInvalid())
6460       return true;
6461     TheCall->setArg(i, Res.get());
6462   }
6463 
6464   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6465 
6466   if (OrigArg->isTypeDependent())
6467     return false;
6468 
6469   // Usual Unary Conversions will convert half to float, which we want for
6470   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6471   // type how it is, but do normal L->Rvalue conversions.
6472   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6473     OrigArg = UsualUnaryConversions(OrigArg).get();
6474   else
6475     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6476   TheCall->setArg(NumArgs - 1, OrigArg);
6477 
6478   // This operation requires a non-_Complex floating-point number.
6479   if (!OrigArg->getType()->isRealFloatingType())
6480     return Diag(OrigArg->getBeginLoc(),
6481                 diag::err_typecheck_call_invalid_unary_fp)
6482            << OrigArg->getType() << OrigArg->getSourceRange();
6483 
6484   return false;
6485 }
6486 
6487 /// Perform semantic analysis for a call to __builtin_complex.
6488 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6489   if (checkArgCount(*this, TheCall, 2))
6490     return true;
6491 
6492   bool Dependent = false;
6493   for (unsigned I = 0; I != 2; ++I) {
6494     Expr *Arg = TheCall->getArg(I);
6495     QualType T = Arg->getType();
6496     if (T->isDependentType()) {
6497       Dependent = true;
6498       continue;
6499     }
6500 
6501     // Despite supporting _Complex int, GCC requires a real floating point type
6502     // for the operands of __builtin_complex.
6503     if (!T->isRealFloatingType()) {
6504       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6505              << Arg->getType() << Arg->getSourceRange();
6506     }
6507 
6508     ExprResult Converted = DefaultLvalueConversion(Arg);
6509     if (Converted.isInvalid())
6510       return true;
6511     TheCall->setArg(I, Converted.get());
6512   }
6513 
6514   if (Dependent) {
6515     TheCall->setType(Context.DependentTy);
6516     return false;
6517   }
6518 
6519   Expr *Real = TheCall->getArg(0);
6520   Expr *Imag = TheCall->getArg(1);
6521   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6522     return Diag(Real->getBeginLoc(),
6523                 diag::err_typecheck_call_different_arg_types)
6524            << Real->getType() << Imag->getType()
6525            << Real->getSourceRange() << Imag->getSourceRange();
6526   }
6527 
6528   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6529   // don't allow this builtin to form those types either.
6530   // FIXME: Should we allow these types?
6531   if (Real->getType()->isFloat16Type())
6532     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6533            << "_Float16";
6534   if (Real->getType()->isHalfType())
6535     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6536            << "half";
6537 
6538   TheCall->setType(Context.getComplexType(Real->getType()));
6539   return false;
6540 }
6541 
6542 // Customized Sema Checking for VSX builtins that have the following signature:
6543 // vector [...] builtinName(vector [...], vector [...], const int);
6544 // Which takes the same type of vectors (any legal vector type) for the first
6545 // two arguments and takes compile time constant for the third argument.
6546 // Example builtins are :
6547 // vector double vec_xxpermdi(vector double, vector double, int);
6548 // vector short vec_xxsldwi(vector short, vector short, int);
6549 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6550   unsigned ExpectedNumArgs = 3;
6551   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6552     return true;
6553 
6554   // Check the third argument is a compile time constant
6555   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6556     return Diag(TheCall->getBeginLoc(),
6557                 diag::err_vsx_builtin_nonconstant_argument)
6558            << 3 /* argument index */ << TheCall->getDirectCallee()
6559            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6560                           TheCall->getArg(2)->getEndLoc());
6561 
6562   QualType Arg1Ty = TheCall->getArg(0)->getType();
6563   QualType Arg2Ty = TheCall->getArg(1)->getType();
6564 
6565   // Check the type of argument 1 and argument 2 are vectors.
6566   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6567   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6568       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6569     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6570            << TheCall->getDirectCallee()
6571            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6572                           TheCall->getArg(1)->getEndLoc());
6573   }
6574 
6575   // Check the first two arguments are the same type.
6576   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6577     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6578            << TheCall->getDirectCallee()
6579            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6580                           TheCall->getArg(1)->getEndLoc());
6581   }
6582 
6583   // When default clang type checking is turned off and the customized type
6584   // checking is used, the returning type of the function must be explicitly
6585   // set. Otherwise it is _Bool by default.
6586   TheCall->setType(Arg1Ty);
6587 
6588   return false;
6589 }
6590 
6591 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6592 // This is declared to take (...), so we have to check everything.
6593 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6594   if (TheCall->getNumArgs() < 2)
6595     return ExprError(Diag(TheCall->getEndLoc(),
6596                           diag::err_typecheck_call_too_few_args_at_least)
6597                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6598                      << TheCall->getSourceRange());
6599 
6600   // Determine which of the following types of shufflevector we're checking:
6601   // 1) unary, vector mask: (lhs, mask)
6602   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6603   QualType resType = TheCall->getArg(0)->getType();
6604   unsigned numElements = 0;
6605 
6606   if (!TheCall->getArg(0)->isTypeDependent() &&
6607       !TheCall->getArg(1)->isTypeDependent()) {
6608     QualType LHSType = TheCall->getArg(0)->getType();
6609     QualType RHSType = TheCall->getArg(1)->getType();
6610 
6611     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6612       return ExprError(
6613           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6614           << TheCall->getDirectCallee()
6615           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6616                          TheCall->getArg(1)->getEndLoc()));
6617 
6618     numElements = LHSType->castAs<VectorType>()->getNumElements();
6619     unsigned numResElements = TheCall->getNumArgs() - 2;
6620 
6621     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6622     // with mask.  If so, verify that RHS is an integer vector type with the
6623     // same number of elts as lhs.
6624     if (TheCall->getNumArgs() == 2) {
6625       if (!RHSType->hasIntegerRepresentation() ||
6626           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6627         return ExprError(Diag(TheCall->getBeginLoc(),
6628                               diag::err_vec_builtin_incompatible_vector)
6629                          << TheCall->getDirectCallee()
6630                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6631                                         TheCall->getArg(1)->getEndLoc()));
6632     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6633       return ExprError(Diag(TheCall->getBeginLoc(),
6634                             diag::err_vec_builtin_incompatible_vector)
6635                        << TheCall->getDirectCallee()
6636                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6637                                       TheCall->getArg(1)->getEndLoc()));
6638     } else if (numElements != numResElements) {
6639       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6640       resType = Context.getVectorType(eltType, numResElements,
6641                                       VectorType::GenericVector);
6642     }
6643   }
6644 
6645   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6646     if (TheCall->getArg(i)->isTypeDependent() ||
6647         TheCall->getArg(i)->isValueDependent())
6648       continue;
6649 
6650     Optional<llvm::APSInt> Result;
6651     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6652       return ExprError(Diag(TheCall->getBeginLoc(),
6653                             diag::err_shufflevector_nonconstant_argument)
6654                        << TheCall->getArg(i)->getSourceRange());
6655 
6656     // Allow -1 which will be translated to undef in the IR.
6657     if (Result->isSigned() && Result->isAllOnes())
6658       continue;
6659 
6660     if (Result->getActiveBits() > 64 ||
6661         Result->getZExtValue() >= numElements * 2)
6662       return ExprError(Diag(TheCall->getBeginLoc(),
6663                             diag::err_shufflevector_argument_too_large)
6664                        << TheCall->getArg(i)->getSourceRange());
6665   }
6666 
6667   SmallVector<Expr*, 32> exprs;
6668 
6669   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6670     exprs.push_back(TheCall->getArg(i));
6671     TheCall->setArg(i, nullptr);
6672   }
6673 
6674   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6675                                          TheCall->getCallee()->getBeginLoc(),
6676                                          TheCall->getRParenLoc());
6677 }
6678 
6679 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6680 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6681                                        SourceLocation BuiltinLoc,
6682                                        SourceLocation RParenLoc) {
6683   ExprValueKind VK = VK_PRValue;
6684   ExprObjectKind OK = OK_Ordinary;
6685   QualType DstTy = TInfo->getType();
6686   QualType SrcTy = E->getType();
6687 
6688   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6689     return ExprError(Diag(BuiltinLoc,
6690                           diag::err_convertvector_non_vector)
6691                      << E->getSourceRange());
6692   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6693     return ExprError(Diag(BuiltinLoc,
6694                           diag::err_convertvector_non_vector_type));
6695 
6696   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6697     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6698     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6699     if (SrcElts != DstElts)
6700       return ExprError(Diag(BuiltinLoc,
6701                             diag::err_convertvector_incompatible_vector)
6702                        << E->getSourceRange());
6703   }
6704 
6705   return new (Context)
6706       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6707 }
6708 
6709 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6710 // This is declared to take (const void*, ...) and can take two
6711 // optional constant int args.
6712 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6713   unsigned NumArgs = TheCall->getNumArgs();
6714 
6715   if (NumArgs > 3)
6716     return Diag(TheCall->getEndLoc(),
6717                 diag::err_typecheck_call_too_many_args_at_most)
6718            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6719 
6720   // Argument 0 is checked for us and the remaining arguments must be
6721   // constant integers.
6722   for (unsigned i = 1; i != NumArgs; ++i)
6723     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6724       return true;
6725 
6726   return false;
6727 }
6728 
6729 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6730 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6731   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6732     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6733            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6734   if (checkArgCount(*this, TheCall, 1))
6735     return true;
6736   Expr *Arg = TheCall->getArg(0);
6737   if (Arg->isInstantiationDependent())
6738     return false;
6739 
6740   QualType ArgTy = Arg->getType();
6741   if (!ArgTy->hasFloatingRepresentation())
6742     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6743            << ArgTy;
6744   if (Arg->isLValue()) {
6745     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6746     TheCall->setArg(0, FirstArg.get());
6747   }
6748   TheCall->setType(TheCall->getArg(0)->getType());
6749   return false;
6750 }
6751 
6752 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6753 // __assume does not evaluate its arguments, and should warn if its argument
6754 // has side effects.
6755 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6756   Expr *Arg = TheCall->getArg(0);
6757   if (Arg->isInstantiationDependent()) return false;
6758 
6759   if (Arg->HasSideEffects(Context))
6760     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6761         << Arg->getSourceRange()
6762         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6763 
6764   return false;
6765 }
6766 
6767 /// Handle __builtin_alloca_with_align. This is declared
6768 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6769 /// than 8.
6770 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6771   // The alignment must be a constant integer.
6772   Expr *Arg = TheCall->getArg(1);
6773 
6774   // We can't check the value of a dependent argument.
6775   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6776     if (const auto *UE =
6777             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6778       if (UE->getKind() == UETT_AlignOf ||
6779           UE->getKind() == UETT_PreferredAlignOf)
6780         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6781             << Arg->getSourceRange();
6782 
6783     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6784 
6785     if (!Result.isPowerOf2())
6786       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6787              << Arg->getSourceRange();
6788 
6789     if (Result < Context.getCharWidth())
6790       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6791              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6792 
6793     if (Result > std::numeric_limits<int32_t>::max())
6794       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6795              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6796   }
6797 
6798   return false;
6799 }
6800 
6801 /// Handle __builtin_assume_aligned. This is declared
6802 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6803 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6804   unsigned NumArgs = TheCall->getNumArgs();
6805 
6806   if (NumArgs > 3)
6807     return Diag(TheCall->getEndLoc(),
6808                 diag::err_typecheck_call_too_many_args_at_most)
6809            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6810 
6811   // The alignment must be a constant integer.
6812   Expr *Arg = TheCall->getArg(1);
6813 
6814   // We can't check the value of a dependent argument.
6815   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6816     llvm::APSInt Result;
6817     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6818       return true;
6819 
6820     if (!Result.isPowerOf2())
6821       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6822              << Arg->getSourceRange();
6823 
6824     if (Result > Sema::MaximumAlignment)
6825       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6826           << Arg->getSourceRange() << Sema::MaximumAlignment;
6827   }
6828 
6829   if (NumArgs > 2) {
6830     ExprResult Arg(TheCall->getArg(2));
6831     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6832       Context.getSizeType(), false);
6833     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6834     if (Arg.isInvalid()) return true;
6835     TheCall->setArg(2, Arg.get());
6836   }
6837 
6838   return false;
6839 }
6840 
6841 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6842   unsigned BuiltinID =
6843       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6844   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6845 
6846   unsigned NumArgs = TheCall->getNumArgs();
6847   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6848   if (NumArgs < NumRequiredArgs) {
6849     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6850            << 0 /* function call */ << NumRequiredArgs << NumArgs
6851            << TheCall->getSourceRange();
6852   }
6853   if (NumArgs >= NumRequiredArgs + 0x100) {
6854     return Diag(TheCall->getEndLoc(),
6855                 diag::err_typecheck_call_too_many_args_at_most)
6856            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6857            << TheCall->getSourceRange();
6858   }
6859   unsigned i = 0;
6860 
6861   // For formatting call, check buffer arg.
6862   if (!IsSizeCall) {
6863     ExprResult Arg(TheCall->getArg(i));
6864     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6865         Context, Context.VoidPtrTy, false);
6866     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6867     if (Arg.isInvalid())
6868       return true;
6869     TheCall->setArg(i, Arg.get());
6870     i++;
6871   }
6872 
6873   // Check string literal arg.
6874   unsigned FormatIdx = i;
6875   {
6876     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6877     if (Arg.isInvalid())
6878       return true;
6879     TheCall->setArg(i, Arg.get());
6880     i++;
6881   }
6882 
6883   // Make sure variadic args are scalar.
6884   unsigned FirstDataArg = i;
6885   while (i < NumArgs) {
6886     ExprResult Arg = DefaultVariadicArgumentPromotion(
6887         TheCall->getArg(i), VariadicFunction, nullptr);
6888     if (Arg.isInvalid())
6889       return true;
6890     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6891     if (ArgSize.getQuantity() >= 0x100) {
6892       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6893              << i << (int)ArgSize.getQuantity() << 0xff
6894              << TheCall->getSourceRange();
6895     }
6896     TheCall->setArg(i, Arg.get());
6897     i++;
6898   }
6899 
6900   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6901   // call to avoid duplicate diagnostics.
6902   if (!IsSizeCall) {
6903     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6904     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6905     bool Success = CheckFormatArguments(
6906         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6907         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6908         CheckedVarArgs);
6909     if (!Success)
6910       return true;
6911   }
6912 
6913   if (IsSizeCall) {
6914     TheCall->setType(Context.getSizeType());
6915   } else {
6916     TheCall->setType(Context.VoidPtrTy);
6917   }
6918   return false;
6919 }
6920 
6921 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6922 /// TheCall is a constant expression.
6923 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6924                                   llvm::APSInt &Result) {
6925   Expr *Arg = TheCall->getArg(ArgNum);
6926   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6927   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6928 
6929   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6930 
6931   Optional<llvm::APSInt> R;
6932   if (!(R = Arg->getIntegerConstantExpr(Context)))
6933     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6934            << FDecl->getDeclName() << Arg->getSourceRange();
6935   Result = *R;
6936   return false;
6937 }
6938 
6939 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6940 /// TheCall is a constant expression in the range [Low, High].
6941 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6942                                        int Low, int High, bool RangeIsError) {
6943   if (isConstantEvaluated())
6944     return false;
6945   llvm::APSInt Result;
6946 
6947   // We can't check the value of a dependent argument.
6948   Expr *Arg = TheCall->getArg(ArgNum);
6949   if (Arg->isTypeDependent() || Arg->isValueDependent())
6950     return false;
6951 
6952   // Check constant-ness first.
6953   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6954     return true;
6955 
6956   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6957     if (RangeIsError)
6958       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6959              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6960     else
6961       // Defer the warning until we know if the code will be emitted so that
6962       // dead code can ignore this.
6963       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6964                           PDiag(diag::warn_argument_invalid_range)
6965                               << toString(Result, 10) << Low << High
6966                               << Arg->getSourceRange());
6967   }
6968 
6969   return false;
6970 }
6971 
6972 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6973 /// TheCall is a constant expression is a multiple of Num..
6974 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6975                                           unsigned Num) {
6976   llvm::APSInt Result;
6977 
6978   // We can't check the value of a dependent argument.
6979   Expr *Arg = TheCall->getArg(ArgNum);
6980   if (Arg->isTypeDependent() || Arg->isValueDependent())
6981     return false;
6982 
6983   // Check constant-ness first.
6984   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6985     return true;
6986 
6987   if (Result.getSExtValue() % Num != 0)
6988     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6989            << Num << Arg->getSourceRange();
6990 
6991   return false;
6992 }
6993 
6994 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6995 /// constant expression representing a power of 2.
6996 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6997   llvm::APSInt Result;
6998 
6999   // We can't check the value of a dependent argument.
7000   Expr *Arg = TheCall->getArg(ArgNum);
7001   if (Arg->isTypeDependent() || Arg->isValueDependent())
7002     return false;
7003 
7004   // Check constant-ness first.
7005   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7006     return true;
7007 
7008   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7009   // and only if x is a power of 2.
7010   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7011     return false;
7012 
7013   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7014          << Arg->getSourceRange();
7015 }
7016 
7017 static bool IsShiftedByte(llvm::APSInt Value) {
7018   if (Value.isNegative())
7019     return false;
7020 
7021   // Check if it's a shifted byte, by shifting it down
7022   while (true) {
7023     // If the value fits in the bottom byte, the check passes.
7024     if (Value < 0x100)
7025       return true;
7026 
7027     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7028     // fails.
7029     if ((Value & 0xFF) != 0)
7030       return false;
7031 
7032     // If the bottom 8 bits are all 0, but something above that is nonzero,
7033     // then shifting the value right by 8 bits won't affect whether it's a
7034     // shifted byte or not. So do that, and go round again.
7035     Value >>= 8;
7036   }
7037 }
7038 
7039 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7040 /// a constant expression representing an arbitrary byte value shifted left by
7041 /// a multiple of 8 bits.
7042 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7043                                              unsigned ArgBits) {
7044   llvm::APSInt Result;
7045 
7046   // We can't check the value of a dependent argument.
7047   Expr *Arg = TheCall->getArg(ArgNum);
7048   if (Arg->isTypeDependent() || Arg->isValueDependent())
7049     return false;
7050 
7051   // Check constant-ness first.
7052   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7053     return true;
7054 
7055   // Truncate to the given size.
7056   Result = Result.getLoBits(ArgBits);
7057   Result.setIsUnsigned(true);
7058 
7059   if (IsShiftedByte(Result))
7060     return false;
7061 
7062   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7063          << Arg->getSourceRange();
7064 }
7065 
7066 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7067 /// TheCall is a constant expression representing either a shifted byte value,
7068 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7069 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7070 /// Arm MVE intrinsics.
7071 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7072                                                    int ArgNum,
7073                                                    unsigned ArgBits) {
7074   llvm::APSInt Result;
7075 
7076   // We can't check the value of a dependent argument.
7077   Expr *Arg = TheCall->getArg(ArgNum);
7078   if (Arg->isTypeDependent() || Arg->isValueDependent())
7079     return false;
7080 
7081   // Check constant-ness first.
7082   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7083     return true;
7084 
7085   // Truncate to the given size.
7086   Result = Result.getLoBits(ArgBits);
7087   Result.setIsUnsigned(true);
7088 
7089   // Check to see if it's in either of the required forms.
7090   if (IsShiftedByte(Result) ||
7091       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7092     return false;
7093 
7094   return Diag(TheCall->getBeginLoc(),
7095               diag::err_argument_not_shifted_byte_or_xxff)
7096          << Arg->getSourceRange();
7097 }
7098 
7099 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7100 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7101   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7102     if (checkArgCount(*this, TheCall, 2))
7103       return true;
7104     Expr *Arg0 = TheCall->getArg(0);
7105     Expr *Arg1 = TheCall->getArg(1);
7106 
7107     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7108     if (FirstArg.isInvalid())
7109       return true;
7110     QualType FirstArgType = FirstArg.get()->getType();
7111     if (!FirstArgType->isAnyPointerType())
7112       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7113                << "first" << FirstArgType << Arg0->getSourceRange();
7114     TheCall->setArg(0, FirstArg.get());
7115 
7116     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7117     if (SecArg.isInvalid())
7118       return true;
7119     QualType SecArgType = SecArg.get()->getType();
7120     if (!SecArgType->isIntegerType())
7121       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7122                << "second" << SecArgType << Arg1->getSourceRange();
7123 
7124     // Derive the return type from the pointer argument.
7125     TheCall->setType(FirstArgType);
7126     return false;
7127   }
7128 
7129   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7130     if (checkArgCount(*this, TheCall, 2))
7131       return true;
7132 
7133     Expr *Arg0 = TheCall->getArg(0);
7134     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7135     if (FirstArg.isInvalid())
7136       return true;
7137     QualType FirstArgType = FirstArg.get()->getType();
7138     if (!FirstArgType->isAnyPointerType())
7139       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7140                << "first" << FirstArgType << Arg0->getSourceRange();
7141     TheCall->setArg(0, FirstArg.get());
7142 
7143     // Derive the return type from the pointer argument.
7144     TheCall->setType(FirstArgType);
7145 
7146     // Second arg must be an constant in range [0,15]
7147     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7148   }
7149 
7150   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7151     if (checkArgCount(*this, TheCall, 2))
7152       return true;
7153     Expr *Arg0 = TheCall->getArg(0);
7154     Expr *Arg1 = TheCall->getArg(1);
7155 
7156     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7157     if (FirstArg.isInvalid())
7158       return true;
7159     QualType FirstArgType = FirstArg.get()->getType();
7160     if (!FirstArgType->isAnyPointerType())
7161       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7162                << "first" << FirstArgType << Arg0->getSourceRange();
7163 
7164     QualType SecArgType = Arg1->getType();
7165     if (!SecArgType->isIntegerType())
7166       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7167                << "second" << SecArgType << Arg1->getSourceRange();
7168     TheCall->setType(Context.IntTy);
7169     return false;
7170   }
7171 
7172   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7173       BuiltinID == AArch64::BI__builtin_arm_stg) {
7174     if (checkArgCount(*this, TheCall, 1))
7175       return true;
7176     Expr *Arg0 = TheCall->getArg(0);
7177     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7178     if (FirstArg.isInvalid())
7179       return true;
7180 
7181     QualType FirstArgType = FirstArg.get()->getType();
7182     if (!FirstArgType->isAnyPointerType())
7183       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7184                << "first" << FirstArgType << Arg0->getSourceRange();
7185     TheCall->setArg(0, FirstArg.get());
7186 
7187     // Derive the return type from the pointer argument.
7188     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7189       TheCall->setType(FirstArgType);
7190     return false;
7191   }
7192 
7193   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7194     Expr *ArgA = TheCall->getArg(0);
7195     Expr *ArgB = TheCall->getArg(1);
7196 
7197     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7198     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7199 
7200     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7201       return true;
7202 
7203     QualType ArgTypeA = ArgExprA.get()->getType();
7204     QualType ArgTypeB = ArgExprB.get()->getType();
7205 
7206     auto isNull = [&] (Expr *E) -> bool {
7207       return E->isNullPointerConstant(
7208                         Context, Expr::NPC_ValueDependentIsNotNull); };
7209 
7210     // argument should be either a pointer or null
7211     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7212       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7213         << "first" << ArgTypeA << ArgA->getSourceRange();
7214 
7215     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7216       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7217         << "second" << ArgTypeB << ArgB->getSourceRange();
7218 
7219     // Ensure Pointee types are compatible
7220     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7221         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7222       QualType pointeeA = ArgTypeA->getPointeeType();
7223       QualType pointeeB = ArgTypeB->getPointeeType();
7224       if (!Context.typesAreCompatible(
7225              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7226              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7227         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7228           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7229           << ArgB->getSourceRange();
7230       }
7231     }
7232 
7233     // at least one argument should be pointer type
7234     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7235       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7236         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7237 
7238     if (isNull(ArgA)) // adopt type of the other pointer
7239       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7240 
7241     if (isNull(ArgB))
7242       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7243 
7244     TheCall->setArg(0, ArgExprA.get());
7245     TheCall->setArg(1, ArgExprB.get());
7246     TheCall->setType(Context.LongLongTy);
7247     return false;
7248   }
7249   assert(false && "Unhandled ARM MTE intrinsic");
7250   return true;
7251 }
7252 
7253 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7254 /// TheCall is an ARM/AArch64 special register string literal.
7255 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7256                                     int ArgNum, unsigned ExpectedFieldNum,
7257                                     bool AllowName) {
7258   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7259                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7260                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7261                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7262                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7263                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7264   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7265                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7266                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7267                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7268                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7269                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7270   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7271 
7272   // We can't check the value of a dependent argument.
7273   Expr *Arg = TheCall->getArg(ArgNum);
7274   if (Arg->isTypeDependent() || Arg->isValueDependent())
7275     return false;
7276 
7277   // Check if the argument is a string literal.
7278   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7279     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7280            << Arg->getSourceRange();
7281 
7282   // Check the type of special register given.
7283   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7284   SmallVector<StringRef, 6> Fields;
7285   Reg.split(Fields, ":");
7286 
7287   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7288     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7289            << Arg->getSourceRange();
7290 
7291   // If the string is the name of a register then we cannot check that it is
7292   // valid here but if the string is of one the forms described in ACLE then we
7293   // can check that the supplied fields are integers and within the valid
7294   // ranges.
7295   if (Fields.size() > 1) {
7296     bool FiveFields = Fields.size() == 5;
7297 
7298     bool ValidString = true;
7299     if (IsARMBuiltin) {
7300       ValidString &= Fields[0].startswith_insensitive("cp") ||
7301                      Fields[0].startswith_insensitive("p");
7302       if (ValidString)
7303         Fields[0] = Fields[0].drop_front(
7304             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7305 
7306       ValidString &= Fields[2].startswith_insensitive("c");
7307       if (ValidString)
7308         Fields[2] = Fields[2].drop_front(1);
7309 
7310       if (FiveFields) {
7311         ValidString &= Fields[3].startswith_insensitive("c");
7312         if (ValidString)
7313           Fields[3] = Fields[3].drop_front(1);
7314       }
7315     }
7316 
7317     SmallVector<int, 5> Ranges;
7318     if (FiveFields)
7319       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7320     else
7321       Ranges.append({15, 7, 15});
7322 
7323     for (unsigned i=0; i<Fields.size(); ++i) {
7324       int IntField;
7325       ValidString &= !Fields[i].getAsInteger(10, IntField);
7326       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7327     }
7328 
7329     if (!ValidString)
7330       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7331              << Arg->getSourceRange();
7332   } else if (IsAArch64Builtin && Fields.size() == 1) {
7333     // If the register name is one of those that appear in the condition below
7334     // and the special register builtin being used is one of the write builtins,
7335     // then we require that the argument provided for writing to the register
7336     // is an integer constant expression. This is because it will be lowered to
7337     // an MSR (immediate) instruction, so we need to know the immediate at
7338     // compile time.
7339     if (TheCall->getNumArgs() != 2)
7340       return false;
7341 
7342     std::string RegLower = Reg.lower();
7343     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7344         RegLower != "pan" && RegLower != "uao")
7345       return false;
7346 
7347     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7348   }
7349 
7350   return false;
7351 }
7352 
7353 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7354 /// Emit an error and return true on failure; return false on success.
7355 /// TypeStr is a string containing the type descriptor of the value returned by
7356 /// the builtin and the descriptors of the expected type of the arguments.
7357 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7358                                  const char *TypeStr) {
7359 
7360   assert((TypeStr[0] != '\0') &&
7361          "Invalid types in PPC MMA builtin declaration");
7362 
7363   switch (BuiltinID) {
7364   default:
7365     // This function is called in CheckPPCBuiltinFunctionCall where the
7366     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7367     // we are isolating the pair vector memop builtins that can be used with mma
7368     // off so the default case is every builtin that requires mma and paired
7369     // vector memops.
7370     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7371                          diag::err_ppc_builtin_only_on_arch, "10") ||
7372         SemaFeatureCheck(*this, TheCall, "mma",
7373                          diag::err_ppc_builtin_only_on_arch, "10"))
7374       return true;
7375     break;
7376   case PPC::BI__builtin_vsx_lxvp:
7377   case PPC::BI__builtin_vsx_stxvp:
7378   case PPC::BI__builtin_vsx_assemble_pair:
7379   case PPC::BI__builtin_vsx_disassemble_pair:
7380     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7381                          diag::err_ppc_builtin_only_on_arch, "10"))
7382       return true;
7383     break;
7384   }
7385 
7386   unsigned Mask = 0;
7387   unsigned ArgNum = 0;
7388 
7389   // The first type in TypeStr is the type of the value returned by the
7390   // builtin. So we first read that type and change the type of TheCall.
7391   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7392   TheCall->setType(type);
7393 
7394   while (*TypeStr != '\0') {
7395     Mask = 0;
7396     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7397     if (ArgNum >= TheCall->getNumArgs()) {
7398       ArgNum++;
7399       break;
7400     }
7401 
7402     Expr *Arg = TheCall->getArg(ArgNum);
7403     QualType PassedType = Arg->getType();
7404     QualType StrippedRVType = PassedType.getCanonicalType();
7405 
7406     // Strip Restrict/Volatile qualifiers.
7407     if (StrippedRVType.isRestrictQualified() ||
7408         StrippedRVType.isVolatileQualified())
7409       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7410 
7411     // The only case where the argument type and expected type are allowed to
7412     // mismatch is if the argument type is a non-void pointer and expected type
7413     // is a void pointer.
7414     if (StrippedRVType != ExpectedType)
7415       if (!(ExpectedType->isVoidPointerType() &&
7416             StrippedRVType->isPointerType()))
7417         return Diag(Arg->getBeginLoc(),
7418                     diag::err_typecheck_convert_incompatible)
7419                << PassedType << ExpectedType << 1 << 0 << 0;
7420 
7421     // If the value of the Mask is not 0, we have a constraint in the size of
7422     // the integer argument so here we ensure the argument is a constant that
7423     // is in the valid range.
7424     if (Mask != 0 &&
7425         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7426       return true;
7427 
7428     ArgNum++;
7429   }
7430 
7431   // In case we exited early from the previous loop, there are other types to
7432   // read from TypeStr. So we need to read them all to ensure we have the right
7433   // number of arguments in TheCall and if it is not the case, to display a
7434   // better error message.
7435   while (*TypeStr != '\0') {
7436     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7437     ArgNum++;
7438   }
7439   if (checkArgCount(*this, TheCall, ArgNum))
7440     return true;
7441 
7442   return false;
7443 }
7444 
7445 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7446 /// This checks that the target supports __builtin_longjmp and
7447 /// that val is a constant 1.
7448 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7449   if (!Context.getTargetInfo().hasSjLjLowering())
7450     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7451            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7452 
7453   Expr *Arg = TheCall->getArg(1);
7454   llvm::APSInt Result;
7455 
7456   // TODO: This is less than ideal. Overload this to take a value.
7457   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7458     return true;
7459 
7460   if (Result != 1)
7461     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7462            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7463 
7464   return false;
7465 }
7466 
7467 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7468 /// This checks that the target supports __builtin_setjmp.
7469 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7470   if (!Context.getTargetInfo().hasSjLjLowering())
7471     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7472            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7473   return false;
7474 }
7475 
7476 namespace {
7477 
7478 class UncoveredArgHandler {
7479   enum { Unknown = -1, AllCovered = -2 };
7480 
7481   signed FirstUncoveredArg = Unknown;
7482   SmallVector<const Expr *, 4> DiagnosticExprs;
7483 
7484 public:
7485   UncoveredArgHandler() = default;
7486 
7487   bool hasUncoveredArg() const {
7488     return (FirstUncoveredArg >= 0);
7489   }
7490 
7491   unsigned getUncoveredArg() const {
7492     assert(hasUncoveredArg() && "no uncovered argument");
7493     return FirstUncoveredArg;
7494   }
7495 
7496   void setAllCovered() {
7497     // A string has been found with all arguments covered, so clear out
7498     // the diagnostics.
7499     DiagnosticExprs.clear();
7500     FirstUncoveredArg = AllCovered;
7501   }
7502 
7503   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7504     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7505 
7506     // Don't update if a previous string covers all arguments.
7507     if (FirstUncoveredArg == AllCovered)
7508       return;
7509 
7510     // UncoveredArgHandler tracks the highest uncovered argument index
7511     // and with it all the strings that match this index.
7512     if (NewFirstUncoveredArg == FirstUncoveredArg)
7513       DiagnosticExprs.push_back(StrExpr);
7514     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7515       DiagnosticExprs.clear();
7516       DiagnosticExprs.push_back(StrExpr);
7517       FirstUncoveredArg = NewFirstUncoveredArg;
7518     }
7519   }
7520 
7521   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7522 };
7523 
7524 enum StringLiteralCheckType {
7525   SLCT_NotALiteral,
7526   SLCT_UncheckedLiteral,
7527   SLCT_CheckedLiteral
7528 };
7529 
7530 } // namespace
7531 
7532 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7533                                      BinaryOperatorKind BinOpKind,
7534                                      bool AddendIsRight) {
7535   unsigned BitWidth = Offset.getBitWidth();
7536   unsigned AddendBitWidth = Addend.getBitWidth();
7537   // There might be negative interim results.
7538   if (Addend.isUnsigned()) {
7539     Addend = Addend.zext(++AddendBitWidth);
7540     Addend.setIsSigned(true);
7541   }
7542   // Adjust the bit width of the APSInts.
7543   if (AddendBitWidth > BitWidth) {
7544     Offset = Offset.sext(AddendBitWidth);
7545     BitWidth = AddendBitWidth;
7546   } else if (BitWidth > AddendBitWidth) {
7547     Addend = Addend.sext(BitWidth);
7548   }
7549 
7550   bool Ov = false;
7551   llvm::APSInt ResOffset = Offset;
7552   if (BinOpKind == BO_Add)
7553     ResOffset = Offset.sadd_ov(Addend, Ov);
7554   else {
7555     assert(AddendIsRight && BinOpKind == BO_Sub &&
7556            "operator must be add or sub with addend on the right");
7557     ResOffset = Offset.ssub_ov(Addend, Ov);
7558   }
7559 
7560   // We add an offset to a pointer here so we should support an offset as big as
7561   // possible.
7562   if (Ov) {
7563     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7564            "index (intermediate) result too big");
7565     Offset = Offset.sext(2 * BitWidth);
7566     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7567     return;
7568   }
7569 
7570   Offset = ResOffset;
7571 }
7572 
7573 namespace {
7574 
7575 // This is a wrapper class around StringLiteral to support offsetted string
7576 // literals as format strings. It takes the offset into account when returning
7577 // the string and its length or the source locations to display notes correctly.
7578 class FormatStringLiteral {
7579   const StringLiteral *FExpr;
7580   int64_t Offset;
7581 
7582  public:
7583   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7584       : FExpr(fexpr), Offset(Offset) {}
7585 
7586   StringRef getString() const {
7587     return FExpr->getString().drop_front(Offset);
7588   }
7589 
7590   unsigned getByteLength() const {
7591     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7592   }
7593 
7594   unsigned getLength() const { return FExpr->getLength() - Offset; }
7595   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7596 
7597   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7598 
7599   QualType getType() const { return FExpr->getType(); }
7600 
7601   bool isAscii() const { return FExpr->isAscii(); }
7602   bool isWide() const { return FExpr->isWide(); }
7603   bool isUTF8() const { return FExpr->isUTF8(); }
7604   bool isUTF16() const { return FExpr->isUTF16(); }
7605   bool isUTF32() const { return FExpr->isUTF32(); }
7606   bool isPascal() const { return FExpr->isPascal(); }
7607 
7608   SourceLocation getLocationOfByte(
7609       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7610       const TargetInfo &Target, unsigned *StartToken = nullptr,
7611       unsigned *StartTokenByteOffset = nullptr) const {
7612     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7613                                     StartToken, StartTokenByteOffset);
7614   }
7615 
7616   SourceLocation getBeginLoc() const LLVM_READONLY {
7617     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7618   }
7619 
7620   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7621 };
7622 
7623 }  // namespace
7624 
7625 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7626                               const Expr *OrigFormatExpr,
7627                               ArrayRef<const Expr *> Args,
7628                               bool HasVAListArg, unsigned format_idx,
7629                               unsigned firstDataArg,
7630                               Sema::FormatStringType Type,
7631                               bool inFunctionCall,
7632                               Sema::VariadicCallType CallType,
7633                               llvm::SmallBitVector &CheckedVarArgs,
7634                               UncoveredArgHandler &UncoveredArg,
7635                               bool IgnoreStringsWithoutSpecifiers);
7636 
7637 // Determine if an expression is a string literal or constant string.
7638 // If this function returns false on the arguments to a function expecting a
7639 // format string, we will usually need to emit a warning.
7640 // True string literals are then checked by CheckFormatString.
7641 static StringLiteralCheckType
7642 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7643                       bool HasVAListArg, unsigned format_idx,
7644                       unsigned firstDataArg, Sema::FormatStringType Type,
7645                       Sema::VariadicCallType CallType, bool InFunctionCall,
7646                       llvm::SmallBitVector &CheckedVarArgs,
7647                       UncoveredArgHandler &UncoveredArg,
7648                       llvm::APSInt Offset,
7649                       bool IgnoreStringsWithoutSpecifiers = false) {
7650   if (S.isConstantEvaluated())
7651     return SLCT_NotALiteral;
7652  tryAgain:
7653   assert(Offset.isSigned() && "invalid offset");
7654 
7655   if (E->isTypeDependent() || E->isValueDependent())
7656     return SLCT_NotALiteral;
7657 
7658   E = E->IgnoreParenCasts();
7659 
7660   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7661     // Technically -Wformat-nonliteral does not warn about this case.
7662     // The behavior of printf and friends in this case is implementation
7663     // dependent.  Ideally if the format string cannot be null then
7664     // it should have a 'nonnull' attribute in the function prototype.
7665     return SLCT_UncheckedLiteral;
7666 
7667   switch (E->getStmtClass()) {
7668   case Stmt::BinaryConditionalOperatorClass:
7669   case Stmt::ConditionalOperatorClass: {
7670     // The expression is a literal if both sub-expressions were, and it was
7671     // completely checked only if both sub-expressions were checked.
7672     const AbstractConditionalOperator *C =
7673         cast<AbstractConditionalOperator>(E);
7674 
7675     // Determine whether it is necessary to check both sub-expressions, for
7676     // example, because the condition expression is a constant that can be
7677     // evaluated at compile time.
7678     bool CheckLeft = true, CheckRight = true;
7679 
7680     bool Cond;
7681     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7682                                                  S.isConstantEvaluated())) {
7683       if (Cond)
7684         CheckRight = false;
7685       else
7686         CheckLeft = false;
7687     }
7688 
7689     // We need to maintain the offsets for the right and the left hand side
7690     // separately to check if every possible indexed expression is a valid
7691     // string literal. They might have different offsets for different string
7692     // literals in the end.
7693     StringLiteralCheckType Left;
7694     if (!CheckLeft)
7695       Left = SLCT_UncheckedLiteral;
7696     else {
7697       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7698                                    HasVAListArg, format_idx, firstDataArg,
7699                                    Type, CallType, InFunctionCall,
7700                                    CheckedVarArgs, UncoveredArg, Offset,
7701                                    IgnoreStringsWithoutSpecifiers);
7702       if (Left == SLCT_NotALiteral || !CheckRight) {
7703         return Left;
7704       }
7705     }
7706 
7707     StringLiteralCheckType Right = checkFormatStringExpr(
7708         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7709         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7710         IgnoreStringsWithoutSpecifiers);
7711 
7712     return (CheckLeft && Left < Right) ? Left : Right;
7713   }
7714 
7715   case Stmt::ImplicitCastExprClass:
7716     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7717     goto tryAgain;
7718 
7719   case Stmt::OpaqueValueExprClass:
7720     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7721       E = src;
7722       goto tryAgain;
7723     }
7724     return SLCT_NotALiteral;
7725 
7726   case Stmt::PredefinedExprClass:
7727     // While __func__, etc., are technically not string literals, they
7728     // cannot contain format specifiers and thus are not a security
7729     // liability.
7730     return SLCT_UncheckedLiteral;
7731 
7732   case Stmt::DeclRefExprClass: {
7733     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7734 
7735     // As an exception, do not flag errors for variables binding to
7736     // const string literals.
7737     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7738       bool isConstant = false;
7739       QualType T = DR->getType();
7740 
7741       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7742         isConstant = AT->getElementType().isConstant(S.Context);
7743       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7744         isConstant = T.isConstant(S.Context) &&
7745                      PT->getPointeeType().isConstant(S.Context);
7746       } else if (T->isObjCObjectPointerType()) {
7747         // In ObjC, there is usually no "const ObjectPointer" type,
7748         // so don't check if the pointee type is constant.
7749         isConstant = T.isConstant(S.Context);
7750       }
7751 
7752       if (isConstant) {
7753         if (const Expr *Init = VD->getAnyInitializer()) {
7754           // Look through initializers like const char c[] = { "foo" }
7755           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7756             if (InitList->isStringLiteralInit())
7757               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7758           }
7759           return checkFormatStringExpr(S, Init, Args,
7760                                        HasVAListArg, format_idx,
7761                                        firstDataArg, Type, CallType,
7762                                        /*InFunctionCall*/ false, CheckedVarArgs,
7763                                        UncoveredArg, Offset);
7764         }
7765       }
7766 
7767       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7768       // special check to see if the format string is a function parameter
7769       // of the function calling the printf function.  If the function
7770       // has an attribute indicating it is a printf-like function, then we
7771       // should suppress warnings concerning non-literals being used in a call
7772       // to a vprintf function.  For example:
7773       //
7774       // void
7775       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7776       //      va_list ap;
7777       //      va_start(ap, fmt);
7778       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7779       //      ...
7780       // }
7781       if (HasVAListArg) {
7782         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7783           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7784             int PVIndex = PV->getFunctionScopeIndex() + 1;
7785             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7786               // adjust for implicit parameter
7787               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7788                 if (MD->isInstance())
7789                   ++PVIndex;
7790               // We also check if the formats are compatible.
7791               // We can't pass a 'scanf' string to a 'printf' function.
7792               if (PVIndex == PVFormat->getFormatIdx() &&
7793                   Type == S.GetFormatStringType(PVFormat))
7794                 return SLCT_UncheckedLiteral;
7795             }
7796           }
7797         }
7798       }
7799     }
7800 
7801     return SLCT_NotALiteral;
7802   }
7803 
7804   case Stmt::CallExprClass:
7805   case Stmt::CXXMemberCallExprClass: {
7806     const CallExpr *CE = cast<CallExpr>(E);
7807     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7808       bool IsFirst = true;
7809       StringLiteralCheckType CommonResult;
7810       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7811         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7812         StringLiteralCheckType Result = checkFormatStringExpr(
7813             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7814             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7815             IgnoreStringsWithoutSpecifiers);
7816         if (IsFirst) {
7817           CommonResult = Result;
7818           IsFirst = false;
7819         }
7820       }
7821       if (!IsFirst)
7822         return CommonResult;
7823 
7824       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7825         unsigned BuiltinID = FD->getBuiltinID();
7826         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7827             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7828           const Expr *Arg = CE->getArg(0);
7829           return checkFormatStringExpr(S, Arg, Args,
7830                                        HasVAListArg, format_idx,
7831                                        firstDataArg, Type, CallType,
7832                                        InFunctionCall, CheckedVarArgs,
7833                                        UncoveredArg, Offset,
7834                                        IgnoreStringsWithoutSpecifiers);
7835         }
7836       }
7837     }
7838 
7839     return SLCT_NotALiteral;
7840   }
7841   case Stmt::ObjCMessageExprClass: {
7842     const auto *ME = cast<ObjCMessageExpr>(E);
7843     if (const auto *MD = ME->getMethodDecl()) {
7844       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7845         // As a special case heuristic, if we're using the method -[NSBundle
7846         // localizedStringForKey:value:table:], ignore any key strings that lack
7847         // format specifiers. The idea is that if the key doesn't have any
7848         // format specifiers then its probably just a key to map to the
7849         // localized strings. If it does have format specifiers though, then its
7850         // likely that the text of the key is the format string in the
7851         // programmer's language, and should be checked.
7852         const ObjCInterfaceDecl *IFace;
7853         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7854             IFace->getIdentifier()->isStr("NSBundle") &&
7855             MD->getSelector().isKeywordSelector(
7856                 {"localizedStringForKey", "value", "table"})) {
7857           IgnoreStringsWithoutSpecifiers = true;
7858         }
7859 
7860         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7861         return checkFormatStringExpr(
7862             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7863             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7864             IgnoreStringsWithoutSpecifiers);
7865       }
7866     }
7867 
7868     return SLCT_NotALiteral;
7869   }
7870   case Stmt::ObjCStringLiteralClass:
7871   case Stmt::StringLiteralClass: {
7872     const StringLiteral *StrE = nullptr;
7873 
7874     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7875       StrE = ObjCFExpr->getString();
7876     else
7877       StrE = cast<StringLiteral>(E);
7878 
7879     if (StrE) {
7880       if (Offset.isNegative() || Offset > StrE->getLength()) {
7881         // TODO: It would be better to have an explicit warning for out of
7882         // bounds literals.
7883         return SLCT_NotALiteral;
7884       }
7885       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7886       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7887                         firstDataArg, Type, InFunctionCall, CallType,
7888                         CheckedVarArgs, UncoveredArg,
7889                         IgnoreStringsWithoutSpecifiers);
7890       return SLCT_CheckedLiteral;
7891     }
7892 
7893     return SLCT_NotALiteral;
7894   }
7895   case Stmt::BinaryOperatorClass: {
7896     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7897 
7898     // A string literal + an int offset is still a string literal.
7899     if (BinOp->isAdditiveOp()) {
7900       Expr::EvalResult LResult, RResult;
7901 
7902       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7903           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7904       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7905           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7906 
7907       if (LIsInt != RIsInt) {
7908         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7909 
7910         if (LIsInt) {
7911           if (BinOpKind == BO_Add) {
7912             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7913             E = BinOp->getRHS();
7914             goto tryAgain;
7915           }
7916         } else {
7917           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7918           E = BinOp->getLHS();
7919           goto tryAgain;
7920         }
7921       }
7922     }
7923 
7924     return SLCT_NotALiteral;
7925   }
7926   case Stmt::UnaryOperatorClass: {
7927     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7928     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7929     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7930       Expr::EvalResult IndexResult;
7931       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7932                                        Expr::SE_NoSideEffects,
7933                                        S.isConstantEvaluated())) {
7934         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7935                    /*RHS is int*/ true);
7936         E = ASE->getBase();
7937         goto tryAgain;
7938       }
7939     }
7940 
7941     return SLCT_NotALiteral;
7942   }
7943 
7944   default:
7945     return SLCT_NotALiteral;
7946   }
7947 }
7948 
7949 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7950   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7951       .Case("scanf", FST_Scanf)
7952       .Cases("printf", "printf0", FST_Printf)
7953       .Cases("NSString", "CFString", FST_NSString)
7954       .Case("strftime", FST_Strftime)
7955       .Case("strfmon", FST_Strfmon)
7956       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7957       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7958       .Case("os_trace", FST_OSLog)
7959       .Case("os_log", FST_OSLog)
7960       .Default(FST_Unknown);
7961 }
7962 
7963 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7964 /// functions) for correct use of format strings.
7965 /// Returns true if a format string has been fully checked.
7966 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7967                                 ArrayRef<const Expr *> Args,
7968                                 bool IsCXXMember,
7969                                 VariadicCallType CallType,
7970                                 SourceLocation Loc, SourceRange Range,
7971                                 llvm::SmallBitVector &CheckedVarArgs) {
7972   FormatStringInfo FSI;
7973   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7974     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7975                                 FSI.FirstDataArg, GetFormatStringType(Format),
7976                                 CallType, Loc, Range, CheckedVarArgs);
7977   return false;
7978 }
7979 
7980 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7981                                 bool HasVAListArg, unsigned format_idx,
7982                                 unsigned firstDataArg, FormatStringType Type,
7983                                 VariadicCallType CallType,
7984                                 SourceLocation Loc, SourceRange Range,
7985                                 llvm::SmallBitVector &CheckedVarArgs) {
7986   // CHECK: printf/scanf-like function is called with no format string.
7987   if (format_idx >= Args.size()) {
7988     Diag(Loc, diag::warn_missing_format_string) << Range;
7989     return false;
7990   }
7991 
7992   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7993 
7994   // CHECK: format string is not a string literal.
7995   //
7996   // Dynamically generated format strings are difficult to
7997   // automatically vet at compile time.  Requiring that format strings
7998   // are string literals: (1) permits the checking of format strings by
7999   // the compiler and thereby (2) can practically remove the source of
8000   // many format string exploits.
8001 
8002   // Format string can be either ObjC string (e.g. @"%d") or
8003   // C string (e.g. "%d")
8004   // ObjC string uses the same format specifiers as C string, so we can use
8005   // the same format string checking logic for both ObjC and C strings.
8006   UncoveredArgHandler UncoveredArg;
8007   StringLiteralCheckType CT =
8008       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8009                             format_idx, firstDataArg, Type, CallType,
8010                             /*IsFunctionCall*/ true, CheckedVarArgs,
8011                             UncoveredArg,
8012                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8013 
8014   // Generate a diagnostic where an uncovered argument is detected.
8015   if (UncoveredArg.hasUncoveredArg()) {
8016     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8017     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8018     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8019   }
8020 
8021   if (CT != SLCT_NotALiteral)
8022     // Literal format string found, check done!
8023     return CT == SLCT_CheckedLiteral;
8024 
8025   // Strftime is particular as it always uses a single 'time' argument,
8026   // so it is safe to pass a non-literal string.
8027   if (Type == FST_Strftime)
8028     return false;
8029 
8030   // Do not emit diag when the string param is a macro expansion and the
8031   // format is either NSString or CFString. This is a hack to prevent
8032   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8033   // which are usually used in place of NS and CF string literals.
8034   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8035   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8036     return false;
8037 
8038   // If there are no arguments specified, warn with -Wformat-security, otherwise
8039   // warn only with -Wformat-nonliteral.
8040   if (Args.size() == firstDataArg) {
8041     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8042       << OrigFormatExpr->getSourceRange();
8043     switch (Type) {
8044     default:
8045       break;
8046     case FST_Kprintf:
8047     case FST_FreeBSDKPrintf:
8048     case FST_Printf:
8049       Diag(FormatLoc, diag::note_format_security_fixit)
8050         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8051       break;
8052     case FST_NSString:
8053       Diag(FormatLoc, diag::note_format_security_fixit)
8054         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8055       break;
8056     }
8057   } else {
8058     Diag(FormatLoc, diag::warn_format_nonliteral)
8059       << OrigFormatExpr->getSourceRange();
8060   }
8061   return false;
8062 }
8063 
8064 namespace {
8065 
8066 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8067 protected:
8068   Sema &S;
8069   const FormatStringLiteral *FExpr;
8070   const Expr *OrigFormatExpr;
8071   const Sema::FormatStringType FSType;
8072   const unsigned FirstDataArg;
8073   const unsigned NumDataArgs;
8074   const char *Beg; // Start of format string.
8075   const bool HasVAListArg;
8076   ArrayRef<const Expr *> Args;
8077   unsigned FormatIdx;
8078   llvm::SmallBitVector CoveredArgs;
8079   bool usesPositionalArgs = false;
8080   bool atFirstArg = true;
8081   bool inFunctionCall;
8082   Sema::VariadicCallType CallType;
8083   llvm::SmallBitVector &CheckedVarArgs;
8084   UncoveredArgHandler &UncoveredArg;
8085 
8086 public:
8087   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8088                      const Expr *origFormatExpr,
8089                      const Sema::FormatStringType type, unsigned firstDataArg,
8090                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8091                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8092                      bool inFunctionCall, Sema::VariadicCallType callType,
8093                      llvm::SmallBitVector &CheckedVarArgs,
8094                      UncoveredArgHandler &UncoveredArg)
8095       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8096         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8097         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8098         inFunctionCall(inFunctionCall), CallType(callType),
8099         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8100     CoveredArgs.resize(numDataArgs);
8101     CoveredArgs.reset();
8102   }
8103 
8104   void DoneProcessing();
8105 
8106   void HandleIncompleteSpecifier(const char *startSpecifier,
8107                                  unsigned specifierLen) override;
8108 
8109   void HandleInvalidLengthModifier(
8110                            const analyze_format_string::FormatSpecifier &FS,
8111                            const analyze_format_string::ConversionSpecifier &CS,
8112                            const char *startSpecifier, unsigned specifierLen,
8113                            unsigned DiagID);
8114 
8115   void HandleNonStandardLengthModifier(
8116                     const analyze_format_string::FormatSpecifier &FS,
8117                     const char *startSpecifier, unsigned specifierLen);
8118 
8119   void HandleNonStandardConversionSpecifier(
8120                     const analyze_format_string::ConversionSpecifier &CS,
8121                     const char *startSpecifier, unsigned specifierLen);
8122 
8123   void HandlePosition(const char *startPos, unsigned posLen) override;
8124 
8125   void HandleInvalidPosition(const char *startSpecifier,
8126                              unsigned specifierLen,
8127                              analyze_format_string::PositionContext p) override;
8128 
8129   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8130 
8131   void HandleNullChar(const char *nullCharacter) override;
8132 
8133   template <typename Range>
8134   static void
8135   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8136                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8137                        bool IsStringLocation, Range StringRange,
8138                        ArrayRef<FixItHint> Fixit = None);
8139 
8140 protected:
8141   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8142                                         const char *startSpec,
8143                                         unsigned specifierLen,
8144                                         const char *csStart, unsigned csLen);
8145 
8146   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8147                                          const char *startSpec,
8148                                          unsigned specifierLen);
8149 
8150   SourceRange getFormatStringRange();
8151   CharSourceRange getSpecifierRange(const char *startSpecifier,
8152                                     unsigned specifierLen);
8153   SourceLocation getLocationOfByte(const char *x);
8154 
8155   const Expr *getDataArg(unsigned i) const;
8156 
8157   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8158                     const analyze_format_string::ConversionSpecifier &CS,
8159                     const char *startSpecifier, unsigned specifierLen,
8160                     unsigned argIndex);
8161 
8162   template <typename Range>
8163   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8164                             bool IsStringLocation, Range StringRange,
8165                             ArrayRef<FixItHint> Fixit = None);
8166 };
8167 
8168 } // namespace
8169 
8170 SourceRange CheckFormatHandler::getFormatStringRange() {
8171   return OrigFormatExpr->getSourceRange();
8172 }
8173 
8174 CharSourceRange CheckFormatHandler::
8175 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8176   SourceLocation Start = getLocationOfByte(startSpecifier);
8177   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8178 
8179   // Advance the end SourceLocation by one due to half-open ranges.
8180   End = End.getLocWithOffset(1);
8181 
8182   return CharSourceRange::getCharRange(Start, End);
8183 }
8184 
8185 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8186   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8187                                   S.getLangOpts(), S.Context.getTargetInfo());
8188 }
8189 
8190 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8191                                                    unsigned specifierLen){
8192   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8193                        getLocationOfByte(startSpecifier),
8194                        /*IsStringLocation*/true,
8195                        getSpecifierRange(startSpecifier, specifierLen));
8196 }
8197 
8198 void CheckFormatHandler::HandleInvalidLengthModifier(
8199     const analyze_format_string::FormatSpecifier &FS,
8200     const analyze_format_string::ConversionSpecifier &CS,
8201     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8202   using namespace analyze_format_string;
8203 
8204   const LengthModifier &LM = FS.getLengthModifier();
8205   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8206 
8207   // See if we know how to fix this length modifier.
8208   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8209   if (FixedLM) {
8210     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8211                          getLocationOfByte(LM.getStart()),
8212                          /*IsStringLocation*/true,
8213                          getSpecifierRange(startSpecifier, specifierLen));
8214 
8215     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8216       << FixedLM->toString()
8217       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8218 
8219   } else {
8220     FixItHint Hint;
8221     if (DiagID == diag::warn_format_nonsensical_length)
8222       Hint = FixItHint::CreateRemoval(LMRange);
8223 
8224     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8225                          getLocationOfByte(LM.getStart()),
8226                          /*IsStringLocation*/true,
8227                          getSpecifierRange(startSpecifier, specifierLen),
8228                          Hint);
8229   }
8230 }
8231 
8232 void CheckFormatHandler::HandleNonStandardLengthModifier(
8233     const analyze_format_string::FormatSpecifier &FS,
8234     const char *startSpecifier, unsigned specifierLen) {
8235   using namespace analyze_format_string;
8236 
8237   const LengthModifier &LM = FS.getLengthModifier();
8238   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8239 
8240   // See if we know how to fix this length modifier.
8241   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8242   if (FixedLM) {
8243     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8244                            << LM.toString() << 0,
8245                          getLocationOfByte(LM.getStart()),
8246                          /*IsStringLocation*/true,
8247                          getSpecifierRange(startSpecifier, specifierLen));
8248 
8249     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8250       << FixedLM->toString()
8251       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8252 
8253   } else {
8254     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8255                            << LM.toString() << 0,
8256                          getLocationOfByte(LM.getStart()),
8257                          /*IsStringLocation*/true,
8258                          getSpecifierRange(startSpecifier, specifierLen));
8259   }
8260 }
8261 
8262 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8263     const analyze_format_string::ConversionSpecifier &CS,
8264     const char *startSpecifier, unsigned specifierLen) {
8265   using namespace analyze_format_string;
8266 
8267   // See if we know how to fix this conversion specifier.
8268   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8269   if (FixedCS) {
8270     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8271                           << CS.toString() << /*conversion specifier*/1,
8272                          getLocationOfByte(CS.getStart()),
8273                          /*IsStringLocation*/true,
8274                          getSpecifierRange(startSpecifier, specifierLen));
8275 
8276     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8277     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8278       << FixedCS->toString()
8279       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8280   } else {
8281     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8282                           << CS.toString() << /*conversion specifier*/1,
8283                          getLocationOfByte(CS.getStart()),
8284                          /*IsStringLocation*/true,
8285                          getSpecifierRange(startSpecifier, specifierLen));
8286   }
8287 }
8288 
8289 void CheckFormatHandler::HandlePosition(const char *startPos,
8290                                         unsigned posLen) {
8291   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8292                                getLocationOfByte(startPos),
8293                                /*IsStringLocation*/true,
8294                                getSpecifierRange(startPos, posLen));
8295 }
8296 
8297 void
8298 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8299                                      analyze_format_string::PositionContext p) {
8300   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8301                          << (unsigned) p,
8302                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8303                        getSpecifierRange(startPos, posLen));
8304 }
8305 
8306 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8307                                             unsigned posLen) {
8308   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8309                                getLocationOfByte(startPos),
8310                                /*IsStringLocation*/true,
8311                                getSpecifierRange(startPos, posLen));
8312 }
8313 
8314 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8315   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8316     // The presence of a null character is likely an error.
8317     EmitFormatDiagnostic(
8318       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8319       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8320       getFormatStringRange());
8321   }
8322 }
8323 
8324 // Note that this may return NULL if there was an error parsing or building
8325 // one of the argument expressions.
8326 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8327   return Args[FirstDataArg + i];
8328 }
8329 
8330 void CheckFormatHandler::DoneProcessing() {
8331   // Does the number of data arguments exceed the number of
8332   // format conversions in the format string?
8333   if (!HasVAListArg) {
8334       // Find any arguments that weren't covered.
8335     CoveredArgs.flip();
8336     signed notCoveredArg = CoveredArgs.find_first();
8337     if (notCoveredArg >= 0) {
8338       assert((unsigned)notCoveredArg < NumDataArgs);
8339       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8340     } else {
8341       UncoveredArg.setAllCovered();
8342     }
8343   }
8344 }
8345 
8346 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8347                                    const Expr *ArgExpr) {
8348   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8349          "Invalid state");
8350 
8351   if (!ArgExpr)
8352     return;
8353 
8354   SourceLocation Loc = ArgExpr->getBeginLoc();
8355 
8356   if (S.getSourceManager().isInSystemMacro(Loc))
8357     return;
8358 
8359   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8360   for (auto E : DiagnosticExprs)
8361     PDiag << E->getSourceRange();
8362 
8363   CheckFormatHandler::EmitFormatDiagnostic(
8364                                   S, IsFunctionCall, DiagnosticExprs[0],
8365                                   PDiag, Loc, /*IsStringLocation*/false,
8366                                   DiagnosticExprs[0]->getSourceRange());
8367 }
8368 
8369 bool
8370 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8371                                                      SourceLocation Loc,
8372                                                      const char *startSpec,
8373                                                      unsigned specifierLen,
8374                                                      const char *csStart,
8375                                                      unsigned csLen) {
8376   bool keepGoing = true;
8377   if (argIndex < NumDataArgs) {
8378     // Consider the argument coverered, even though the specifier doesn't
8379     // make sense.
8380     CoveredArgs.set(argIndex);
8381   }
8382   else {
8383     // If argIndex exceeds the number of data arguments we
8384     // don't issue a warning because that is just a cascade of warnings (and
8385     // they may have intended '%%' anyway). We don't want to continue processing
8386     // the format string after this point, however, as we will like just get
8387     // gibberish when trying to match arguments.
8388     keepGoing = false;
8389   }
8390 
8391   StringRef Specifier(csStart, csLen);
8392 
8393   // If the specifier in non-printable, it could be the first byte of a UTF-8
8394   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8395   // hex value.
8396   std::string CodePointStr;
8397   if (!llvm::sys::locale::isPrint(*csStart)) {
8398     llvm::UTF32 CodePoint;
8399     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8400     const llvm::UTF8 *E =
8401         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8402     llvm::ConversionResult Result =
8403         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8404 
8405     if (Result != llvm::conversionOK) {
8406       unsigned char FirstChar = *csStart;
8407       CodePoint = (llvm::UTF32)FirstChar;
8408     }
8409 
8410     llvm::raw_string_ostream OS(CodePointStr);
8411     if (CodePoint < 256)
8412       OS << "\\x" << llvm::format("%02x", CodePoint);
8413     else if (CodePoint <= 0xFFFF)
8414       OS << "\\u" << llvm::format("%04x", CodePoint);
8415     else
8416       OS << "\\U" << llvm::format("%08x", CodePoint);
8417     OS.flush();
8418     Specifier = CodePointStr;
8419   }
8420 
8421   EmitFormatDiagnostic(
8422       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8423       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8424 
8425   return keepGoing;
8426 }
8427 
8428 void
8429 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8430                                                       const char *startSpec,
8431                                                       unsigned specifierLen) {
8432   EmitFormatDiagnostic(
8433     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8434     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8435 }
8436 
8437 bool
8438 CheckFormatHandler::CheckNumArgs(
8439   const analyze_format_string::FormatSpecifier &FS,
8440   const analyze_format_string::ConversionSpecifier &CS,
8441   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8442 
8443   if (argIndex >= NumDataArgs) {
8444     PartialDiagnostic PDiag = FS.usesPositionalArg()
8445       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8446            << (argIndex+1) << NumDataArgs)
8447       : S.PDiag(diag::warn_printf_insufficient_data_args);
8448     EmitFormatDiagnostic(
8449       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8450       getSpecifierRange(startSpecifier, specifierLen));
8451 
8452     // Since more arguments than conversion tokens are given, by extension
8453     // all arguments are covered, so mark this as so.
8454     UncoveredArg.setAllCovered();
8455     return false;
8456   }
8457   return true;
8458 }
8459 
8460 template<typename Range>
8461 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8462                                               SourceLocation Loc,
8463                                               bool IsStringLocation,
8464                                               Range StringRange,
8465                                               ArrayRef<FixItHint> FixIt) {
8466   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8467                        Loc, IsStringLocation, StringRange, FixIt);
8468 }
8469 
8470 /// If the format string is not within the function call, emit a note
8471 /// so that the function call and string are in diagnostic messages.
8472 ///
8473 /// \param InFunctionCall if true, the format string is within the function
8474 /// call and only one diagnostic message will be produced.  Otherwise, an
8475 /// extra note will be emitted pointing to location of the format string.
8476 ///
8477 /// \param ArgumentExpr the expression that is passed as the format string
8478 /// argument in the function call.  Used for getting locations when two
8479 /// diagnostics are emitted.
8480 ///
8481 /// \param PDiag the callee should already have provided any strings for the
8482 /// diagnostic message.  This function only adds locations and fixits
8483 /// to diagnostics.
8484 ///
8485 /// \param Loc primary location for diagnostic.  If two diagnostics are
8486 /// required, one will be at Loc and a new SourceLocation will be created for
8487 /// the other one.
8488 ///
8489 /// \param IsStringLocation if true, Loc points to the format string should be
8490 /// used for the note.  Otherwise, Loc points to the argument list and will
8491 /// be used with PDiag.
8492 ///
8493 /// \param StringRange some or all of the string to highlight.  This is
8494 /// templated so it can accept either a CharSourceRange or a SourceRange.
8495 ///
8496 /// \param FixIt optional fix it hint for the format string.
8497 template <typename Range>
8498 void CheckFormatHandler::EmitFormatDiagnostic(
8499     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8500     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8501     Range StringRange, ArrayRef<FixItHint> FixIt) {
8502   if (InFunctionCall) {
8503     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8504     D << StringRange;
8505     D << FixIt;
8506   } else {
8507     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8508       << ArgumentExpr->getSourceRange();
8509 
8510     const Sema::SemaDiagnosticBuilder &Note =
8511       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8512              diag::note_format_string_defined);
8513 
8514     Note << StringRange;
8515     Note << FixIt;
8516   }
8517 }
8518 
8519 //===--- CHECK: Printf format string checking ------------------------------===//
8520 
8521 namespace {
8522 
8523 class CheckPrintfHandler : public CheckFormatHandler {
8524 public:
8525   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8526                      const Expr *origFormatExpr,
8527                      const Sema::FormatStringType type, unsigned firstDataArg,
8528                      unsigned numDataArgs, bool isObjC, const char *beg,
8529                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8530                      unsigned formatIdx, bool inFunctionCall,
8531                      Sema::VariadicCallType CallType,
8532                      llvm::SmallBitVector &CheckedVarArgs,
8533                      UncoveredArgHandler &UncoveredArg)
8534       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8535                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8536                            inFunctionCall, CallType, CheckedVarArgs,
8537                            UncoveredArg) {}
8538 
8539   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8540 
8541   /// Returns true if '%@' specifiers are allowed in the format string.
8542   bool allowsObjCArg() const {
8543     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8544            FSType == Sema::FST_OSTrace;
8545   }
8546 
8547   bool HandleInvalidPrintfConversionSpecifier(
8548                                       const analyze_printf::PrintfSpecifier &FS,
8549                                       const char *startSpecifier,
8550                                       unsigned specifierLen) override;
8551 
8552   void handleInvalidMaskType(StringRef MaskType) override;
8553 
8554   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8555                              const char *startSpecifier,
8556                              unsigned specifierLen) override;
8557   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8558                        const char *StartSpecifier,
8559                        unsigned SpecifierLen,
8560                        const Expr *E);
8561 
8562   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8563                     const char *startSpecifier, unsigned specifierLen);
8564   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8565                            const analyze_printf::OptionalAmount &Amt,
8566                            unsigned type,
8567                            const char *startSpecifier, unsigned specifierLen);
8568   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8569                   const analyze_printf::OptionalFlag &flag,
8570                   const char *startSpecifier, unsigned specifierLen);
8571   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8572                          const analyze_printf::OptionalFlag &ignoredFlag,
8573                          const analyze_printf::OptionalFlag &flag,
8574                          const char *startSpecifier, unsigned specifierLen);
8575   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8576                            const Expr *E);
8577 
8578   void HandleEmptyObjCModifierFlag(const char *startFlag,
8579                                    unsigned flagLen) override;
8580 
8581   void HandleInvalidObjCModifierFlag(const char *startFlag,
8582                                             unsigned flagLen) override;
8583 
8584   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8585                                            const char *flagsEnd,
8586                                            const char *conversionPosition)
8587                                              override;
8588 };
8589 
8590 } // namespace
8591 
8592 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8593                                       const analyze_printf::PrintfSpecifier &FS,
8594                                       const char *startSpecifier,
8595                                       unsigned specifierLen) {
8596   const analyze_printf::PrintfConversionSpecifier &CS =
8597     FS.getConversionSpecifier();
8598 
8599   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8600                                           getLocationOfByte(CS.getStart()),
8601                                           startSpecifier, specifierLen,
8602                                           CS.getStart(), CS.getLength());
8603 }
8604 
8605 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8606   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8607 }
8608 
8609 bool CheckPrintfHandler::HandleAmount(
8610                                const analyze_format_string::OptionalAmount &Amt,
8611                                unsigned k, const char *startSpecifier,
8612                                unsigned specifierLen) {
8613   if (Amt.hasDataArgument()) {
8614     if (!HasVAListArg) {
8615       unsigned argIndex = Amt.getArgIndex();
8616       if (argIndex >= NumDataArgs) {
8617         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8618                                << k,
8619                              getLocationOfByte(Amt.getStart()),
8620                              /*IsStringLocation*/true,
8621                              getSpecifierRange(startSpecifier, specifierLen));
8622         // Don't do any more checking.  We will just emit
8623         // spurious errors.
8624         return false;
8625       }
8626 
8627       // Type check the data argument.  It should be an 'int'.
8628       // Although not in conformance with C99, we also allow the argument to be
8629       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8630       // doesn't emit a warning for that case.
8631       CoveredArgs.set(argIndex);
8632       const Expr *Arg = getDataArg(argIndex);
8633       if (!Arg)
8634         return false;
8635 
8636       QualType T = Arg->getType();
8637 
8638       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8639       assert(AT.isValid());
8640 
8641       if (!AT.matchesType(S.Context, T)) {
8642         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8643                                << k << AT.getRepresentativeTypeName(S.Context)
8644                                << T << Arg->getSourceRange(),
8645                              getLocationOfByte(Amt.getStart()),
8646                              /*IsStringLocation*/true,
8647                              getSpecifierRange(startSpecifier, specifierLen));
8648         // Don't do any more checking.  We will just emit
8649         // spurious errors.
8650         return false;
8651       }
8652     }
8653   }
8654   return true;
8655 }
8656 
8657 void CheckPrintfHandler::HandleInvalidAmount(
8658                                       const analyze_printf::PrintfSpecifier &FS,
8659                                       const analyze_printf::OptionalAmount &Amt,
8660                                       unsigned type,
8661                                       const char *startSpecifier,
8662                                       unsigned specifierLen) {
8663   const analyze_printf::PrintfConversionSpecifier &CS =
8664     FS.getConversionSpecifier();
8665 
8666   FixItHint fixit =
8667     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8668       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8669                                  Amt.getConstantLength()))
8670       : FixItHint();
8671 
8672   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8673                          << type << CS.toString(),
8674                        getLocationOfByte(Amt.getStart()),
8675                        /*IsStringLocation*/true,
8676                        getSpecifierRange(startSpecifier, specifierLen),
8677                        fixit);
8678 }
8679 
8680 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8681                                     const analyze_printf::OptionalFlag &flag,
8682                                     const char *startSpecifier,
8683                                     unsigned specifierLen) {
8684   // Warn about pointless flag with a fixit removal.
8685   const analyze_printf::PrintfConversionSpecifier &CS =
8686     FS.getConversionSpecifier();
8687   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8688                          << flag.toString() << CS.toString(),
8689                        getLocationOfByte(flag.getPosition()),
8690                        /*IsStringLocation*/true,
8691                        getSpecifierRange(startSpecifier, specifierLen),
8692                        FixItHint::CreateRemoval(
8693                          getSpecifierRange(flag.getPosition(), 1)));
8694 }
8695 
8696 void CheckPrintfHandler::HandleIgnoredFlag(
8697                                 const analyze_printf::PrintfSpecifier &FS,
8698                                 const analyze_printf::OptionalFlag &ignoredFlag,
8699                                 const analyze_printf::OptionalFlag &flag,
8700                                 const char *startSpecifier,
8701                                 unsigned specifierLen) {
8702   // Warn about ignored flag with a fixit removal.
8703   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8704                          << ignoredFlag.toString() << flag.toString(),
8705                        getLocationOfByte(ignoredFlag.getPosition()),
8706                        /*IsStringLocation*/true,
8707                        getSpecifierRange(startSpecifier, specifierLen),
8708                        FixItHint::CreateRemoval(
8709                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8710 }
8711 
8712 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8713                                                      unsigned flagLen) {
8714   // Warn about an empty flag.
8715   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8716                        getLocationOfByte(startFlag),
8717                        /*IsStringLocation*/true,
8718                        getSpecifierRange(startFlag, flagLen));
8719 }
8720 
8721 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8722                                                        unsigned flagLen) {
8723   // Warn about an invalid flag.
8724   auto Range = getSpecifierRange(startFlag, flagLen);
8725   StringRef flag(startFlag, flagLen);
8726   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8727                       getLocationOfByte(startFlag),
8728                       /*IsStringLocation*/true,
8729                       Range, FixItHint::CreateRemoval(Range));
8730 }
8731 
8732 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8733     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8734     // Warn about using '[...]' without a '@' conversion.
8735     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8736     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8737     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8738                          getLocationOfByte(conversionPosition),
8739                          /*IsStringLocation*/true,
8740                          Range, FixItHint::CreateRemoval(Range));
8741 }
8742 
8743 // Determines if the specified is a C++ class or struct containing
8744 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8745 // "c_str()").
8746 template<typename MemberKind>
8747 static llvm::SmallPtrSet<MemberKind*, 1>
8748 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8749   const RecordType *RT = Ty->getAs<RecordType>();
8750   llvm::SmallPtrSet<MemberKind*, 1> Results;
8751 
8752   if (!RT)
8753     return Results;
8754   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8755   if (!RD || !RD->getDefinition())
8756     return Results;
8757 
8758   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8759                  Sema::LookupMemberName);
8760   R.suppressDiagnostics();
8761 
8762   // We just need to include all members of the right kind turned up by the
8763   // filter, at this point.
8764   if (S.LookupQualifiedName(R, RT->getDecl()))
8765     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8766       NamedDecl *decl = (*I)->getUnderlyingDecl();
8767       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8768         Results.insert(FK);
8769     }
8770   return Results;
8771 }
8772 
8773 /// Check if we could call '.c_str()' on an object.
8774 ///
8775 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8776 /// allow the call, or if it would be ambiguous).
8777 bool Sema::hasCStrMethod(const Expr *E) {
8778   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8779 
8780   MethodSet Results =
8781       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8782   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8783        MI != ME; ++MI)
8784     if ((*MI)->getMinRequiredArguments() == 0)
8785       return true;
8786   return false;
8787 }
8788 
8789 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8790 // better diagnostic if so. AT is assumed to be valid.
8791 // Returns true when a c_str() conversion method is found.
8792 bool CheckPrintfHandler::checkForCStrMembers(
8793     const analyze_printf::ArgType &AT, const Expr *E) {
8794   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8795 
8796   MethodSet Results =
8797       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8798 
8799   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8800        MI != ME; ++MI) {
8801     const CXXMethodDecl *Method = *MI;
8802     if (Method->getMinRequiredArguments() == 0 &&
8803         AT.matchesType(S.Context, Method->getReturnType())) {
8804       // FIXME: Suggest parens if the expression needs them.
8805       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8806       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8807           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8808       return true;
8809     }
8810   }
8811 
8812   return false;
8813 }
8814 
8815 bool
8816 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8817                                             &FS,
8818                                           const char *startSpecifier,
8819                                           unsigned specifierLen) {
8820   using namespace analyze_format_string;
8821   using namespace analyze_printf;
8822 
8823   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8824 
8825   if (FS.consumesDataArgument()) {
8826     if (atFirstArg) {
8827         atFirstArg = false;
8828         usesPositionalArgs = FS.usesPositionalArg();
8829     }
8830     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8831       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8832                                         startSpecifier, specifierLen);
8833       return false;
8834     }
8835   }
8836 
8837   // First check if the field width, precision, and conversion specifier
8838   // have matching data arguments.
8839   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8840                     startSpecifier, specifierLen)) {
8841     return false;
8842   }
8843 
8844   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8845                     startSpecifier, specifierLen)) {
8846     return false;
8847   }
8848 
8849   if (!CS.consumesDataArgument()) {
8850     // FIXME: Technically specifying a precision or field width here
8851     // makes no sense.  Worth issuing a warning at some point.
8852     return true;
8853   }
8854 
8855   // Consume the argument.
8856   unsigned argIndex = FS.getArgIndex();
8857   if (argIndex < NumDataArgs) {
8858     // The check to see if the argIndex is valid will come later.
8859     // We set the bit here because we may exit early from this
8860     // function if we encounter some other error.
8861     CoveredArgs.set(argIndex);
8862   }
8863 
8864   // FreeBSD kernel extensions.
8865   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8866       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8867     // We need at least two arguments.
8868     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8869       return false;
8870 
8871     // Claim the second argument.
8872     CoveredArgs.set(argIndex + 1);
8873 
8874     // Type check the first argument (int for %b, pointer for %D)
8875     const Expr *Ex = getDataArg(argIndex);
8876     const analyze_printf::ArgType &AT =
8877       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8878         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8879     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8880       EmitFormatDiagnostic(
8881           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8882               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8883               << false << Ex->getSourceRange(),
8884           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8885           getSpecifierRange(startSpecifier, specifierLen));
8886 
8887     // Type check the second argument (char * for both %b and %D)
8888     Ex = getDataArg(argIndex + 1);
8889     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8890     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8891       EmitFormatDiagnostic(
8892           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8893               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8894               << false << Ex->getSourceRange(),
8895           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8896           getSpecifierRange(startSpecifier, specifierLen));
8897 
8898      return true;
8899   }
8900 
8901   // Check for using an Objective-C specific conversion specifier
8902   // in a non-ObjC literal.
8903   if (!allowsObjCArg() && CS.isObjCArg()) {
8904     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8905                                                   specifierLen);
8906   }
8907 
8908   // %P can only be used with os_log.
8909   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8910     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8911                                                   specifierLen);
8912   }
8913 
8914   // %n is not allowed with os_log.
8915   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8916     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8917                          getLocationOfByte(CS.getStart()),
8918                          /*IsStringLocation*/ false,
8919                          getSpecifierRange(startSpecifier, specifierLen));
8920 
8921     return true;
8922   }
8923 
8924   // Only scalars are allowed for os_trace.
8925   if (FSType == Sema::FST_OSTrace &&
8926       (CS.getKind() == ConversionSpecifier::PArg ||
8927        CS.getKind() == ConversionSpecifier::sArg ||
8928        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8929     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8930                                                   specifierLen);
8931   }
8932 
8933   // Check for use of public/private annotation outside of os_log().
8934   if (FSType != Sema::FST_OSLog) {
8935     if (FS.isPublic().isSet()) {
8936       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8937                                << "public",
8938                            getLocationOfByte(FS.isPublic().getPosition()),
8939                            /*IsStringLocation*/ false,
8940                            getSpecifierRange(startSpecifier, specifierLen));
8941     }
8942     if (FS.isPrivate().isSet()) {
8943       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8944                                << "private",
8945                            getLocationOfByte(FS.isPrivate().getPosition()),
8946                            /*IsStringLocation*/ false,
8947                            getSpecifierRange(startSpecifier, specifierLen));
8948     }
8949   }
8950 
8951   // Check for invalid use of field width
8952   if (!FS.hasValidFieldWidth()) {
8953     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8954         startSpecifier, specifierLen);
8955   }
8956 
8957   // Check for invalid use of precision
8958   if (!FS.hasValidPrecision()) {
8959     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8960         startSpecifier, specifierLen);
8961   }
8962 
8963   // Precision is mandatory for %P specifier.
8964   if (CS.getKind() == ConversionSpecifier::PArg &&
8965       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8966     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8967                          getLocationOfByte(startSpecifier),
8968                          /*IsStringLocation*/ false,
8969                          getSpecifierRange(startSpecifier, specifierLen));
8970   }
8971 
8972   // Check each flag does not conflict with any other component.
8973   if (!FS.hasValidThousandsGroupingPrefix())
8974     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8975   if (!FS.hasValidLeadingZeros())
8976     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8977   if (!FS.hasValidPlusPrefix())
8978     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8979   if (!FS.hasValidSpacePrefix())
8980     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8981   if (!FS.hasValidAlternativeForm())
8982     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8983   if (!FS.hasValidLeftJustified())
8984     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8985 
8986   // Check that flags are not ignored by another flag
8987   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8988     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8989         startSpecifier, specifierLen);
8990   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8991     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8992             startSpecifier, specifierLen);
8993 
8994   // Check the length modifier is valid with the given conversion specifier.
8995   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8996                                  S.getLangOpts()))
8997     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8998                                 diag::warn_format_nonsensical_length);
8999   else if (!FS.hasStandardLengthModifier())
9000     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9001   else if (!FS.hasStandardLengthConversionCombination())
9002     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9003                                 diag::warn_format_non_standard_conversion_spec);
9004 
9005   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9006     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9007 
9008   // The remaining checks depend on the data arguments.
9009   if (HasVAListArg)
9010     return true;
9011 
9012   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9013     return false;
9014 
9015   const Expr *Arg = getDataArg(argIndex);
9016   if (!Arg)
9017     return true;
9018 
9019   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9020 }
9021 
9022 static bool requiresParensToAddCast(const Expr *E) {
9023   // FIXME: We should have a general way to reason about operator
9024   // precedence and whether parens are actually needed here.
9025   // Take care of a few common cases where they aren't.
9026   const Expr *Inside = E->IgnoreImpCasts();
9027   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9028     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9029 
9030   switch (Inside->getStmtClass()) {
9031   case Stmt::ArraySubscriptExprClass:
9032   case Stmt::CallExprClass:
9033   case Stmt::CharacterLiteralClass:
9034   case Stmt::CXXBoolLiteralExprClass:
9035   case Stmt::DeclRefExprClass:
9036   case Stmt::FloatingLiteralClass:
9037   case Stmt::IntegerLiteralClass:
9038   case Stmt::MemberExprClass:
9039   case Stmt::ObjCArrayLiteralClass:
9040   case Stmt::ObjCBoolLiteralExprClass:
9041   case Stmt::ObjCBoxedExprClass:
9042   case Stmt::ObjCDictionaryLiteralClass:
9043   case Stmt::ObjCEncodeExprClass:
9044   case Stmt::ObjCIvarRefExprClass:
9045   case Stmt::ObjCMessageExprClass:
9046   case Stmt::ObjCPropertyRefExprClass:
9047   case Stmt::ObjCStringLiteralClass:
9048   case Stmt::ObjCSubscriptRefExprClass:
9049   case Stmt::ParenExprClass:
9050   case Stmt::StringLiteralClass:
9051   case Stmt::UnaryOperatorClass:
9052     return false;
9053   default:
9054     return true;
9055   }
9056 }
9057 
9058 static std::pair<QualType, StringRef>
9059 shouldNotPrintDirectly(const ASTContext &Context,
9060                        QualType IntendedTy,
9061                        const Expr *E) {
9062   // Use a 'while' to peel off layers of typedefs.
9063   QualType TyTy = IntendedTy;
9064   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9065     StringRef Name = UserTy->getDecl()->getName();
9066     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9067       .Case("CFIndex", Context.getNSIntegerType())
9068       .Case("NSInteger", Context.getNSIntegerType())
9069       .Case("NSUInteger", Context.getNSUIntegerType())
9070       .Case("SInt32", Context.IntTy)
9071       .Case("UInt32", Context.UnsignedIntTy)
9072       .Default(QualType());
9073 
9074     if (!CastTy.isNull())
9075       return std::make_pair(CastTy, Name);
9076 
9077     TyTy = UserTy->desugar();
9078   }
9079 
9080   // Strip parens if necessary.
9081   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9082     return shouldNotPrintDirectly(Context,
9083                                   PE->getSubExpr()->getType(),
9084                                   PE->getSubExpr());
9085 
9086   // If this is a conditional expression, then its result type is constructed
9087   // via usual arithmetic conversions and thus there might be no necessary
9088   // typedef sugar there.  Recurse to operands to check for NSInteger &
9089   // Co. usage condition.
9090   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9091     QualType TrueTy, FalseTy;
9092     StringRef TrueName, FalseName;
9093 
9094     std::tie(TrueTy, TrueName) =
9095       shouldNotPrintDirectly(Context,
9096                              CO->getTrueExpr()->getType(),
9097                              CO->getTrueExpr());
9098     std::tie(FalseTy, FalseName) =
9099       shouldNotPrintDirectly(Context,
9100                              CO->getFalseExpr()->getType(),
9101                              CO->getFalseExpr());
9102 
9103     if (TrueTy == FalseTy)
9104       return std::make_pair(TrueTy, TrueName);
9105     else if (TrueTy.isNull())
9106       return std::make_pair(FalseTy, FalseName);
9107     else if (FalseTy.isNull())
9108       return std::make_pair(TrueTy, TrueName);
9109   }
9110 
9111   return std::make_pair(QualType(), StringRef());
9112 }
9113 
9114 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9115 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9116 /// type do not count.
9117 static bool
9118 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9119   QualType From = ICE->getSubExpr()->getType();
9120   QualType To = ICE->getType();
9121   // It's an integer promotion if the destination type is the promoted
9122   // source type.
9123   if (ICE->getCastKind() == CK_IntegralCast &&
9124       From->isPromotableIntegerType() &&
9125       S.Context.getPromotedIntegerType(From) == To)
9126     return true;
9127   // Look through vector types, since we do default argument promotion for
9128   // those in OpenCL.
9129   if (const auto *VecTy = From->getAs<ExtVectorType>())
9130     From = VecTy->getElementType();
9131   if (const auto *VecTy = To->getAs<ExtVectorType>())
9132     To = VecTy->getElementType();
9133   // It's a floating promotion if the source type is a lower rank.
9134   return ICE->getCastKind() == CK_FloatingCast &&
9135          S.Context.getFloatingTypeOrder(From, To) < 0;
9136 }
9137 
9138 bool
9139 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9140                                     const char *StartSpecifier,
9141                                     unsigned SpecifierLen,
9142                                     const Expr *E) {
9143   using namespace analyze_format_string;
9144   using namespace analyze_printf;
9145 
9146   // Now type check the data expression that matches the
9147   // format specifier.
9148   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9149   if (!AT.isValid())
9150     return true;
9151 
9152   QualType ExprTy = E->getType();
9153   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9154     ExprTy = TET->getUnderlyingExpr()->getType();
9155   }
9156 
9157   // Diagnose attempts to print a boolean value as a character. Unlike other
9158   // -Wformat diagnostics, this is fine from a type perspective, but it still
9159   // doesn't make sense.
9160   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9161       E->isKnownToHaveBooleanValue()) {
9162     const CharSourceRange &CSR =
9163         getSpecifierRange(StartSpecifier, SpecifierLen);
9164     SmallString<4> FSString;
9165     llvm::raw_svector_ostream os(FSString);
9166     FS.toString(os);
9167     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9168                              << FSString,
9169                          E->getExprLoc(), false, CSR);
9170     return true;
9171   }
9172 
9173   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9174   if (Match == analyze_printf::ArgType::Match)
9175     return true;
9176 
9177   // Look through argument promotions for our error message's reported type.
9178   // This includes the integral and floating promotions, but excludes array
9179   // and function pointer decay (seeing that an argument intended to be a
9180   // string has type 'char [6]' is probably more confusing than 'char *') and
9181   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9182   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9183     if (isArithmeticArgumentPromotion(S, ICE)) {
9184       E = ICE->getSubExpr();
9185       ExprTy = E->getType();
9186 
9187       // Check if we didn't match because of an implicit cast from a 'char'
9188       // or 'short' to an 'int'.  This is done because printf is a varargs
9189       // function.
9190       if (ICE->getType() == S.Context.IntTy ||
9191           ICE->getType() == S.Context.UnsignedIntTy) {
9192         // All further checking is done on the subexpression
9193         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9194             AT.matchesType(S.Context, ExprTy);
9195         if (ImplicitMatch == analyze_printf::ArgType::Match)
9196           return true;
9197         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9198             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9199           Match = ImplicitMatch;
9200       }
9201     }
9202   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9203     // Special case for 'a', which has type 'int' in C.
9204     // Note, however, that we do /not/ want to treat multibyte constants like
9205     // 'MooV' as characters! This form is deprecated but still exists. In
9206     // addition, don't treat expressions as of type 'char' if one byte length
9207     // modifier is provided.
9208     if (ExprTy == S.Context.IntTy &&
9209         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9210       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9211         ExprTy = S.Context.CharTy;
9212   }
9213 
9214   // Look through enums to their underlying type.
9215   bool IsEnum = false;
9216   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9217     ExprTy = EnumTy->getDecl()->getIntegerType();
9218     IsEnum = true;
9219   }
9220 
9221   // %C in an Objective-C context prints a unichar, not a wchar_t.
9222   // If the argument is an integer of some kind, believe the %C and suggest
9223   // a cast instead of changing the conversion specifier.
9224   QualType IntendedTy = ExprTy;
9225   if (isObjCContext() &&
9226       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9227     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9228         !ExprTy->isCharType()) {
9229       // 'unichar' is defined as a typedef of unsigned short, but we should
9230       // prefer using the typedef if it is visible.
9231       IntendedTy = S.Context.UnsignedShortTy;
9232 
9233       // While we are here, check if the value is an IntegerLiteral that happens
9234       // to be within the valid range.
9235       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9236         const llvm::APInt &V = IL->getValue();
9237         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9238           return true;
9239       }
9240 
9241       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9242                           Sema::LookupOrdinaryName);
9243       if (S.LookupName(Result, S.getCurScope())) {
9244         NamedDecl *ND = Result.getFoundDecl();
9245         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9246           if (TD->getUnderlyingType() == IntendedTy)
9247             IntendedTy = S.Context.getTypedefType(TD);
9248       }
9249     }
9250   }
9251 
9252   // Special-case some of Darwin's platform-independence types by suggesting
9253   // casts to primitive types that are known to be large enough.
9254   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9255   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9256     QualType CastTy;
9257     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9258     if (!CastTy.isNull()) {
9259       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9260       // (long in ASTContext). Only complain to pedants.
9261       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9262           (AT.isSizeT() || AT.isPtrdiffT()) &&
9263           AT.matchesType(S.Context, CastTy))
9264         Match = ArgType::NoMatchPedantic;
9265       IntendedTy = CastTy;
9266       ShouldNotPrintDirectly = true;
9267     }
9268   }
9269 
9270   // We may be able to offer a FixItHint if it is a supported type.
9271   PrintfSpecifier fixedFS = FS;
9272   bool Success =
9273       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9274 
9275   if (Success) {
9276     // Get the fix string from the fixed format specifier
9277     SmallString<16> buf;
9278     llvm::raw_svector_ostream os(buf);
9279     fixedFS.toString(os);
9280 
9281     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9282 
9283     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9284       unsigned Diag;
9285       switch (Match) {
9286       case ArgType::Match: llvm_unreachable("expected non-matching");
9287       case ArgType::NoMatchPedantic:
9288         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9289         break;
9290       case ArgType::NoMatchTypeConfusion:
9291         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9292         break;
9293       case ArgType::NoMatch:
9294         Diag = diag::warn_format_conversion_argument_type_mismatch;
9295         break;
9296       }
9297 
9298       // In this case, the specifier is wrong and should be changed to match
9299       // the argument.
9300       EmitFormatDiagnostic(S.PDiag(Diag)
9301                                << AT.getRepresentativeTypeName(S.Context)
9302                                << IntendedTy << IsEnum << E->getSourceRange(),
9303                            E->getBeginLoc(),
9304                            /*IsStringLocation*/ false, SpecRange,
9305                            FixItHint::CreateReplacement(SpecRange, os.str()));
9306     } else {
9307       // The canonical type for formatting this value is different from the
9308       // actual type of the expression. (This occurs, for example, with Darwin's
9309       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9310       // should be printed as 'long' for 64-bit compatibility.)
9311       // Rather than emitting a normal format/argument mismatch, we want to
9312       // add a cast to the recommended type (and correct the format string
9313       // if necessary).
9314       SmallString<16> CastBuf;
9315       llvm::raw_svector_ostream CastFix(CastBuf);
9316       CastFix << "(";
9317       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9318       CastFix << ")";
9319 
9320       SmallVector<FixItHint,4> Hints;
9321       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9322         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9323 
9324       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9325         // If there's already a cast present, just replace it.
9326         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9327         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9328 
9329       } else if (!requiresParensToAddCast(E)) {
9330         // If the expression has high enough precedence,
9331         // just write the C-style cast.
9332         Hints.push_back(
9333             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9334       } else {
9335         // Otherwise, add parens around the expression as well as the cast.
9336         CastFix << "(";
9337         Hints.push_back(
9338             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9339 
9340         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9341         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9342       }
9343 
9344       if (ShouldNotPrintDirectly) {
9345         // The expression has a type that should not be printed directly.
9346         // We extract the name from the typedef because we don't want to show
9347         // the underlying type in the diagnostic.
9348         StringRef Name;
9349         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9350           Name = TypedefTy->getDecl()->getName();
9351         else
9352           Name = CastTyName;
9353         unsigned Diag = Match == ArgType::NoMatchPedantic
9354                             ? diag::warn_format_argument_needs_cast_pedantic
9355                             : diag::warn_format_argument_needs_cast;
9356         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9357                                            << E->getSourceRange(),
9358                              E->getBeginLoc(), /*IsStringLocation=*/false,
9359                              SpecRange, Hints);
9360       } else {
9361         // In this case, the expression could be printed using a different
9362         // specifier, but we've decided that the specifier is probably correct
9363         // and we should cast instead. Just use the normal warning message.
9364         EmitFormatDiagnostic(
9365             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9366                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9367                 << E->getSourceRange(),
9368             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9369       }
9370     }
9371   } else {
9372     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9373                                                    SpecifierLen);
9374     // Since the warning for passing non-POD types to variadic functions
9375     // was deferred until now, we emit a warning for non-POD
9376     // arguments here.
9377     switch (S.isValidVarArgType(ExprTy)) {
9378     case Sema::VAK_Valid:
9379     case Sema::VAK_ValidInCXX11: {
9380       unsigned Diag;
9381       switch (Match) {
9382       case ArgType::Match: llvm_unreachable("expected non-matching");
9383       case ArgType::NoMatchPedantic:
9384         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9385         break;
9386       case ArgType::NoMatchTypeConfusion:
9387         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9388         break;
9389       case ArgType::NoMatch:
9390         Diag = diag::warn_format_conversion_argument_type_mismatch;
9391         break;
9392       }
9393 
9394       EmitFormatDiagnostic(
9395           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9396                         << IsEnum << CSR << E->getSourceRange(),
9397           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9398       break;
9399     }
9400     case Sema::VAK_Undefined:
9401     case Sema::VAK_MSVCUndefined:
9402       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9403                                << S.getLangOpts().CPlusPlus11 << ExprTy
9404                                << CallType
9405                                << AT.getRepresentativeTypeName(S.Context) << CSR
9406                                << E->getSourceRange(),
9407                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9408       checkForCStrMembers(AT, E);
9409       break;
9410 
9411     case Sema::VAK_Invalid:
9412       if (ExprTy->isObjCObjectType())
9413         EmitFormatDiagnostic(
9414             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9415                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9416                 << AT.getRepresentativeTypeName(S.Context) << CSR
9417                 << E->getSourceRange(),
9418             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9419       else
9420         // FIXME: If this is an initializer list, suggest removing the braces
9421         // or inserting a cast to the target type.
9422         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9423             << isa<InitListExpr>(E) << ExprTy << CallType
9424             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9425       break;
9426     }
9427 
9428     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9429            "format string specifier index out of range");
9430     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9431   }
9432 
9433   return true;
9434 }
9435 
9436 //===--- CHECK: Scanf format string checking ------------------------------===//
9437 
9438 namespace {
9439 
9440 class CheckScanfHandler : public CheckFormatHandler {
9441 public:
9442   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9443                     const Expr *origFormatExpr, Sema::FormatStringType type,
9444                     unsigned firstDataArg, unsigned numDataArgs,
9445                     const char *beg, bool hasVAListArg,
9446                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9447                     bool inFunctionCall, Sema::VariadicCallType CallType,
9448                     llvm::SmallBitVector &CheckedVarArgs,
9449                     UncoveredArgHandler &UncoveredArg)
9450       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9451                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9452                            inFunctionCall, CallType, CheckedVarArgs,
9453                            UncoveredArg) {}
9454 
9455   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9456                             const char *startSpecifier,
9457                             unsigned specifierLen) override;
9458 
9459   bool HandleInvalidScanfConversionSpecifier(
9460           const analyze_scanf::ScanfSpecifier &FS,
9461           const char *startSpecifier,
9462           unsigned specifierLen) override;
9463 
9464   void HandleIncompleteScanList(const char *start, const char *end) override;
9465 };
9466 
9467 } // namespace
9468 
9469 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9470                                                  const char *end) {
9471   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9472                        getLocationOfByte(end), /*IsStringLocation*/true,
9473                        getSpecifierRange(start, end - start));
9474 }
9475 
9476 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9477                                         const analyze_scanf::ScanfSpecifier &FS,
9478                                         const char *startSpecifier,
9479                                         unsigned specifierLen) {
9480   const analyze_scanf::ScanfConversionSpecifier &CS =
9481     FS.getConversionSpecifier();
9482 
9483   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9484                                           getLocationOfByte(CS.getStart()),
9485                                           startSpecifier, specifierLen,
9486                                           CS.getStart(), CS.getLength());
9487 }
9488 
9489 bool CheckScanfHandler::HandleScanfSpecifier(
9490                                        const analyze_scanf::ScanfSpecifier &FS,
9491                                        const char *startSpecifier,
9492                                        unsigned specifierLen) {
9493   using namespace analyze_scanf;
9494   using namespace analyze_format_string;
9495 
9496   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9497 
9498   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9499   // be used to decide if we are using positional arguments consistently.
9500   if (FS.consumesDataArgument()) {
9501     if (atFirstArg) {
9502       atFirstArg = false;
9503       usesPositionalArgs = FS.usesPositionalArg();
9504     }
9505     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9506       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9507                                         startSpecifier, specifierLen);
9508       return false;
9509     }
9510   }
9511 
9512   // Check if the field with is non-zero.
9513   const OptionalAmount &Amt = FS.getFieldWidth();
9514   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9515     if (Amt.getConstantAmount() == 0) {
9516       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9517                                                    Amt.getConstantLength());
9518       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9519                            getLocationOfByte(Amt.getStart()),
9520                            /*IsStringLocation*/true, R,
9521                            FixItHint::CreateRemoval(R));
9522     }
9523   }
9524 
9525   if (!FS.consumesDataArgument()) {
9526     // FIXME: Technically specifying a precision or field width here
9527     // makes no sense.  Worth issuing a warning at some point.
9528     return true;
9529   }
9530 
9531   // Consume the argument.
9532   unsigned argIndex = FS.getArgIndex();
9533   if (argIndex < NumDataArgs) {
9534       // The check to see if the argIndex is valid will come later.
9535       // We set the bit here because we may exit early from this
9536       // function if we encounter some other error.
9537     CoveredArgs.set(argIndex);
9538   }
9539 
9540   // Check the length modifier is valid with the given conversion specifier.
9541   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9542                                  S.getLangOpts()))
9543     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9544                                 diag::warn_format_nonsensical_length);
9545   else if (!FS.hasStandardLengthModifier())
9546     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9547   else if (!FS.hasStandardLengthConversionCombination())
9548     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9549                                 diag::warn_format_non_standard_conversion_spec);
9550 
9551   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9552     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9553 
9554   // The remaining checks depend on the data arguments.
9555   if (HasVAListArg)
9556     return true;
9557 
9558   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9559     return false;
9560 
9561   // Check that the argument type matches the format specifier.
9562   const Expr *Ex = getDataArg(argIndex);
9563   if (!Ex)
9564     return true;
9565 
9566   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9567 
9568   if (!AT.isValid()) {
9569     return true;
9570   }
9571 
9572   analyze_format_string::ArgType::MatchKind Match =
9573       AT.matchesType(S.Context, Ex->getType());
9574   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9575   if (Match == analyze_format_string::ArgType::Match)
9576     return true;
9577 
9578   ScanfSpecifier fixedFS = FS;
9579   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9580                                  S.getLangOpts(), S.Context);
9581 
9582   unsigned Diag =
9583       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9584                : diag::warn_format_conversion_argument_type_mismatch;
9585 
9586   if (Success) {
9587     // Get the fix string from the fixed format specifier.
9588     SmallString<128> buf;
9589     llvm::raw_svector_ostream os(buf);
9590     fixedFS.toString(os);
9591 
9592     EmitFormatDiagnostic(
9593         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9594                       << Ex->getType() << false << Ex->getSourceRange(),
9595         Ex->getBeginLoc(),
9596         /*IsStringLocation*/ false,
9597         getSpecifierRange(startSpecifier, specifierLen),
9598         FixItHint::CreateReplacement(
9599             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9600   } else {
9601     EmitFormatDiagnostic(S.PDiag(Diag)
9602                              << AT.getRepresentativeTypeName(S.Context)
9603                              << Ex->getType() << false << Ex->getSourceRange(),
9604                          Ex->getBeginLoc(),
9605                          /*IsStringLocation*/ false,
9606                          getSpecifierRange(startSpecifier, specifierLen));
9607   }
9608 
9609   return true;
9610 }
9611 
9612 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9613                               const Expr *OrigFormatExpr,
9614                               ArrayRef<const Expr *> Args,
9615                               bool HasVAListArg, unsigned format_idx,
9616                               unsigned firstDataArg,
9617                               Sema::FormatStringType Type,
9618                               bool inFunctionCall,
9619                               Sema::VariadicCallType CallType,
9620                               llvm::SmallBitVector &CheckedVarArgs,
9621                               UncoveredArgHandler &UncoveredArg,
9622                               bool IgnoreStringsWithoutSpecifiers) {
9623   // CHECK: is the format string a wide literal?
9624   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9625     CheckFormatHandler::EmitFormatDiagnostic(
9626         S, inFunctionCall, Args[format_idx],
9627         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9628         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9629     return;
9630   }
9631 
9632   // Str - The format string.  NOTE: this is NOT null-terminated!
9633   StringRef StrRef = FExpr->getString();
9634   const char *Str = StrRef.data();
9635   // Account for cases where the string literal is truncated in a declaration.
9636   const ConstantArrayType *T =
9637     S.Context.getAsConstantArrayType(FExpr->getType());
9638   assert(T && "String literal not of constant array type!");
9639   size_t TypeSize = T->getSize().getZExtValue();
9640   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9641   const unsigned numDataArgs = Args.size() - firstDataArg;
9642 
9643   if (IgnoreStringsWithoutSpecifiers &&
9644       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9645           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9646     return;
9647 
9648   // Emit a warning if the string literal is truncated and does not contain an
9649   // embedded null character.
9650   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9651     CheckFormatHandler::EmitFormatDiagnostic(
9652         S, inFunctionCall, Args[format_idx],
9653         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9654         FExpr->getBeginLoc(),
9655         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9656     return;
9657   }
9658 
9659   // CHECK: empty format string?
9660   if (StrLen == 0 && numDataArgs > 0) {
9661     CheckFormatHandler::EmitFormatDiagnostic(
9662         S, inFunctionCall, Args[format_idx],
9663         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9664         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9665     return;
9666   }
9667 
9668   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9669       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9670       Type == Sema::FST_OSTrace) {
9671     CheckPrintfHandler H(
9672         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9673         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9674         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9675         CheckedVarArgs, UncoveredArg);
9676 
9677     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9678                                                   S.getLangOpts(),
9679                                                   S.Context.getTargetInfo(),
9680                                             Type == Sema::FST_FreeBSDKPrintf))
9681       H.DoneProcessing();
9682   } else if (Type == Sema::FST_Scanf) {
9683     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9684                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9685                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9686 
9687     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9688                                                  S.getLangOpts(),
9689                                                  S.Context.getTargetInfo()))
9690       H.DoneProcessing();
9691   } // TODO: handle other formats
9692 }
9693 
9694 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9695   // Str - The format string.  NOTE: this is NOT null-terminated!
9696   StringRef StrRef = FExpr->getString();
9697   const char *Str = StrRef.data();
9698   // Account for cases where the string literal is truncated in a declaration.
9699   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9700   assert(T && "String literal not of constant array type!");
9701   size_t TypeSize = T->getSize().getZExtValue();
9702   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9703   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9704                                                          getLangOpts(),
9705                                                          Context.getTargetInfo());
9706 }
9707 
9708 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9709 
9710 // Returns the related absolute value function that is larger, of 0 if one
9711 // does not exist.
9712 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9713   switch (AbsFunction) {
9714   default:
9715     return 0;
9716 
9717   case Builtin::BI__builtin_abs:
9718     return Builtin::BI__builtin_labs;
9719   case Builtin::BI__builtin_labs:
9720     return Builtin::BI__builtin_llabs;
9721   case Builtin::BI__builtin_llabs:
9722     return 0;
9723 
9724   case Builtin::BI__builtin_fabsf:
9725     return Builtin::BI__builtin_fabs;
9726   case Builtin::BI__builtin_fabs:
9727     return Builtin::BI__builtin_fabsl;
9728   case Builtin::BI__builtin_fabsl:
9729     return 0;
9730 
9731   case Builtin::BI__builtin_cabsf:
9732     return Builtin::BI__builtin_cabs;
9733   case Builtin::BI__builtin_cabs:
9734     return Builtin::BI__builtin_cabsl;
9735   case Builtin::BI__builtin_cabsl:
9736     return 0;
9737 
9738   case Builtin::BIabs:
9739     return Builtin::BIlabs;
9740   case Builtin::BIlabs:
9741     return Builtin::BIllabs;
9742   case Builtin::BIllabs:
9743     return 0;
9744 
9745   case Builtin::BIfabsf:
9746     return Builtin::BIfabs;
9747   case Builtin::BIfabs:
9748     return Builtin::BIfabsl;
9749   case Builtin::BIfabsl:
9750     return 0;
9751 
9752   case Builtin::BIcabsf:
9753    return Builtin::BIcabs;
9754   case Builtin::BIcabs:
9755     return Builtin::BIcabsl;
9756   case Builtin::BIcabsl:
9757     return 0;
9758   }
9759 }
9760 
9761 // Returns the argument type of the absolute value function.
9762 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9763                                              unsigned AbsType) {
9764   if (AbsType == 0)
9765     return QualType();
9766 
9767   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9768   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9769   if (Error != ASTContext::GE_None)
9770     return QualType();
9771 
9772   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9773   if (!FT)
9774     return QualType();
9775 
9776   if (FT->getNumParams() != 1)
9777     return QualType();
9778 
9779   return FT->getParamType(0);
9780 }
9781 
9782 // Returns the best absolute value function, or zero, based on type and
9783 // current absolute value function.
9784 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9785                                    unsigned AbsFunctionKind) {
9786   unsigned BestKind = 0;
9787   uint64_t ArgSize = Context.getTypeSize(ArgType);
9788   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9789        Kind = getLargerAbsoluteValueFunction(Kind)) {
9790     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9791     if (Context.getTypeSize(ParamType) >= ArgSize) {
9792       if (BestKind == 0)
9793         BestKind = Kind;
9794       else if (Context.hasSameType(ParamType, ArgType)) {
9795         BestKind = Kind;
9796         break;
9797       }
9798     }
9799   }
9800   return BestKind;
9801 }
9802 
9803 enum AbsoluteValueKind {
9804   AVK_Integer,
9805   AVK_Floating,
9806   AVK_Complex
9807 };
9808 
9809 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9810   if (T->isIntegralOrEnumerationType())
9811     return AVK_Integer;
9812   if (T->isRealFloatingType())
9813     return AVK_Floating;
9814   if (T->isAnyComplexType())
9815     return AVK_Complex;
9816 
9817   llvm_unreachable("Type not integer, floating, or complex");
9818 }
9819 
9820 // Changes the absolute value function to a different type.  Preserves whether
9821 // the function is a builtin.
9822 static unsigned changeAbsFunction(unsigned AbsKind,
9823                                   AbsoluteValueKind ValueKind) {
9824   switch (ValueKind) {
9825   case AVK_Integer:
9826     switch (AbsKind) {
9827     default:
9828       return 0;
9829     case Builtin::BI__builtin_fabsf:
9830     case Builtin::BI__builtin_fabs:
9831     case Builtin::BI__builtin_fabsl:
9832     case Builtin::BI__builtin_cabsf:
9833     case Builtin::BI__builtin_cabs:
9834     case Builtin::BI__builtin_cabsl:
9835       return Builtin::BI__builtin_abs;
9836     case Builtin::BIfabsf:
9837     case Builtin::BIfabs:
9838     case Builtin::BIfabsl:
9839     case Builtin::BIcabsf:
9840     case Builtin::BIcabs:
9841     case Builtin::BIcabsl:
9842       return Builtin::BIabs;
9843     }
9844   case AVK_Floating:
9845     switch (AbsKind) {
9846     default:
9847       return 0;
9848     case Builtin::BI__builtin_abs:
9849     case Builtin::BI__builtin_labs:
9850     case Builtin::BI__builtin_llabs:
9851     case Builtin::BI__builtin_cabsf:
9852     case Builtin::BI__builtin_cabs:
9853     case Builtin::BI__builtin_cabsl:
9854       return Builtin::BI__builtin_fabsf;
9855     case Builtin::BIabs:
9856     case Builtin::BIlabs:
9857     case Builtin::BIllabs:
9858     case Builtin::BIcabsf:
9859     case Builtin::BIcabs:
9860     case Builtin::BIcabsl:
9861       return Builtin::BIfabsf;
9862     }
9863   case AVK_Complex:
9864     switch (AbsKind) {
9865     default:
9866       return 0;
9867     case Builtin::BI__builtin_abs:
9868     case Builtin::BI__builtin_labs:
9869     case Builtin::BI__builtin_llabs:
9870     case Builtin::BI__builtin_fabsf:
9871     case Builtin::BI__builtin_fabs:
9872     case Builtin::BI__builtin_fabsl:
9873       return Builtin::BI__builtin_cabsf;
9874     case Builtin::BIabs:
9875     case Builtin::BIlabs:
9876     case Builtin::BIllabs:
9877     case Builtin::BIfabsf:
9878     case Builtin::BIfabs:
9879     case Builtin::BIfabsl:
9880       return Builtin::BIcabsf;
9881     }
9882   }
9883   llvm_unreachable("Unable to convert function");
9884 }
9885 
9886 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9887   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9888   if (!FnInfo)
9889     return 0;
9890 
9891   switch (FDecl->getBuiltinID()) {
9892   default:
9893     return 0;
9894   case Builtin::BI__builtin_abs:
9895   case Builtin::BI__builtin_fabs:
9896   case Builtin::BI__builtin_fabsf:
9897   case Builtin::BI__builtin_fabsl:
9898   case Builtin::BI__builtin_labs:
9899   case Builtin::BI__builtin_llabs:
9900   case Builtin::BI__builtin_cabs:
9901   case Builtin::BI__builtin_cabsf:
9902   case Builtin::BI__builtin_cabsl:
9903   case Builtin::BIabs:
9904   case Builtin::BIlabs:
9905   case Builtin::BIllabs:
9906   case Builtin::BIfabs:
9907   case Builtin::BIfabsf:
9908   case Builtin::BIfabsl:
9909   case Builtin::BIcabs:
9910   case Builtin::BIcabsf:
9911   case Builtin::BIcabsl:
9912     return FDecl->getBuiltinID();
9913   }
9914   llvm_unreachable("Unknown Builtin type");
9915 }
9916 
9917 // If the replacement is valid, emit a note with replacement function.
9918 // Additionally, suggest including the proper header if not already included.
9919 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9920                             unsigned AbsKind, QualType ArgType) {
9921   bool EmitHeaderHint = true;
9922   const char *HeaderName = nullptr;
9923   const char *FunctionName = nullptr;
9924   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9925     FunctionName = "std::abs";
9926     if (ArgType->isIntegralOrEnumerationType()) {
9927       HeaderName = "cstdlib";
9928     } else if (ArgType->isRealFloatingType()) {
9929       HeaderName = "cmath";
9930     } else {
9931       llvm_unreachable("Invalid Type");
9932     }
9933 
9934     // Lookup all std::abs
9935     if (NamespaceDecl *Std = S.getStdNamespace()) {
9936       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9937       R.suppressDiagnostics();
9938       S.LookupQualifiedName(R, Std);
9939 
9940       for (const auto *I : R) {
9941         const FunctionDecl *FDecl = nullptr;
9942         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9943           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9944         } else {
9945           FDecl = dyn_cast<FunctionDecl>(I);
9946         }
9947         if (!FDecl)
9948           continue;
9949 
9950         // Found std::abs(), check that they are the right ones.
9951         if (FDecl->getNumParams() != 1)
9952           continue;
9953 
9954         // Check that the parameter type can handle the argument.
9955         QualType ParamType = FDecl->getParamDecl(0)->getType();
9956         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9957             S.Context.getTypeSize(ArgType) <=
9958                 S.Context.getTypeSize(ParamType)) {
9959           // Found a function, don't need the header hint.
9960           EmitHeaderHint = false;
9961           break;
9962         }
9963       }
9964     }
9965   } else {
9966     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9967     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9968 
9969     if (HeaderName) {
9970       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9971       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9972       R.suppressDiagnostics();
9973       S.LookupName(R, S.getCurScope());
9974 
9975       if (R.isSingleResult()) {
9976         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9977         if (FD && FD->getBuiltinID() == AbsKind) {
9978           EmitHeaderHint = false;
9979         } else {
9980           return;
9981         }
9982       } else if (!R.empty()) {
9983         return;
9984       }
9985     }
9986   }
9987 
9988   S.Diag(Loc, diag::note_replace_abs_function)
9989       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9990 
9991   if (!HeaderName)
9992     return;
9993 
9994   if (!EmitHeaderHint)
9995     return;
9996 
9997   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9998                                                     << FunctionName;
9999 }
10000 
10001 template <std::size_t StrLen>
10002 static bool IsStdFunction(const FunctionDecl *FDecl,
10003                           const char (&Str)[StrLen]) {
10004   if (!FDecl)
10005     return false;
10006   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10007     return false;
10008   if (!FDecl->isInStdNamespace())
10009     return false;
10010 
10011   return true;
10012 }
10013 
10014 // Warn when using the wrong abs() function.
10015 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10016                                       const FunctionDecl *FDecl) {
10017   if (Call->getNumArgs() != 1)
10018     return;
10019 
10020   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10021   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10022   if (AbsKind == 0 && !IsStdAbs)
10023     return;
10024 
10025   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10026   QualType ParamType = Call->getArg(0)->getType();
10027 
10028   // Unsigned types cannot be negative.  Suggest removing the absolute value
10029   // function call.
10030   if (ArgType->isUnsignedIntegerType()) {
10031     const char *FunctionName =
10032         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10033     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10034     Diag(Call->getExprLoc(), diag::note_remove_abs)
10035         << FunctionName
10036         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10037     return;
10038   }
10039 
10040   // Taking the absolute value of a pointer is very suspicious, they probably
10041   // wanted to index into an array, dereference a pointer, call a function, etc.
10042   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10043     unsigned DiagType = 0;
10044     if (ArgType->isFunctionType())
10045       DiagType = 1;
10046     else if (ArgType->isArrayType())
10047       DiagType = 2;
10048 
10049     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10050     return;
10051   }
10052 
10053   // std::abs has overloads which prevent most of the absolute value problems
10054   // from occurring.
10055   if (IsStdAbs)
10056     return;
10057 
10058   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10059   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10060 
10061   // The argument and parameter are the same kind.  Check if they are the right
10062   // size.
10063   if (ArgValueKind == ParamValueKind) {
10064     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10065       return;
10066 
10067     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10068     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10069         << FDecl << ArgType << ParamType;
10070 
10071     if (NewAbsKind == 0)
10072       return;
10073 
10074     emitReplacement(*this, Call->getExprLoc(),
10075                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10076     return;
10077   }
10078 
10079   // ArgValueKind != ParamValueKind
10080   // The wrong type of absolute value function was used.  Attempt to find the
10081   // proper one.
10082   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10083   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10084   if (NewAbsKind == 0)
10085     return;
10086 
10087   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10088       << FDecl << ParamValueKind << ArgValueKind;
10089 
10090   emitReplacement(*this, Call->getExprLoc(),
10091                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10092 }
10093 
10094 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10095 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10096                                 const FunctionDecl *FDecl) {
10097   if (!Call || !FDecl) return;
10098 
10099   // Ignore template specializations and macros.
10100   if (inTemplateInstantiation()) return;
10101   if (Call->getExprLoc().isMacroID()) return;
10102 
10103   // Only care about the one template argument, two function parameter std::max
10104   if (Call->getNumArgs() != 2) return;
10105   if (!IsStdFunction(FDecl, "max")) return;
10106   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10107   if (!ArgList) return;
10108   if (ArgList->size() != 1) return;
10109 
10110   // Check that template type argument is unsigned integer.
10111   const auto& TA = ArgList->get(0);
10112   if (TA.getKind() != TemplateArgument::Type) return;
10113   QualType ArgType = TA.getAsType();
10114   if (!ArgType->isUnsignedIntegerType()) return;
10115 
10116   // See if either argument is a literal zero.
10117   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10118     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10119     if (!MTE) return false;
10120     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10121     if (!Num) return false;
10122     if (Num->getValue() != 0) return false;
10123     return true;
10124   };
10125 
10126   const Expr *FirstArg = Call->getArg(0);
10127   const Expr *SecondArg = Call->getArg(1);
10128   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10129   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10130 
10131   // Only warn when exactly one argument is zero.
10132   if (IsFirstArgZero == IsSecondArgZero) return;
10133 
10134   SourceRange FirstRange = FirstArg->getSourceRange();
10135   SourceRange SecondRange = SecondArg->getSourceRange();
10136 
10137   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10138 
10139   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10140       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10141 
10142   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10143   SourceRange RemovalRange;
10144   if (IsFirstArgZero) {
10145     RemovalRange = SourceRange(FirstRange.getBegin(),
10146                                SecondRange.getBegin().getLocWithOffset(-1));
10147   } else {
10148     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10149                                SecondRange.getEnd());
10150   }
10151 
10152   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10153         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10154         << FixItHint::CreateRemoval(RemovalRange);
10155 }
10156 
10157 //===--- CHECK: Standard memory functions ---------------------------------===//
10158 
10159 /// Takes the expression passed to the size_t parameter of functions
10160 /// such as memcmp, strncat, etc and warns if it's a comparison.
10161 ///
10162 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10163 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10164                                            IdentifierInfo *FnName,
10165                                            SourceLocation FnLoc,
10166                                            SourceLocation RParenLoc) {
10167   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10168   if (!Size)
10169     return false;
10170 
10171   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10172   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10173     return false;
10174 
10175   SourceRange SizeRange = Size->getSourceRange();
10176   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10177       << SizeRange << FnName;
10178   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10179       << FnName
10180       << FixItHint::CreateInsertion(
10181              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10182       << FixItHint::CreateRemoval(RParenLoc);
10183   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10184       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10185       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10186                                     ")");
10187 
10188   return true;
10189 }
10190 
10191 /// Determine whether the given type is or contains a dynamic class type
10192 /// (e.g., whether it has a vtable).
10193 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10194                                                      bool &IsContained) {
10195   // Look through array types while ignoring qualifiers.
10196   const Type *Ty = T->getBaseElementTypeUnsafe();
10197   IsContained = false;
10198 
10199   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10200   RD = RD ? RD->getDefinition() : nullptr;
10201   if (!RD || RD->isInvalidDecl())
10202     return nullptr;
10203 
10204   if (RD->isDynamicClass())
10205     return RD;
10206 
10207   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10208   // It's impossible for a class to transitively contain itself by value, so
10209   // infinite recursion is impossible.
10210   for (auto *FD : RD->fields()) {
10211     bool SubContained;
10212     if (const CXXRecordDecl *ContainedRD =
10213             getContainedDynamicClass(FD->getType(), SubContained)) {
10214       IsContained = true;
10215       return ContainedRD;
10216     }
10217   }
10218 
10219   return nullptr;
10220 }
10221 
10222 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10223   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10224     if (Unary->getKind() == UETT_SizeOf)
10225       return Unary;
10226   return nullptr;
10227 }
10228 
10229 /// If E is a sizeof expression, returns its argument expression,
10230 /// otherwise returns NULL.
10231 static const Expr *getSizeOfExprArg(const Expr *E) {
10232   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10233     if (!SizeOf->isArgumentType())
10234       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10235   return nullptr;
10236 }
10237 
10238 /// If E is a sizeof expression, returns its argument type.
10239 static QualType getSizeOfArgType(const Expr *E) {
10240   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10241     return SizeOf->getTypeOfArgument();
10242   return QualType();
10243 }
10244 
10245 namespace {
10246 
10247 struct SearchNonTrivialToInitializeField
10248     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10249   using Super =
10250       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10251 
10252   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10253 
10254   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10255                      SourceLocation SL) {
10256     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10257       asDerived().visitArray(PDIK, AT, SL);
10258       return;
10259     }
10260 
10261     Super::visitWithKind(PDIK, FT, SL);
10262   }
10263 
10264   void visitARCStrong(QualType FT, SourceLocation SL) {
10265     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10266   }
10267   void visitARCWeak(QualType FT, SourceLocation SL) {
10268     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10269   }
10270   void visitStruct(QualType FT, SourceLocation SL) {
10271     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10272       visit(FD->getType(), FD->getLocation());
10273   }
10274   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10275                   const ArrayType *AT, SourceLocation SL) {
10276     visit(getContext().getBaseElementType(AT), SL);
10277   }
10278   void visitTrivial(QualType FT, SourceLocation SL) {}
10279 
10280   static void diag(QualType RT, const Expr *E, Sema &S) {
10281     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10282   }
10283 
10284   ASTContext &getContext() { return S.getASTContext(); }
10285 
10286   const Expr *E;
10287   Sema &S;
10288 };
10289 
10290 struct SearchNonTrivialToCopyField
10291     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10292   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10293 
10294   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10295 
10296   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10297                      SourceLocation SL) {
10298     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10299       asDerived().visitArray(PCK, AT, SL);
10300       return;
10301     }
10302 
10303     Super::visitWithKind(PCK, FT, SL);
10304   }
10305 
10306   void visitARCStrong(QualType FT, SourceLocation SL) {
10307     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10308   }
10309   void visitARCWeak(QualType FT, SourceLocation SL) {
10310     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10311   }
10312   void visitStruct(QualType FT, SourceLocation SL) {
10313     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10314       visit(FD->getType(), FD->getLocation());
10315   }
10316   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10317                   SourceLocation SL) {
10318     visit(getContext().getBaseElementType(AT), SL);
10319   }
10320   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10321                 SourceLocation SL) {}
10322   void visitTrivial(QualType FT, SourceLocation SL) {}
10323   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10324 
10325   static void diag(QualType RT, const Expr *E, Sema &S) {
10326     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10327   }
10328 
10329   ASTContext &getContext() { return S.getASTContext(); }
10330 
10331   const Expr *E;
10332   Sema &S;
10333 };
10334 
10335 }
10336 
10337 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10338 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10339   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10340 
10341   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10342     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10343       return false;
10344 
10345     return doesExprLikelyComputeSize(BO->getLHS()) ||
10346            doesExprLikelyComputeSize(BO->getRHS());
10347   }
10348 
10349   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10350 }
10351 
10352 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10353 ///
10354 /// \code
10355 ///   #define MACRO 0
10356 ///   foo(MACRO);
10357 ///   foo(0);
10358 /// \endcode
10359 ///
10360 /// This should return true for the first call to foo, but not for the second
10361 /// (regardless of whether foo is a macro or function).
10362 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10363                                         SourceLocation CallLoc,
10364                                         SourceLocation ArgLoc) {
10365   if (!CallLoc.isMacroID())
10366     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10367 
10368   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10369          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10370 }
10371 
10372 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10373 /// last two arguments transposed.
10374 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10375   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10376     return;
10377 
10378   const Expr *SizeArg =
10379     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10380 
10381   auto isLiteralZero = [](const Expr *E) {
10382     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10383   };
10384 
10385   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10386   SourceLocation CallLoc = Call->getRParenLoc();
10387   SourceManager &SM = S.getSourceManager();
10388   if (isLiteralZero(SizeArg) &&
10389       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10390 
10391     SourceLocation DiagLoc = SizeArg->getExprLoc();
10392 
10393     // Some platforms #define bzero to __builtin_memset. See if this is the
10394     // case, and if so, emit a better diagnostic.
10395     if (BId == Builtin::BIbzero ||
10396         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10397                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10398       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10399       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10400     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10401       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10402       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10403     }
10404     return;
10405   }
10406 
10407   // If the second argument to a memset is a sizeof expression and the third
10408   // isn't, this is also likely an error. This should catch
10409   // 'memset(buf, sizeof(buf), 0xff)'.
10410   if (BId == Builtin::BImemset &&
10411       doesExprLikelyComputeSize(Call->getArg(1)) &&
10412       !doesExprLikelyComputeSize(Call->getArg(2))) {
10413     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10414     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10415     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10416     return;
10417   }
10418 }
10419 
10420 /// Check for dangerous or invalid arguments to memset().
10421 ///
10422 /// This issues warnings on known problematic, dangerous or unspecified
10423 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10424 /// function calls.
10425 ///
10426 /// \param Call The call expression to diagnose.
10427 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10428                                    unsigned BId,
10429                                    IdentifierInfo *FnName) {
10430   assert(BId != 0);
10431 
10432   // It is possible to have a non-standard definition of memset.  Validate
10433   // we have enough arguments, and if not, abort further checking.
10434   unsigned ExpectedNumArgs =
10435       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10436   if (Call->getNumArgs() < ExpectedNumArgs)
10437     return;
10438 
10439   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10440                       BId == Builtin::BIstrndup ? 1 : 2);
10441   unsigned LenArg =
10442       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10443   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10444 
10445   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10446                                      Call->getBeginLoc(), Call->getRParenLoc()))
10447     return;
10448 
10449   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10450   CheckMemaccessSize(*this, BId, Call);
10451 
10452   // We have special checking when the length is a sizeof expression.
10453   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10454   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10455   llvm::FoldingSetNodeID SizeOfArgID;
10456 
10457   // Although widely used, 'bzero' is not a standard function. Be more strict
10458   // with the argument types before allowing diagnostics and only allow the
10459   // form bzero(ptr, sizeof(...)).
10460   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10461   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10462     return;
10463 
10464   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10465     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10466     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10467 
10468     QualType DestTy = Dest->getType();
10469     QualType PointeeTy;
10470     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10471       PointeeTy = DestPtrTy->getPointeeType();
10472 
10473       // Never warn about void type pointers. This can be used to suppress
10474       // false positives.
10475       if (PointeeTy->isVoidType())
10476         continue;
10477 
10478       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10479       // actually comparing the expressions for equality. Because computing the
10480       // expression IDs can be expensive, we only do this if the diagnostic is
10481       // enabled.
10482       if (SizeOfArg &&
10483           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10484                            SizeOfArg->getExprLoc())) {
10485         // We only compute IDs for expressions if the warning is enabled, and
10486         // cache the sizeof arg's ID.
10487         if (SizeOfArgID == llvm::FoldingSetNodeID())
10488           SizeOfArg->Profile(SizeOfArgID, Context, true);
10489         llvm::FoldingSetNodeID DestID;
10490         Dest->Profile(DestID, Context, true);
10491         if (DestID == SizeOfArgID) {
10492           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10493           //       over sizeof(src) as well.
10494           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10495           StringRef ReadableName = FnName->getName();
10496 
10497           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10498             if (UnaryOp->getOpcode() == UO_AddrOf)
10499               ActionIdx = 1; // If its an address-of operator, just remove it.
10500           if (!PointeeTy->isIncompleteType() &&
10501               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10502             ActionIdx = 2; // If the pointee's size is sizeof(char),
10503                            // suggest an explicit length.
10504 
10505           // If the function is defined as a builtin macro, do not show macro
10506           // expansion.
10507           SourceLocation SL = SizeOfArg->getExprLoc();
10508           SourceRange DSR = Dest->getSourceRange();
10509           SourceRange SSR = SizeOfArg->getSourceRange();
10510           SourceManager &SM = getSourceManager();
10511 
10512           if (SM.isMacroArgExpansion(SL)) {
10513             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10514             SL = SM.getSpellingLoc(SL);
10515             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10516                              SM.getSpellingLoc(DSR.getEnd()));
10517             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10518                              SM.getSpellingLoc(SSR.getEnd()));
10519           }
10520 
10521           DiagRuntimeBehavior(SL, SizeOfArg,
10522                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10523                                 << ReadableName
10524                                 << PointeeTy
10525                                 << DestTy
10526                                 << DSR
10527                                 << SSR);
10528           DiagRuntimeBehavior(SL, SizeOfArg,
10529                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10530                                 << ActionIdx
10531                                 << SSR);
10532 
10533           break;
10534         }
10535       }
10536 
10537       // Also check for cases where the sizeof argument is the exact same
10538       // type as the memory argument, and where it points to a user-defined
10539       // record type.
10540       if (SizeOfArgTy != QualType()) {
10541         if (PointeeTy->isRecordType() &&
10542             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10543           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10544                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10545                                 << FnName << SizeOfArgTy << ArgIdx
10546                                 << PointeeTy << Dest->getSourceRange()
10547                                 << LenExpr->getSourceRange());
10548           break;
10549         }
10550       }
10551     } else if (DestTy->isArrayType()) {
10552       PointeeTy = DestTy;
10553     }
10554 
10555     if (PointeeTy == QualType())
10556       continue;
10557 
10558     // Always complain about dynamic classes.
10559     bool IsContained;
10560     if (const CXXRecordDecl *ContainedRD =
10561             getContainedDynamicClass(PointeeTy, IsContained)) {
10562 
10563       unsigned OperationType = 0;
10564       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10565       // "overwritten" if we're warning about the destination for any call
10566       // but memcmp; otherwise a verb appropriate to the call.
10567       if (ArgIdx != 0 || IsCmp) {
10568         if (BId == Builtin::BImemcpy)
10569           OperationType = 1;
10570         else if(BId == Builtin::BImemmove)
10571           OperationType = 2;
10572         else if (IsCmp)
10573           OperationType = 3;
10574       }
10575 
10576       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10577                           PDiag(diag::warn_dyn_class_memaccess)
10578                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10579                               << IsContained << ContainedRD << OperationType
10580                               << Call->getCallee()->getSourceRange());
10581     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10582              BId != Builtin::BImemset)
10583       DiagRuntimeBehavior(
10584         Dest->getExprLoc(), Dest,
10585         PDiag(diag::warn_arc_object_memaccess)
10586           << ArgIdx << FnName << PointeeTy
10587           << Call->getCallee()->getSourceRange());
10588     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10589       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10590           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10591         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10592                             PDiag(diag::warn_cstruct_memaccess)
10593                                 << ArgIdx << FnName << PointeeTy << 0);
10594         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10595       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10596                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10597         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10598                             PDiag(diag::warn_cstruct_memaccess)
10599                                 << ArgIdx << FnName << PointeeTy << 1);
10600         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10601       } else {
10602         continue;
10603       }
10604     } else
10605       continue;
10606 
10607     DiagRuntimeBehavior(
10608       Dest->getExprLoc(), Dest,
10609       PDiag(diag::note_bad_memaccess_silence)
10610         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10611     break;
10612   }
10613 }
10614 
10615 // A little helper routine: ignore addition and subtraction of integer literals.
10616 // This intentionally does not ignore all integer constant expressions because
10617 // we don't want to remove sizeof().
10618 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10619   Ex = Ex->IgnoreParenCasts();
10620 
10621   while (true) {
10622     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10623     if (!BO || !BO->isAdditiveOp())
10624       break;
10625 
10626     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10627     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10628 
10629     if (isa<IntegerLiteral>(RHS))
10630       Ex = LHS;
10631     else if (isa<IntegerLiteral>(LHS))
10632       Ex = RHS;
10633     else
10634       break;
10635   }
10636 
10637   return Ex;
10638 }
10639 
10640 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10641                                                       ASTContext &Context) {
10642   // Only handle constant-sized or VLAs, but not flexible members.
10643   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10644     // Only issue the FIXIT for arrays of size > 1.
10645     if (CAT->getSize().getSExtValue() <= 1)
10646       return false;
10647   } else if (!Ty->isVariableArrayType()) {
10648     return false;
10649   }
10650   return true;
10651 }
10652 
10653 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10654 // be the size of the source, instead of the destination.
10655 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10656                                     IdentifierInfo *FnName) {
10657 
10658   // Don't crash if the user has the wrong number of arguments
10659   unsigned NumArgs = Call->getNumArgs();
10660   if ((NumArgs != 3) && (NumArgs != 4))
10661     return;
10662 
10663   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10664   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10665   const Expr *CompareWithSrc = nullptr;
10666 
10667   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10668                                      Call->getBeginLoc(), Call->getRParenLoc()))
10669     return;
10670 
10671   // Look for 'strlcpy(dst, x, sizeof(x))'
10672   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10673     CompareWithSrc = Ex;
10674   else {
10675     // Look for 'strlcpy(dst, x, strlen(x))'
10676     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10677       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10678           SizeCall->getNumArgs() == 1)
10679         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10680     }
10681   }
10682 
10683   if (!CompareWithSrc)
10684     return;
10685 
10686   // Determine if the argument to sizeof/strlen is equal to the source
10687   // argument.  In principle there's all kinds of things you could do
10688   // here, for instance creating an == expression and evaluating it with
10689   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10690   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10691   if (!SrcArgDRE)
10692     return;
10693 
10694   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10695   if (!CompareWithSrcDRE ||
10696       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10697     return;
10698 
10699   const Expr *OriginalSizeArg = Call->getArg(2);
10700   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10701       << OriginalSizeArg->getSourceRange() << FnName;
10702 
10703   // Output a FIXIT hint if the destination is an array (rather than a
10704   // pointer to an array).  This could be enhanced to handle some
10705   // pointers if we know the actual size, like if DstArg is 'array+2'
10706   // we could say 'sizeof(array)-2'.
10707   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10708   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10709     return;
10710 
10711   SmallString<128> sizeString;
10712   llvm::raw_svector_ostream OS(sizeString);
10713   OS << "sizeof(";
10714   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10715   OS << ")";
10716 
10717   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10718       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10719                                       OS.str());
10720 }
10721 
10722 /// Check if two expressions refer to the same declaration.
10723 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10724   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10725     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10726       return D1->getDecl() == D2->getDecl();
10727   return false;
10728 }
10729 
10730 static const Expr *getStrlenExprArg(const Expr *E) {
10731   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10732     const FunctionDecl *FD = CE->getDirectCallee();
10733     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10734       return nullptr;
10735     return CE->getArg(0)->IgnoreParenCasts();
10736   }
10737   return nullptr;
10738 }
10739 
10740 // Warn on anti-patterns as the 'size' argument to strncat.
10741 // The correct size argument should look like following:
10742 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10743 void Sema::CheckStrncatArguments(const CallExpr *CE,
10744                                  IdentifierInfo *FnName) {
10745   // Don't crash if the user has the wrong number of arguments.
10746   if (CE->getNumArgs() < 3)
10747     return;
10748   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10749   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10750   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10751 
10752   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10753                                      CE->getRParenLoc()))
10754     return;
10755 
10756   // Identify common expressions, which are wrongly used as the size argument
10757   // to strncat and may lead to buffer overflows.
10758   unsigned PatternType = 0;
10759   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10760     // - sizeof(dst)
10761     if (referToTheSameDecl(SizeOfArg, DstArg))
10762       PatternType = 1;
10763     // - sizeof(src)
10764     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10765       PatternType = 2;
10766   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10767     if (BE->getOpcode() == BO_Sub) {
10768       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10769       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10770       // - sizeof(dst) - strlen(dst)
10771       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10772           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10773         PatternType = 1;
10774       // - sizeof(src) - (anything)
10775       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10776         PatternType = 2;
10777     }
10778   }
10779 
10780   if (PatternType == 0)
10781     return;
10782 
10783   // Generate the diagnostic.
10784   SourceLocation SL = LenArg->getBeginLoc();
10785   SourceRange SR = LenArg->getSourceRange();
10786   SourceManager &SM = getSourceManager();
10787 
10788   // If the function is defined as a builtin macro, do not show macro expansion.
10789   if (SM.isMacroArgExpansion(SL)) {
10790     SL = SM.getSpellingLoc(SL);
10791     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10792                      SM.getSpellingLoc(SR.getEnd()));
10793   }
10794 
10795   // Check if the destination is an array (rather than a pointer to an array).
10796   QualType DstTy = DstArg->getType();
10797   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10798                                                                     Context);
10799   if (!isKnownSizeArray) {
10800     if (PatternType == 1)
10801       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10802     else
10803       Diag(SL, diag::warn_strncat_src_size) << SR;
10804     return;
10805   }
10806 
10807   if (PatternType == 1)
10808     Diag(SL, diag::warn_strncat_large_size) << SR;
10809   else
10810     Diag(SL, diag::warn_strncat_src_size) << SR;
10811 
10812   SmallString<128> sizeString;
10813   llvm::raw_svector_ostream OS(sizeString);
10814   OS << "sizeof(";
10815   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10816   OS << ") - ";
10817   OS << "strlen(";
10818   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10819   OS << ") - 1";
10820 
10821   Diag(SL, diag::note_strncat_wrong_size)
10822     << FixItHint::CreateReplacement(SR, OS.str());
10823 }
10824 
10825 namespace {
10826 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10827                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10828   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10829     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10830         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10831     return;
10832   }
10833 }
10834 
10835 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10836                                  const UnaryOperator *UnaryExpr) {
10837   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10838     const Decl *D = Lvalue->getDecl();
10839     if (isa<DeclaratorDecl>(D))
10840       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10841         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10842   }
10843 
10844   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10845     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10846                                       Lvalue->getMemberDecl());
10847 }
10848 
10849 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10850                             const UnaryOperator *UnaryExpr) {
10851   const auto *Lambda = dyn_cast<LambdaExpr>(
10852       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10853   if (!Lambda)
10854     return;
10855 
10856   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10857       << CalleeName << 2 /*object: lambda expression*/;
10858 }
10859 
10860 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10861                                   const DeclRefExpr *Lvalue) {
10862   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10863   if (Var == nullptr)
10864     return;
10865 
10866   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10867       << CalleeName << 0 /*object: */ << Var;
10868 }
10869 
10870 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10871                             const CastExpr *Cast) {
10872   SmallString<128> SizeString;
10873   llvm::raw_svector_ostream OS(SizeString);
10874 
10875   clang::CastKind Kind = Cast->getCastKind();
10876   if (Kind == clang::CK_BitCast &&
10877       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10878     return;
10879   if (Kind == clang::CK_IntegralToPointer &&
10880       !isa<IntegerLiteral>(
10881           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10882     return;
10883 
10884   switch (Cast->getCastKind()) {
10885   case clang::CK_BitCast:
10886   case clang::CK_IntegralToPointer:
10887   case clang::CK_FunctionToPointerDecay:
10888     OS << '\'';
10889     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10890     OS << '\'';
10891     break;
10892   default:
10893     return;
10894   }
10895 
10896   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10897       << CalleeName << 0 /*object: */ << OS.str();
10898 }
10899 } // namespace
10900 
10901 /// Alerts the user that they are attempting to free a non-malloc'd object.
10902 void Sema::CheckFreeArguments(const CallExpr *E) {
10903   const std::string CalleeName =
10904       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10905 
10906   { // Prefer something that doesn't involve a cast to make things simpler.
10907     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10908     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10909       switch (UnaryExpr->getOpcode()) {
10910       case UnaryOperator::Opcode::UO_AddrOf:
10911         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10912       case UnaryOperator::Opcode::UO_Plus:
10913         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10914       default:
10915         break;
10916       }
10917 
10918     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10919       if (Lvalue->getType()->isArrayType())
10920         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10921 
10922     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10923       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10924           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10925       return;
10926     }
10927 
10928     if (isa<BlockExpr>(Arg)) {
10929       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10930           << CalleeName << 1 /*object: block*/;
10931       return;
10932     }
10933   }
10934   // Maybe the cast was important, check after the other cases.
10935   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10936     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10937 }
10938 
10939 void
10940 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10941                          SourceLocation ReturnLoc,
10942                          bool isObjCMethod,
10943                          const AttrVec *Attrs,
10944                          const FunctionDecl *FD) {
10945   // Check if the return value is null but should not be.
10946   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10947        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10948       CheckNonNullExpr(*this, RetValExp))
10949     Diag(ReturnLoc, diag::warn_null_ret)
10950       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10951 
10952   // C++11 [basic.stc.dynamic.allocation]p4:
10953   //   If an allocation function declared with a non-throwing
10954   //   exception-specification fails to allocate storage, it shall return
10955   //   a null pointer. Any other allocation function that fails to allocate
10956   //   storage shall indicate failure only by throwing an exception [...]
10957   if (FD) {
10958     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10959     if (Op == OO_New || Op == OO_Array_New) {
10960       const FunctionProtoType *Proto
10961         = FD->getType()->castAs<FunctionProtoType>();
10962       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10963           CheckNonNullExpr(*this, RetValExp))
10964         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10965           << FD << getLangOpts().CPlusPlus11;
10966     }
10967   }
10968 
10969   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10970   // here prevent the user from using a PPC MMA type as trailing return type.
10971   if (Context.getTargetInfo().getTriple().isPPC64())
10972     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10973 }
10974 
10975 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10976 
10977 /// Check for comparisons of floating point operands using != and ==.
10978 /// Issue a warning if these are no self-comparisons, as they are not likely
10979 /// to do what the programmer intended.
10980 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10981   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10982   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10983 
10984   // Special case: check for x == x (which is OK).
10985   // Do not emit warnings for such cases.
10986   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10987     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10988       if (DRL->getDecl() == DRR->getDecl())
10989         return;
10990 
10991   // Special case: check for comparisons against literals that can be exactly
10992   //  represented by APFloat.  In such cases, do not emit a warning.  This
10993   //  is a heuristic: often comparison against such literals are used to
10994   //  detect if a value in a variable has not changed.  This clearly can
10995   //  lead to false negatives.
10996   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10997     if (FLL->isExact())
10998       return;
10999   } else
11000     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11001       if (FLR->isExact())
11002         return;
11003 
11004   // Check for comparisons with builtin types.
11005   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11006     if (CL->getBuiltinCallee())
11007       return;
11008 
11009   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11010     if (CR->getBuiltinCallee())
11011       return;
11012 
11013   // Emit the diagnostic.
11014   Diag(Loc, diag::warn_floatingpoint_eq)
11015     << LHS->getSourceRange() << RHS->getSourceRange();
11016 }
11017 
11018 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11019 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11020 
11021 namespace {
11022 
11023 /// Structure recording the 'active' range of an integer-valued
11024 /// expression.
11025 struct IntRange {
11026   /// The number of bits active in the int. Note that this includes exactly one
11027   /// sign bit if !NonNegative.
11028   unsigned Width;
11029 
11030   /// True if the int is known not to have negative values. If so, all leading
11031   /// bits before Width are known zero, otherwise they are known to be the
11032   /// same as the MSB within Width.
11033   bool NonNegative;
11034 
11035   IntRange(unsigned Width, bool NonNegative)
11036       : Width(Width), NonNegative(NonNegative) {}
11037 
11038   /// Number of bits excluding the sign bit.
11039   unsigned valueBits() const {
11040     return NonNegative ? Width : Width - 1;
11041   }
11042 
11043   /// Returns the range of the bool type.
11044   static IntRange forBoolType() {
11045     return IntRange(1, true);
11046   }
11047 
11048   /// Returns the range of an opaque value of the given integral type.
11049   static IntRange forValueOfType(ASTContext &C, QualType T) {
11050     return forValueOfCanonicalType(C,
11051                           T->getCanonicalTypeInternal().getTypePtr());
11052   }
11053 
11054   /// Returns the range of an opaque value of a canonical integral type.
11055   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11056     assert(T->isCanonicalUnqualified());
11057 
11058     if (const VectorType *VT = dyn_cast<VectorType>(T))
11059       T = VT->getElementType().getTypePtr();
11060     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11061       T = CT->getElementType().getTypePtr();
11062     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11063       T = AT->getValueType().getTypePtr();
11064 
11065     if (!C.getLangOpts().CPlusPlus) {
11066       // For enum types in C code, use the underlying datatype.
11067       if (const EnumType *ET = dyn_cast<EnumType>(T))
11068         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11069     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11070       // For enum types in C++, use the known bit width of the enumerators.
11071       EnumDecl *Enum = ET->getDecl();
11072       // In C++11, enums can have a fixed underlying type. Use this type to
11073       // compute the range.
11074       if (Enum->isFixed()) {
11075         return IntRange(C.getIntWidth(QualType(T, 0)),
11076                         !ET->isSignedIntegerOrEnumerationType());
11077       }
11078 
11079       unsigned NumPositive = Enum->getNumPositiveBits();
11080       unsigned NumNegative = Enum->getNumNegativeBits();
11081 
11082       if (NumNegative == 0)
11083         return IntRange(NumPositive, true/*NonNegative*/);
11084       else
11085         return IntRange(std::max(NumPositive + 1, NumNegative),
11086                         false/*NonNegative*/);
11087     }
11088 
11089     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11090       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11091 
11092     const BuiltinType *BT = cast<BuiltinType>(T);
11093     assert(BT->isInteger());
11094 
11095     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11096   }
11097 
11098   /// Returns the "target" range of a canonical integral type, i.e.
11099   /// the range of values expressible in the type.
11100   ///
11101   /// This matches forValueOfCanonicalType except that enums have the
11102   /// full range of their type, not the range of their enumerators.
11103   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11104     assert(T->isCanonicalUnqualified());
11105 
11106     if (const VectorType *VT = dyn_cast<VectorType>(T))
11107       T = VT->getElementType().getTypePtr();
11108     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11109       T = CT->getElementType().getTypePtr();
11110     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11111       T = AT->getValueType().getTypePtr();
11112     if (const EnumType *ET = dyn_cast<EnumType>(T))
11113       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11114 
11115     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11116       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11117 
11118     const BuiltinType *BT = cast<BuiltinType>(T);
11119     assert(BT->isInteger());
11120 
11121     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11122   }
11123 
11124   /// Returns the supremum of two ranges: i.e. their conservative merge.
11125   static IntRange join(IntRange L, IntRange R) {
11126     bool Unsigned = L.NonNegative && R.NonNegative;
11127     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11128                     L.NonNegative && R.NonNegative);
11129   }
11130 
11131   /// Return the range of a bitwise-AND of the two ranges.
11132   static IntRange bit_and(IntRange L, IntRange R) {
11133     unsigned Bits = std::max(L.Width, R.Width);
11134     bool NonNegative = false;
11135     if (L.NonNegative) {
11136       Bits = std::min(Bits, L.Width);
11137       NonNegative = true;
11138     }
11139     if (R.NonNegative) {
11140       Bits = std::min(Bits, R.Width);
11141       NonNegative = true;
11142     }
11143     return IntRange(Bits, NonNegative);
11144   }
11145 
11146   /// Return the range of a sum of the two ranges.
11147   static IntRange sum(IntRange L, IntRange R) {
11148     bool Unsigned = L.NonNegative && R.NonNegative;
11149     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11150                     Unsigned);
11151   }
11152 
11153   /// Return the range of a difference of the two ranges.
11154   static IntRange difference(IntRange L, IntRange R) {
11155     // We need a 1-bit-wider range if:
11156     //   1) LHS can be negative: least value can be reduced.
11157     //   2) RHS can be negative: greatest value can be increased.
11158     bool CanWiden = !L.NonNegative || !R.NonNegative;
11159     bool Unsigned = L.NonNegative && R.Width == 0;
11160     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11161                         !Unsigned,
11162                     Unsigned);
11163   }
11164 
11165   /// Return the range of a product of the two ranges.
11166   static IntRange product(IntRange L, IntRange R) {
11167     // If both LHS and RHS can be negative, we can form
11168     //   -2^L * -2^R = 2^(L + R)
11169     // which requires L + R + 1 value bits to represent.
11170     bool CanWiden = !L.NonNegative && !R.NonNegative;
11171     bool Unsigned = L.NonNegative && R.NonNegative;
11172     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11173                     Unsigned);
11174   }
11175 
11176   /// Return the range of a remainder operation between the two ranges.
11177   static IntRange rem(IntRange L, IntRange R) {
11178     // The result of a remainder can't be larger than the result of
11179     // either side. The sign of the result is the sign of the LHS.
11180     bool Unsigned = L.NonNegative;
11181     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11182                     Unsigned);
11183   }
11184 };
11185 
11186 } // namespace
11187 
11188 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11189                               unsigned MaxWidth) {
11190   if (value.isSigned() && value.isNegative())
11191     return IntRange(value.getMinSignedBits(), false);
11192 
11193   if (value.getBitWidth() > MaxWidth)
11194     value = value.trunc(MaxWidth);
11195 
11196   // isNonNegative() just checks the sign bit without considering
11197   // signedness.
11198   return IntRange(value.getActiveBits(), true);
11199 }
11200 
11201 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11202                               unsigned MaxWidth) {
11203   if (result.isInt())
11204     return GetValueRange(C, result.getInt(), MaxWidth);
11205 
11206   if (result.isVector()) {
11207     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11208     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11209       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11210       R = IntRange::join(R, El);
11211     }
11212     return R;
11213   }
11214 
11215   if (result.isComplexInt()) {
11216     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11217     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11218     return IntRange::join(R, I);
11219   }
11220 
11221   // This can happen with lossless casts to intptr_t of "based" lvalues.
11222   // Assume it might use arbitrary bits.
11223   // FIXME: The only reason we need to pass the type in here is to get
11224   // the sign right on this one case.  It would be nice if APValue
11225   // preserved this.
11226   assert(result.isLValue() || result.isAddrLabelDiff());
11227   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11228 }
11229 
11230 static QualType GetExprType(const Expr *E) {
11231   QualType Ty = E->getType();
11232   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11233     Ty = AtomicRHS->getValueType();
11234   return Ty;
11235 }
11236 
11237 /// Pseudo-evaluate the given integer expression, estimating the
11238 /// range of values it might take.
11239 ///
11240 /// \param MaxWidth The width to which the value will be truncated.
11241 /// \param Approximate If \c true, return a likely range for the result: in
11242 ///        particular, assume that arithmetic on narrower types doesn't leave
11243 ///        those types. If \c false, return a range including all possible
11244 ///        result values.
11245 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11246                              bool InConstantContext, bool Approximate) {
11247   E = E->IgnoreParens();
11248 
11249   // Try a full evaluation first.
11250   Expr::EvalResult result;
11251   if (E->EvaluateAsRValue(result, C, InConstantContext))
11252     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11253 
11254   // I think we only want to look through implicit casts here; if the
11255   // user has an explicit widening cast, we should treat the value as
11256   // being of the new, wider type.
11257   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11258     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11259       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11260                           Approximate);
11261 
11262     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11263 
11264     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11265                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11266 
11267     // Assume that non-integer casts can span the full range of the type.
11268     if (!isIntegerCast)
11269       return OutputTypeRange;
11270 
11271     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11272                                      std::min(MaxWidth, OutputTypeRange.Width),
11273                                      InConstantContext, Approximate);
11274 
11275     // Bail out if the subexpr's range is as wide as the cast type.
11276     if (SubRange.Width >= OutputTypeRange.Width)
11277       return OutputTypeRange;
11278 
11279     // Otherwise, we take the smaller width, and we're non-negative if
11280     // either the output type or the subexpr is.
11281     return IntRange(SubRange.Width,
11282                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11283   }
11284 
11285   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11286     // If we can fold the condition, just take that operand.
11287     bool CondResult;
11288     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11289       return GetExprRange(C,
11290                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11291                           MaxWidth, InConstantContext, Approximate);
11292 
11293     // Otherwise, conservatively merge.
11294     // GetExprRange requires an integer expression, but a throw expression
11295     // results in a void type.
11296     Expr *E = CO->getTrueExpr();
11297     IntRange L = E->getType()->isVoidType()
11298                      ? IntRange{0, true}
11299                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11300     E = CO->getFalseExpr();
11301     IntRange R = E->getType()->isVoidType()
11302                      ? IntRange{0, true}
11303                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11304     return IntRange::join(L, R);
11305   }
11306 
11307   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11308     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11309 
11310     switch (BO->getOpcode()) {
11311     case BO_Cmp:
11312       llvm_unreachable("builtin <=> should have class type");
11313 
11314     // Boolean-valued operations are single-bit and positive.
11315     case BO_LAnd:
11316     case BO_LOr:
11317     case BO_LT:
11318     case BO_GT:
11319     case BO_LE:
11320     case BO_GE:
11321     case BO_EQ:
11322     case BO_NE:
11323       return IntRange::forBoolType();
11324 
11325     // The type of the assignments is the type of the LHS, so the RHS
11326     // is not necessarily the same type.
11327     case BO_MulAssign:
11328     case BO_DivAssign:
11329     case BO_RemAssign:
11330     case BO_AddAssign:
11331     case BO_SubAssign:
11332     case BO_XorAssign:
11333     case BO_OrAssign:
11334       // TODO: bitfields?
11335       return IntRange::forValueOfType(C, GetExprType(E));
11336 
11337     // Simple assignments just pass through the RHS, which will have
11338     // been coerced to the LHS type.
11339     case BO_Assign:
11340       // TODO: bitfields?
11341       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11342                           Approximate);
11343 
11344     // Operations with opaque sources are black-listed.
11345     case BO_PtrMemD:
11346     case BO_PtrMemI:
11347       return IntRange::forValueOfType(C, GetExprType(E));
11348 
11349     // Bitwise-and uses the *infinum* of the two source ranges.
11350     case BO_And:
11351     case BO_AndAssign:
11352       Combine = IntRange::bit_and;
11353       break;
11354 
11355     // Left shift gets black-listed based on a judgement call.
11356     case BO_Shl:
11357       // ...except that we want to treat '1 << (blah)' as logically
11358       // positive.  It's an important idiom.
11359       if (IntegerLiteral *I
11360             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11361         if (I->getValue() == 1) {
11362           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11363           return IntRange(R.Width, /*NonNegative*/ true);
11364         }
11365       }
11366       LLVM_FALLTHROUGH;
11367 
11368     case BO_ShlAssign:
11369       return IntRange::forValueOfType(C, GetExprType(E));
11370 
11371     // Right shift by a constant can narrow its left argument.
11372     case BO_Shr:
11373     case BO_ShrAssign: {
11374       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11375                                 Approximate);
11376 
11377       // If the shift amount is a positive constant, drop the width by
11378       // that much.
11379       if (Optional<llvm::APSInt> shift =
11380               BO->getRHS()->getIntegerConstantExpr(C)) {
11381         if (shift->isNonNegative()) {
11382           unsigned zext = shift->getZExtValue();
11383           if (zext >= L.Width)
11384             L.Width = (L.NonNegative ? 0 : 1);
11385           else
11386             L.Width -= zext;
11387         }
11388       }
11389 
11390       return L;
11391     }
11392 
11393     // Comma acts as its right operand.
11394     case BO_Comma:
11395       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11396                           Approximate);
11397 
11398     case BO_Add:
11399       if (!Approximate)
11400         Combine = IntRange::sum;
11401       break;
11402 
11403     case BO_Sub:
11404       if (BO->getLHS()->getType()->isPointerType())
11405         return IntRange::forValueOfType(C, GetExprType(E));
11406       if (!Approximate)
11407         Combine = IntRange::difference;
11408       break;
11409 
11410     case BO_Mul:
11411       if (!Approximate)
11412         Combine = IntRange::product;
11413       break;
11414 
11415     // The width of a division result is mostly determined by the size
11416     // of the LHS.
11417     case BO_Div: {
11418       // Don't 'pre-truncate' the operands.
11419       unsigned opWidth = C.getIntWidth(GetExprType(E));
11420       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11421                                 Approximate);
11422 
11423       // If the divisor is constant, use that.
11424       if (Optional<llvm::APSInt> divisor =
11425               BO->getRHS()->getIntegerConstantExpr(C)) {
11426         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11427         if (log2 >= L.Width)
11428           L.Width = (L.NonNegative ? 0 : 1);
11429         else
11430           L.Width = std::min(L.Width - log2, MaxWidth);
11431         return L;
11432       }
11433 
11434       // Otherwise, just use the LHS's width.
11435       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11436       // could be -1.
11437       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11438                                 Approximate);
11439       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11440     }
11441 
11442     case BO_Rem:
11443       Combine = IntRange::rem;
11444       break;
11445 
11446     // The default behavior is okay for these.
11447     case BO_Xor:
11448     case BO_Or:
11449       break;
11450     }
11451 
11452     // Combine the two ranges, but limit the result to the type in which we
11453     // performed the computation.
11454     QualType T = GetExprType(E);
11455     unsigned opWidth = C.getIntWidth(T);
11456     IntRange L =
11457         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11458     IntRange R =
11459         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11460     IntRange C = Combine(L, R);
11461     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11462     C.Width = std::min(C.Width, MaxWidth);
11463     return C;
11464   }
11465 
11466   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11467     switch (UO->getOpcode()) {
11468     // Boolean-valued operations are white-listed.
11469     case UO_LNot:
11470       return IntRange::forBoolType();
11471 
11472     // Operations with opaque sources are black-listed.
11473     case UO_Deref:
11474     case UO_AddrOf: // should be impossible
11475       return IntRange::forValueOfType(C, GetExprType(E));
11476 
11477     default:
11478       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11479                           Approximate);
11480     }
11481   }
11482 
11483   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11484     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11485                         Approximate);
11486 
11487   if (const auto *BitField = E->getSourceBitField())
11488     return IntRange(BitField->getBitWidthValue(C),
11489                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11490 
11491   return IntRange::forValueOfType(C, GetExprType(E));
11492 }
11493 
11494 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11495                              bool InConstantContext, bool Approximate) {
11496   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11497                       Approximate);
11498 }
11499 
11500 /// Checks whether the given value, which currently has the given
11501 /// source semantics, has the same value when coerced through the
11502 /// target semantics.
11503 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11504                                  const llvm::fltSemantics &Src,
11505                                  const llvm::fltSemantics &Tgt) {
11506   llvm::APFloat truncated = value;
11507 
11508   bool ignored;
11509   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11510   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11511 
11512   return truncated.bitwiseIsEqual(value);
11513 }
11514 
11515 /// Checks whether the given value, which currently has the given
11516 /// source semantics, has the same value when coerced through the
11517 /// target semantics.
11518 ///
11519 /// The value might be a vector of floats (or a complex number).
11520 static bool IsSameFloatAfterCast(const APValue &value,
11521                                  const llvm::fltSemantics &Src,
11522                                  const llvm::fltSemantics &Tgt) {
11523   if (value.isFloat())
11524     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11525 
11526   if (value.isVector()) {
11527     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11528       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11529         return false;
11530     return true;
11531   }
11532 
11533   assert(value.isComplexFloat());
11534   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11535           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11536 }
11537 
11538 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11539                                        bool IsListInit = false);
11540 
11541 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11542   // Suppress cases where we are comparing against an enum constant.
11543   if (const DeclRefExpr *DR =
11544       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11545     if (isa<EnumConstantDecl>(DR->getDecl()))
11546       return true;
11547 
11548   // Suppress cases where the value is expanded from a macro, unless that macro
11549   // is how a language represents a boolean literal. This is the case in both C
11550   // and Objective-C.
11551   SourceLocation BeginLoc = E->getBeginLoc();
11552   if (BeginLoc.isMacroID()) {
11553     StringRef MacroName = Lexer::getImmediateMacroName(
11554         BeginLoc, S.getSourceManager(), S.getLangOpts());
11555     return MacroName != "YES" && MacroName != "NO" &&
11556            MacroName != "true" && MacroName != "false";
11557   }
11558 
11559   return false;
11560 }
11561 
11562 static bool isKnownToHaveUnsignedValue(Expr *E) {
11563   return E->getType()->isIntegerType() &&
11564          (!E->getType()->isSignedIntegerType() ||
11565           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11566 }
11567 
11568 namespace {
11569 /// The promoted range of values of a type. In general this has the
11570 /// following structure:
11571 ///
11572 ///     |-----------| . . . |-----------|
11573 ///     ^           ^       ^           ^
11574 ///    Min       HoleMin  HoleMax      Max
11575 ///
11576 /// ... where there is only a hole if a signed type is promoted to unsigned
11577 /// (in which case Min and Max are the smallest and largest representable
11578 /// values).
11579 struct PromotedRange {
11580   // Min, or HoleMax if there is a hole.
11581   llvm::APSInt PromotedMin;
11582   // Max, or HoleMin if there is a hole.
11583   llvm::APSInt PromotedMax;
11584 
11585   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11586     if (R.Width == 0)
11587       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11588     else if (R.Width >= BitWidth && !Unsigned) {
11589       // Promotion made the type *narrower*. This happens when promoting
11590       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11591       // Treat all values of 'signed int' as being in range for now.
11592       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11593       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11594     } else {
11595       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11596                         .extOrTrunc(BitWidth);
11597       PromotedMin.setIsUnsigned(Unsigned);
11598 
11599       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11600                         .extOrTrunc(BitWidth);
11601       PromotedMax.setIsUnsigned(Unsigned);
11602     }
11603   }
11604 
11605   // Determine whether this range is contiguous (has no hole).
11606   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11607 
11608   // Where a constant value is within the range.
11609   enum ComparisonResult {
11610     LT = 0x1,
11611     LE = 0x2,
11612     GT = 0x4,
11613     GE = 0x8,
11614     EQ = 0x10,
11615     NE = 0x20,
11616     InRangeFlag = 0x40,
11617 
11618     Less = LE | LT | NE,
11619     Min = LE | InRangeFlag,
11620     InRange = InRangeFlag,
11621     Max = GE | InRangeFlag,
11622     Greater = GE | GT | NE,
11623 
11624     OnlyValue = LE | GE | EQ | InRangeFlag,
11625     InHole = NE
11626   };
11627 
11628   ComparisonResult compare(const llvm::APSInt &Value) const {
11629     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11630            Value.isUnsigned() == PromotedMin.isUnsigned());
11631     if (!isContiguous()) {
11632       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11633       if (Value.isMinValue()) return Min;
11634       if (Value.isMaxValue()) return Max;
11635       if (Value >= PromotedMin) return InRange;
11636       if (Value <= PromotedMax) return InRange;
11637       return InHole;
11638     }
11639 
11640     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11641     case -1: return Less;
11642     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11643     case 1:
11644       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11645       case -1: return InRange;
11646       case 0: return Max;
11647       case 1: return Greater;
11648       }
11649     }
11650 
11651     llvm_unreachable("impossible compare result");
11652   }
11653 
11654   static llvm::Optional<StringRef>
11655   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11656     if (Op == BO_Cmp) {
11657       ComparisonResult LTFlag = LT, GTFlag = GT;
11658       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11659 
11660       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11661       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11662       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11663       return llvm::None;
11664     }
11665 
11666     ComparisonResult TrueFlag, FalseFlag;
11667     if (Op == BO_EQ) {
11668       TrueFlag = EQ;
11669       FalseFlag = NE;
11670     } else if (Op == BO_NE) {
11671       TrueFlag = NE;
11672       FalseFlag = EQ;
11673     } else {
11674       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11675         TrueFlag = LT;
11676         FalseFlag = GE;
11677       } else {
11678         TrueFlag = GT;
11679         FalseFlag = LE;
11680       }
11681       if (Op == BO_GE || Op == BO_LE)
11682         std::swap(TrueFlag, FalseFlag);
11683     }
11684     if (R & TrueFlag)
11685       return StringRef("true");
11686     if (R & FalseFlag)
11687       return StringRef("false");
11688     return llvm::None;
11689   }
11690 };
11691 }
11692 
11693 static bool HasEnumType(Expr *E) {
11694   // Strip off implicit integral promotions.
11695   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11696     if (ICE->getCastKind() != CK_IntegralCast &&
11697         ICE->getCastKind() != CK_NoOp)
11698       break;
11699     E = ICE->getSubExpr();
11700   }
11701 
11702   return E->getType()->isEnumeralType();
11703 }
11704 
11705 static int classifyConstantValue(Expr *Constant) {
11706   // The values of this enumeration are used in the diagnostics
11707   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11708   enum ConstantValueKind {
11709     Miscellaneous = 0,
11710     LiteralTrue,
11711     LiteralFalse
11712   };
11713   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11714     return BL->getValue() ? ConstantValueKind::LiteralTrue
11715                           : ConstantValueKind::LiteralFalse;
11716   return ConstantValueKind::Miscellaneous;
11717 }
11718 
11719 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11720                                         Expr *Constant, Expr *Other,
11721                                         const llvm::APSInt &Value,
11722                                         bool RhsConstant) {
11723   if (S.inTemplateInstantiation())
11724     return false;
11725 
11726   Expr *OriginalOther = Other;
11727 
11728   Constant = Constant->IgnoreParenImpCasts();
11729   Other = Other->IgnoreParenImpCasts();
11730 
11731   // Suppress warnings on tautological comparisons between values of the same
11732   // enumeration type. There are only two ways we could warn on this:
11733   //  - If the constant is outside the range of representable values of
11734   //    the enumeration. In such a case, we should warn about the cast
11735   //    to enumeration type, not about the comparison.
11736   //  - If the constant is the maximum / minimum in-range value. For an
11737   //    enumeratin type, such comparisons can be meaningful and useful.
11738   if (Constant->getType()->isEnumeralType() &&
11739       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11740     return false;
11741 
11742   IntRange OtherValueRange = GetExprRange(
11743       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11744 
11745   QualType OtherT = Other->getType();
11746   if (const auto *AT = OtherT->getAs<AtomicType>())
11747     OtherT = AT->getValueType();
11748   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11749 
11750   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11751   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11752   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11753                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11754                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11755 
11756   // Whether we're treating Other as being a bool because of the form of
11757   // expression despite it having another type (typically 'int' in C).
11758   bool OtherIsBooleanDespiteType =
11759       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11760   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11761     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11762 
11763   // Check if all values in the range of possible values of this expression
11764   // lead to the same comparison outcome.
11765   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11766                                         Value.isUnsigned());
11767   auto Cmp = OtherPromotedValueRange.compare(Value);
11768   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11769   if (!Result)
11770     return false;
11771 
11772   // Also consider the range determined by the type alone. This allows us to
11773   // classify the warning under the proper diagnostic group.
11774   bool TautologicalTypeCompare = false;
11775   {
11776     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11777                                          Value.isUnsigned());
11778     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11779     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11780                                                        RhsConstant)) {
11781       TautologicalTypeCompare = true;
11782       Cmp = TypeCmp;
11783       Result = TypeResult;
11784     }
11785   }
11786 
11787   // Don't warn if the non-constant operand actually always evaluates to the
11788   // same value.
11789   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11790     return false;
11791 
11792   // Suppress the diagnostic for an in-range comparison if the constant comes
11793   // from a macro or enumerator. We don't want to diagnose
11794   //
11795   //   some_long_value <= INT_MAX
11796   //
11797   // when sizeof(int) == sizeof(long).
11798   bool InRange = Cmp & PromotedRange::InRangeFlag;
11799   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11800     return false;
11801 
11802   // A comparison of an unsigned bit-field against 0 is really a type problem,
11803   // even though at the type level the bit-field might promote to 'signed int'.
11804   if (Other->refersToBitField() && InRange && Value == 0 &&
11805       Other->getType()->isUnsignedIntegerOrEnumerationType())
11806     TautologicalTypeCompare = true;
11807 
11808   // If this is a comparison to an enum constant, include that
11809   // constant in the diagnostic.
11810   const EnumConstantDecl *ED = nullptr;
11811   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11812     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11813 
11814   // Should be enough for uint128 (39 decimal digits)
11815   SmallString<64> PrettySourceValue;
11816   llvm::raw_svector_ostream OS(PrettySourceValue);
11817   if (ED) {
11818     OS << '\'' << *ED << "' (" << Value << ")";
11819   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11820                Constant->IgnoreParenImpCasts())) {
11821     OS << (BL->getValue() ? "YES" : "NO");
11822   } else {
11823     OS << Value;
11824   }
11825 
11826   if (!TautologicalTypeCompare) {
11827     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11828         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11829         << E->getOpcodeStr() << OS.str() << *Result
11830         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11831     return true;
11832   }
11833 
11834   if (IsObjCSignedCharBool) {
11835     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11836                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11837                               << OS.str() << *Result);
11838     return true;
11839   }
11840 
11841   // FIXME: We use a somewhat different formatting for the in-range cases and
11842   // cases involving boolean values for historical reasons. We should pick a
11843   // consistent way of presenting these diagnostics.
11844   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11845 
11846     S.DiagRuntimeBehavior(
11847         E->getOperatorLoc(), E,
11848         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11849                          : diag::warn_tautological_bool_compare)
11850             << OS.str() << classifyConstantValue(Constant) << OtherT
11851             << OtherIsBooleanDespiteType << *Result
11852             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11853   } else {
11854     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11855     unsigned Diag =
11856         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11857             ? (HasEnumType(OriginalOther)
11858                    ? diag::warn_unsigned_enum_always_true_comparison
11859                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11860                               : diag::warn_unsigned_always_true_comparison)
11861             : diag::warn_tautological_constant_compare;
11862 
11863     S.Diag(E->getOperatorLoc(), Diag)
11864         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11865         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11866   }
11867 
11868   return true;
11869 }
11870 
11871 /// Analyze the operands of the given comparison.  Implements the
11872 /// fallback case from AnalyzeComparison.
11873 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11874   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11875   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11876 }
11877 
11878 /// Implements -Wsign-compare.
11879 ///
11880 /// \param E the binary operator to check for warnings
11881 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11882   // The type the comparison is being performed in.
11883   QualType T = E->getLHS()->getType();
11884 
11885   // Only analyze comparison operators where both sides have been converted to
11886   // the same type.
11887   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11888     return AnalyzeImpConvsInComparison(S, E);
11889 
11890   // Don't analyze value-dependent comparisons directly.
11891   if (E->isValueDependent())
11892     return AnalyzeImpConvsInComparison(S, E);
11893 
11894   Expr *LHS = E->getLHS();
11895   Expr *RHS = E->getRHS();
11896 
11897   if (T->isIntegralType(S.Context)) {
11898     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11899     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11900 
11901     // We don't care about expressions whose result is a constant.
11902     if (RHSValue && LHSValue)
11903       return AnalyzeImpConvsInComparison(S, E);
11904 
11905     // We only care about expressions where just one side is literal
11906     if ((bool)RHSValue ^ (bool)LHSValue) {
11907       // Is the constant on the RHS or LHS?
11908       const bool RhsConstant = (bool)RHSValue;
11909       Expr *Const = RhsConstant ? RHS : LHS;
11910       Expr *Other = RhsConstant ? LHS : RHS;
11911       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11912 
11913       // Check whether an integer constant comparison results in a value
11914       // of 'true' or 'false'.
11915       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11916         return AnalyzeImpConvsInComparison(S, E);
11917     }
11918   }
11919 
11920   if (!T->hasUnsignedIntegerRepresentation()) {
11921     // We don't do anything special if this isn't an unsigned integral
11922     // comparison:  we're only interested in integral comparisons, and
11923     // signed comparisons only happen in cases we don't care to warn about.
11924     return AnalyzeImpConvsInComparison(S, E);
11925   }
11926 
11927   LHS = LHS->IgnoreParenImpCasts();
11928   RHS = RHS->IgnoreParenImpCasts();
11929 
11930   if (!S.getLangOpts().CPlusPlus) {
11931     // Avoid warning about comparison of integers with different signs when
11932     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11933     // the type of `E`.
11934     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11935       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11936     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11937       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11938   }
11939 
11940   // Check to see if one of the (unmodified) operands is of different
11941   // signedness.
11942   Expr *signedOperand, *unsignedOperand;
11943   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11944     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11945            "unsigned comparison between two signed integer expressions?");
11946     signedOperand = LHS;
11947     unsignedOperand = RHS;
11948   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11949     signedOperand = RHS;
11950     unsignedOperand = LHS;
11951   } else {
11952     return AnalyzeImpConvsInComparison(S, E);
11953   }
11954 
11955   // Otherwise, calculate the effective range of the signed operand.
11956   IntRange signedRange = GetExprRange(
11957       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11958 
11959   // Go ahead and analyze implicit conversions in the operands.  Note
11960   // that we skip the implicit conversions on both sides.
11961   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11962   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11963 
11964   // If the signed range is non-negative, -Wsign-compare won't fire.
11965   if (signedRange.NonNegative)
11966     return;
11967 
11968   // For (in)equality comparisons, if the unsigned operand is a
11969   // constant which cannot collide with a overflowed signed operand,
11970   // then reinterpreting the signed operand as unsigned will not
11971   // change the result of the comparison.
11972   if (E->isEqualityOp()) {
11973     unsigned comparisonWidth = S.Context.getIntWidth(T);
11974     IntRange unsignedRange =
11975         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11976                      /*Approximate*/ true);
11977 
11978     // We should never be unable to prove that the unsigned operand is
11979     // non-negative.
11980     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11981 
11982     if (unsignedRange.Width < comparisonWidth)
11983       return;
11984   }
11985 
11986   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11987                         S.PDiag(diag::warn_mixed_sign_comparison)
11988                             << LHS->getType() << RHS->getType()
11989                             << LHS->getSourceRange() << RHS->getSourceRange());
11990 }
11991 
11992 /// Analyzes an attempt to assign the given value to a bitfield.
11993 ///
11994 /// Returns true if there was something fishy about the attempt.
11995 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11996                                       SourceLocation InitLoc) {
11997   assert(Bitfield->isBitField());
11998   if (Bitfield->isInvalidDecl())
11999     return false;
12000 
12001   // White-list bool bitfields.
12002   QualType BitfieldType = Bitfield->getType();
12003   if (BitfieldType->isBooleanType())
12004      return false;
12005 
12006   if (BitfieldType->isEnumeralType()) {
12007     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12008     // If the underlying enum type was not explicitly specified as an unsigned
12009     // type and the enum contain only positive values, MSVC++ will cause an
12010     // inconsistency by storing this as a signed type.
12011     if (S.getLangOpts().CPlusPlus11 &&
12012         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12013         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12014         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12015       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12016           << BitfieldEnumDecl;
12017     }
12018   }
12019 
12020   if (Bitfield->getType()->isBooleanType())
12021     return false;
12022 
12023   // Ignore value- or type-dependent expressions.
12024   if (Bitfield->getBitWidth()->isValueDependent() ||
12025       Bitfield->getBitWidth()->isTypeDependent() ||
12026       Init->isValueDependent() ||
12027       Init->isTypeDependent())
12028     return false;
12029 
12030   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12031   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12032 
12033   Expr::EvalResult Result;
12034   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12035                                    Expr::SE_AllowSideEffects)) {
12036     // The RHS is not constant.  If the RHS has an enum type, make sure the
12037     // bitfield is wide enough to hold all the values of the enum without
12038     // truncation.
12039     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12040       EnumDecl *ED = EnumTy->getDecl();
12041       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12042 
12043       // Enum types are implicitly signed on Windows, so check if there are any
12044       // negative enumerators to see if the enum was intended to be signed or
12045       // not.
12046       bool SignedEnum = ED->getNumNegativeBits() > 0;
12047 
12048       // Check for surprising sign changes when assigning enum values to a
12049       // bitfield of different signedness.  If the bitfield is signed and we
12050       // have exactly the right number of bits to store this unsigned enum,
12051       // suggest changing the enum to an unsigned type. This typically happens
12052       // on Windows where unfixed enums always use an underlying type of 'int'.
12053       unsigned DiagID = 0;
12054       if (SignedEnum && !SignedBitfield) {
12055         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12056       } else if (SignedBitfield && !SignedEnum &&
12057                  ED->getNumPositiveBits() == FieldWidth) {
12058         DiagID = diag::warn_signed_bitfield_enum_conversion;
12059       }
12060 
12061       if (DiagID) {
12062         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12063         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12064         SourceRange TypeRange =
12065             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12066         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12067             << SignedEnum << TypeRange;
12068       }
12069 
12070       // Compute the required bitwidth. If the enum has negative values, we need
12071       // one more bit than the normal number of positive bits to represent the
12072       // sign bit.
12073       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12074                                                   ED->getNumNegativeBits())
12075                                        : ED->getNumPositiveBits();
12076 
12077       // Check the bitwidth.
12078       if (BitsNeeded > FieldWidth) {
12079         Expr *WidthExpr = Bitfield->getBitWidth();
12080         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12081             << Bitfield << ED;
12082         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12083             << BitsNeeded << ED << WidthExpr->getSourceRange();
12084       }
12085     }
12086 
12087     return false;
12088   }
12089 
12090   llvm::APSInt Value = Result.Val.getInt();
12091 
12092   unsigned OriginalWidth = Value.getBitWidth();
12093 
12094   if (!Value.isSigned() || Value.isNegative())
12095     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12096       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12097         OriginalWidth = Value.getMinSignedBits();
12098 
12099   if (OriginalWidth <= FieldWidth)
12100     return false;
12101 
12102   // Compute the value which the bitfield will contain.
12103   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12104   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12105 
12106   // Check whether the stored value is equal to the original value.
12107   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12108   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12109     return false;
12110 
12111   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12112   // therefore don't strictly fit into a signed bitfield of width 1.
12113   if (FieldWidth == 1 && Value == 1)
12114     return false;
12115 
12116   std::string PrettyValue = toString(Value, 10);
12117   std::string PrettyTrunc = toString(TruncatedValue, 10);
12118 
12119   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12120     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12121     << Init->getSourceRange();
12122 
12123   return true;
12124 }
12125 
12126 /// Analyze the given simple or compound assignment for warning-worthy
12127 /// operations.
12128 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12129   // Just recurse on the LHS.
12130   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12131 
12132   // We want to recurse on the RHS as normal unless we're assigning to
12133   // a bitfield.
12134   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12135     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12136                                   E->getOperatorLoc())) {
12137       // Recurse, ignoring any implicit conversions on the RHS.
12138       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12139                                         E->getOperatorLoc());
12140     }
12141   }
12142 
12143   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12144 
12145   // Diagnose implicitly sequentially-consistent atomic assignment.
12146   if (E->getLHS()->getType()->isAtomicType())
12147     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12148 }
12149 
12150 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12151 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12152                             SourceLocation CContext, unsigned diag,
12153                             bool pruneControlFlow = false) {
12154   if (pruneControlFlow) {
12155     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12156                           S.PDiag(diag)
12157                               << SourceType << T << E->getSourceRange()
12158                               << SourceRange(CContext));
12159     return;
12160   }
12161   S.Diag(E->getExprLoc(), diag)
12162     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12163 }
12164 
12165 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12166 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12167                             SourceLocation CContext,
12168                             unsigned diag, bool pruneControlFlow = false) {
12169   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12170 }
12171 
12172 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12173   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12174       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12175 }
12176 
12177 static void adornObjCBoolConversionDiagWithTernaryFixit(
12178     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12179   Expr *Ignored = SourceExpr->IgnoreImplicit();
12180   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12181     Ignored = OVE->getSourceExpr();
12182   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12183                      isa<BinaryOperator>(Ignored) ||
12184                      isa<CXXOperatorCallExpr>(Ignored);
12185   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12186   if (NeedsParens)
12187     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12188             << FixItHint::CreateInsertion(EndLoc, ")");
12189   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12190 }
12191 
12192 /// Diagnose an implicit cast from a floating point value to an integer value.
12193 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12194                                     SourceLocation CContext) {
12195   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12196   const bool PruneWarnings = S.inTemplateInstantiation();
12197 
12198   Expr *InnerE = E->IgnoreParenImpCasts();
12199   // We also want to warn on, e.g., "int i = -1.234"
12200   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12201     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12202       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12203 
12204   const bool IsLiteral =
12205       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12206 
12207   llvm::APFloat Value(0.0);
12208   bool IsConstant =
12209     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12210   if (!IsConstant) {
12211     if (isObjCSignedCharBool(S, T)) {
12212       return adornObjCBoolConversionDiagWithTernaryFixit(
12213           S, E,
12214           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12215               << E->getType());
12216     }
12217 
12218     return DiagnoseImpCast(S, E, T, CContext,
12219                            diag::warn_impcast_float_integer, PruneWarnings);
12220   }
12221 
12222   bool isExact = false;
12223 
12224   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12225                             T->hasUnsignedIntegerRepresentation());
12226   llvm::APFloat::opStatus Result = Value.convertToInteger(
12227       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12228 
12229   // FIXME: Force the precision of the source value down so we don't print
12230   // digits which are usually useless (we don't really care here if we
12231   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12232   // would automatically print the shortest representation, but it's a bit
12233   // tricky to implement.
12234   SmallString<16> PrettySourceValue;
12235   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12236   precision = (precision * 59 + 195) / 196;
12237   Value.toString(PrettySourceValue, precision);
12238 
12239   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12240     return adornObjCBoolConversionDiagWithTernaryFixit(
12241         S, E,
12242         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12243             << PrettySourceValue);
12244   }
12245 
12246   if (Result == llvm::APFloat::opOK && isExact) {
12247     if (IsLiteral) return;
12248     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12249                            PruneWarnings);
12250   }
12251 
12252   // Conversion of a floating-point value to a non-bool integer where the
12253   // integral part cannot be represented by the integer type is undefined.
12254   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12255     return DiagnoseImpCast(
12256         S, E, T, CContext,
12257         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12258                   : diag::warn_impcast_float_to_integer_out_of_range,
12259         PruneWarnings);
12260 
12261   unsigned DiagID = 0;
12262   if (IsLiteral) {
12263     // Warn on floating point literal to integer.
12264     DiagID = diag::warn_impcast_literal_float_to_integer;
12265   } else if (IntegerValue == 0) {
12266     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12267       return DiagnoseImpCast(S, E, T, CContext,
12268                              diag::warn_impcast_float_integer, PruneWarnings);
12269     }
12270     // Warn on non-zero to zero conversion.
12271     DiagID = diag::warn_impcast_float_to_integer_zero;
12272   } else {
12273     if (IntegerValue.isUnsigned()) {
12274       if (!IntegerValue.isMaxValue()) {
12275         return DiagnoseImpCast(S, E, T, CContext,
12276                                diag::warn_impcast_float_integer, PruneWarnings);
12277       }
12278     } else {  // IntegerValue.isSigned()
12279       if (!IntegerValue.isMaxSignedValue() &&
12280           !IntegerValue.isMinSignedValue()) {
12281         return DiagnoseImpCast(S, E, T, CContext,
12282                                diag::warn_impcast_float_integer, PruneWarnings);
12283       }
12284     }
12285     // Warn on evaluatable floating point expression to integer conversion.
12286     DiagID = diag::warn_impcast_float_to_integer;
12287   }
12288 
12289   SmallString<16> PrettyTargetValue;
12290   if (IsBool)
12291     PrettyTargetValue = Value.isZero() ? "false" : "true";
12292   else
12293     IntegerValue.toString(PrettyTargetValue);
12294 
12295   if (PruneWarnings) {
12296     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12297                           S.PDiag(DiagID)
12298                               << E->getType() << T.getUnqualifiedType()
12299                               << PrettySourceValue << PrettyTargetValue
12300                               << E->getSourceRange() << SourceRange(CContext));
12301   } else {
12302     S.Diag(E->getExprLoc(), DiagID)
12303         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12304         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12305   }
12306 }
12307 
12308 /// Analyze the given compound assignment for the possible losing of
12309 /// floating-point precision.
12310 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12311   assert(isa<CompoundAssignOperator>(E) &&
12312          "Must be compound assignment operation");
12313   // Recurse on the LHS and RHS in here
12314   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12315   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12316 
12317   if (E->getLHS()->getType()->isAtomicType())
12318     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12319 
12320   // Now check the outermost expression
12321   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12322   const auto *RBT = cast<CompoundAssignOperator>(E)
12323                         ->getComputationResultType()
12324                         ->getAs<BuiltinType>();
12325 
12326   // The below checks assume source is floating point.
12327   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12328 
12329   // If source is floating point but target is an integer.
12330   if (ResultBT->isInteger())
12331     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12332                            E->getExprLoc(), diag::warn_impcast_float_integer);
12333 
12334   if (!ResultBT->isFloatingPoint())
12335     return;
12336 
12337   // If both source and target are floating points, warn about losing precision.
12338   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12339       QualType(ResultBT, 0), QualType(RBT, 0));
12340   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12341     // warn about dropping FP rank.
12342     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12343                     diag::warn_impcast_float_result_precision);
12344 }
12345 
12346 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12347                                       IntRange Range) {
12348   if (!Range.Width) return "0";
12349 
12350   llvm::APSInt ValueInRange = Value;
12351   ValueInRange.setIsSigned(!Range.NonNegative);
12352   ValueInRange = ValueInRange.trunc(Range.Width);
12353   return toString(ValueInRange, 10);
12354 }
12355 
12356 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12357   if (!isa<ImplicitCastExpr>(Ex))
12358     return false;
12359 
12360   Expr *InnerE = Ex->IgnoreParenImpCasts();
12361   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12362   const Type *Source =
12363     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12364   if (Target->isDependentType())
12365     return false;
12366 
12367   const BuiltinType *FloatCandidateBT =
12368     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12369   const Type *BoolCandidateType = ToBool ? Target : Source;
12370 
12371   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12372           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12373 }
12374 
12375 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12376                                              SourceLocation CC) {
12377   unsigned NumArgs = TheCall->getNumArgs();
12378   for (unsigned i = 0; i < NumArgs; ++i) {
12379     Expr *CurrA = TheCall->getArg(i);
12380     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12381       continue;
12382 
12383     bool IsSwapped = ((i > 0) &&
12384         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12385     IsSwapped |= ((i < (NumArgs - 1)) &&
12386         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12387     if (IsSwapped) {
12388       // Warn on this floating-point to bool conversion.
12389       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12390                       CurrA->getType(), CC,
12391                       diag::warn_impcast_floating_point_to_bool);
12392     }
12393   }
12394 }
12395 
12396 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12397                                    SourceLocation CC) {
12398   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12399                         E->getExprLoc()))
12400     return;
12401 
12402   // Don't warn on functions which have return type nullptr_t.
12403   if (isa<CallExpr>(E))
12404     return;
12405 
12406   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12407   const Expr::NullPointerConstantKind NullKind =
12408       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12409   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12410     return;
12411 
12412   // Return if target type is a safe conversion.
12413   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12414       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12415     return;
12416 
12417   SourceLocation Loc = E->getSourceRange().getBegin();
12418 
12419   // Venture through the macro stacks to get to the source of macro arguments.
12420   // The new location is a better location than the complete location that was
12421   // passed in.
12422   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12423   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12424 
12425   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12426   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12427     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12428         Loc, S.SourceMgr, S.getLangOpts());
12429     if (MacroName == "NULL")
12430       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12431   }
12432 
12433   // Only warn if the null and context location are in the same macro expansion.
12434   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12435     return;
12436 
12437   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12438       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12439       << FixItHint::CreateReplacement(Loc,
12440                                       S.getFixItZeroLiteralForType(T, Loc));
12441 }
12442 
12443 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12444                                   ObjCArrayLiteral *ArrayLiteral);
12445 
12446 static void
12447 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12448                            ObjCDictionaryLiteral *DictionaryLiteral);
12449 
12450 /// Check a single element within a collection literal against the
12451 /// target element type.
12452 static void checkObjCCollectionLiteralElement(Sema &S,
12453                                               QualType TargetElementType,
12454                                               Expr *Element,
12455                                               unsigned ElementKind) {
12456   // Skip a bitcast to 'id' or qualified 'id'.
12457   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12458     if (ICE->getCastKind() == CK_BitCast &&
12459         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12460       Element = ICE->getSubExpr();
12461   }
12462 
12463   QualType ElementType = Element->getType();
12464   ExprResult ElementResult(Element);
12465   if (ElementType->getAs<ObjCObjectPointerType>() &&
12466       S.CheckSingleAssignmentConstraints(TargetElementType,
12467                                          ElementResult,
12468                                          false, false)
12469         != Sema::Compatible) {
12470     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12471         << ElementType << ElementKind << TargetElementType
12472         << Element->getSourceRange();
12473   }
12474 
12475   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12476     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12477   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12478     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12479 }
12480 
12481 /// Check an Objective-C array literal being converted to the given
12482 /// target type.
12483 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12484                                   ObjCArrayLiteral *ArrayLiteral) {
12485   if (!S.NSArrayDecl)
12486     return;
12487 
12488   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12489   if (!TargetObjCPtr)
12490     return;
12491 
12492   if (TargetObjCPtr->isUnspecialized() ||
12493       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12494         != S.NSArrayDecl->getCanonicalDecl())
12495     return;
12496 
12497   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12498   if (TypeArgs.size() != 1)
12499     return;
12500 
12501   QualType TargetElementType = TypeArgs[0];
12502   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12503     checkObjCCollectionLiteralElement(S, TargetElementType,
12504                                       ArrayLiteral->getElement(I),
12505                                       0);
12506   }
12507 }
12508 
12509 /// Check an Objective-C dictionary literal being converted to the given
12510 /// target type.
12511 static void
12512 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12513                            ObjCDictionaryLiteral *DictionaryLiteral) {
12514   if (!S.NSDictionaryDecl)
12515     return;
12516 
12517   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12518   if (!TargetObjCPtr)
12519     return;
12520 
12521   if (TargetObjCPtr->isUnspecialized() ||
12522       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12523         != S.NSDictionaryDecl->getCanonicalDecl())
12524     return;
12525 
12526   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12527   if (TypeArgs.size() != 2)
12528     return;
12529 
12530   QualType TargetKeyType = TypeArgs[0];
12531   QualType TargetObjectType = TypeArgs[1];
12532   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12533     auto Element = DictionaryLiteral->getKeyValueElement(I);
12534     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12535     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12536   }
12537 }
12538 
12539 // Helper function to filter out cases for constant width constant conversion.
12540 // Don't warn on char array initialization or for non-decimal values.
12541 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12542                                           SourceLocation CC) {
12543   // If initializing from a constant, and the constant starts with '0',
12544   // then it is a binary, octal, or hexadecimal.  Allow these constants
12545   // to fill all the bits, even if there is a sign change.
12546   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12547     const char FirstLiteralCharacter =
12548         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12549     if (FirstLiteralCharacter == '0')
12550       return false;
12551   }
12552 
12553   // If the CC location points to a '{', and the type is char, then assume
12554   // assume it is an array initialization.
12555   if (CC.isValid() && T->isCharType()) {
12556     const char FirstContextCharacter =
12557         S.getSourceManager().getCharacterData(CC)[0];
12558     if (FirstContextCharacter == '{')
12559       return false;
12560   }
12561 
12562   return true;
12563 }
12564 
12565 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12566   const auto *IL = dyn_cast<IntegerLiteral>(E);
12567   if (!IL) {
12568     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12569       if (UO->getOpcode() == UO_Minus)
12570         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12571     }
12572   }
12573 
12574   return IL;
12575 }
12576 
12577 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12578   E = E->IgnoreParenImpCasts();
12579   SourceLocation ExprLoc = E->getExprLoc();
12580 
12581   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12582     BinaryOperator::Opcode Opc = BO->getOpcode();
12583     Expr::EvalResult Result;
12584     // Do not diagnose unsigned shifts.
12585     if (Opc == BO_Shl) {
12586       const auto *LHS = getIntegerLiteral(BO->getLHS());
12587       const auto *RHS = getIntegerLiteral(BO->getRHS());
12588       if (LHS && LHS->getValue() == 0)
12589         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12590       else if (!E->isValueDependent() && LHS && RHS &&
12591                RHS->getValue().isNonNegative() &&
12592                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12593         S.Diag(ExprLoc, diag::warn_left_shift_always)
12594             << (Result.Val.getInt() != 0);
12595       else if (E->getType()->isSignedIntegerType())
12596         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12597     }
12598   }
12599 
12600   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12601     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12602     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12603     if (!LHS || !RHS)
12604       return;
12605     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12606         (RHS->getValue() == 0 || RHS->getValue() == 1))
12607       // Do not diagnose common idioms.
12608       return;
12609     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12610       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12611   }
12612 }
12613 
12614 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12615                                     SourceLocation CC,
12616                                     bool *ICContext = nullptr,
12617                                     bool IsListInit = false) {
12618   if (E->isTypeDependent() || E->isValueDependent()) return;
12619 
12620   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12621   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12622   if (Source == Target) return;
12623   if (Target->isDependentType()) return;
12624 
12625   // If the conversion context location is invalid don't complain. We also
12626   // don't want to emit a warning if the issue occurs from the expansion of
12627   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12628   // delay this check as long as possible. Once we detect we are in that
12629   // scenario, we just return.
12630   if (CC.isInvalid())
12631     return;
12632 
12633   if (Source->isAtomicType())
12634     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12635 
12636   // Diagnose implicit casts to bool.
12637   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12638     if (isa<StringLiteral>(E))
12639       // Warn on string literal to bool.  Checks for string literals in logical
12640       // and expressions, for instance, assert(0 && "error here"), are
12641       // prevented by a check in AnalyzeImplicitConversions().
12642       return DiagnoseImpCast(S, E, T, CC,
12643                              diag::warn_impcast_string_literal_to_bool);
12644     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12645         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12646       // This covers the literal expressions that evaluate to Objective-C
12647       // objects.
12648       return DiagnoseImpCast(S, E, T, CC,
12649                              diag::warn_impcast_objective_c_literal_to_bool);
12650     }
12651     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12652       // Warn on pointer to bool conversion that is always true.
12653       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12654                                      SourceRange(CC));
12655     }
12656   }
12657 
12658   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12659   // is a typedef for signed char (macOS), then that constant value has to be 1
12660   // or 0.
12661   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12662     Expr::EvalResult Result;
12663     if (E->EvaluateAsInt(Result, S.getASTContext(),
12664                          Expr::SE_AllowSideEffects)) {
12665       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12666         adornObjCBoolConversionDiagWithTernaryFixit(
12667             S, E,
12668             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12669                 << toString(Result.Val.getInt(), 10));
12670       }
12671       return;
12672     }
12673   }
12674 
12675   // Check implicit casts from Objective-C collection literals to specialized
12676   // collection types, e.g., NSArray<NSString *> *.
12677   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12678     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12679   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12680     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12681 
12682   // Strip vector types.
12683   if (isa<VectorType>(Source)) {
12684     if (Target->isVLSTBuiltinType() &&
12685         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12686                                          QualType(Source, 0)) ||
12687          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12688                                             QualType(Source, 0))))
12689       return;
12690 
12691     if (!isa<VectorType>(Target)) {
12692       if (S.SourceMgr.isInSystemMacro(CC))
12693         return;
12694       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12695     }
12696 
12697     // If the vector cast is cast between two vectors of the same size, it is
12698     // a bitcast, not a conversion.
12699     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12700       return;
12701 
12702     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12703     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12704   }
12705   if (auto VecTy = dyn_cast<VectorType>(Target))
12706     Target = VecTy->getElementType().getTypePtr();
12707 
12708   // Strip complex types.
12709   if (isa<ComplexType>(Source)) {
12710     if (!isa<ComplexType>(Target)) {
12711       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12712         return;
12713 
12714       return DiagnoseImpCast(S, E, T, CC,
12715                              S.getLangOpts().CPlusPlus
12716                                  ? diag::err_impcast_complex_scalar
12717                                  : diag::warn_impcast_complex_scalar);
12718     }
12719 
12720     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12721     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12722   }
12723 
12724   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12725   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12726 
12727   // If the source is floating point...
12728   if (SourceBT && SourceBT->isFloatingPoint()) {
12729     // ...and the target is floating point...
12730     if (TargetBT && TargetBT->isFloatingPoint()) {
12731       // ...then warn if we're dropping FP rank.
12732 
12733       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12734           QualType(SourceBT, 0), QualType(TargetBT, 0));
12735       if (Order > 0) {
12736         // Don't warn about float constants that are precisely
12737         // representable in the target type.
12738         Expr::EvalResult result;
12739         if (E->EvaluateAsRValue(result, S.Context)) {
12740           // Value might be a float, a float vector, or a float complex.
12741           if (IsSameFloatAfterCast(result.Val,
12742                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12743                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12744             return;
12745         }
12746 
12747         if (S.SourceMgr.isInSystemMacro(CC))
12748           return;
12749 
12750         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12751       }
12752       // ... or possibly if we're increasing rank, too
12753       else if (Order < 0) {
12754         if (S.SourceMgr.isInSystemMacro(CC))
12755           return;
12756 
12757         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12758       }
12759       return;
12760     }
12761 
12762     // If the target is integral, always warn.
12763     if (TargetBT && TargetBT->isInteger()) {
12764       if (S.SourceMgr.isInSystemMacro(CC))
12765         return;
12766 
12767       DiagnoseFloatingImpCast(S, E, T, CC);
12768     }
12769 
12770     // Detect the case where a call result is converted from floating-point to
12771     // to bool, and the final argument to the call is converted from bool, to
12772     // discover this typo:
12773     //
12774     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12775     //
12776     // FIXME: This is an incredibly special case; is there some more general
12777     // way to detect this class of misplaced-parentheses bug?
12778     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12779       // Check last argument of function call to see if it is an
12780       // implicit cast from a type matching the type the result
12781       // is being cast to.
12782       CallExpr *CEx = cast<CallExpr>(E);
12783       if (unsigned NumArgs = CEx->getNumArgs()) {
12784         Expr *LastA = CEx->getArg(NumArgs - 1);
12785         Expr *InnerE = LastA->IgnoreParenImpCasts();
12786         if (isa<ImplicitCastExpr>(LastA) &&
12787             InnerE->getType()->isBooleanType()) {
12788           // Warn on this floating-point to bool conversion
12789           DiagnoseImpCast(S, E, T, CC,
12790                           diag::warn_impcast_floating_point_to_bool);
12791         }
12792       }
12793     }
12794     return;
12795   }
12796 
12797   // Valid casts involving fixed point types should be accounted for here.
12798   if (Source->isFixedPointType()) {
12799     if (Target->isUnsaturatedFixedPointType()) {
12800       Expr::EvalResult Result;
12801       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12802                                   S.isConstantEvaluated())) {
12803         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12804         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12805         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12806         if (Value > MaxVal || Value < MinVal) {
12807           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12808                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12809                                     << Value.toString() << T
12810                                     << E->getSourceRange()
12811                                     << clang::SourceRange(CC));
12812           return;
12813         }
12814       }
12815     } else if (Target->isIntegerType()) {
12816       Expr::EvalResult Result;
12817       if (!S.isConstantEvaluated() &&
12818           E->EvaluateAsFixedPoint(Result, S.Context,
12819                                   Expr::SE_AllowSideEffects)) {
12820         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12821 
12822         bool Overflowed;
12823         llvm::APSInt IntResult = FXResult.convertToInt(
12824             S.Context.getIntWidth(T),
12825             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12826 
12827         if (Overflowed) {
12828           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12829                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12830                                     << FXResult.toString() << T
12831                                     << E->getSourceRange()
12832                                     << clang::SourceRange(CC));
12833           return;
12834         }
12835       }
12836     }
12837   } else if (Target->isUnsaturatedFixedPointType()) {
12838     if (Source->isIntegerType()) {
12839       Expr::EvalResult Result;
12840       if (!S.isConstantEvaluated() &&
12841           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12842         llvm::APSInt Value = Result.Val.getInt();
12843 
12844         bool Overflowed;
12845         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12846             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12847 
12848         if (Overflowed) {
12849           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12850                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12851                                     << toString(Value, /*Radix=*/10) << T
12852                                     << E->getSourceRange()
12853                                     << clang::SourceRange(CC));
12854           return;
12855         }
12856       }
12857     }
12858   }
12859 
12860   // If we are casting an integer type to a floating point type without
12861   // initialization-list syntax, we might lose accuracy if the floating
12862   // point type has a narrower significand than the integer type.
12863   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12864       TargetBT->isFloatingType() && !IsListInit) {
12865     // Determine the number of precision bits in the source integer type.
12866     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12867                                         /*Approximate*/ true);
12868     unsigned int SourcePrecision = SourceRange.Width;
12869 
12870     // Determine the number of precision bits in the
12871     // target floating point type.
12872     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12873         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12874 
12875     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12876         SourcePrecision > TargetPrecision) {
12877 
12878       if (Optional<llvm::APSInt> SourceInt =
12879               E->getIntegerConstantExpr(S.Context)) {
12880         // If the source integer is a constant, convert it to the target
12881         // floating point type. Issue a warning if the value changes
12882         // during the whole conversion.
12883         llvm::APFloat TargetFloatValue(
12884             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12885         llvm::APFloat::opStatus ConversionStatus =
12886             TargetFloatValue.convertFromAPInt(
12887                 *SourceInt, SourceBT->isSignedInteger(),
12888                 llvm::APFloat::rmNearestTiesToEven);
12889 
12890         if (ConversionStatus != llvm::APFloat::opOK) {
12891           SmallString<32> PrettySourceValue;
12892           SourceInt->toString(PrettySourceValue, 10);
12893           SmallString<32> PrettyTargetValue;
12894           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12895 
12896           S.DiagRuntimeBehavior(
12897               E->getExprLoc(), E,
12898               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12899                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12900                   << E->getSourceRange() << clang::SourceRange(CC));
12901         }
12902       } else {
12903         // Otherwise, the implicit conversion may lose precision.
12904         DiagnoseImpCast(S, E, T, CC,
12905                         diag::warn_impcast_integer_float_precision);
12906       }
12907     }
12908   }
12909 
12910   DiagnoseNullConversion(S, E, T, CC);
12911 
12912   S.DiscardMisalignedMemberAddress(Target, E);
12913 
12914   if (Target->isBooleanType())
12915     DiagnoseIntInBoolContext(S, E);
12916 
12917   if (!Source->isIntegerType() || !Target->isIntegerType())
12918     return;
12919 
12920   // TODO: remove this early return once the false positives for constant->bool
12921   // in templates, macros, etc, are reduced or removed.
12922   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12923     return;
12924 
12925   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12926       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12927     return adornObjCBoolConversionDiagWithTernaryFixit(
12928         S, E,
12929         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12930             << E->getType());
12931   }
12932 
12933   IntRange SourceTypeRange =
12934       IntRange::forTargetOfCanonicalType(S.Context, Source);
12935   IntRange LikelySourceRange =
12936       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12937   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12938 
12939   if (LikelySourceRange.Width > TargetRange.Width) {
12940     // If the source is a constant, use a default-on diagnostic.
12941     // TODO: this should happen for bitfield stores, too.
12942     Expr::EvalResult Result;
12943     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12944                          S.isConstantEvaluated())) {
12945       llvm::APSInt Value(32);
12946       Value = Result.Val.getInt();
12947 
12948       if (S.SourceMgr.isInSystemMacro(CC))
12949         return;
12950 
12951       std::string PrettySourceValue = toString(Value, 10);
12952       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12953 
12954       S.DiagRuntimeBehavior(
12955           E->getExprLoc(), E,
12956           S.PDiag(diag::warn_impcast_integer_precision_constant)
12957               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12958               << E->getSourceRange() << SourceRange(CC));
12959       return;
12960     }
12961 
12962     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12963     if (S.SourceMgr.isInSystemMacro(CC))
12964       return;
12965 
12966     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12967       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12968                              /* pruneControlFlow */ true);
12969     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12970   }
12971 
12972   if (TargetRange.Width > SourceTypeRange.Width) {
12973     if (auto *UO = dyn_cast<UnaryOperator>(E))
12974       if (UO->getOpcode() == UO_Minus)
12975         if (Source->isUnsignedIntegerType()) {
12976           if (Target->isUnsignedIntegerType())
12977             return DiagnoseImpCast(S, E, T, CC,
12978                                    diag::warn_impcast_high_order_zero_bits);
12979           if (Target->isSignedIntegerType())
12980             return DiagnoseImpCast(S, E, T, CC,
12981                                    diag::warn_impcast_nonnegative_result);
12982         }
12983   }
12984 
12985   if (TargetRange.Width == LikelySourceRange.Width &&
12986       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12987       Source->isSignedIntegerType()) {
12988     // Warn when doing a signed to signed conversion, warn if the positive
12989     // source value is exactly the width of the target type, which will
12990     // cause a negative value to be stored.
12991 
12992     Expr::EvalResult Result;
12993     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12994         !S.SourceMgr.isInSystemMacro(CC)) {
12995       llvm::APSInt Value = Result.Val.getInt();
12996       if (isSameWidthConstantConversion(S, E, T, CC)) {
12997         std::string PrettySourceValue = toString(Value, 10);
12998         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12999 
13000         S.DiagRuntimeBehavior(
13001             E->getExprLoc(), E,
13002             S.PDiag(diag::warn_impcast_integer_precision_constant)
13003                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13004                 << E->getSourceRange() << SourceRange(CC));
13005         return;
13006       }
13007     }
13008 
13009     // Fall through for non-constants to give a sign conversion warning.
13010   }
13011 
13012   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13013       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13014        LikelySourceRange.Width == TargetRange.Width)) {
13015     if (S.SourceMgr.isInSystemMacro(CC))
13016       return;
13017 
13018     unsigned DiagID = diag::warn_impcast_integer_sign;
13019 
13020     // Traditionally, gcc has warned about this under -Wsign-compare.
13021     // We also want to warn about it in -Wconversion.
13022     // So if -Wconversion is off, use a completely identical diagnostic
13023     // in the sign-compare group.
13024     // The conditional-checking code will
13025     if (ICContext) {
13026       DiagID = diag::warn_impcast_integer_sign_conditional;
13027       *ICContext = true;
13028     }
13029 
13030     return DiagnoseImpCast(S, E, T, CC, DiagID);
13031   }
13032 
13033   // Diagnose conversions between different enumeration types.
13034   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13035   // type, to give us better diagnostics.
13036   QualType SourceType = E->getType();
13037   if (!S.getLangOpts().CPlusPlus) {
13038     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13039       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13040         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13041         SourceType = S.Context.getTypeDeclType(Enum);
13042         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13043       }
13044   }
13045 
13046   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13047     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13048       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13049           TargetEnum->getDecl()->hasNameForLinkage() &&
13050           SourceEnum != TargetEnum) {
13051         if (S.SourceMgr.isInSystemMacro(CC))
13052           return;
13053 
13054         return DiagnoseImpCast(S, E, SourceType, T, CC,
13055                                diag::warn_impcast_different_enum_types);
13056       }
13057 }
13058 
13059 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13060                                      SourceLocation CC, QualType T);
13061 
13062 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13063                                     SourceLocation CC, bool &ICContext) {
13064   E = E->IgnoreParenImpCasts();
13065 
13066   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13067     return CheckConditionalOperator(S, CO, CC, T);
13068 
13069   AnalyzeImplicitConversions(S, E, CC);
13070   if (E->getType() != T)
13071     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13072 }
13073 
13074 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13075                                      SourceLocation CC, QualType T) {
13076   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13077 
13078   Expr *TrueExpr = E->getTrueExpr();
13079   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13080     TrueExpr = BCO->getCommon();
13081 
13082   bool Suspicious = false;
13083   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13084   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13085 
13086   if (T->isBooleanType())
13087     DiagnoseIntInBoolContext(S, E);
13088 
13089   // If -Wconversion would have warned about either of the candidates
13090   // for a signedness conversion to the context type...
13091   if (!Suspicious) return;
13092 
13093   // ...but it's currently ignored...
13094   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13095     return;
13096 
13097   // ...then check whether it would have warned about either of the
13098   // candidates for a signedness conversion to the condition type.
13099   if (E->getType() == T) return;
13100 
13101   Suspicious = false;
13102   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13103                           E->getType(), CC, &Suspicious);
13104   if (!Suspicious)
13105     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13106                             E->getType(), CC, &Suspicious);
13107 }
13108 
13109 /// Check conversion of given expression to boolean.
13110 /// Input argument E is a logical expression.
13111 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13112   if (S.getLangOpts().Bool)
13113     return;
13114   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13115     return;
13116   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13117 }
13118 
13119 namespace {
13120 struct AnalyzeImplicitConversionsWorkItem {
13121   Expr *E;
13122   SourceLocation CC;
13123   bool IsListInit;
13124 };
13125 }
13126 
13127 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13128 /// that should be visited are added to WorkList.
13129 static void AnalyzeImplicitConversions(
13130     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13131     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13132   Expr *OrigE = Item.E;
13133   SourceLocation CC = Item.CC;
13134 
13135   QualType T = OrigE->getType();
13136   Expr *E = OrigE->IgnoreParenImpCasts();
13137 
13138   // Propagate whether we are in a C++ list initialization expression.
13139   // If so, we do not issue warnings for implicit int-float conversion
13140   // precision loss, because C++11 narrowing already handles it.
13141   bool IsListInit = Item.IsListInit ||
13142                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13143 
13144   if (E->isTypeDependent() || E->isValueDependent())
13145     return;
13146 
13147   Expr *SourceExpr = E;
13148   // Examine, but don't traverse into the source expression of an
13149   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13150   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13151   // evaluate it in the context of checking the specific conversion to T though.
13152   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13153     if (auto *Src = OVE->getSourceExpr())
13154       SourceExpr = Src;
13155 
13156   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13157     if (UO->getOpcode() == UO_Not &&
13158         UO->getSubExpr()->isKnownToHaveBooleanValue())
13159       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13160           << OrigE->getSourceRange() << T->isBooleanType()
13161           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13162 
13163   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13164     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13165         BO->getLHS()->isKnownToHaveBooleanValue() &&
13166         BO->getRHS()->isKnownToHaveBooleanValue() &&
13167         BO->getLHS()->HasSideEffects(S.Context) &&
13168         BO->getRHS()->HasSideEffects(S.Context)) {
13169       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13170           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13171           << FixItHint::CreateReplacement(
13172                  BO->getOperatorLoc(),
13173                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13174       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13175     }
13176 
13177   // For conditional operators, we analyze the arguments as if they
13178   // were being fed directly into the output.
13179   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13180     CheckConditionalOperator(S, CO, CC, T);
13181     return;
13182   }
13183 
13184   // Check implicit argument conversions for function calls.
13185   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13186     CheckImplicitArgumentConversions(S, Call, CC);
13187 
13188   // Go ahead and check any implicit conversions we might have skipped.
13189   // The non-canonical typecheck is just an optimization;
13190   // CheckImplicitConversion will filter out dead implicit conversions.
13191   if (SourceExpr->getType() != T)
13192     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13193 
13194   // Now continue drilling into this expression.
13195 
13196   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13197     // The bound subexpressions in a PseudoObjectExpr are not reachable
13198     // as transitive children.
13199     // FIXME: Use a more uniform representation for this.
13200     for (auto *SE : POE->semantics())
13201       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13202         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13203   }
13204 
13205   // Skip past explicit casts.
13206   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13207     E = CE->getSubExpr()->IgnoreParenImpCasts();
13208     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13209       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13210     WorkList.push_back({E, CC, IsListInit});
13211     return;
13212   }
13213 
13214   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13215     // Do a somewhat different check with comparison operators.
13216     if (BO->isComparisonOp())
13217       return AnalyzeComparison(S, BO);
13218 
13219     // And with simple assignments.
13220     if (BO->getOpcode() == BO_Assign)
13221       return AnalyzeAssignment(S, BO);
13222     // And with compound assignments.
13223     if (BO->isAssignmentOp())
13224       return AnalyzeCompoundAssignment(S, BO);
13225   }
13226 
13227   // These break the otherwise-useful invariant below.  Fortunately,
13228   // we don't really need to recurse into them, because any internal
13229   // expressions should have been analyzed already when they were
13230   // built into statements.
13231   if (isa<StmtExpr>(E)) return;
13232 
13233   // Don't descend into unevaluated contexts.
13234   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13235 
13236   // Now just recurse over the expression's children.
13237   CC = E->getExprLoc();
13238   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13239   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13240   for (Stmt *SubStmt : E->children()) {
13241     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13242     if (!ChildExpr)
13243       continue;
13244 
13245     if (IsLogicalAndOperator &&
13246         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13247       // Ignore checking string literals that are in logical and operators.
13248       // This is a common pattern for asserts.
13249       continue;
13250     WorkList.push_back({ChildExpr, CC, IsListInit});
13251   }
13252 
13253   if (BO && BO->isLogicalOp()) {
13254     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13255     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13256       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13257 
13258     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13259     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13260       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13261   }
13262 
13263   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13264     if (U->getOpcode() == UO_LNot) {
13265       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13266     } else if (U->getOpcode() != UO_AddrOf) {
13267       if (U->getSubExpr()->getType()->isAtomicType())
13268         S.Diag(U->getSubExpr()->getBeginLoc(),
13269                diag::warn_atomic_implicit_seq_cst);
13270     }
13271   }
13272 }
13273 
13274 /// AnalyzeImplicitConversions - Find and report any interesting
13275 /// implicit conversions in the given expression.  There are a couple
13276 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13277 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13278                                        bool IsListInit/*= false*/) {
13279   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13280   WorkList.push_back({OrigE, CC, IsListInit});
13281   while (!WorkList.empty())
13282     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13283 }
13284 
13285 /// Diagnose integer type and any valid implicit conversion to it.
13286 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13287   // Taking into account implicit conversions,
13288   // allow any integer.
13289   if (!E->getType()->isIntegerType()) {
13290     S.Diag(E->getBeginLoc(),
13291            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13292     return true;
13293   }
13294   // Potentially emit standard warnings for implicit conversions if enabled
13295   // using -Wconversion.
13296   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13297   return false;
13298 }
13299 
13300 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13301 // Returns true when emitting a warning about taking the address of a reference.
13302 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13303                               const PartialDiagnostic &PD) {
13304   E = E->IgnoreParenImpCasts();
13305 
13306   const FunctionDecl *FD = nullptr;
13307 
13308   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13309     if (!DRE->getDecl()->getType()->isReferenceType())
13310       return false;
13311   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13312     if (!M->getMemberDecl()->getType()->isReferenceType())
13313       return false;
13314   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13315     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13316       return false;
13317     FD = Call->getDirectCallee();
13318   } else {
13319     return false;
13320   }
13321 
13322   SemaRef.Diag(E->getExprLoc(), PD);
13323 
13324   // If possible, point to location of function.
13325   if (FD) {
13326     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13327   }
13328 
13329   return true;
13330 }
13331 
13332 // Returns true if the SourceLocation is expanded from any macro body.
13333 // Returns false if the SourceLocation is invalid, is from not in a macro
13334 // expansion, or is from expanded from a top-level macro argument.
13335 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13336   if (Loc.isInvalid())
13337     return false;
13338 
13339   while (Loc.isMacroID()) {
13340     if (SM.isMacroBodyExpansion(Loc))
13341       return true;
13342     Loc = SM.getImmediateMacroCallerLoc(Loc);
13343   }
13344 
13345   return false;
13346 }
13347 
13348 /// Diagnose pointers that are always non-null.
13349 /// \param E the expression containing the pointer
13350 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13351 /// compared to a null pointer
13352 /// \param IsEqual True when the comparison is equal to a null pointer
13353 /// \param Range Extra SourceRange to highlight in the diagnostic
13354 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13355                                         Expr::NullPointerConstantKind NullKind,
13356                                         bool IsEqual, SourceRange Range) {
13357   if (!E)
13358     return;
13359 
13360   // Don't warn inside macros.
13361   if (E->getExprLoc().isMacroID()) {
13362     const SourceManager &SM = getSourceManager();
13363     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13364         IsInAnyMacroBody(SM, Range.getBegin()))
13365       return;
13366   }
13367   E = E->IgnoreImpCasts();
13368 
13369   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13370 
13371   if (isa<CXXThisExpr>(E)) {
13372     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13373                                 : diag::warn_this_bool_conversion;
13374     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13375     return;
13376   }
13377 
13378   bool IsAddressOf = false;
13379 
13380   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13381     if (UO->getOpcode() != UO_AddrOf)
13382       return;
13383     IsAddressOf = true;
13384     E = UO->getSubExpr();
13385   }
13386 
13387   if (IsAddressOf) {
13388     unsigned DiagID = IsCompare
13389                           ? diag::warn_address_of_reference_null_compare
13390                           : diag::warn_address_of_reference_bool_conversion;
13391     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13392                                          << IsEqual;
13393     if (CheckForReference(*this, E, PD)) {
13394       return;
13395     }
13396   }
13397 
13398   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13399     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13400     std::string Str;
13401     llvm::raw_string_ostream S(Str);
13402     E->printPretty(S, nullptr, getPrintingPolicy());
13403     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13404                                 : diag::warn_cast_nonnull_to_bool;
13405     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13406       << E->getSourceRange() << Range << IsEqual;
13407     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13408   };
13409 
13410   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13411   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13412     if (auto *Callee = Call->getDirectCallee()) {
13413       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13414         ComplainAboutNonnullParamOrCall(A);
13415         return;
13416       }
13417     }
13418   }
13419 
13420   // Expect to find a single Decl.  Skip anything more complicated.
13421   ValueDecl *D = nullptr;
13422   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13423     D = R->getDecl();
13424   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13425     D = M->getMemberDecl();
13426   }
13427 
13428   // Weak Decls can be null.
13429   if (!D || D->isWeak())
13430     return;
13431 
13432   // Check for parameter decl with nonnull attribute
13433   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13434     if (getCurFunction() &&
13435         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13436       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13437         ComplainAboutNonnullParamOrCall(A);
13438         return;
13439       }
13440 
13441       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13442         // Skip function template not specialized yet.
13443         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13444           return;
13445         auto ParamIter = llvm::find(FD->parameters(), PV);
13446         assert(ParamIter != FD->param_end());
13447         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13448 
13449         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13450           if (!NonNull->args_size()) {
13451               ComplainAboutNonnullParamOrCall(NonNull);
13452               return;
13453           }
13454 
13455           for (const ParamIdx &ArgNo : NonNull->args()) {
13456             if (ArgNo.getASTIndex() == ParamNo) {
13457               ComplainAboutNonnullParamOrCall(NonNull);
13458               return;
13459             }
13460           }
13461         }
13462       }
13463     }
13464   }
13465 
13466   QualType T = D->getType();
13467   const bool IsArray = T->isArrayType();
13468   const bool IsFunction = T->isFunctionType();
13469 
13470   // Address of function is used to silence the function warning.
13471   if (IsAddressOf && IsFunction) {
13472     return;
13473   }
13474 
13475   // Found nothing.
13476   if (!IsAddressOf && !IsFunction && !IsArray)
13477     return;
13478 
13479   // Pretty print the expression for the diagnostic.
13480   std::string Str;
13481   llvm::raw_string_ostream S(Str);
13482   E->printPretty(S, nullptr, getPrintingPolicy());
13483 
13484   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13485                               : diag::warn_impcast_pointer_to_bool;
13486   enum {
13487     AddressOf,
13488     FunctionPointer,
13489     ArrayPointer
13490   } DiagType;
13491   if (IsAddressOf)
13492     DiagType = AddressOf;
13493   else if (IsFunction)
13494     DiagType = FunctionPointer;
13495   else if (IsArray)
13496     DiagType = ArrayPointer;
13497   else
13498     llvm_unreachable("Could not determine diagnostic.");
13499   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13500                                 << Range << IsEqual;
13501 
13502   if (!IsFunction)
13503     return;
13504 
13505   // Suggest '&' to silence the function warning.
13506   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13507       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13508 
13509   // Check to see if '()' fixit should be emitted.
13510   QualType ReturnType;
13511   UnresolvedSet<4> NonTemplateOverloads;
13512   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13513   if (ReturnType.isNull())
13514     return;
13515 
13516   if (IsCompare) {
13517     // There are two cases here.  If there is null constant, the only suggest
13518     // for a pointer return type.  If the null is 0, then suggest if the return
13519     // type is a pointer or an integer type.
13520     if (!ReturnType->isPointerType()) {
13521       if (NullKind == Expr::NPCK_ZeroExpression ||
13522           NullKind == Expr::NPCK_ZeroLiteral) {
13523         if (!ReturnType->isIntegerType())
13524           return;
13525       } else {
13526         return;
13527       }
13528     }
13529   } else { // !IsCompare
13530     // For function to bool, only suggest if the function pointer has bool
13531     // return type.
13532     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13533       return;
13534   }
13535   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13536       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13537 }
13538 
13539 /// Diagnoses "dangerous" implicit conversions within the given
13540 /// expression (which is a full expression).  Implements -Wconversion
13541 /// and -Wsign-compare.
13542 ///
13543 /// \param CC the "context" location of the implicit conversion, i.e.
13544 ///   the most location of the syntactic entity requiring the implicit
13545 ///   conversion
13546 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13547   // Don't diagnose in unevaluated contexts.
13548   if (isUnevaluatedContext())
13549     return;
13550 
13551   // Don't diagnose for value- or type-dependent expressions.
13552   if (E->isTypeDependent() || E->isValueDependent())
13553     return;
13554 
13555   // Check for array bounds violations in cases where the check isn't triggered
13556   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13557   // ArraySubscriptExpr is on the RHS of a variable initialization.
13558   CheckArrayAccess(E);
13559 
13560   // This is not the right CC for (e.g.) a variable initialization.
13561   AnalyzeImplicitConversions(*this, E, CC);
13562 }
13563 
13564 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13565 /// Input argument E is a logical expression.
13566 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13567   ::CheckBoolLikeConversion(*this, E, CC);
13568 }
13569 
13570 /// Diagnose when expression is an integer constant expression and its evaluation
13571 /// results in integer overflow
13572 void Sema::CheckForIntOverflow (Expr *E) {
13573   // Use a work list to deal with nested struct initializers.
13574   SmallVector<Expr *, 2> Exprs(1, E);
13575 
13576   do {
13577     Expr *OriginalE = Exprs.pop_back_val();
13578     Expr *E = OriginalE->IgnoreParenCasts();
13579 
13580     if (isa<BinaryOperator>(E)) {
13581       E->EvaluateForOverflow(Context);
13582       continue;
13583     }
13584 
13585     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13586       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13587     else if (isa<ObjCBoxedExpr>(OriginalE))
13588       E->EvaluateForOverflow(Context);
13589     else if (auto Call = dyn_cast<CallExpr>(E))
13590       Exprs.append(Call->arg_begin(), Call->arg_end());
13591     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13592       Exprs.append(Message->arg_begin(), Message->arg_end());
13593   } while (!Exprs.empty());
13594 }
13595 
13596 namespace {
13597 
13598 /// Visitor for expressions which looks for unsequenced operations on the
13599 /// same object.
13600 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13601   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13602 
13603   /// A tree of sequenced regions within an expression. Two regions are
13604   /// unsequenced if one is an ancestor or a descendent of the other. When we
13605   /// finish processing an expression with sequencing, such as a comma
13606   /// expression, we fold its tree nodes into its parent, since they are
13607   /// unsequenced with respect to nodes we will visit later.
13608   class SequenceTree {
13609     struct Value {
13610       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13611       unsigned Parent : 31;
13612       unsigned Merged : 1;
13613     };
13614     SmallVector<Value, 8> Values;
13615 
13616   public:
13617     /// A region within an expression which may be sequenced with respect
13618     /// to some other region.
13619     class Seq {
13620       friend class SequenceTree;
13621 
13622       unsigned Index;
13623 
13624       explicit Seq(unsigned N) : Index(N) {}
13625 
13626     public:
13627       Seq() : Index(0) {}
13628     };
13629 
13630     SequenceTree() { Values.push_back(Value(0)); }
13631     Seq root() const { return Seq(0); }
13632 
13633     /// Create a new sequence of operations, which is an unsequenced
13634     /// subset of \p Parent. This sequence of operations is sequenced with
13635     /// respect to other children of \p Parent.
13636     Seq allocate(Seq Parent) {
13637       Values.push_back(Value(Parent.Index));
13638       return Seq(Values.size() - 1);
13639     }
13640 
13641     /// Merge a sequence of operations into its parent.
13642     void merge(Seq S) {
13643       Values[S.Index].Merged = true;
13644     }
13645 
13646     /// Determine whether two operations are unsequenced. This operation
13647     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13648     /// should have been merged into its parent as appropriate.
13649     bool isUnsequenced(Seq Cur, Seq Old) {
13650       unsigned C = representative(Cur.Index);
13651       unsigned Target = representative(Old.Index);
13652       while (C >= Target) {
13653         if (C == Target)
13654           return true;
13655         C = Values[C].Parent;
13656       }
13657       return false;
13658     }
13659 
13660   private:
13661     /// Pick a representative for a sequence.
13662     unsigned representative(unsigned K) {
13663       if (Values[K].Merged)
13664         // Perform path compression as we go.
13665         return Values[K].Parent = representative(Values[K].Parent);
13666       return K;
13667     }
13668   };
13669 
13670   /// An object for which we can track unsequenced uses.
13671   using Object = const NamedDecl *;
13672 
13673   /// Different flavors of object usage which we track. We only track the
13674   /// least-sequenced usage of each kind.
13675   enum UsageKind {
13676     /// A read of an object. Multiple unsequenced reads are OK.
13677     UK_Use,
13678 
13679     /// A modification of an object which is sequenced before the value
13680     /// computation of the expression, such as ++n in C++.
13681     UK_ModAsValue,
13682 
13683     /// A modification of an object which is not sequenced before the value
13684     /// computation of the expression, such as n++.
13685     UK_ModAsSideEffect,
13686 
13687     UK_Count = UK_ModAsSideEffect + 1
13688   };
13689 
13690   /// Bundle together a sequencing region and the expression corresponding
13691   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13692   struct Usage {
13693     const Expr *UsageExpr;
13694     SequenceTree::Seq Seq;
13695 
13696     Usage() : UsageExpr(nullptr), Seq() {}
13697   };
13698 
13699   struct UsageInfo {
13700     Usage Uses[UK_Count];
13701 
13702     /// Have we issued a diagnostic for this object already?
13703     bool Diagnosed;
13704 
13705     UsageInfo() : Uses(), Diagnosed(false) {}
13706   };
13707   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13708 
13709   Sema &SemaRef;
13710 
13711   /// Sequenced regions within the expression.
13712   SequenceTree Tree;
13713 
13714   /// Declaration modifications and references which we have seen.
13715   UsageInfoMap UsageMap;
13716 
13717   /// The region we are currently within.
13718   SequenceTree::Seq Region;
13719 
13720   /// Filled in with declarations which were modified as a side-effect
13721   /// (that is, post-increment operations).
13722   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13723 
13724   /// Expressions to check later. We defer checking these to reduce
13725   /// stack usage.
13726   SmallVectorImpl<const Expr *> &WorkList;
13727 
13728   /// RAII object wrapping the visitation of a sequenced subexpression of an
13729   /// expression. At the end of this process, the side-effects of the evaluation
13730   /// become sequenced with respect to the value computation of the result, so
13731   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13732   /// UK_ModAsValue.
13733   struct SequencedSubexpression {
13734     SequencedSubexpression(SequenceChecker &Self)
13735       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13736       Self.ModAsSideEffect = &ModAsSideEffect;
13737     }
13738 
13739     ~SequencedSubexpression() {
13740       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13741         // Add a new usage with usage kind UK_ModAsValue, and then restore
13742         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13743         // the previous one was empty).
13744         UsageInfo &UI = Self.UsageMap[M.first];
13745         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13746         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13747         SideEffectUsage = M.second;
13748       }
13749       Self.ModAsSideEffect = OldModAsSideEffect;
13750     }
13751 
13752     SequenceChecker &Self;
13753     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13754     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13755   };
13756 
13757   /// RAII object wrapping the visitation of a subexpression which we might
13758   /// choose to evaluate as a constant. If any subexpression is evaluated and
13759   /// found to be non-constant, this allows us to suppress the evaluation of
13760   /// the outer expression.
13761   class EvaluationTracker {
13762   public:
13763     EvaluationTracker(SequenceChecker &Self)
13764         : Self(Self), Prev(Self.EvalTracker) {
13765       Self.EvalTracker = this;
13766     }
13767 
13768     ~EvaluationTracker() {
13769       Self.EvalTracker = Prev;
13770       if (Prev)
13771         Prev->EvalOK &= EvalOK;
13772     }
13773 
13774     bool evaluate(const Expr *E, bool &Result) {
13775       if (!EvalOK || E->isValueDependent())
13776         return false;
13777       EvalOK = E->EvaluateAsBooleanCondition(
13778           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13779       return EvalOK;
13780     }
13781 
13782   private:
13783     SequenceChecker &Self;
13784     EvaluationTracker *Prev;
13785     bool EvalOK = true;
13786   } *EvalTracker = nullptr;
13787 
13788   /// Find the object which is produced by the specified expression,
13789   /// if any.
13790   Object getObject(const Expr *E, bool Mod) const {
13791     E = E->IgnoreParenCasts();
13792     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13793       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13794         return getObject(UO->getSubExpr(), Mod);
13795     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13796       if (BO->getOpcode() == BO_Comma)
13797         return getObject(BO->getRHS(), Mod);
13798       if (Mod && BO->isAssignmentOp())
13799         return getObject(BO->getLHS(), Mod);
13800     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13801       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13802       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13803         return ME->getMemberDecl();
13804     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13805       // FIXME: If this is a reference, map through to its value.
13806       return DRE->getDecl();
13807     return nullptr;
13808   }
13809 
13810   /// Note that an object \p O was modified or used by an expression
13811   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13812   /// the object \p O as obtained via the \p UsageMap.
13813   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13814     // Get the old usage for the given object and usage kind.
13815     Usage &U = UI.Uses[UK];
13816     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13817       // If we have a modification as side effect and are in a sequenced
13818       // subexpression, save the old Usage so that we can restore it later
13819       // in SequencedSubexpression::~SequencedSubexpression.
13820       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13821         ModAsSideEffect->push_back(std::make_pair(O, U));
13822       // Then record the new usage with the current sequencing region.
13823       U.UsageExpr = UsageExpr;
13824       U.Seq = Region;
13825     }
13826   }
13827 
13828   /// Check whether a modification or use of an object \p O in an expression
13829   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13830   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13831   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13832   /// usage and false we are checking for a mod-use unsequenced usage.
13833   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13834                   UsageKind OtherKind, bool IsModMod) {
13835     if (UI.Diagnosed)
13836       return;
13837 
13838     const Usage &U = UI.Uses[OtherKind];
13839     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13840       return;
13841 
13842     const Expr *Mod = U.UsageExpr;
13843     const Expr *ModOrUse = UsageExpr;
13844     if (OtherKind == UK_Use)
13845       std::swap(Mod, ModOrUse);
13846 
13847     SemaRef.DiagRuntimeBehavior(
13848         Mod->getExprLoc(), {Mod, ModOrUse},
13849         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13850                                : diag::warn_unsequenced_mod_use)
13851             << O << SourceRange(ModOrUse->getExprLoc()));
13852     UI.Diagnosed = true;
13853   }
13854 
13855   // A note on note{Pre, Post}{Use, Mod}:
13856   //
13857   // (It helps to follow the algorithm with an expression such as
13858   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13859   //  operations before C++17 and both are well-defined in C++17).
13860   //
13861   // When visiting a node which uses/modify an object we first call notePreUse
13862   // or notePreMod before visiting its sub-expression(s). At this point the
13863   // children of the current node have not yet been visited and so the eventual
13864   // uses/modifications resulting from the children of the current node have not
13865   // been recorded yet.
13866   //
13867   // We then visit the children of the current node. After that notePostUse or
13868   // notePostMod is called. These will 1) detect an unsequenced modification
13869   // as side effect (as in "k++ + k") and 2) add a new usage with the
13870   // appropriate usage kind.
13871   //
13872   // We also have to be careful that some operation sequences modification as
13873   // side effect as well (for example: || or ,). To account for this we wrap
13874   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13875   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13876   // which record usages which are modifications as side effect, and then
13877   // downgrade them (or more accurately restore the previous usage which was a
13878   // modification as side effect) when exiting the scope of the sequenced
13879   // subexpression.
13880 
13881   void notePreUse(Object O, const Expr *UseExpr) {
13882     UsageInfo &UI = UsageMap[O];
13883     // Uses conflict with other modifications.
13884     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13885   }
13886 
13887   void notePostUse(Object O, const Expr *UseExpr) {
13888     UsageInfo &UI = UsageMap[O];
13889     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13890                /*IsModMod=*/false);
13891     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13892   }
13893 
13894   void notePreMod(Object O, const Expr *ModExpr) {
13895     UsageInfo &UI = UsageMap[O];
13896     // Modifications conflict with other modifications and with uses.
13897     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13898     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13899   }
13900 
13901   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13902     UsageInfo &UI = UsageMap[O];
13903     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13904                /*IsModMod=*/true);
13905     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13906   }
13907 
13908 public:
13909   SequenceChecker(Sema &S, const Expr *E,
13910                   SmallVectorImpl<const Expr *> &WorkList)
13911       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13912     Visit(E);
13913     // Silence a -Wunused-private-field since WorkList is now unused.
13914     // TODO: Evaluate if it can be used, and if not remove it.
13915     (void)this->WorkList;
13916   }
13917 
13918   void VisitStmt(const Stmt *S) {
13919     // Skip all statements which aren't expressions for now.
13920   }
13921 
13922   void VisitExpr(const Expr *E) {
13923     // By default, just recurse to evaluated subexpressions.
13924     Base::VisitStmt(E);
13925   }
13926 
13927   void VisitCastExpr(const CastExpr *E) {
13928     Object O = Object();
13929     if (E->getCastKind() == CK_LValueToRValue)
13930       O = getObject(E->getSubExpr(), false);
13931 
13932     if (O)
13933       notePreUse(O, E);
13934     VisitExpr(E);
13935     if (O)
13936       notePostUse(O, E);
13937   }
13938 
13939   void VisitSequencedExpressions(const Expr *SequencedBefore,
13940                                  const Expr *SequencedAfter) {
13941     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13942     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13943     SequenceTree::Seq OldRegion = Region;
13944 
13945     {
13946       SequencedSubexpression SeqBefore(*this);
13947       Region = BeforeRegion;
13948       Visit(SequencedBefore);
13949     }
13950 
13951     Region = AfterRegion;
13952     Visit(SequencedAfter);
13953 
13954     Region = OldRegion;
13955 
13956     Tree.merge(BeforeRegion);
13957     Tree.merge(AfterRegion);
13958   }
13959 
13960   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13961     // C++17 [expr.sub]p1:
13962     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13963     //   expression E1 is sequenced before the expression E2.
13964     if (SemaRef.getLangOpts().CPlusPlus17)
13965       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13966     else {
13967       Visit(ASE->getLHS());
13968       Visit(ASE->getRHS());
13969     }
13970   }
13971 
13972   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13973   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13974   void VisitBinPtrMem(const BinaryOperator *BO) {
13975     // C++17 [expr.mptr.oper]p4:
13976     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13977     //  the expression E1 is sequenced before the expression E2.
13978     if (SemaRef.getLangOpts().CPlusPlus17)
13979       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13980     else {
13981       Visit(BO->getLHS());
13982       Visit(BO->getRHS());
13983     }
13984   }
13985 
13986   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13987   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13988   void VisitBinShlShr(const BinaryOperator *BO) {
13989     // C++17 [expr.shift]p4:
13990     //  The expression E1 is sequenced before the expression E2.
13991     if (SemaRef.getLangOpts().CPlusPlus17)
13992       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13993     else {
13994       Visit(BO->getLHS());
13995       Visit(BO->getRHS());
13996     }
13997   }
13998 
13999   void VisitBinComma(const BinaryOperator *BO) {
14000     // C++11 [expr.comma]p1:
14001     //   Every value computation and side effect associated with the left
14002     //   expression is sequenced before every value computation and side
14003     //   effect associated with the right expression.
14004     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14005   }
14006 
14007   void VisitBinAssign(const BinaryOperator *BO) {
14008     SequenceTree::Seq RHSRegion;
14009     SequenceTree::Seq LHSRegion;
14010     if (SemaRef.getLangOpts().CPlusPlus17) {
14011       RHSRegion = Tree.allocate(Region);
14012       LHSRegion = Tree.allocate(Region);
14013     } else {
14014       RHSRegion = Region;
14015       LHSRegion = Region;
14016     }
14017     SequenceTree::Seq OldRegion = Region;
14018 
14019     // C++11 [expr.ass]p1:
14020     //  [...] the assignment is sequenced after the value computation
14021     //  of the right and left operands, [...]
14022     //
14023     // so check it before inspecting the operands and update the
14024     // map afterwards.
14025     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14026     if (O)
14027       notePreMod(O, BO);
14028 
14029     if (SemaRef.getLangOpts().CPlusPlus17) {
14030       // C++17 [expr.ass]p1:
14031       //  [...] The right operand is sequenced before the left operand. [...]
14032       {
14033         SequencedSubexpression SeqBefore(*this);
14034         Region = RHSRegion;
14035         Visit(BO->getRHS());
14036       }
14037 
14038       Region = LHSRegion;
14039       Visit(BO->getLHS());
14040 
14041       if (O && isa<CompoundAssignOperator>(BO))
14042         notePostUse(O, BO);
14043 
14044     } else {
14045       // C++11 does not specify any sequencing between the LHS and RHS.
14046       Region = LHSRegion;
14047       Visit(BO->getLHS());
14048 
14049       if (O && isa<CompoundAssignOperator>(BO))
14050         notePostUse(O, BO);
14051 
14052       Region = RHSRegion;
14053       Visit(BO->getRHS());
14054     }
14055 
14056     // C++11 [expr.ass]p1:
14057     //  the assignment is sequenced [...] before the value computation of the
14058     //  assignment expression.
14059     // C11 6.5.16/3 has no such rule.
14060     Region = OldRegion;
14061     if (O)
14062       notePostMod(O, BO,
14063                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14064                                                   : UK_ModAsSideEffect);
14065     if (SemaRef.getLangOpts().CPlusPlus17) {
14066       Tree.merge(RHSRegion);
14067       Tree.merge(LHSRegion);
14068     }
14069   }
14070 
14071   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14072     VisitBinAssign(CAO);
14073   }
14074 
14075   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14076   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14077   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14078     Object O = getObject(UO->getSubExpr(), true);
14079     if (!O)
14080       return VisitExpr(UO);
14081 
14082     notePreMod(O, UO);
14083     Visit(UO->getSubExpr());
14084     // C++11 [expr.pre.incr]p1:
14085     //   the expression ++x is equivalent to x+=1
14086     notePostMod(O, UO,
14087                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14088                                                 : UK_ModAsSideEffect);
14089   }
14090 
14091   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14092   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14093   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14094     Object O = getObject(UO->getSubExpr(), true);
14095     if (!O)
14096       return VisitExpr(UO);
14097 
14098     notePreMod(O, UO);
14099     Visit(UO->getSubExpr());
14100     notePostMod(O, UO, UK_ModAsSideEffect);
14101   }
14102 
14103   void VisitBinLOr(const BinaryOperator *BO) {
14104     // C++11 [expr.log.or]p2:
14105     //  If the second expression is evaluated, every value computation and
14106     //  side effect associated with the first expression is sequenced before
14107     //  every value computation and side effect associated with the
14108     //  second expression.
14109     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14110     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14111     SequenceTree::Seq OldRegion = Region;
14112 
14113     EvaluationTracker Eval(*this);
14114     {
14115       SequencedSubexpression Sequenced(*this);
14116       Region = LHSRegion;
14117       Visit(BO->getLHS());
14118     }
14119 
14120     // C++11 [expr.log.or]p1:
14121     //  [...] the second operand is not evaluated if the first operand
14122     //  evaluates to true.
14123     bool EvalResult = false;
14124     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14125     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14126     if (ShouldVisitRHS) {
14127       Region = RHSRegion;
14128       Visit(BO->getRHS());
14129     }
14130 
14131     Region = OldRegion;
14132     Tree.merge(LHSRegion);
14133     Tree.merge(RHSRegion);
14134   }
14135 
14136   void VisitBinLAnd(const BinaryOperator *BO) {
14137     // C++11 [expr.log.and]p2:
14138     //  If the second expression is evaluated, every value computation and
14139     //  side effect associated with the first expression is sequenced before
14140     //  every value computation and side effect associated with the
14141     //  second expression.
14142     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14143     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14144     SequenceTree::Seq OldRegion = Region;
14145 
14146     EvaluationTracker Eval(*this);
14147     {
14148       SequencedSubexpression Sequenced(*this);
14149       Region = LHSRegion;
14150       Visit(BO->getLHS());
14151     }
14152 
14153     // C++11 [expr.log.and]p1:
14154     //  [...] the second operand is not evaluated if the first operand is false.
14155     bool EvalResult = false;
14156     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14157     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14158     if (ShouldVisitRHS) {
14159       Region = RHSRegion;
14160       Visit(BO->getRHS());
14161     }
14162 
14163     Region = OldRegion;
14164     Tree.merge(LHSRegion);
14165     Tree.merge(RHSRegion);
14166   }
14167 
14168   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14169     // C++11 [expr.cond]p1:
14170     //  [...] Every value computation and side effect associated with the first
14171     //  expression is sequenced before every value computation and side effect
14172     //  associated with the second or third expression.
14173     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14174 
14175     // No sequencing is specified between the true and false expression.
14176     // However since exactly one of both is going to be evaluated we can
14177     // consider them to be sequenced. This is needed to avoid warning on
14178     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14179     // both the true and false expressions because we can't evaluate x.
14180     // This will still allow us to detect an expression like (pre C++17)
14181     // "(x ? y += 1 : y += 2) = y".
14182     //
14183     // We don't wrap the visitation of the true and false expression with
14184     // SequencedSubexpression because we don't want to downgrade modifications
14185     // as side effect in the true and false expressions after the visition
14186     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14187     // not warn between the two "y++", but we should warn between the "y++"
14188     // and the "y".
14189     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14190     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14191     SequenceTree::Seq OldRegion = Region;
14192 
14193     EvaluationTracker Eval(*this);
14194     {
14195       SequencedSubexpression Sequenced(*this);
14196       Region = ConditionRegion;
14197       Visit(CO->getCond());
14198     }
14199 
14200     // C++11 [expr.cond]p1:
14201     // [...] The first expression is contextually converted to bool (Clause 4).
14202     // It is evaluated and if it is true, the result of the conditional
14203     // expression is the value of the second expression, otherwise that of the
14204     // third expression. Only one of the second and third expressions is
14205     // evaluated. [...]
14206     bool EvalResult = false;
14207     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14208     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14209     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14210     if (ShouldVisitTrueExpr) {
14211       Region = TrueRegion;
14212       Visit(CO->getTrueExpr());
14213     }
14214     if (ShouldVisitFalseExpr) {
14215       Region = FalseRegion;
14216       Visit(CO->getFalseExpr());
14217     }
14218 
14219     Region = OldRegion;
14220     Tree.merge(ConditionRegion);
14221     Tree.merge(TrueRegion);
14222     Tree.merge(FalseRegion);
14223   }
14224 
14225   void VisitCallExpr(const CallExpr *CE) {
14226     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14227 
14228     if (CE->isUnevaluatedBuiltinCall(Context))
14229       return;
14230 
14231     // C++11 [intro.execution]p15:
14232     //   When calling a function [...], every value computation and side effect
14233     //   associated with any argument expression, or with the postfix expression
14234     //   designating the called function, is sequenced before execution of every
14235     //   expression or statement in the body of the function [and thus before
14236     //   the value computation of its result].
14237     SequencedSubexpression Sequenced(*this);
14238     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14239       // C++17 [expr.call]p5
14240       //   The postfix-expression is sequenced before each expression in the
14241       //   expression-list and any default argument. [...]
14242       SequenceTree::Seq CalleeRegion;
14243       SequenceTree::Seq OtherRegion;
14244       if (SemaRef.getLangOpts().CPlusPlus17) {
14245         CalleeRegion = Tree.allocate(Region);
14246         OtherRegion = Tree.allocate(Region);
14247       } else {
14248         CalleeRegion = Region;
14249         OtherRegion = Region;
14250       }
14251       SequenceTree::Seq OldRegion = Region;
14252 
14253       // Visit the callee expression first.
14254       Region = CalleeRegion;
14255       if (SemaRef.getLangOpts().CPlusPlus17) {
14256         SequencedSubexpression Sequenced(*this);
14257         Visit(CE->getCallee());
14258       } else {
14259         Visit(CE->getCallee());
14260       }
14261 
14262       // Then visit the argument expressions.
14263       Region = OtherRegion;
14264       for (const Expr *Argument : CE->arguments())
14265         Visit(Argument);
14266 
14267       Region = OldRegion;
14268       if (SemaRef.getLangOpts().CPlusPlus17) {
14269         Tree.merge(CalleeRegion);
14270         Tree.merge(OtherRegion);
14271       }
14272     });
14273   }
14274 
14275   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14276     // C++17 [over.match.oper]p2:
14277     //   [...] the operator notation is first transformed to the equivalent
14278     //   function-call notation as summarized in Table 12 (where @ denotes one
14279     //   of the operators covered in the specified subclause). However, the
14280     //   operands are sequenced in the order prescribed for the built-in
14281     //   operator (Clause 8).
14282     //
14283     // From the above only overloaded binary operators and overloaded call
14284     // operators have sequencing rules in C++17 that we need to handle
14285     // separately.
14286     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14287         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14288       return VisitCallExpr(CXXOCE);
14289 
14290     enum {
14291       NoSequencing,
14292       LHSBeforeRHS,
14293       RHSBeforeLHS,
14294       LHSBeforeRest
14295     } SequencingKind;
14296     switch (CXXOCE->getOperator()) {
14297     case OO_Equal:
14298     case OO_PlusEqual:
14299     case OO_MinusEqual:
14300     case OO_StarEqual:
14301     case OO_SlashEqual:
14302     case OO_PercentEqual:
14303     case OO_CaretEqual:
14304     case OO_AmpEqual:
14305     case OO_PipeEqual:
14306     case OO_LessLessEqual:
14307     case OO_GreaterGreaterEqual:
14308       SequencingKind = RHSBeforeLHS;
14309       break;
14310 
14311     case OO_LessLess:
14312     case OO_GreaterGreater:
14313     case OO_AmpAmp:
14314     case OO_PipePipe:
14315     case OO_Comma:
14316     case OO_ArrowStar:
14317     case OO_Subscript:
14318       SequencingKind = LHSBeforeRHS;
14319       break;
14320 
14321     case OO_Call:
14322       SequencingKind = LHSBeforeRest;
14323       break;
14324 
14325     default:
14326       SequencingKind = NoSequencing;
14327       break;
14328     }
14329 
14330     if (SequencingKind == NoSequencing)
14331       return VisitCallExpr(CXXOCE);
14332 
14333     // This is a call, so all subexpressions are sequenced before the result.
14334     SequencedSubexpression Sequenced(*this);
14335 
14336     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14337       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14338              "Should only get there with C++17 and above!");
14339       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14340              "Should only get there with an overloaded binary operator"
14341              " or an overloaded call operator!");
14342 
14343       if (SequencingKind == LHSBeforeRest) {
14344         assert(CXXOCE->getOperator() == OO_Call &&
14345                "We should only have an overloaded call operator here!");
14346 
14347         // This is very similar to VisitCallExpr, except that we only have the
14348         // C++17 case. The postfix-expression is the first argument of the
14349         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14350         // are in the following arguments.
14351         //
14352         // Note that we intentionally do not visit the callee expression since
14353         // it is just a decayed reference to a function.
14354         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14355         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14356         SequenceTree::Seq OldRegion = Region;
14357 
14358         assert(CXXOCE->getNumArgs() >= 1 &&
14359                "An overloaded call operator must have at least one argument"
14360                " for the postfix-expression!");
14361         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14362         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14363                                           CXXOCE->getNumArgs() - 1);
14364 
14365         // Visit the postfix-expression first.
14366         {
14367           Region = PostfixExprRegion;
14368           SequencedSubexpression Sequenced(*this);
14369           Visit(PostfixExpr);
14370         }
14371 
14372         // Then visit the argument expressions.
14373         Region = ArgsRegion;
14374         for (const Expr *Arg : Args)
14375           Visit(Arg);
14376 
14377         Region = OldRegion;
14378         Tree.merge(PostfixExprRegion);
14379         Tree.merge(ArgsRegion);
14380       } else {
14381         assert(CXXOCE->getNumArgs() == 2 &&
14382                "Should only have two arguments here!");
14383         assert((SequencingKind == LHSBeforeRHS ||
14384                 SequencingKind == RHSBeforeLHS) &&
14385                "Unexpected sequencing kind!");
14386 
14387         // We do not visit the callee expression since it is just a decayed
14388         // reference to a function.
14389         const Expr *E1 = CXXOCE->getArg(0);
14390         const Expr *E2 = CXXOCE->getArg(1);
14391         if (SequencingKind == RHSBeforeLHS)
14392           std::swap(E1, E2);
14393 
14394         return VisitSequencedExpressions(E1, E2);
14395       }
14396     });
14397   }
14398 
14399   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14400     // This is a call, so all subexpressions are sequenced before the result.
14401     SequencedSubexpression Sequenced(*this);
14402 
14403     if (!CCE->isListInitialization())
14404       return VisitExpr(CCE);
14405 
14406     // In C++11, list initializations are sequenced.
14407     SmallVector<SequenceTree::Seq, 32> Elts;
14408     SequenceTree::Seq Parent = Region;
14409     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14410                                               E = CCE->arg_end();
14411          I != E; ++I) {
14412       Region = Tree.allocate(Parent);
14413       Elts.push_back(Region);
14414       Visit(*I);
14415     }
14416 
14417     // Forget that the initializers are sequenced.
14418     Region = Parent;
14419     for (unsigned I = 0; I < Elts.size(); ++I)
14420       Tree.merge(Elts[I]);
14421   }
14422 
14423   void VisitInitListExpr(const InitListExpr *ILE) {
14424     if (!SemaRef.getLangOpts().CPlusPlus11)
14425       return VisitExpr(ILE);
14426 
14427     // In C++11, list initializations are sequenced.
14428     SmallVector<SequenceTree::Seq, 32> Elts;
14429     SequenceTree::Seq Parent = Region;
14430     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14431       const Expr *E = ILE->getInit(I);
14432       if (!E)
14433         continue;
14434       Region = Tree.allocate(Parent);
14435       Elts.push_back(Region);
14436       Visit(E);
14437     }
14438 
14439     // Forget that the initializers are sequenced.
14440     Region = Parent;
14441     for (unsigned I = 0; I < Elts.size(); ++I)
14442       Tree.merge(Elts[I]);
14443   }
14444 };
14445 
14446 } // namespace
14447 
14448 void Sema::CheckUnsequencedOperations(const Expr *E) {
14449   SmallVector<const Expr *, 8> WorkList;
14450   WorkList.push_back(E);
14451   while (!WorkList.empty()) {
14452     const Expr *Item = WorkList.pop_back_val();
14453     SequenceChecker(*this, Item, WorkList);
14454   }
14455 }
14456 
14457 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14458                               bool IsConstexpr) {
14459   llvm::SaveAndRestore<bool> ConstantContext(
14460       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14461   CheckImplicitConversions(E, CheckLoc);
14462   if (!E->isInstantiationDependent())
14463     CheckUnsequencedOperations(E);
14464   if (!IsConstexpr && !E->isValueDependent())
14465     CheckForIntOverflow(E);
14466   DiagnoseMisalignedMembers();
14467 }
14468 
14469 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14470                                        FieldDecl *BitField,
14471                                        Expr *Init) {
14472   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14473 }
14474 
14475 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14476                                          SourceLocation Loc) {
14477   if (!PType->isVariablyModifiedType())
14478     return;
14479   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14480     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14481     return;
14482   }
14483   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14484     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14485     return;
14486   }
14487   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14488     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14489     return;
14490   }
14491 
14492   const ArrayType *AT = S.Context.getAsArrayType(PType);
14493   if (!AT)
14494     return;
14495 
14496   if (AT->getSizeModifier() != ArrayType::Star) {
14497     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14498     return;
14499   }
14500 
14501   S.Diag(Loc, diag::err_array_star_in_function_definition);
14502 }
14503 
14504 /// CheckParmsForFunctionDef - Check that the parameters of the given
14505 /// function are appropriate for the definition of a function. This
14506 /// takes care of any checks that cannot be performed on the
14507 /// declaration itself, e.g., that the types of each of the function
14508 /// parameters are complete.
14509 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14510                                     bool CheckParameterNames) {
14511   bool HasInvalidParm = false;
14512   for (ParmVarDecl *Param : Parameters) {
14513     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14514     // function declarator that is part of a function definition of
14515     // that function shall not have incomplete type.
14516     //
14517     // This is also C++ [dcl.fct]p6.
14518     if (!Param->isInvalidDecl() &&
14519         RequireCompleteType(Param->getLocation(), Param->getType(),
14520                             diag::err_typecheck_decl_incomplete_type)) {
14521       Param->setInvalidDecl();
14522       HasInvalidParm = true;
14523     }
14524 
14525     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14526     // declaration of each parameter shall include an identifier.
14527     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14528         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14529       // Diagnose this as an extension in C17 and earlier.
14530       if (!getLangOpts().C2x)
14531         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14532     }
14533 
14534     // C99 6.7.5.3p12:
14535     //   If the function declarator is not part of a definition of that
14536     //   function, parameters may have incomplete type and may use the [*]
14537     //   notation in their sequences of declarator specifiers to specify
14538     //   variable length array types.
14539     QualType PType = Param->getOriginalType();
14540     // FIXME: This diagnostic should point the '[*]' if source-location
14541     // information is added for it.
14542     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14543 
14544     // If the parameter is a c++ class type and it has to be destructed in the
14545     // callee function, declare the destructor so that it can be called by the
14546     // callee function. Do not perform any direct access check on the dtor here.
14547     if (!Param->isInvalidDecl()) {
14548       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14549         if (!ClassDecl->isInvalidDecl() &&
14550             !ClassDecl->hasIrrelevantDestructor() &&
14551             !ClassDecl->isDependentContext() &&
14552             ClassDecl->isParamDestroyedInCallee()) {
14553           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14554           MarkFunctionReferenced(Param->getLocation(), Destructor);
14555           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14556         }
14557       }
14558     }
14559 
14560     // Parameters with the pass_object_size attribute only need to be marked
14561     // constant at function definitions. Because we lack information about
14562     // whether we're on a declaration or definition when we're instantiating the
14563     // attribute, we need to check for constness here.
14564     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14565       if (!Param->getType().isConstQualified())
14566         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14567             << Attr->getSpelling() << 1;
14568 
14569     // Check for parameter names shadowing fields from the class.
14570     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14571       // The owning context for the parameter should be the function, but we
14572       // want to see if this function's declaration context is a record.
14573       DeclContext *DC = Param->getDeclContext();
14574       if (DC && DC->isFunctionOrMethod()) {
14575         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14576           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14577                                      RD, /*DeclIsField*/ false);
14578       }
14579     }
14580   }
14581 
14582   return HasInvalidParm;
14583 }
14584 
14585 Optional<std::pair<CharUnits, CharUnits>>
14586 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14587 
14588 /// Compute the alignment and offset of the base class object given the
14589 /// derived-to-base cast expression and the alignment and offset of the derived
14590 /// class object.
14591 static std::pair<CharUnits, CharUnits>
14592 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14593                                    CharUnits BaseAlignment, CharUnits Offset,
14594                                    ASTContext &Ctx) {
14595   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14596        ++PathI) {
14597     const CXXBaseSpecifier *Base = *PathI;
14598     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14599     if (Base->isVirtual()) {
14600       // The complete object may have a lower alignment than the non-virtual
14601       // alignment of the base, in which case the base may be misaligned. Choose
14602       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14603       // conservative lower bound of the complete object alignment.
14604       CharUnits NonVirtualAlignment =
14605           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14606       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14607       Offset = CharUnits::Zero();
14608     } else {
14609       const ASTRecordLayout &RL =
14610           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14611       Offset += RL.getBaseClassOffset(BaseDecl);
14612     }
14613     DerivedType = Base->getType();
14614   }
14615 
14616   return std::make_pair(BaseAlignment, Offset);
14617 }
14618 
14619 /// Compute the alignment and offset of a binary additive operator.
14620 static Optional<std::pair<CharUnits, CharUnits>>
14621 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14622                                      bool IsSub, ASTContext &Ctx) {
14623   QualType PointeeType = PtrE->getType()->getPointeeType();
14624 
14625   if (!PointeeType->isConstantSizeType())
14626     return llvm::None;
14627 
14628   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14629 
14630   if (!P)
14631     return llvm::None;
14632 
14633   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14634   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14635     CharUnits Offset = EltSize * IdxRes->getExtValue();
14636     if (IsSub)
14637       Offset = -Offset;
14638     return std::make_pair(P->first, P->second + Offset);
14639   }
14640 
14641   // If the integer expression isn't a constant expression, compute the lower
14642   // bound of the alignment using the alignment and offset of the pointer
14643   // expression and the element size.
14644   return std::make_pair(
14645       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14646       CharUnits::Zero());
14647 }
14648 
14649 /// This helper function takes an lvalue expression and returns the alignment of
14650 /// a VarDecl and a constant offset from the VarDecl.
14651 Optional<std::pair<CharUnits, CharUnits>>
14652 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14653   E = E->IgnoreParens();
14654   switch (E->getStmtClass()) {
14655   default:
14656     break;
14657   case Stmt::CStyleCastExprClass:
14658   case Stmt::CXXStaticCastExprClass:
14659   case Stmt::ImplicitCastExprClass: {
14660     auto *CE = cast<CastExpr>(E);
14661     const Expr *From = CE->getSubExpr();
14662     switch (CE->getCastKind()) {
14663     default:
14664       break;
14665     case CK_NoOp:
14666       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14667     case CK_UncheckedDerivedToBase:
14668     case CK_DerivedToBase: {
14669       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14670       if (!P)
14671         break;
14672       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14673                                                 P->second, Ctx);
14674     }
14675     }
14676     break;
14677   }
14678   case Stmt::ArraySubscriptExprClass: {
14679     auto *ASE = cast<ArraySubscriptExpr>(E);
14680     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14681                                                 false, Ctx);
14682   }
14683   case Stmt::DeclRefExprClass: {
14684     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14685       // FIXME: If VD is captured by copy or is an escaping __block variable,
14686       // use the alignment of VD's type.
14687       if (!VD->getType()->isReferenceType())
14688         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14689       if (VD->hasInit())
14690         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14691     }
14692     break;
14693   }
14694   case Stmt::MemberExprClass: {
14695     auto *ME = cast<MemberExpr>(E);
14696     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14697     if (!FD || FD->getType()->isReferenceType() ||
14698         FD->getParent()->isInvalidDecl())
14699       break;
14700     Optional<std::pair<CharUnits, CharUnits>> P;
14701     if (ME->isArrow())
14702       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14703     else
14704       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14705     if (!P)
14706       break;
14707     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14708     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14709     return std::make_pair(P->first,
14710                           P->second + CharUnits::fromQuantity(Offset));
14711   }
14712   case Stmt::UnaryOperatorClass: {
14713     auto *UO = cast<UnaryOperator>(E);
14714     switch (UO->getOpcode()) {
14715     default:
14716       break;
14717     case UO_Deref:
14718       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14719     }
14720     break;
14721   }
14722   case Stmt::BinaryOperatorClass: {
14723     auto *BO = cast<BinaryOperator>(E);
14724     auto Opcode = BO->getOpcode();
14725     switch (Opcode) {
14726     default:
14727       break;
14728     case BO_Comma:
14729       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14730     }
14731     break;
14732   }
14733   }
14734   return llvm::None;
14735 }
14736 
14737 /// This helper function takes a pointer expression and returns the alignment of
14738 /// a VarDecl and a constant offset from the VarDecl.
14739 Optional<std::pair<CharUnits, CharUnits>>
14740 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14741   E = E->IgnoreParens();
14742   switch (E->getStmtClass()) {
14743   default:
14744     break;
14745   case Stmt::CStyleCastExprClass:
14746   case Stmt::CXXStaticCastExprClass:
14747   case Stmt::ImplicitCastExprClass: {
14748     auto *CE = cast<CastExpr>(E);
14749     const Expr *From = CE->getSubExpr();
14750     switch (CE->getCastKind()) {
14751     default:
14752       break;
14753     case CK_NoOp:
14754       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14755     case CK_ArrayToPointerDecay:
14756       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14757     case CK_UncheckedDerivedToBase:
14758     case CK_DerivedToBase: {
14759       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14760       if (!P)
14761         break;
14762       return getDerivedToBaseAlignmentAndOffset(
14763           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14764     }
14765     }
14766     break;
14767   }
14768   case Stmt::CXXThisExprClass: {
14769     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14770     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14771     return std::make_pair(Alignment, CharUnits::Zero());
14772   }
14773   case Stmt::UnaryOperatorClass: {
14774     auto *UO = cast<UnaryOperator>(E);
14775     if (UO->getOpcode() == UO_AddrOf)
14776       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14777     break;
14778   }
14779   case Stmt::BinaryOperatorClass: {
14780     auto *BO = cast<BinaryOperator>(E);
14781     auto Opcode = BO->getOpcode();
14782     switch (Opcode) {
14783     default:
14784       break;
14785     case BO_Add:
14786     case BO_Sub: {
14787       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14788       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14789         std::swap(LHS, RHS);
14790       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14791                                                   Ctx);
14792     }
14793     case BO_Comma:
14794       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14795     }
14796     break;
14797   }
14798   }
14799   return llvm::None;
14800 }
14801 
14802 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14803   // See if we can compute the alignment of a VarDecl and an offset from it.
14804   Optional<std::pair<CharUnits, CharUnits>> P =
14805       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14806 
14807   if (P)
14808     return P->first.alignmentAtOffset(P->second);
14809 
14810   // If that failed, return the type's alignment.
14811   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14812 }
14813 
14814 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14815 /// pointer cast increases the alignment requirements.
14816 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14817   // This is actually a lot of work to potentially be doing on every
14818   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14819   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14820     return;
14821 
14822   // Ignore dependent types.
14823   if (T->isDependentType() || Op->getType()->isDependentType())
14824     return;
14825 
14826   // Require that the destination be a pointer type.
14827   const PointerType *DestPtr = T->getAs<PointerType>();
14828   if (!DestPtr) return;
14829 
14830   // If the destination has alignment 1, we're done.
14831   QualType DestPointee = DestPtr->getPointeeType();
14832   if (DestPointee->isIncompleteType()) return;
14833   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14834   if (DestAlign.isOne()) return;
14835 
14836   // Require that the source be a pointer type.
14837   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14838   if (!SrcPtr) return;
14839   QualType SrcPointee = SrcPtr->getPointeeType();
14840 
14841   // Explicitly allow casts from cv void*.  We already implicitly
14842   // allowed casts to cv void*, since they have alignment 1.
14843   // Also allow casts involving incomplete types, which implicitly
14844   // includes 'void'.
14845   if (SrcPointee->isIncompleteType()) return;
14846 
14847   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14848 
14849   if (SrcAlign >= DestAlign) return;
14850 
14851   Diag(TRange.getBegin(), diag::warn_cast_align)
14852     << Op->getType() << T
14853     << static_cast<unsigned>(SrcAlign.getQuantity())
14854     << static_cast<unsigned>(DestAlign.getQuantity())
14855     << TRange << Op->getSourceRange();
14856 }
14857 
14858 /// Check whether this array fits the idiom of a size-one tail padded
14859 /// array member of a struct.
14860 ///
14861 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14862 /// commonly used to emulate flexible arrays in C89 code.
14863 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14864                                     const NamedDecl *ND) {
14865   if (Size != 1 || !ND) return false;
14866 
14867   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14868   if (!FD) return false;
14869 
14870   // Don't consider sizes resulting from macro expansions or template argument
14871   // substitution to form C89 tail-padded arrays.
14872 
14873   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14874   while (TInfo) {
14875     TypeLoc TL = TInfo->getTypeLoc();
14876     // Look through typedefs.
14877     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14878       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14879       TInfo = TDL->getTypeSourceInfo();
14880       continue;
14881     }
14882     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14883       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14884       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14885         return false;
14886     }
14887     break;
14888   }
14889 
14890   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14891   if (!RD) return false;
14892   if (RD->isUnion()) return false;
14893   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14894     if (!CRD->isStandardLayout()) return false;
14895   }
14896 
14897   // See if this is the last field decl in the record.
14898   const Decl *D = FD;
14899   while ((D = D->getNextDeclInContext()))
14900     if (isa<FieldDecl>(D))
14901       return false;
14902   return true;
14903 }
14904 
14905 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14906                             const ArraySubscriptExpr *ASE,
14907                             bool AllowOnePastEnd, bool IndexNegated) {
14908   // Already diagnosed by the constant evaluator.
14909   if (isConstantEvaluated())
14910     return;
14911 
14912   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14913   if (IndexExpr->isValueDependent())
14914     return;
14915 
14916   const Type *EffectiveType =
14917       BaseExpr->getType()->getPointeeOrArrayElementType();
14918   BaseExpr = BaseExpr->IgnoreParenCasts();
14919   const ConstantArrayType *ArrayTy =
14920       Context.getAsConstantArrayType(BaseExpr->getType());
14921 
14922   const Type *BaseType =
14923       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14924   bool IsUnboundedArray = (BaseType == nullptr);
14925   if (EffectiveType->isDependentType() ||
14926       (!IsUnboundedArray && BaseType->isDependentType()))
14927     return;
14928 
14929   Expr::EvalResult Result;
14930   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14931     return;
14932 
14933   llvm::APSInt index = Result.Val.getInt();
14934   if (IndexNegated) {
14935     index.setIsUnsigned(false);
14936     index = -index;
14937   }
14938 
14939   const NamedDecl *ND = nullptr;
14940   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14941     ND = DRE->getDecl();
14942   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14943     ND = ME->getMemberDecl();
14944 
14945   if (IsUnboundedArray) {
14946     if (index.isUnsigned() || !index.isNegative()) {
14947       const auto &ASTC = getASTContext();
14948       unsigned AddrBits =
14949           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14950               EffectiveType->getCanonicalTypeInternal()));
14951       if (index.getBitWidth() < AddrBits)
14952         index = index.zext(AddrBits);
14953       Optional<CharUnits> ElemCharUnits =
14954           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14955       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14956       // pointer) bounds-checking isn't meaningful.
14957       if (!ElemCharUnits)
14958         return;
14959       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14960       // If index has more active bits than address space, we already know
14961       // we have a bounds violation to warn about.  Otherwise, compute
14962       // address of (index + 1)th element, and warn about bounds violation
14963       // only if that address exceeds address space.
14964       if (index.getActiveBits() <= AddrBits) {
14965         bool Overflow;
14966         llvm::APInt Product(index);
14967         Product += 1;
14968         Product = Product.umul_ov(ElemBytes, Overflow);
14969         if (!Overflow && Product.getActiveBits() <= AddrBits)
14970           return;
14971       }
14972 
14973       // Need to compute max possible elements in address space, since that
14974       // is included in diag message.
14975       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14976       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14977       MaxElems += 1;
14978       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14979       MaxElems = MaxElems.udiv(ElemBytes);
14980 
14981       unsigned DiagID =
14982           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14983               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14984 
14985       // Diag message shows element size in bits and in "bytes" (platform-
14986       // dependent CharUnits)
14987       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14988                           PDiag(DiagID)
14989                               << toString(index, 10, true) << AddrBits
14990                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14991                               << toString(ElemBytes, 10, false)
14992                               << toString(MaxElems, 10, false)
14993                               << (unsigned)MaxElems.getLimitedValue(~0U)
14994                               << IndexExpr->getSourceRange());
14995 
14996       if (!ND) {
14997         // Try harder to find a NamedDecl to point at in the note.
14998         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14999           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15000         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15001           ND = DRE->getDecl();
15002         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15003           ND = ME->getMemberDecl();
15004       }
15005 
15006       if (ND)
15007         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15008                             PDiag(diag::note_array_declared_here) << ND);
15009     }
15010     return;
15011   }
15012 
15013   if (index.isUnsigned() || !index.isNegative()) {
15014     // It is possible that the type of the base expression after
15015     // IgnoreParenCasts is incomplete, even though the type of the base
15016     // expression before IgnoreParenCasts is complete (see PR39746 for an
15017     // example). In this case we have no information about whether the array
15018     // access exceeds the array bounds. However we can still diagnose an array
15019     // access which precedes the array bounds.
15020     if (BaseType->isIncompleteType())
15021       return;
15022 
15023     llvm::APInt size = ArrayTy->getSize();
15024     if (!size.isStrictlyPositive())
15025       return;
15026 
15027     if (BaseType != EffectiveType) {
15028       // Make sure we're comparing apples to apples when comparing index to size
15029       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15030       uint64_t array_typesize = Context.getTypeSize(BaseType);
15031       // Handle ptrarith_typesize being zero, such as when casting to void*
15032       if (!ptrarith_typesize) ptrarith_typesize = 1;
15033       if (ptrarith_typesize != array_typesize) {
15034         // There's a cast to a different size type involved
15035         uint64_t ratio = array_typesize / ptrarith_typesize;
15036         // TODO: Be smarter about handling cases where array_typesize is not a
15037         // multiple of ptrarith_typesize
15038         if (ptrarith_typesize * ratio == array_typesize)
15039           size *= llvm::APInt(size.getBitWidth(), ratio);
15040       }
15041     }
15042 
15043     if (size.getBitWidth() > index.getBitWidth())
15044       index = index.zext(size.getBitWidth());
15045     else if (size.getBitWidth() < index.getBitWidth())
15046       size = size.zext(index.getBitWidth());
15047 
15048     // For array subscripting the index must be less than size, but for pointer
15049     // arithmetic also allow the index (offset) to be equal to size since
15050     // computing the next address after the end of the array is legal and
15051     // commonly done e.g. in C++ iterators and range-based for loops.
15052     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15053       return;
15054 
15055     // Also don't warn for arrays of size 1 which are members of some
15056     // structure. These are often used to approximate flexible arrays in C89
15057     // code.
15058     if (IsTailPaddedMemberArray(*this, size, ND))
15059       return;
15060 
15061     // Suppress the warning if the subscript expression (as identified by the
15062     // ']' location) and the index expression are both from macro expansions
15063     // within a system header.
15064     if (ASE) {
15065       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15066           ASE->getRBracketLoc());
15067       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15068         SourceLocation IndexLoc =
15069             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15070         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15071           return;
15072       }
15073     }
15074 
15075     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15076                           : diag::warn_ptr_arith_exceeds_bounds;
15077 
15078     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15079                         PDiag(DiagID) << toString(index, 10, true)
15080                                       << toString(size, 10, true)
15081                                       << (unsigned)size.getLimitedValue(~0U)
15082                                       << IndexExpr->getSourceRange());
15083   } else {
15084     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15085     if (!ASE) {
15086       DiagID = diag::warn_ptr_arith_precedes_bounds;
15087       if (index.isNegative()) index = -index;
15088     }
15089 
15090     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15091                         PDiag(DiagID) << toString(index, 10, true)
15092                                       << IndexExpr->getSourceRange());
15093   }
15094 
15095   if (!ND) {
15096     // Try harder to find a NamedDecl to point at in the note.
15097     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15098       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15099     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15100       ND = DRE->getDecl();
15101     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15102       ND = ME->getMemberDecl();
15103   }
15104 
15105   if (ND)
15106     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15107                         PDiag(diag::note_array_declared_here) << ND);
15108 }
15109 
15110 void Sema::CheckArrayAccess(const Expr *expr) {
15111   int AllowOnePastEnd = 0;
15112   while (expr) {
15113     expr = expr->IgnoreParenImpCasts();
15114     switch (expr->getStmtClass()) {
15115       case Stmt::ArraySubscriptExprClass: {
15116         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15117         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15118                          AllowOnePastEnd > 0);
15119         expr = ASE->getBase();
15120         break;
15121       }
15122       case Stmt::MemberExprClass: {
15123         expr = cast<MemberExpr>(expr)->getBase();
15124         break;
15125       }
15126       case Stmt::OMPArraySectionExprClass: {
15127         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15128         if (ASE->getLowerBound())
15129           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15130                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15131         return;
15132       }
15133       case Stmt::UnaryOperatorClass: {
15134         // Only unwrap the * and & unary operators
15135         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15136         expr = UO->getSubExpr();
15137         switch (UO->getOpcode()) {
15138           case UO_AddrOf:
15139             AllowOnePastEnd++;
15140             break;
15141           case UO_Deref:
15142             AllowOnePastEnd--;
15143             break;
15144           default:
15145             return;
15146         }
15147         break;
15148       }
15149       case Stmt::ConditionalOperatorClass: {
15150         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15151         if (const Expr *lhs = cond->getLHS())
15152           CheckArrayAccess(lhs);
15153         if (const Expr *rhs = cond->getRHS())
15154           CheckArrayAccess(rhs);
15155         return;
15156       }
15157       case Stmt::CXXOperatorCallExprClass: {
15158         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15159         for (const auto *Arg : OCE->arguments())
15160           CheckArrayAccess(Arg);
15161         return;
15162       }
15163       default:
15164         return;
15165     }
15166   }
15167 }
15168 
15169 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15170 
15171 namespace {
15172 
15173 struct RetainCycleOwner {
15174   VarDecl *Variable = nullptr;
15175   SourceRange Range;
15176   SourceLocation Loc;
15177   bool Indirect = false;
15178 
15179   RetainCycleOwner() = default;
15180 
15181   void setLocsFrom(Expr *e) {
15182     Loc = e->getExprLoc();
15183     Range = e->getSourceRange();
15184   }
15185 };
15186 
15187 } // namespace
15188 
15189 /// Consider whether capturing the given variable can possibly lead to
15190 /// a retain cycle.
15191 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15192   // In ARC, it's captured strongly iff the variable has __strong
15193   // lifetime.  In MRR, it's captured strongly if the variable is
15194   // __block and has an appropriate type.
15195   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15196     return false;
15197 
15198   owner.Variable = var;
15199   if (ref)
15200     owner.setLocsFrom(ref);
15201   return true;
15202 }
15203 
15204 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15205   while (true) {
15206     e = e->IgnoreParens();
15207     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15208       switch (cast->getCastKind()) {
15209       case CK_BitCast:
15210       case CK_LValueBitCast:
15211       case CK_LValueToRValue:
15212       case CK_ARCReclaimReturnedObject:
15213         e = cast->getSubExpr();
15214         continue;
15215 
15216       default:
15217         return false;
15218       }
15219     }
15220 
15221     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15222       ObjCIvarDecl *ivar = ref->getDecl();
15223       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15224         return false;
15225 
15226       // Try to find a retain cycle in the base.
15227       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15228         return false;
15229 
15230       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15231       owner.Indirect = true;
15232       return true;
15233     }
15234 
15235     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15236       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15237       if (!var) return false;
15238       return considerVariable(var, ref, owner);
15239     }
15240 
15241     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15242       if (member->isArrow()) return false;
15243 
15244       // Don't count this as an indirect ownership.
15245       e = member->getBase();
15246       continue;
15247     }
15248 
15249     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15250       // Only pay attention to pseudo-objects on property references.
15251       ObjCPropertyRefExpr *pre
15252         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15253                                               ->IgnoreParens());
15254       if (!pre) return false;
15255       if (pre->isImplicitProperty()) return false;
15256       ObjCPropertyDecl *property = pre->getExplicitProperty();
15257       if (!property->isRetaining() &&
15258           !(property->getPropertyIvarDecl() &&
15259             property->getPropertyIvarDecl()->getType()
15260               .getObjCLifetime() == Qualifiers::OCL_Strong))
15261           return false;
15262 
15263       owner.Indirect = true;
15264       if (pre->isSuperReceiver()) {
15265         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15266         if (!owner.Variable)
15267           return false;
15268         owner.Loc = pre->getLocation();
15269         owner.Range = pre->getSourceRange();
15270         return true;
15271       }
15272       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15273                               ->getSourceExpr());
15274       continue;
15275     }
15276 
15277     // Array ivars?
15278 
15279     return false;
15280   }
15281 }
15282 
15283 namespace {
15284 
15285   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15286     ASTContext &Context;
15287     VarDecl *Variable;
15288     Expr *Capturer = nullptr;
15289     bool VarWillBeReased = false;
15290 
15291     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15292         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15293           Context(Context), Variable(variable) {}
15294 
15295     void VisitDeclRefExpr(DeclRefExpr *ref) {
15296       if (ref->getDecl() == Variable && !Capturer)
15297         Capturer = ref;
15298     }
15299 
15300     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15301       if (Capturer) return;
15302       Visit(ref->getBase());
15303       if (Capturer && ref->isFreeIvar())
15304         Capturer = ref;
15305     }
15306 
15307     void VisitBlockExpr(BlockExpr *block) {
15308       // Look inside nested blocks
15309       if (block->getBlockDecl()->capturesVariable(Variable))
15310         Visit(block->getBlockDecl()->getBody());
15311     }
15312 
15313     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15314       if (Capturer) return;
15315       if (OVE->getSourceExpr())
15316         Visit(OVE->getSourceExpr());
15317     }
15318 
15319     void VisitBinaryOperator(BinaryOperator *BinOp) {
15320       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15321         return;
15322       Expr *LHS = BinOp->getLHS();
15323       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15324         if (DRE->getDecl() != Variable)
15325           return;
15326         if (Expr *RHS = BinOp->getRHS()) {
15327           RHS = RHS->IgnoreParenCasts();
15328           Optional<llvm::APSInt> Value;
15329           VarWillBeReased =
15330               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15331                *Value == 0);
15332         }
15333       }
15334     }
15335   };
15336 
15337 } // namespace
15338 
15339 /// Check whether the given argument is a block which captures a
15340 /// variable.
15341 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15342   assert(owner.Variable && owner.Loc.isValid());
15343 
15344   e = e->IgnoreParenCasts();
15345 
15346   // Look through [^{...} copy] and Block_copy(^{...}).
15347   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15348     Selector Cmd = ME->getSelector();
15349     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15350       e = ME->getInstanceReceiver();
15351       if (!e)
15352         return nullptr;
15353       e = e->IgnoreParenCasts();
15354     }
15355   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15356     if (CE->getNumArgs() == 1) {
15357       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15358       if (Fn) {
15359         const IdentifierInfo *FnI = Fn->getIdentifier();
15360         if (FnI && FnI->isStr("_Block_copy")) {
15361           e = CE->getArg(0)->IgnoreParenCasts();
15362         }
15363       }
15364     }
15365   }
15366 
15367   BlockExpr *block = dyn_cast<BlockExpr>(e);
15368   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15369     return nullptr;
15370 
15371   FindCaptureVisitor visitor(S.Context, owner.Variable);
15372   visitor.Visit(block->getBlockDecl()->getBody());
15373   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15374 }
15375 
15376 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15377                                 RetainCycleOwner &owner) {
15378   assert(capturer);
15379   assert(owner.Variable && owner.Loc.isValid());
15380 
15381   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15382     << owner.Variable << capturer->getSourceRange();
15383   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15384     << owner.Indirect << owner.Range;
15385 }
15386 
15387 /// Check for a keyword selector that starts with the word 'add' or
15388 /// 'set'.
15389 static bool isSetterLikeSelector(Selector sel) {
15390   if (sel.isUnarySelector()) return false;
15391 
15392   StringRef str = sel.getNameForSlot(0);
15393   while (!str.empty() && str.front() == '_') str = str.substr(1);
15394   if (str.startswith("set"))
15395     str = str.substr(3);
15396   else if (str.startswith("add")) {
15397     // Specially allow 'addOperationWithBlock:'.
15398     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15399       return false;
15400     str = str.substr(3);
15401   }
15402   else
15403     return false;
15404 
15405   if (str.empty()) return true;
15406   return !isLowercase(str.front());
15407 }
15408 
15409 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15410                                                     ObjCMessageExpr *Message) {
15411   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15412                                                 Message->getReceiverInterface(),
15413                                                 NSAPI::ClassId_NSMutableArray);
15414   if (!IsMutableArray) {
15415     return None;
15416   }
15417 
15418   Selector Sel = Message->getSelector();
15419 
15420   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15421     S.NSAPIObj->getNSArrayMethodKind(Sel);
15422   if (!MKOpt) {
15423     return None;
15424   }
15425 
15426   NSAPI::NSArrayMethodKind MK = *MKOpt;
15427 
15428   switch (MK) {
15429     case NSAPI::NSMutableArr_addObject:
15430     case NSAPI::NSMutableArr_insertObjectAtIndex:
15431     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15432       return 0;
15433     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15434       return 1;
15435 
15436     default:
15437       return None;
15438   }
15439 
15440   return None;
15441 }
15442 
15443 static
15444 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15445                                                   ObjCMessageExpr *Message) {
15446   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15447                                             Message->getReceiverInterface(),
15448                                             NSAPI::ClassId_NSMutableDictionary);
15449   if (!IsMutableDictionary) {
15450     return None;
15451   }
15452 
15453   Selector Sel = Message->getSelector();
15454 
15455   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15456     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15457   if (!MKOpt) {
15458     return None;
15459   }
15460 
15461   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15462 
15463   switch (MK) {
15464     case NSAPI::NSMutableDict_setObjectForKey:
15465     case NSAPI::NSMutableDict_setValueForKey:
15466     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15467       return 0;
15468 
15469     default:
15470       return None;
15471   }
15472 
15473   return None;
15474 }
15475 
15476 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15477   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15478                                                 Message->getReceiverInterface(),
15479                                                 NSAPI::ClassId_NSMutableSet);
15480 
15481   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15482                                             Message->getReceiverInterface(),
15483                                             NSAPI::ClassId_NSMutableOrderedSet);
15484   if (!IsMutableSet && !IsMutableOrderedSet) {
15485     return None;
15486   }
15487 
15488   Selector Sel = Message->getSelector();
15489 
15490   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15491   if (!MKOpt) {
15492     return None;
15493   }
15494 
15495   NSAPI::NSSetMethodKind MK = *MKOpt;
15496 
15497   switch (MK) {
15498     case NSAPI::NSMutableSet_addObject:
15499     case NSAPI::NSOrderedSet_setObjectAtIndex:
15500     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15501     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15502       return 0;
15503     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15504       return 1;
15505   }
15506 
15507   return None;
15508 }
15509 
15510 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15511   if (!Message->isInstanceMessage()) {
15512     return;
15513   }
15514 
15515   Optional<int> ArgOpt;
15516 
15517   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15518       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15519       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15520     return;
15521   }
15522 
15523   int ArgIndex = *ArgOpt;
15524 
15525   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15526   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15527     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15528   }
15529 
15530   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15531     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15532       if (ArgRE->isObjCSelfExpr()) {
15533         Diag(Message->getSourceRange().getBegin(),
15534              diag::warn_objc_circular_container)
15535           << ArgRE->getDecl() << StringRef("'super'");
15536       }
15537     }
15538   } else {
15539     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15540 
15541     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15542       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15543     }
15544 
15545     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15546       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15547         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15548           ValueDecl *Decl = ReceiverRE->getDecl();
15549           Diag(Message->getSourceRange().getBegin(),
15550                diag::warn_objc_circular_container)
15551             << Decl << Decl;
15552           if (!ArgRE->isObjCSelfExpr()) {
15553             Diag(Decl->getLocation(),
15554                  diag::note_objc_circular_container_declared_here)
15555               << Decl;
15556           }
15557         }
15558       }
15559     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15560       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15561         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15562           ObjCIvarDecl *Decl = IvarRE->getDecl();
15563           Diag(Message->getSourceRange().getBegin(),
15564                diag::warn_objc_circular_container)
15565             << Decl << Decl;
15566           Diag(Decl->getLocation(),
15567                diag::note_objc_circular_container_declared_here)
15568             << Decl;
15569         }
15570       }
15571     }
15572   }
15573 }
15574 
15575 /// Check a message send to see if it's likely to cause a retain cycle.
15576 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15577   // Only check instance methods whose selector looks like a setter.
15578   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15579     return;
15580 
15581   // Try to find a variable that the receiver is strongly owned by.
15582   RetainCycleOwner owner;
15583   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15584     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15585       return;
15586   } else {
15587     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15588     owner.Variable = getCurMethodDecl()->getSelfDecl();
15589     owner.Loc = msg->getSuperLoc();
15590     owner.Range = msg->getSuperLoc();
15591   }
15592 
15593   // Check whether the receiver is captured by any of the arguments.
15594   const ObjCMethodDecl *MD = msg->getMethodDecl();
15595   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15596     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15597       // noescape blocks should not be retained by the method.
15598       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15599         continue;
15600       return diagnoseRetainCycle(*this, capturer, owner);
15601     }
15602   }
15603 }
15604 
15605 /// Check a property assign to see if it's likely to cause a retain cycle.
15606 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15607   RetainCycleOwner owner;
15608   if (!findRetainCycleOwner(*this, receiver, owner))
15609     return;
15610 
15611   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15612     diagnoseRetainCycle(*this, capturer, owner);
15613 }
15614 
15615 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15616   RetainCycleOwner Owner;
15617   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15618     return;
15619 
15620   // Because we don't have an expression for the variable, we have to set the
15621   // location explicitly here.
15622   Owner.Loc = Var->getLocation();
15623   Owner.Range = Var->getSourceRange();
15624 
15625   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15626     diagnoseRetainCycle(*this, Capturer, Owner);
15627 }
15628 
15629 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15630                                      Expr *RHS, bool isProperty) {
15631   // Check if RHS is an Objective-C object literal, which also can get
15632   // immediately zapped in a weak reference.  Note that we explicitly
15633   // allow ObjCStringLiterals, since those are designed to never really die.
15634   RHS = RHS->IgnoreParenImpCasts();
15635 
15636   // This enum needs to match with the 'select' in
15637   // warn_objc_arc_literal_assign (off-by-1).
15638   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15639   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15640     return false;
15641 
15642   S.Diag(Loc, diag::warn_arc_literal_assign)
15643     << (unsigned) Kind
15644     << (isProperty ? 0 : 1)
15645     << RHS->getSourceRange();
15646 
15647   return true;
15648 }
15649 
15650 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15651                                     Qualifiers::ObjCLifetime LT,
15652                                     Expr *RHS, bool isProperty) {
15653   // Strip off any implicit cast added to get to the one ARC-specific.
15654   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15655     if (cast->getCastKind() == CK_ARCConsumeObject) {
15656       S.Diag(Loc, diag::warn_arc_retained_assign)
15657         << (LT == Qualifiers::OCL_ExplicitNone)
15658         << (isProperty ? 0 : 1)
15659         << RHS->getSourceRange();
15660       return true;
15661     }
15662     RHS = cast->getSubExpr();
15663   }
15664 
15665   if (LT == Qualifiers::OCL_Weak &&
15666       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15667     return true;
15668 
15669   return false;
15670 }
15671 
15672 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15673                               QualType LHS, Expr *RHS) {
15674   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15675 
15676   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15677     return false;
15678 
15679   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15680     return true;
15681 
15682   return false;
15683 }
15684 
15685 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15686                               Expr *LHS, Expr *RHS) {
15687   QualType LHSType;
15688   // PropertyRef on LHS type need be directly obtained from
15689   // its declaration as it has a PseudoType.
15690   ObjCPropertyRefExpr *PRE
15691     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15692   if (PRE && !PRE->isImplicitProperty()) {
15693     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15694     if (PD)
15695       LHSType = PD->getType();
15696   }
15697 
15698   if (LHSType.isNull())
15699     LHSType = LHS->getType();
15700 
15701   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15702 
15703   if (LT == Qualifiers::OCL_Weak) {
15704     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15705       getCurFunction()->markSafeWeakUse(LHS);
15706   }
15707 
15708   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15709     return;
15710 
15711   // FIXME. Check for other life times.
15712   if (LT != Qualifiers::OCL_None)
15713     return;
15714 
15715   if (PRE) {
15716     if (PRE->isImplicitProperty())
15717       return;
15718     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15719     if (!PD)
15720       return;
15721 
15722     unsigned Attributes = PD->getPropertyAttributes();
15723     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15724       // when 'assign' attribute was not explicitly specified
15725       // by user, ignore it and rely on property type itself
15726       // for lifetime info.
15727       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15728       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15729           LHSType->isObjCRetainableType())
15730         return;
15731 
15732       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15733         if (cast->getCastKind() == CK_ARCConsumeObject) {
15734           Diag(Loc, diag::warn_arc_retained_property_assign)
15735           << RHS->getSourceRange();
15736           return;
15737         }
15738         RHS = cast->getSubExpr();
15739       }
15740     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15741       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15742         return;
15743     }
15744   }
15745 }
15746 
15747 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15748 
15749 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15750                                         SourceLocation StmtLoc,
15751                                         const NullStmt *Body) {
15752   // Do not warn if the body is a macro that expands to nothing, e.g:
15753   //
15754   // #define CALL(x)
15755   // if (condition)
15756   //   CALL(0);
15757   if (Body->hasLeadingEmptyMacro())
15758     return false;
15759 
15760   // Get line numbers of statement and body.
15761   bool StmtLineInvalid;
15762   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15763                                                       &StmtLineInvalid);
15764   if (StmtLineInvalid)
15765     return false;
15766 
15767   bool BodyLineInvalid;
15768   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15769                                                       &BodyLineInvalid);
15770   if (BodyLineInvalid)
15771     return false;
15772 
15773   // Warn if null statement and body are on the same line.
15774   if (StmtLine != BodyLine)
15775     return false;
15776 
15777   return true;
15778 }
15779 
15780 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15781                                  const Stmt *Body,
15782                                  unsigned DiagID) {
15783   // Since this is a syntactic check, don't emit diagnostic for template
15784   // instantiations, this just adds noise.
15785   if (CurrentInstantiationScope)
15786     return;
15787 
15788   // The body should be a null statement.
15789   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15790   if (!NBody)
15791     return;
15792 
15793   // Do the usual checks.
15794   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15795     return;
15796 
15797   Diag(NBody->getSemiLoc(), DiagID);
15798   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15799 }
15800 
15801 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15802                                  const Stmt *PossibleBody) {
15803   assert(!CurrentInstantiationScope); // Ensured by caller
15804 
15805   SourceLocation StmtLoc;
15806   const Stmt *Body;
15807   unsigned DiagID;
15808   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15809     StmtLoc = FS->getRParenLoc();
15810     Body = FS->getBody();
15811     DiagID = diag::warn_empty_for_body;
15812   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15813     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15814     Body = WS->getBody();
15815     DiagID = diag::warn_empty_while_body;
15816   } else
15817     return; // Neither `for' nor `while'.
15818 
15819   // The body should be a null statement.
15820   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15821   if (!NBody)
15822     return;
15823 
15824   // Skip expensive checks if diagnostic is disabled.
15825   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15826     return;
15827 
15828   // Do the usual checks.
15829   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15830     return;
15831 
15832   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15833   // noise level low, emit diagnostics only if for/while is followed by a
15834   // CompoundStmt, e.g.:
15835   //    for (int i = 0; i < n; i++);
15836   //    {
15837   //      a(i);
15838   //    }
15839   // or if for/while is followed by a statement with more indentation
15840   // than for/while itself:
15841   //    for (int i = 0; i < n; i++);
15842   //      a(i);
15843   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15844   if (!ProbableTypo) {
15845     bool BodyColInvalid;
15846     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15847         PossibleBody->getBeginLoc(), &BodyColInvalid);
15848     if (BodyColInvalid)
15849       return;
15850 
15851     bool StmtColInvalid;
15852     unsigned StmtCol =
15853         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15854     if (StmtColInvalid)
15855       return;
15856 
15857     if (BodyCol > StmtCol)
15858       ProbableTypo = true;
15859   }
15860 
15861   if (ProbableTypo) {
15862     Diag(NBody->getSemiLoc(), DiagID);
15863     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15864   }
15865 }
15866 
15867 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15868 
15869 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15870 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15871                              SourceLocation OpLoc) {
15872   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15873     return;
15874 
15875   if (inTemplateInstantiation())
15876     return;
15877 
15878   // Strip parens and casts away.
15879   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15880   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15881 
15882   // Check for a call expression
15883   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15884   if (!CE || CE->getNumArgs() != 1)
15885     return;
15886 
15887   // Check for a call to std::move
15888   if (!CE->isCallToStdMove())
15889     return;
15890 
15891   // Get argument from std::move
15892   RHSExpr = CE->getArg(0);
15893 
15894   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15895   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15896 
15897   // Two DeclRefExpr's, check that the decls are the same.
15898   if (LHSDeclRef && RHSDeclRef) {
15899     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15900       return;
15901     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15902         RHSDeclRef->getDecl()->getCanonicalDecl())
15903       return;
15904 
15905     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15906                                         << LHSExpr->getSourceRange()
15907                                         << RHSExpr->getSourceRange();
15908     return;
15909   }
15910 
15911   // Member variables require a different approach to check for self moves.
15912   // MemberExpr's are the same if every nested MemberExpr refers to the same
15913   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15914   // the base Expr's are CXXThisExpr's.
15915   const Expr *LHSBase = LHSExpr;
15916   const Expr *RHSBase = RHSExpr;
15917   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15918   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15919   if (!LHSME || !RHSME)
15920     return;
15921 
15922   while (LHSME && RHSME) {
15923     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15924         RHSME->getMemberDecl()->getCanonicalDecl())
15925       return;
15926 
15927     LHSBase = LHSME->getBase();
15928     RHSBase = RHSME->getBase();
15929     LHSME = dyn_cast<MemberExpr>(LHSBase);
15930     RHSME = dyn_cast<MemberExpr>(RHSBase);
15931   }
15932 
15933   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15934   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15935   if (LHSDeclRef && RHSDeclRef) {
15936     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15937       return;
15938     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15939         RHSDeclRef->getDecl()->getCanonicalDecl())
15940       return;
15941 
15942     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15943                                         << LHSExpr->getSourceRange()
15944                                         << RHSExpr->getSourceRange();
15945     return;
15946   }
15947 
15948   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15949     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15950                                         << LHSExpr->getSourceRange()
15951                                         << RHSExpr->getSourceRange();
15952 }
15953 
15954 //===--- Layout compatibility ----------------------------------------------//
15955 
15956 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15957 
15958 /// Check if two enumeration types are layout-compatible.
15959 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15960   // C++11 [dcl.enum] p8:
15961   // Two enumeration types are layout-compatible if they have the same
15962   // underlying type.
15963   return ED1->isComplete() && ED2->isComplete() &&
15964          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15965 }
15966 
15967 /// Check if two fields are layout-compatible.
15968 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15969                                FieldDecl *Field2) {
15970   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15971     return false;
15972 
15973   if (Field1->isBitField() != Field2->isBitField())
15974     return false;
15975 
15976   if (Field1->isBitField()) {
15977     // Make sure that the bit-fields are the same length.
15978     unsigned Bits1 = Field1->getBitWidthValue(C);
15979     unsigned Bits2 = Field2->getBitWidthValue(C);
15980 
15981     if (Bits1 != Bits2)
15982       return false;
15983   }
15984 
15985   return true;
15986 }
15987 
15988 /// Check if two standard-layout structs are layout-compatible.
15989 /// (C++11 [class.mem] p17)
15990 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15991                                      RecordDecl *RD2) {
15992   // If both records are C++ classes, check that base classes match.
15993   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15994     // If one of records is a CXXRecordDecl we are in C++ mode,
15995     // thus the other one is a CXXRecordDecl, too.
15996     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15997     // Check number of base classes.
15998     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15999       return false;
16000 
16001     // Check the base classes.
16002     for (CXXRecordDecl::base_class_const_iterator
16003                Base1 = D1CXX->bases_begin(),
16004            BaseEnd1 = D1CXX->bases_end(),
16005               Base2 = D2CXX->bases_begin();
16006          Base1 != BaseEnd1;
16007          ++Base1, ++Base2) {
16008       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16009         return false;
16010     }
16011   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16012     // If only RD2 is a C++ class, it should have zero base classes.
16013     if (D2CXX->getNumBases() > 0)
16014       return false;
16015   }
16016 
16017   // Check the fields.
16018   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16019                              Field2End = RD2->field_end(),
16020                              Field1 = RD1->field_begin(),
16021                              Field1End = RD1->field_end();
16022   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16023     if (!isLayoutCompatible(C, *Field1, *Field2))
16024       return false;
16025   }
16026   if (Field1 != Field1End || Field2 != Field2End)
16027     return false;
16028 
16029   return true;
16030 }
16031 
16032 /// Check if two standard-layout unions are layout-compatible.
16033 /// (C++11 [class.mem] p18)
16034 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16035                                     RecordDecl *RD2) {
16036   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16037   for (auto *Field2 : RD2->fields())
16038     UnmatchedFields.insert(Field2);
16039 
16040   for (auto *Field1 : RD1->fields()) {
16041     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16042         I = UnmatchedFields.begin(),
16043         E = UnmatchedFields.end();
16044 
16045     for ( ; I != E; ++I) {
16046       if (isLayoutCompatible(C, Field1, *I)) {
16047         bool Result = UnmatchedFields.erase(*I);
16048         (void) Result;
16049         assert(Result);
16050         break;
16051       }
16052     }
16053     if (I == E)
16054       return false;
16055   }
16056 
16057   return UnmatchedFields.empty();
16058 }
16059 
16060 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16061                                RecordDecl *RD2) {
16062   if (RD1->isUnion() != RD2->isUnion())
16063     return false;
16064 
16065   if (RD1->isUnion())
16066     return isLayoutCompatibleUnion(C, RD1, RD2);
16067   else
16068     return isLayoutCompatibleStruct(C, RD1, RD2);
16069 }
16070 
16071 /// Check if two types are layout-compatible in C++11 sense.
16072 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16073   if (T1.isNull() || T2.isNull())
16074     return false;
16075 
16076   // C++11 [basic.types] p11:
16077   // If two types T1 and T2 are the same type, then T1 and T2 are
16078   // layout-compatible types.
16079   if (C.hasSameType(T1, T2))
16080     return true;
16081 
16082   T1 = T1.getCanonicalType().getUnqualifiedType();
16083   T2 = T2.getCanonicalType().getUnqualifiedType();
16084 
16085   const Type::TypeClass TC1 = T1->getTypeClass();
16086   const Type::TypeClass TC2 = T2->getTypeClass();
16087 
16088   if (TC1 != TC2)
16089     return false;
16090 
16091   if (TC1 == Type::Enum) {
16092     return isLayoutCompatible(C,
16093                               cast<EnumType>(T1)->getDecl(),
16094                               cast<EnumType>(T2)->getDecl());
16095   } else if (TC1 == Type::Record) {
16096     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16097       return false;
16098 
16099     return isLayoutCompatible(C,
16100                               cast<RecordType>(T1)->getDecl(),
16101                               cast<RecordType>(T2)->getDecl());
16102   }
16103 
16104   return false;
16105 }
16106 
16107 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16108 
16109 /// Given a type tag expression find the type tag itself.
16110 ///
16111 /// \param TypeExpr Type tag expression, as it appears in user's code.
16112 ///
16113 /// \param VD Declaration of an identifier that appears in a type tag.
16114 ///
16115 /// \param MagicValue Type tag magic value.
16116 ///
16117 /// \param isConstantEvaluated whether the evalaution should be performed in
16118 
16119 /// constant context.
16120 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16121                             const ValueDecl **VD, uint64_t *MagicValue,
16122                             bool isConstantEvaluated) {
16123   while(true) {
16124     if (!TypeExpr)
16125       return false;
16126 
16127     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16128 
16129     switch (TypeExpr->getStmtClass()) {
16130     case Stmt::UnaryOperatorClass: {
16131       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16132       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16133         TypeExpr = UO->getSubExpr();
16134         continue;
16135       }
16136       return false;
16137     }
16138 
16139     case Stmt::DeclRefExprClass: {
16140       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16141       *VD = DRE->getDecl();
16142       return true;
16143     }
16144 
16145     case Stmt::IntegerLiteralClass: {
16146       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16147       llvm::APInt MagicValueAPInt = IL->getValue();
16148       if (MagicValueAPInt.getActiveBits() <= 64) {
16149         *MagicValue = MagicValueAPInt.getZExtValue();
16150         return true;
16151       } else
16152         return false;
16153     }
16154 
16155     case Stmt::BinaryConditionalOperatorClass:
16156     case Stmt::ConditionalOperatorClass: {
16157       const AbstractConditionalOperator *ACO =
16158           cast<AbstractConditionalOperator>(TypeExpr);
16159       bool Result;
16160       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16161                                                      isConstantEvaluated)) {
16162         if (Result)
16163           TypeExpr = ACO->getTrueExpr();
16164         else
16165           TypeExpr = ACO->getFalseExpr();
16166         continue;
16167       }
16168       return false;
16169     }
16170 
16171     case Stmt::BinaryOperatorClass: {
16172       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16173       if (BO->getOpcode() == BO_Comma) {
16174         TypeExpr = BO->getRHS();
16175         continue;
16176       }
16177       return false;
16178     }
16179 
16180     default:
16181       return false;
16182     }
16183   }
16184 }
16185 
16186 /// Retrieve the C type corresponding to type tag TypeExpr.
16187 ///
16188 /// \param TypeExpr Expression that specifies a type tag.
16189 ///
16190 /// \param MagicValues Registered magic values.
16191 ///
16192 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16193 ///        kind.
16194 ///
16195 /// \param TypeInfo Information about the corresponding C type.
16196 ///
16197 /// \param isConstantEvaluated whether the evalaution should be performed in
16198 /// constant context.
16199 ///
16200 /// \returns true if the corresponding C type was found.
16201 static bool GetMatchingCType(
16202     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16203     const ASTContext &Ctx,
16204     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16205         *MagicValues,
16206     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16207     bool isConstantEvaluated) {
16208   FoundWrongKind = false;
16209 
16210   // Variable declaration that has type_tag_for_datatype attribute.
16211   const ValueDecl *VD = nullptr;
16212 
16213   uint64_t MagicValue;
16214 
16215   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16216     return false;
16217 
16218   if (VD) {
16219     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16220       if (I->getArgumentKind() != ArgumentKind) {
16221         FoundWrongKind = true;
16222         return false;
16223       }
16224       TypeInfo.Type = I->getMatchingCType();
16225       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16226       TypeInfo.MustBeNull = I->getMustBeNull();
16227       return true;
16228     }
16229     return false;
16230   }
16231 
16232   if (!MagicValues)
16233     return false;
16234 
16235   llvm::DenseMap<Sema::TypeTagMagicValue,
16236                  Sema::TypeTagData>::const_iterator I =
16237       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16238   if (I == MagicValues->end())
16239     return false;
16240 
16241   TypeInfo = I->second;
16242   return true;
16243 }
16244 
16245 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16246                                       uint64_t MagicValue, QualType Type,
16247                                       bool LayoutCompatible,
16248                                       bool MustBeNull) {
16249   if (!TypeTagForDatatypeMagicValues)
16250     TypeTagForDatatypeMagicValues.reset(
16251         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16252 
16253   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16254   (*TypeTagForDatatypeMagicValues)[Magic] =
16255       TypeTagData(Type, LayoutCompatible, MustBeNull);
16256 }
16257 
16258 static bool IsSameCharType(QualType T1, QualType T2) {
16259   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16260   if (!BT1)
16261     return false;
16262 
16263   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16264   if (!BT2)
16265     return false;
16266 
16267   BuiltinType::Kind T1Kind = BT1->getKind();
16268   BuiltinType::Kind T2Kind = BT2->getKind();
16269 
16270   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16271          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16272          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16273          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16274 }
16275 
16276 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16277                                     const ArrayRef<const Expr *> ExprArgs,
16278                                     SourceLocation CallSiteLoc) {
16279   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16280   bool IsPointerAttr = Attr->getIsPointer();
16281 
16282   // Retrieve the argument representing the 'type_tag'.
16283   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16284   if (TypeTagIdxAST >= ExprArgs.size()) {
16285     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16286         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16287     return;
16288   }
16289   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16290   bool FoundWrongKind;
16291   TypeTagData TypeInfo;
16292   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16293                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16294                         TypeInfo, isConstantEvaluated())) {
16295     if (FoundWrongKind)
16296       Diag(TypeTagExpr->getExprLoc(),
16297            diag::warn_type_tag_for_datatype_wrong_kind)
16298         << TypeTagExpr->getSourceRange();
16299     return;
16300   }
16301 
16302   // Retrieve the argument representing the 'arg_idx'.
16303   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16304   if (ArgumentIdxAST >= ExprArgs.size()) {
16305     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16306         << 1 << Attr->getArgumentIdx().getSourceIndex();
16307     return;
16308   }
16309   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16310   if (IsPointerAttr) {
16311     // Skip implicit cast of pointer to `void *' (as a function argument).
16312     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16313       if (ICE->getType()->isVoidPointerType() &&
16314           ICE->getCastKind() == CK_BitCast)
16315         ArgumentExpr = ICE->getSubExpr();
16316   }
16317   QualType ArgumentType = ArgumentExpr->getType();
16318 
16319   // Passing a `void*' pointer shouldn't trigger a warning.
16320   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16321     return;
16322 
16323   if (TypeInfo.MustBeNull) {
16324     // Type tag with matching void type requires a null pointer.
16325     if (!ArgumentExpr->isNullPointerConstant(Context,
16326                                              Expr::NPC_ValueDependentIsNotNull)) {
16327       Diag(ArgumentExpr->getExprLoc(),
16328            diag::warn_type_safety_null_pointer_required)
16329           << ArgumentKind->getName()
16330           << ArgumentExpr->getSourceRange()
16331           << TypeTagExpr->getSourceRange();
16332     }
16333     return;
16334   }
16335 
16336   QualType RequiredType = TypeInfo.Type;
16337   if (IsPointerAttr)
16338     RequiredType = Context.getPointerType(RequiredType);
16339 
16340   bool mismatch = false;
16341   if (!TypeInfo.LayoutCompatible) {
16342     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16343 
16344     // C++11 [basic.fundamental] p1:
16345     // Plain char, signed char, and unsigned char are three distinct types.
16346     //
16347     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16348     // char' depending on the current char signedness mode.
16349     if (mismatch)
16350       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16351                                            RequiredType->getPointeeType())) ||
16352           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16353         mismatch = false;
16354   } else
16355     if (IsPointerAttr)
16356       mismatch = !isLayoutCompatible(Context,
16357                                      ArgumentType->getPointeeType(),
16358                                      RequiredType->getPointeeType());
16359     else
16360       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16361 
16362   if (mismatch)
16363     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16364         << ArgumentType << ArgumentKind
16365         << TypeInfo.LayoutCompatible << RequiredType
16366         << ArgumentExpr->getSourceRange()
16367         << TypeTagExpr->getSourceRange();
16368 }
16369 
16370 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16371                                          CharUnits Alignment) {
16372   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16373 }
16374 
16375 void Sema::DiagnoseMisalignedMembers() {
16376   for (MisalignedMember &m : MisalignedMembers) {
16377     const NamedDecl *ND = m.RD;
16378     if (ND->getName().empty()) {
16379       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16380         ND = TD;
16381     }
16382     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16383         << m.MD << ND << m.E->getSourceRange();
16384   }
16385   MisalignedMembers.clear();
16386 }
16387 
16388 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16389   E = E->IgnoreParens();
16390   if (!T->isPointerType() && !T->isIntegerType())
16391     return;
16392   if (isa<UnaryOperator>(E) &&
16393       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16394     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16395     if (isa<MemberExpr>(Op)) {
16396       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16397       if (MA != MisalignedMembers.end() &&
16398           (T->isIntegerType() ||
16399            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16400                                    Context.getTypeAlignInChars(
16401                                        T->getPointeeType()) <= MA->Alignment))))
16402         MisalignedMembers.erase(MA);
16403     }
16404   }
16405 }
16406 
16407 void Sema::RefersToMemberWithReducedAlignment(
16408     Expr *E,
16409     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16410         Action) {
16411   const auto *ME = dyn_cast<MemberExpr>(E);
16412   if (!ME)
16413     return;
16414 
16415   // No need to check expressions with an __unaligned-qualified type.
16416   if (E->getType().getQualifiers().hasUnaligned())
16417     return;
16418 
16419   // For a chain of MemberExpr like "a.b.c.d" this list
16420   // will keep FieldDecl's like [d, c, b].
16421   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16422   const MemberExpr *TopME = nullptr;
16423   bool AnyIsPacked = false;
16424   do {
16425     QualType BaseType = ME->getBase()->getType();
16426     if (BaseType->isDependentType())
16427       return;
16428     if (ME->isArrow())
16429       BaseType = BaseType->getPointeeType();
16430     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16431     if (RD->isInvalidDecl())
16432       return;
16433 
16434     ValueDecl *MD = ME->getMemberDecl();
16435     auto *FD = dyn_cast<FieldDecl>(MD);
16436     // We do not care about non-data members.
16437     if (!FD || FD->isInvalidDecl())
16438       return;
16439 
16440     AnyIsPacked =
16441         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16442     ReverseMemberChain.push_back(FD);
16443 
16444     TopME = ME;
16445     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16446   } while (ME);
16447   assert(TopME && "We did not compute a topmost MemberExpr!");
16448 
16449   // Not the scope of this diagnostic.
16450   if (!AnyIsPacked)
16451     return;
16452 
16453   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16454   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16455   // TODO: The innermost base of the member expression may be too complicated.
16456   // For now, just disregard these cases. This is left for future
16457   // improvement.
16458   if (!DRE && !isa<CXXThisExpr>(TopBase))
16459       return;
16460 
16461   // Alignment expected by the whole expression.
16462   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16463 
16464   // No need to do anything else with this case.
16465   if (ExpectedAlignment.isOne())
16466     return;
16467 
16468   // Synthesize offset of the whole access.
16469   CharUnits Offset;
16470   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16471        I++) {
16472     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16473   }
16474 
16475   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16476   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16477       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16478 
16479   // The base expression of the innermost MemberExpr may give
16480   // stronger guarantees than the class containing the member.
16481   if (DRE && !TopME->isArrow()) {
16482     const ValueDecl *VD = DRE->getDecl();
16483     if (!VD->getType()->isReferenceType())
16484       CompleteObjectAlignment =
16485           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16486   }
16487 
16488   // Check if the synthesized offset fulfills the alignment.
16489   if (Offset % ExpectedAlignment != 0 ||
16490       // It may fulfill the offset it but the effective alignment may still be
16491       // lower than the expected expression alignment.
16492       CompleteObjectAlignment < ExpectedAlignment) {
16493     // If this happens, we want to determine a sensible culprit of this.
16494     // Intuitively, watching the chain of member expressions from right to
16495     // left, we start with the required alignment (as required by the field
16496     // type) but some packed attribute in that chain has reduced the alignment.
16497     // It may happen that another packed structure increases it again. But if
16498     // we are here such increase has not been enough. So pointing the first
16499     // FieldDecl that either is packed or else its RecordDecl is,
16500     // seems reasonable.
16501     FieldDecl *FD = nullptr;
16502     CharUnits Alignment;
16503     for (FieldDecl *FDI : ReverseMemberChain) {
16504       if (FDI->hasAttr<PackedAttr>() ||
16505           FDI->getParent()->hasAttr<PackedAttr>()) {
16506         FD = FDI;
16507         Alignment = std::min(
16508             Context.getTypeAlignInChars(FD->getType()),
16509             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16510         break;
16511       }
16512     }
16513     assert(FD && "We did not find a packed FieldDecl!");
16514     Action(E, FD->getParent(), FD, Alignment);
16515   }
16516 }
16517 
16518 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16519   using namespace std::placeholders;
16520 
16521   RefersToMemberWithReducedAlignment(
16522       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16523                      _2, _3, _4));
16524 }
16525 
16526 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16527 // not a valid type, emit an error message and return true. Otherwise return
16528 // false.
16529 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16530                                         QualType Ty) {
16531   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16532     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16533         << 1 << "vector, integer or floating point type" << Ty;
16534     return true;
16535   }
16536   return false;
16537 }
16538 
16539 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16540   if (checkArgCount(*this, TheCall, 2))
16541     return true;
16542 
16543   ExprResult A = TheCall->getArg(0);
16544   ExprResult B = TheCall->getArg(1);
16545   // Do standard promotions between the two arguments, returning their common
16546   // type.
16547   QualType Res =
16548       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16549   if (A.isInvalid() || B.isInvalid())
16550     return true;
16551 
16552   QualType TyA = A.get()->getType();
16553   QualType TyB = B.get()->getType();
16554 
16555   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16556     return Diag(A.get()->getBeginLoc(),
16557                 diag::err_typecheck_call_different_arg_types)
16558            << TyA << TyB;
16559 
16560   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16561     return true;
16562 
16563   TheCall->setArg(0, A.get());
16564   TheCall->setArg(1, B.get());
16565   TheCall->setType(Res);
16566   return false;
16567 }
16568 
16569 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16570                                             ExprResult CallResult) {
16571   if (checkArgCount(*this, TheCall, 1))
16572     return ExprError();
16573 
16574   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16575   if (MatrixArg.isInvalid())
16576     return MatrixArg;
16577   Expr *Matrix = MatrixArg.get();
16578 
16579   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16580   if (!MType) {
16581     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16582     return ExprError();
16583   }
16584 
16585   // Create returned matrix type by swapping rows and columns of the argument
16586   // matrix type.
16587   QualType ResultType = Context.getConstantMatrixType(
16588       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16589 
16590   // Change the return type to the type of the returned matrix.
16591   TheCall->setType(ResultType);
16592 
16593   // Update call argument to use the possibly converted matrix argument.
16594   TheCall->setArg(0, Matrix);
16595   return CallResult;
16596 }
16597 
16598 // Get and verify the matrix dimensions.
16599 static llvm::Optional<unsigned>
16600 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16601   SourceLocation ErrorPos;
16602   Optional<llvm::APSInt> Value =
16603       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16604   if (!Value) {
16605     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16606         << Name;
16607     return {};
16608   }
16609   uint64_t Dim = Value->getZExtValue();
16610   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16611     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16612         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16613     return {};
16614   }
16615   return Dim;
16616 }
16617 
16618 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16619                                                   ExprResult CallResult) {
16620   if (!getLangOpts().MatrixTypes) {
16621     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16622     return ExprError();
16623   }
16624 
16625   if (checkArgCount(*this, TheCall, 4))
16626     return ExprError();
16627 
16628   unsigned PtrArgIdx = 0;
16629   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16630   Expr *RowsExpr = TheCall->getArg(1);
16631   Expr *ColumnsExpr = TheCall->getArg(2);
16632   Expr *StrideExpr = TheCall->getArg(3);
16633 
16634   bool ArgError = false;
16635 
16636   // Check pointer argument.
16637   {
16638     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16639     if (PtrConv.isInvalid())
16640       return PtrConv;
16641     PtrExpr = PtrConv.get();
16642     TheCall->setArg(0, PtrExpr);
16643     if (PtrExpr->isTypeDependent()) {
16644       TheCall->setType(Context.DependentTy);
16645       return TheCall;
16646     }
16647   }
16648 
16649   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16650   QualType ElementTy;
16651   if (!PtrTy) {
16652     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16653         << PtrArgIdx + 1;
16654     ArgError = true;
16655   } else {
16656     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16657 
16658     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16659       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16660           << PtrArgIdx + 1;
16661       ArgError = true;
16662     }
16663   }
16664 
16665   // Apply default Lvalue conversions and convert the expression to size_t.
16666   auto ApplyArgumentConversions = [this](Expr *E) {
16667     ExprResult Conv = DefaultLvalueConversion(E);
16668     if (Conv.isInvalid())
16669       return Conv;
16670 
16671     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16672   };
16673 
16674   // Apply conversion to row and column expressions.
16675   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16676   if (!RowsConv.isInvalid()) {
16677     RowsExpr = RowsConv.get();
16678     TheCall->setArg(1, RowsExpr);
16679   } else
16680     RowsExpr = nullptr;
16681 
16682   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16683   if (!ColumnsConv.isInvalid()) {
16684     ColumnsExpr = ColumnsConv.get();
16685     TheCall->setArg(2, ColumnsExpr);
16686   } else
16687     ColumnsExpr = nullptr;
16688 
16689   // If any any part of the result matrix type is still pending, just use
16690   // Context.DependentTy, until all parts are resolved.
16691   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16692       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16693     TheCall->setType(Context.DependentTy);
16694     return CallResult;
16695   }
16696 
16697   // Check row and column dimensions.
16698   llvm::Optional<unsigned> MaybeRows;
16699   if (RowsExpr)
16700     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16701 
16702   llvm::Optional<unsigned> MaybeColumns;
16703   if (ColumnsExpr)
16704     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16705 
16706   // Check stride argument.
16707   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16708   if (StrideConv.isInvalid())
16709     return ExprError();
16710   StrideExpr = StrideConv.get();
16711   TheCall->setArg(3, StrideExpr);
16712 
16713   if (MaybeRows) {
16714     if (Optional<llvm::APSInt> Value =
16715             StrideExpr->getIntegerConstantExpr(Context)) {
16716       uint64_t Stride = Value->getZExtValue();
16717       if (Stride < *MaybeRows) {
16718         Diag(StrideExpr->getBeginLoc(),
16719              diag::err_builtin_matrix_stride_too_small);
16720         ArgError = true;
16721       }
16722     }
16723   }
16724 
16725   if (ArgError || !MaybeRows || !MaybeColumns)
16726     return ExprError();
16727 
16728   TheCall->setType(
16729       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16730   return CallResult;
16731 }
16732 
16733 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16734                                                    ExprResult CallResult) {
16735   if (checkArgCount(*this, TheCall, 3))
16736     return ExprError();
16737 
16738   unsigned PtrArgIdx = 1;
16739   Expr *MatrixExpr = TheCall->getArg(0);
16740   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16741   Expr *StrideExpr = TheCall->getArg(2);
16742 
16743   bool ArgError = false;
16744 
16745   {
16746     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16747     if (MatrixConv.isInvalid())
16748       return MatrixConv;
16749     MatrixExpr = MatrixConv.get();
16750     TheCall->setArg(0, MatrixExpr);
16751   }
16752   if (MatrixExpr->isTypeDependent()) {
16753     TheCall->setType(Context.DependentTy);
16754     return TheCall;
16755   }
16756 
16757   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16758   if (!MatrixTy) {
16759     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16760     ArgError = true;
16761   }
16762 
16763   {
16764     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16765     if (PtrConv.isInvalid())
16766       return PtrConv;
16767     PtrExpr = PtrConv.get();
16768     TheCall->setArg(1, PtrExpr);
16769     if (PtrExpr->isTypeDependent()) {
16770       TheCall->setType(Context.DependentTy);
16771       return TheCall;
16772     }
16773   }
16774 
16775   // Check pointer argument.
16776   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16777   if (!PtrTy) {
16778     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16779         << PtrArgIdx + 1;
16780     ArgError = true;
16781   } else {
16782     QualType ElementTy = PtrTy->getPointeeType();
16783     if (ElementTy.isConstQualified()) {
16784       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16785       ArgError = true;
16786     }
16787     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16788     if (MatrixTy &&
16789         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16790       Diag(PtrExpr->getBeginLoc(),
16791            diag::err_builtin_matrix_pointer_arg_mismatch)
16792           << ElementTy << MatrixTy->getElementType();
16793       ArgError = true;
16794     }
16795   }
16796 
16797   // Apply default Lvalue conversions and convert the stride expression to
16798   // size_t.
16799   {
16800     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16801     if (StrideConv.isInvalid())
16802       return StrideConv;
16803 
16804     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16805     if (StrideConv.isInvalid())
16806       return StrideConv;
16807     StrideExpr = StrideConv.get();
16808     TheCall->setArg(2, StrideExpr);
16809   }
16810 
16811   // Check stride argument.
16812   if (MatrixTy) {
16813     if (Optional<llvm::APSInt> Value =
16814             StrideExpr->getIntegerConstantExpr(Context)) {
16815       uint64_t Stride = Value->getZExtValue();
16816       if (Stride < MatrixTy->getNumRows()) {
16817         Diag(StrideExpr->getBeginLoc(),
16818              diag::err_builtin_matrix_stride_too_small);
16819         ArgError = true;
16820       }
16821     }
16822   }
16823 
16824   if (ArgError)
16825     return ExprError();
16826 
16827   return CallResult;
16828 }
16829 
16830 /// \brief Enforce the bounds of a TCB
16831 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16832 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16833 /// and enforce_tcb_leaf attributes.
16834 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16835                                const FunctionDecl *Callee) {
16836   const FunctionDecl *Caller = getCurFunctionDecl();
16837 
16838   // Calls to builtins are not enforced.
16839   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16840       Callee->getBuiltinID() != 0)
16841     return;
16842 
16843   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16844   // all TCBs the callee is a part of.
16845   llvm::StringSet<> CalleeTCBs;
16846   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16847            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16848   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16849            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16850 
16851   // Go through the TCBs the caller is a part of and emit warnings if Caller
16852   // is in a TCB that the Callee is not.
16853   for_each(
16854       Caller->specific_attrs<EnforceTCBAttr>(),
16855       [&](const auto *A) {
16856         StringRef CallerTCB = A->getTCBName();
16857         if (CalleeTCBs.count(CallerTCB) == 0) {
16858           this->Diag(TheCall->getExprLoc(),
16859                      diag::warn_tcb_enforcement_violation) << Callee
16860                                                            << CallerTCB;
16861         }
16862       });
16863 }
16864